text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
#!/boot/bin/sh
# 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.
set -x
# Kill any existing dart runners.
killall dart* || true
# Start up a dart runner app that is guaranteed to be JIT, non-product, and
# won't terminate.
run -d fuchsia-pkg://fuchsia.com/hello_dart_jit#meta/hello_dart_jit.cmx
# Wait for it to come up.
sleep 2
# Find the path to its vm service port.
# NB: This is the command used by the Flutter host-side command line tools.
# If the use of 'find' here breaks, the Flutter host-side command line tools
# will also be broken. If this is intentional, then craft and land a Flutter PR.
# See: https://github.com/flutter/flutter/commit/b18a2b1794606a6cddb6d7f3486557e473e3bfbb
# Then, land a hard transition to GI that updates Flutter and this test.
FIND_RESULT=`find /hub -name vmservice-port | grep dart_jit_runner`
echo "find result:\n${FIND_RESULT}"
killall dart* || true
if [ -z "${FIND_RESULT}" ]; then
echo "FAILURE: Dart VM service not found in the Hub!"
exit 1
fi
exit 0
| engine/shell/platform/fuchsia/runtime/dart/utils/run_vmservice_object_tests.sh/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/run_vmservice_object_tests.sh",
"repo_id": "engine",
"token_count": 372
} | 500 |
// 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_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_H_
#include <flutter_glfw.h>
#include <string>
#include <vector>
#include "plugin_registrar.h"
namespace flutter {
// A data type for window position and size.
struct WindowFrame {
int left;
int top;
int width;
int height;
};
// A window displaying Flutter content.
class FlutterWindow {
public:
explicit FlutterWindow(FlutterDesktopWindowRef window) : window_(window) {}
~FlutterWindow() = default;
// Prevent copying.
FlutterWindow(FlutterWindow const&) = delete;
FlutterWindow& operator=(FlutterWindow const&) = delete;
// Enables or disables hover tracking.
//
// If hover is enabled, mouse movement will send hover events to the Flutter
// engine, rather than only tracking the mouse while the button is pressed.
// Defaults to off.
void SetHoverEnabled(bool enabled) {
FlutterDesktopWindowSetHoverEnabled(window_, enabled);
}
// Sets the displayed title of the window.
void SetTitle(const std::string& title) {
FlutterDesktopWindowSetTitle(window_, title.c_str());
}
// Sets the displayed icon for the window.
//
// The pixel format is 32-bit RGBA. The provided image data only needs to be
// valid for the duration of the call to this method. Pass a nullptr to revert
// to the default icon.
void SetIcon(uint8_t* pixel_data, int width, int height) {
FlutterDesktopWindowSetIcon(window_, pixel_data, width, height);
}
// Returns the frame of the window, including any decoration (e.g., title
// bar), in screen coordinates.
WindowFrame GetFrame() {
WindowFrame frame = {};
FlutterDesktopWindowGetFrame(window_, &frame.left, &frame.top, &frame.width,
&frame.height);
return frame;
}
// Set the frame of the window, including any decoration (e.g., title
// bar), in screen coordinates.
void SetFrame(const WindowFrame& frame) {
FlutterDesktopWindowSetFrame(window_, frame.left, frame.top, frame.width,
frame.height);
}
// Returns the number of pixels per screen coordinate for the window.
//
// Flutter uses pixel coordinates, so this is the ratio of positions and sizes
// seen by Flutter as compared to the screen.
double GetScaleFactor() {
return FlutterDesktopWindowGetScaleFactor(window_);
}
// Forces a specific pixel ratio for Flutter rendering, rather than one
// computed automatically from screen information.
//
// To clear a previously set override, pass an override value of zero.
void SetPixelRatioOverride(double pixel_ratio) {
FlutterDesktopWindowSetPixelRatioOverride(window_, pixel_ratio);
}
// Sets the min/max size of |flutter_window| in screen coordinates. Use
// kFlutterDesktopDontCare for any dimension you wish to leave unconstrained.
void SetSizeLimits(FlutterDesktopSize minimum_size,
FlutterDesktopSize maximum_size) {
FlutterDesktopWindowSetSizeLimits(window_, minimum_size, maximum_size);
}
private:
// Handle for interacting with the C API's window.
//
// Note: window_ is conceptually owned by the controller, not this object.
FlutterDesktopWindowRef window_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_H_
| engine/shell/platform/glfw/client_wrapper/include/flutter/flutter_window.h/0 | {
"file_path": "engine/shell/platform/glfw/client_wrapper/include/flutter/flutter_window.h",
"repo_id": "engine",
"token_count": 1159
} | 501 |
// 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_KEYBOARD_HOOK_HANDLER_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_KEYBOARD_HOOK_HANDLER_H_
#include <GLFW/glfw3.h>
#include "flutter/shell/platform/glfw/public/flutter_glfw.h"
namespace flutter {
// Abstract class for handling keyboard input events.
class KeyboardHookHandler {
public:
virtual ~KeyboardHookHandler() = default;
// A function for hooking into keyboard input.
virtual void KeyboardHook(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) = 0;
// A function for hooking into unicode code point input.
virtual void CharHook(GLFWwindow* window, unsigned int code_point) = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_KEYBOARD_HOOK_HANDLER_H_
| engine/shell/platform/glfw/keyboard_hook_handler.h/0 | {
"file_path": "engine/shell/platform/glfw/keyboard_hook_handler.h",
"repo_id": "engine",
"token_count": 423
} | 502 |
// 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/embedder/test_utils/proc_table_replacement.h"
#include "flutter/shell/platform/linux/fl_accessible_text_field.h"
#include "flutter/shell/platform/linux/fl_engine_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h"
#include "flutter/shell/platform/linux/testing/fl_test.h"
#include "flutter/shell/platform/linux/testing/mock_signal_handler.h"
// MOCK_ENGINE_PROC is leaky by design
// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape)
static FlValue* decode_semantic_data(const uint8_t* data, size_t data_length) {
g_autoptr(GBytes) bytes = g_bytes_new(data, data_length);
g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new();
return fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), bytes,
nullptr);
}
// Tests that semantic node value updates from Flutter emit AtkText::text-insert
// and AtkText::text-remove signals as expected.
TEST(FlAccessibleTextFieldTest, SetValue) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
// "" -> "Flutter"
{
flutter::testing::MockSignalHandler2<int, int> text_inserted(node,
"text-insert");
flutter::testing::MockSignalHandler text_removed(node, "text-remove");
EXPECT_SIGNAL2(text_inserted, ::testing::Eq(0), ::testing::Eq(7));
EXPECT_SIGNAL(text_removed).Times(0);
fl_accessible_node_set_value(node, "Flutter");
}
// "Flutter" -> "Flutter"
{
flutter::testing::MockSignalHandler text_inserted(node, "text-insert");
flutter::testing::MockSignalHandler text_removed(node, "text-remove");
EXPECT_SIGNAL(text_inserted).Times(0);
EXPECT_SIGNAL(text_removed).Times(0);
fl_accessible_node_set_value(node, "Flutter");
}
// "Flutter" -> "engine"
{
flutter::testing::MockSignalHandler2<int, int> text_inserted(node,
"text-insert");
flutter::testing::MockSignalHandler2<int, int> text_removed(node,
"text-remove");
EXPECT_SIGNAL2(text_inserted, ::testing::Eq(0), ::testing::Eq(6));
EXPECT_SIGNAL2(text_removed, ::testing::Eq(0), ::testing::Eq(7));
fl_accessible_node_set_value(node, "engine");
}
// "engine" -> ""
{
flutter::testing::MockSignalHandler text_inserted(node, "text-insert");
flutter::testing::MockSignalHandler2<int, int> text_removed(node,
"text-remove");
EXPECT_SIGNAL(text_inserted).Times(0);
EXPECT_SIGNAL2(text_removed, ::testing::Eq(0), ::testing::Eq(6));
fl_accessible_node_set_value(node, "");
}
}
// Tests that semantic node selection updates from Flutter emit
// AtkText::text-selection-changed and AtkText::text-caret-moved signals as
// expected.
TEST(FlAccessibleTextFieldTest, SetTextSelection) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
// [-1,-1] -> [2,3]
{
flutter::testing::MockSignalHandler text_selection_changed(
node, "text-selection-changed");
flutter::testing::MockSignalHandler1<int> text_caret_moved(
node, "text-caret-moved");
EXPECT_SIGNAL(text_selection_changed);
EXPECT_SIGNAL1(text_caret_moved, ::testing::Eq(3));
fl_accessible_node_set_text_selection(node, 2, 3);
}
// [2,3] -> [3,3]
{
flutter::testing::MockSignalHandler text_selection_changed(
node, "text-selection-changed");
flutter::testing::MockSignalHandler text_caret_moved(node,
"text-caret-moved");
EXPECT_SIGNAL(text_selection_changed);
EXPECT_SIGNAL(text_caret_moved).Times(0);
fl_accessible_node_set_text_selection(node, 3, 3);
}
// [3,3] -> [3,3]
{
flutter::testing::MockSignalHandler text_selection_changed(
node, "text-selection-changed");
flutter::testing::MockSignalHandler text_caret_moved(node,
"text-caret-moved");
EXPECT_SIGNAL(text_selection_changed).Times(0);
EXPECT_SIGNAL(text_caret_moved).Times(0);
fl_accessible_node_set_text_selection(node, 3, 3);
}
// [3,3] -> [4,4]
{
flutter::testing::MockSignalHandler text_selection_changed(
node, "text-selection-changed");
flutter::testing::MockSignalHandler1<int> text_caret_moved(
node, "text-caret-moved");
EXPECT_SIGNAL(text_selection_changed).Times(0);
EXPECT_SIGNAL1(text_caret_moved, ::testing::Eq(4));
fl_accessible_node_set_text_selection(node, 4, 4);
}
}
// Tests that fl_accessible_text_field_perform_action() passes the required
// "expandSelection" argument for semantic cursor move actions.
TEST(FlAccessibleTextFieldTest, PerformAction) {
g_autoptr(GPtrArray) action_datas = g_ptr_array_new_with_free_func(
reinterpret_cast<GDestroyNotify>(fl_value_unref));
g_autoptr(FlEngine) engine = make_mock_engine();
fl_engine_get_embedder_api(engine)->DispatchSemanticsAction =
MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&action_datas](auto engine, uint64_t id,
FlutterSemanticsAction action, const uint8_t* data,
size_t data_length) {
g_ptr_array_add(action_datas,
decode_semantic_data(data, data_length));
return kSuccess;
}));
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
fl_accessible_node_set_actions(
node, static_cast<FlutterSemanticsAction>(
kFlutterSemanticsActionMoveCursorForwardByCharacter |
kFlutterSemanticsActionMoveCursorBackwardByCharacter |
kFlutterSemanticsActionMoveCursorForwardByWord |
kFlutterSemanticsActionMoveCursorBackwardByWord));
g_autoptr(FlValue) expand_selection = fl_value_new_bool(false);
for (int i = 0; i < 4; ++i) {
atk_action_do_action(ATK_ACTION(node), i);
FlValue* data = static_cast<FlValue*>(g_ptr_array_index(action_datas, i));
EXPECT_NE(data, nullptr);
EXPECT_TRUE(fl_value_equal(data, expand_selection));
}
}
// Tests AtkText::get_character_count.
TEST(FlAccessibleTextFieldTest, GetCharacterCount) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
EXPECT_EQ(atk_text_get_character_count(ATK_TEXT(node)), 0);
fl_accessible_node_set_value(node, "Flutter!");
EXPECT_EQ(atk_text_get_character_count(ATK_TEXT(node)), 8);
}
// Tests AtkText::get_text.
TEST(FlAccessibleTextFieldTest, GetText) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
g_autofree gchar* empty = atk_text_get_text(ATK_TEXT(node), 0, -1);
EXPECT_STREQ(empty, "");
flutter::testing::MockSignalHandler text_inserted(node, "text-insert");
EXPECT_SIGNAL(text_inserted).Times(1);
fl_accessible_node_set_value(node, "Flutter!");
g_autofree gchar* flutter = atk_text_get_text(ATK_TEXT(node), 0, -1);
EXPECT_STREQ(flutter, "Flutter!");
g_autofree gchar* tt = atk_text_get_text(ATK_TEXT(node), 3, 5);
EXPECT_STREQ(tt, "tt");
}
// Tests AtkText::get_caret_offset.
TEST(FlAccessibleTextFieldTest, GetCaretOffset) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
EXPECT_EQ(atk_text_get_caret_offset(ATK_TEXT(node)), -1);
fl_accessible_node_set_text_selection(node, 1, 2);
EXPECT_EQ(atk_text_get_caret_offset(ATK_TEXT(node)), 2);
}
// Tests AtkText::set_caret_offset.
TEST(FlAccessibleTextFieldTest, SetCaretOffset) {
int base = -1;
int extent = -1;
g_autoptr(FlEngine) engine = make_mock_engine();
fl_engine_get_embedder_api(engine)->DispatchSemanticsAction =
MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&base, &extent](auto engine, uint64_t id,
FlutterSemanticsAction action, const uint8_t* data,
size_t data_length) {
EXPECT_EQ(action, kFlutterSemanticsActionSetSelection);
g_autoptr(FlValue) value = decode_semantic_data(data, data_length);
EXPECT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
base = fl_value_get_int(fl_value_lookup_string(value, "base"));
extent = fl_value_get_int(fl_value_lookup_string(value, "extent"));
return kSuccess;
}));
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
EXPECT_TRUE(atk_text_set_caret_offset(ATK_TEXT(node), 3));
EXPECT_EQ(base, 3);
EXPECT_EQ(extent, 3);
}
// Tests AtkText::get_n_selections.
TEST(FlAccessibleTextFieldTest, GetNSelections) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
EXPECT_EQ(atk_text_get_n_selections(ATK_TEXT(node)), 0);
fl_accessible_node_set_text_selection(node, 1, 2);
EXPECT_EQ(atk_text_get_n_selections(ATK_TEXT(node)), 1);
}
// Tests AtkText::get_selection.
TEST(FlAccessibleTextFieldTest, GetSelection) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
EXPECT_EQ(atk_text_get_selection(ATK_TEXT(node), 0, nullptr, nullptr),
nullptr);
fl_accessible_node_set_value(node, "Flutter");
fl_accessible_node_set_text_selection(node, 2, 5);
gint start, end;
g_autofree gchar* selection =
atk_text_get_selection(ATK_TEXT(node), 0, &start, &end);
EXPECT_STREQ(selection, "utt");
EXPECT_EQ(start, 2);
EXPECT_EQ(end, 5);
// reverse
fl_accessible_node_set_text_selection(node, 5, 2);
g_autofree gchar* reverse =
atk_text_get_selection(ATK_TEXT(node), 0, &start, &end);
EXPECT_STREQ(reverse, "utt");
EXPECT_EQ(start, 2);
EXPECT_EQ(end, 5);
// empty
fl_accessible_node_set_text_selection(node, 5, 5);
EXPECT_EQ(atk_text_get_selection(ATK_TEXT(node), 0, &start, &end), nullptr);
// selection num != 0
EXPECT_EQ(atk_text_get_selection(ATK_TEXT(node), 1, &start, &end), nullptr);
}
// Tests AtkText::add_selection.
TEST(FlAccessibleTextFieldTest, AddSelection) {
int base = -1;
int extent = -1;
g_autoptr(FlEngine) engine = make_mock_engine();
fl_engine_get_embedder_api(engine)->DispatchSemanticsAction =
MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&base, &extent](auto engine, uint64_t id,
FlutterSemanticsAction action, const uint8_t* data,
size_t data_length) {
EXPECT_EQ(action, kFlutterSemanticsActionSetSelection);
g_autoptr(FlValue) value = decode_semantic_data(data, data_length);
EXPECT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
base = fl_value_get_int(fl_value_lookup_string(value, "base"));
extent = fl_value_get_int(fl_value_lookup_string(value, "extent"));
return kSuccess;
}));
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
EXPECT_TRUE(atk_text_add_selection(ATK_TEXT(node), 2, 4));
EXPECT_EQ(base, 2);
EXPECT_EQ(extent, 4);
fl_accessible_node_set_text_selection(node, 2, 4);
// already has selection
EXPECT_FALSE(atk_text_add_selection(ATK_TEXT(node), 6, 7));
EXPECT_EQ(base, 2);
EXPECT_EQ(extent, 4);
}
// Tests AtkText::remove_selection.
TEST(FlAccessibleTextFieldTest, RemoveSelection) {
int base = -1;
int extent = -1;
g_autoptr(FlEngine) engine = make_mock_engine();
fl_engine_get_embedder_api(engine)->DispatchSemanticsAction =
MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&base, &extent](auto engine, uint64_t id,
FlutterSemanticsAction action, const uint8_t* data,
size_t data_length) {
EXPECT_EQ(action, kFlutterSemanticsActionSetSelection);
g_autoptr(FlValue) value = decode_semantic_data(data, data_length);
EXPECT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
base = fl_value_get_int(fl_value_lookup_string(value, "base"));
extent = fl_value_get_int(fl_value_lookup_string(value, "extent"));
return kSuccess;
}));
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
// no selection
EXPECT_FALSE(atk_text_remove_selection(ATK_TEXT(node), 0));
EXPECT_EQ(base, -1);
EXPECT_EQ(extent, -1);
fl_accessible_node_set_text_selection(node, 2, 4);
// selection num != 0
EXPECT_FALSE(atk_text_remove_selection(ATK_TEXT(node), 1));
EXPECT_EQ(base, -1);
EXPECT_EQ(extent, -1);
// ok, collapses selection
EXPECT_TRUE(atk_text_remove_selection(ATK_TEXT(node), 0));
EXPECT_EQ(base, 4);
EXPECT_EQ(extent, 4);
}
// Tests AtkText::set_selection.
TEST(FlAccessibleTextFieldTest, SetSelection) {
int base = -1;
int extent = -1;
g_autoptr(FlEngine) engine = make_mock_engine();
fl_engine_get_embedder_api(engine)->DispatchSemanticsAction =
MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&base, &extent](auto engine, uint64_t id,
FlutterSemanticsAction action, const uint8_t* data,
size_t data_length) {
EXPECT_EQ(action, kFlutterSemanticsActionSetSelection);
g_autoptr(FlValue) value = decode_semantic_data(data, data_length);
EXPECT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
base = fl_value_get_int(fl_value_lookup_string(value, "base"));
extent = fl_value_get_int(fl_value_lookup_string(value, "extent"));
return kSuccess;
}));
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
// selection num != 0
EXPECT_FALSE(atk_text_set_selection(ATK_TEXT(node), 1, 2, 4));
EXPECT_EQ(base, -1);
EXPECT_EQ(extent, -1);
EXPECT_TRUE(atk_text_set_selection(ATK_TEXT(node), 0, 2, 4));
EXPECT_EQ(base, 2);
EXPECT_EQ(extent, 4);
EXPECT_TRUE(atk_text_set_selection(ATK_TEXT(node), 0, 5, 1));
EXPECT_EQ(base, 5);
EXPECT_EQ(extent, 1);
}
// Tests AtkEditableText::set_text_contents.
TEST(FlAccessibleTextFieldTest, SetTextContents) {
g_autofree gchar* text = nullptr;
g_autoptr(FlEngine) engine = make_mock_engine();
fl_engine_get_embedder_api(engine)->DispatchSemanticsAction =
MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&text](auto engine, uint64_t id, FlutterSemanticsAction action,
const uint8_t* data, size_t data_length) {
EXPECT_EQ(action, kFlutterSemanticsActionSetText);
g_autoptr(FlValue) value = decode_semantic_data(data, data_length);
EXPECT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING);
text = g_strdup(fl_value_get_string(value));
return kSuccess;
}));
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
atk_editable_text_set_text_contents(ATK_EDITABLE_TEXT(node), "Flutter");
EXPECT_STREQ(text, "Flutter");
}
// Tests AtkEditableText::insert/delete_text.
TEST(FlAccessibleTextFieldTest, InsertDeleteText) {
g_autofree gchar* text = nullptr;
int base = -1;
int extent = -1;
g_autoptr(FlEngine) engine = make_mock_engine();
fl_engine_get_embedder_api(engine)->DispatchSemanticsAction =
MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&text, &base, &extent](auto engine, uint64_t id,
FlutterSemanticsAction action,
const uint8_t* data, size_t data_length) {
EXPECT_THAT(action,
::testing::AnyOf(kFlutterSemanticsActionSetText,
kFlutterSemanticsActionSetSelection));
if (action == kFlutterSemanticsActionSetText) {
g_autoptr(FlValue) value =
decode_semantic_data(data, data_length);
EXPECT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING);
g_free(text);
text = g_strdup(fl_value_get_string(value));
} else {
g_autoptr(FlValue) value =
decode_semantic_data(data, data_length);
EXPECT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
base = fl_value_get_int(fl_value_lookup_string(value, "base"));
extent =
fl_value_get_int(fl_value_lookup_string(value, "extent"));
}
return kSuccess;
}));
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
fl_accessible_node_set_value(node, "Fler");
gint pos = 2;
atk_editable_text_insert_text(ATK_EDITABLE_TEXT(node), "utt", 3, &pos);
EXPECT_EQ(pos, 5);
EXPECT_STREQ(text, "Flutter");
EXPECT_EQ(base, pos);
EXPECT_EQ(extent, pos);
atk_editable_text_delete_text(ATK_EDITABLE_TEXT(node), 2, 5);
EXPECT_STREQ(text, "Fler");
EXPECT_EQ(base, 2);
EXPECT_EQ(extent, 2);
}
// Tests AtkEditableText::copy/cut/paste_text.
TEST(FlAccessibleTextFieldTest, CopyCutPasteText) {
int base = -1;
int extent = -1;
FlutterSemanticsAction act = kFlutterSemanticsActionCustomAction;
g_autoptr(FlEngine) engine = make_mock_engine();
fl_engine_get_embedder_api(engine)->DispatchSemanticsAction =
MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&act, &base, &extent](auto engine, uint64_t id,
FlutterSemanticsAction action,
const uint8_t* data, size_t data_length) {
EXPECT_THAT(action,
::testing::AnyOf(kFlutterSemanticsActionCut,
kFlutterSemanticsActionCopy,
kFlutterSemanticsActionPaste,
kFlutterSemanticsActionSetSelection));
act = action;
if (action == kFlutterSemanticsActionSetSelection) {
g_autoptr(FlValue) value =
decode_semantic_data(data, data_length);
EXPECT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
base = fl_value_get_int(fl_value_lookup_string(value, "base"));
extent =
fl_value_get_int(fl_value_lookup_string(value, "extent"));
}
return kSuccess;
}));
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
atk_editable_text_copy_text(ATK_EDITABLE_TEXT(node), 2, 5);
EXPECT_EQ(base, 2);
EXPECT_EQ(extent, 5);
EXPECT_EQ(act, kFlutterSemanticsActionCopy);
atk_editable_text_cut_text(ATK_EDITABLE_TEXT(node), 1, 4);
EXPECT_EQ(base, 1);
EXPECT_EQ(extent, 4);
EXPECT_EQ(act, kFlutterSemanticsActionCut);
atk_editable_text_paste_text(ATK_EDITABLE_TEXT(node), 3);
EXPECT_EQ(base, 3);
EXPECT_EQ(extent, 3);
EXPECT_EQ(act, kFlutterSemanticsActionPaste);
}
TEST(FlAccessibleTextFieldTest, TextBoundary) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_text_field_new(engine, 1);
fl_accessible_node_set_value(node,
"Lorem ipsum.\nDolor sit amet. Praesent commodo?"
"\n\nPraesent et felis dui.");
// |Lorem
gint start_offset = -1, end_offset = -1;
g_autofree gchar* lorem_char = atk_text_get_string_at_offset(
ATK_TEXT(node), 0, ATK_TEXT_GRANULARITY_CHAR, &start_offset, &end_offset);
EXPECT_STREQ(lorem_char, "L");
EXPECT_EQ(start_offset, 0);
EXPECT_EQ(end_offset, 1);
g_autofree gchar* lorem_word = atk_text_get_string_at_offset(
ATK_TEXT(node), 0, ATK_TEXT_GRANULARITY_WORD, &start_offset, &end_offset);
EXPECT_STREQ(lorem_word, "Lorem");
EXPECT_EQ(start_offset, 0);
EXPECT_EQ(end_offset, 5);
g_autofree gchar* lorem_sentence = atk_text_get_string_at_offset(
ATK_TEXT(node), 0, ATK_TEXT_GRANULARITY_SENTENCE, &start_offset,
&end_offset);
EXPECT_STREQ(lorem_sentence, "Lorem ipsum.");
EXPECT_EQ(start_offset, 0);
EXPECT_EQ(end_offset, 12);
g_autofree gchar* lorem_line = atk_text_get_string_at_offset(
ATK_TEXT(node), 0, ATK_TEXT_GRANULARITY_LINE, &start_offset, &end_offset);
EXPECT_STREQ(lorem_line, "Lorem ipsum.");
EXPECT_EQ(start_offset, 0);
EXPECT_EQ(end_offset, 12);
g_autofree gchar* lorem_paragraph = atk_text_get_string_at_offset(
ATK_TEXT(node), 0, ATK_TEXT_GRANULARITY_PARAGRAPH, &start_offset,
&end_offset);
EXPECT_STREQ(lorem_paragraph,
"Lorem ipsum.\nDolor sit amet. Praesent commodo?");
EXPECT_EQ(start_offset, 0);
EXPECT_EQ(end_offset, 46);
// Pra|esent
g_autofree gchar* praesent_char = atk_text_get_string_at_offset(
ATK_TEXT(node), 32, ATK_TEXT_GRANULARITY_CHAR, &start_offset,
&end_offset);
EXPECT_STREQ(praesent_char, "e");
EXPECT_EQ(start_offset, 32);
EXPECT_EQ(end_offset, 33);
g_autofree gchar* praesent_word = atk_text_get_string_at_offset(
ATK_TEXT(node), 32, ATK_TEXT_GRANULARITY_WORD, &start_offset,
&end_offset);
EXPECT_STREQ(praesent_word, "Praesent");
EXPECT_EQ(start_offset, 29);
EXPECT_EQ(end_offset, 37);
g_autofree gchar* praesent_sentence = atk_text_get_string_at_offset(
ATK_TEXT(node), 32, ATK_TEXT_GRANULARITY_SENTENCE, &start_offset,
&end_offset);
EXPECT_STREQ(praesent_sentence, "Praesent commodo?");
EXPECT_EQ(start_offset, 29);
EXPECT_EQ(end_offset, 46);
g_autofree gchar* praesent_line = atk_text_get_string_at_offset(
ATK_TEXT(node), 32, ATK_TEXT_GRANULARITY_LINE, &start_offset,
&end_offset);
EXPECT_STREQ(praesent_line, "Dolor sit amet. Praesent commodo?");
EXPECT_EQ(start_offset, 13);
EXPECT_EQ(end_offset, 46);
g_autofree gchar* praesent_paragraph = atk_text_get_string_at_offset(
ATK_TEXT(node), 32, ATK_TEXT_GRANULARITY_PARAGRAPH, &start_offset,
&end_offset);
EXPECT_STREQ(praesent_paragraph,
"Lorem ipsum.\nDolor sit amet. Praesent commodo?");
EXPECT_EQ(start_offset, 0);
EXPECT_EQ(end_offset, 46);
// feli|s
g_autofree gchar* felis_char = atk_text_get_string_at_offset(
ATK_TEXT(node), 64, ATK_TEXT_GRANULARITY_CHAR, &start_offset,
&end_offset);
EXPECT_STREQ(felis_char, "s");
EXPECT_EQ(start_offset, 64);
EXPECT_EQ(end_offset, 65);
g_autofree gchar* felis_word = atk_text_get_string_at_offset(
ATK_TEXT(node), 64, ATK_TEXT_GRANULARITY_WORD, &start_offset,
&end_offset);
EXPECT_STREQ(felis_word, "felis");
EXPECT_EQ(start_offset, 60);
EXPECT_EQ(end_offset, 65);
g_autofree gchar* felis_sentence = atk_text_get_string_at_offset(
ATK_TEXT(node), 64, ATK_TEXT_GRANULARITY_SENTENCE, &start_offset,
&end_offset);
EXPECT_STREQ(felis_sentence, "Praesent et felis dui.");
EXPECT_EQ(start_offset, 48);
EXPECT_EQ(end_offset, 70);
g_autofree gchar* felis_line = atk_text_get_string_at_offset(
ATK_TEXT(node), 64, ATK_TEXT_GRANULARITY_LINE, &start_offset,
&end_offset);
EXPECT_STREQ(felis_line, "Praesent et felis dui.");
EXPECT_EQ(start_offset, 48);
EXPECT_EQ(end_offset, 70);
g_autofree gchar* felis_paragraph = atk_text_get_string_at_offset(
ATK_TEXT(node), 64, ATK_TEXT_GRANULARITY_PARAGRAPH, &start_offset,
&end_offset);
EXPECT_STREQ(felis_paragraph, "\nPraesent et felis dui.");
EXPECT_EQ(start_offset, 47);
EXPECT_EQ(end_offset, 70);
}
// NOLINTEND(clang-analyzer-core.StackAddressEscape)
| engine/shell/platform/linux/fl_accessible_text_field_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_accessible_text_field_test.cc",
"repo_id": "engine",
"token_count": 10999
} | 503 |
// 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_event_channel.h"
#include <gmodule.h>
#include "flutter/shell/platform/linux/fl_method_codec_private.h"
static constexpr char kListenMethod[] = "listen";
static constexpr char kCancelMethod[] = "cancel";
static constexpr char kEventRequestError[] = "error";
struct _FlEventChannel {
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 the stream is listened to / cancelled.
FlEventChannelHandler listen_handler;
FlEventChannelHandler cancel_handler;
gpointer handler_data;
GDestroyNotify handler_data_destroy_notify;
};
struct _FlEventChannelResponseHandle {
GObject parent_instance;
FlBinaryMessengerResponseHandle* response_handle;
};
G_DEFINE_TYPE(FlEventChannel, fl_event_channel, G_TYPE_OBJECT)
// Handle method calls from the Dart side of the channel.
static FlMethodErrorResponse* handle_method_call(FlEventChannel* self,
const gchar* name,
FlValue* args) {
FlEventChannelHandler handler;
if (g_strcmp0(name, kListenMethod) == 0) {
handler = self->listen_handler;
} else if (g_strcmp0(name, kCancelMethod) == 0) {
handler = self->cancel_handler;
} else {
g_autofree gchar* message =
g_strdup_printf("Unknown event channel request '%s'", name);
return fl_method_error_response_new(kEventRequestError, message, nullptr);
}
// If not handled, just accept requests.
if (handler == nullptr) {
return nullptr;
}
return handler(self, args, self->handler_data);
}
// 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) {
FlEventChannel* self = FL_EVENT_CHANNEL(user_data);
g_autofree gchar* name = nullptr;
g_autoptr(GError) error = nullptr;
g_autoptr(FlValue) args = nullptr;
if (!fl_method_codec_decode_method_call(self->codec, message, &name, &args,
&error)) {
g_warning("Failed to decode message on event channel %s: %s", self->name,
error->message);
fl_binary_messenger_send_response(messenger, response_handle, nullptr,
nullptr);
return;
}
g_autoptr(FlMethodErrorResponse) response =
handle_method_call(self, name, args);
g_autoptr(GBytes) data = nullptr;
if (response == nullptr) {
g_autoptr(GError) codec_error = nullptr;
data = fl_method_codec_encode_success_envelope(self->codec, nullptr,
&codec_error);
if (data == nullptr) {
g_warning("Failed to encode event channel %s success response: %s",
self->name, codec_error->message);
}
} else {
g_autoptr(GError) codec_error = nullptr;
data = fl_method_codec_encode_error_envelope(
self->codec, fl_method_error_response_get_code(response),
fl_method_error_response_get_message(response),
fl_method_error_response_get_details(response), &codec_error);
if (data == nullptr) {
g_warning("Failed to encode event channel %s error response: %s",
self->name, codec_error->message);
}
}
if (!fl_binary_messenger_send_response(messenger, response_handle, data,
&error)) {
g_warning("Failed to send event channel response: %s", error->message);
}
}
// Removes handlers and their associated data.
static void remove_handlers(FlEventChannel* self) {
if (self->handler_data_destroy_notify != nullptr) {
self->handler_data_destroy_notify(self->handler_data);
}
self->listen_handler = nullptr;
self->cancel_handler = nullptr;
self->handler_data = nullptr;
self->handler_data_destroy_notify = nullptr;
}
// Called when the channel handler is closed.
static void channel_closed_cb(gpointer user_data) {
g_autoptr(FlEventChannel) self = FL_EVENT_CHANNEL(user_data);
self->channel_closed = TRUE;
remove_handlers(self);
}
static void fl_event_channel_dispose(GObject* object) {
FlEventChannel* self = FL_EVENT_CHANNEL(object);
if (!self->channel_closed) {
fl_binary_messenger_set_message_handler_on_channel(
self->messenger, self->name, nullptr, nullptr, nullptr);
}
g_clear_object(&self->messenger);
g_clear_pointer(&self->name, g_free);
g_clear_object(&self->codec);
remove_handlers(self);
G_OBJECT_CLASS(fl_event_channel_parent_class)->dispose(object);
}
static void fl_event_channel_class_init(FlEventChannelClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_event_channel_dispose;
}
static void fl_event_channel_init(FlEventChannel* self) {}
G_MODULE_EXPORT FlEventChannel* fl_event_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);
FlEventChannel* self =
FL_EVENT_CHANNEL(g_object_new(fl_event_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_event_channel_set_stream_handlers(
FlEventChannel* self,
FlEventChannelHandler listen_handler,
FlEventChannelHandler cancel_handler,
gpointer user_data,
GDestroyNotify destroy_notify) {
g_return_if_fail(FL_IS_EVENT_CHANNEL(self));
remove_handlers(self);
self->listen_handler = listen_handler;
self->cancel_handler = cancel_handler;
self->handler_data = user_data;
self->handler_data_destroy_notify = destroy_notify;
}
G_MODULE_EXPORT gboolean fl_event_channel_send(FlEventChannel* self,
FlValue* event,
GCancellable* cancellable,
GError** error) {
g_return_val_if_fail(FL_IS_EVENT_CHANNEL(self), FALSE);
g_return_val_if_fail(event != nullptr, FALSE);
g_autoptr(GBytes) data =
fl_method_codec_encode_success_envelope(self->codec, event, error);
if (data == nullptr) {
return FALSE;
}
fl_binary_messenger_send_on_channel(self->messenger, self->name, data,
cancellable, nullptr, nullptr);
return TRUE;
}
G_MODULE_EXPORT gboolean fl_event_channel_send_error(FlEventChannel* self,
const gchar* code,
const gchar* message,
FlValue* details,
GCancellable* cancellable,
GError** error) {
g_return_val_if_fail(FL_IS_EVENT_CHANNEL(self), FALSE);
g_return_val_if_fail(code != nullptr, FALSE);
g_return_val_if_fail(message != nullptr, FALSE);
g_autoptr(GBytes) data = fl_method_codec_encode_error_envelope(
self->codec, code, message, details, error);
if (data == nullptr) {
return FALSE;
}
fl_binary_messenger_send_on_channel(self->messenger, self->name, data,
cancellable, nullptr, nullptr);
return TRUE;
}
G_MODULE_EXPORT gboolean fl_event_channel_send_end_of_stream(
FlEventChannel* self,
GCancellable* cancellable,
GError** error) {
g_return_val_if_fail(FL_IS_EVENT_CHANNEL(self), FALSE);
fl_binary_messenger_send_on_channel(self->messenger, self->name, nullptr,
cancellable, nullptr, nullptr);
return TRUE;
}
| engine/shell/platform/linux/fl_event_channel.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_event_channel.cc",
"repo_id": "engine",
"token_count": 3639
} | 504 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/fl_key_event.h"
FlKeyEvent* fl_key_event_new_from_gdk_event(GdkEvent* event) {
g_return_val_if_fail(event != nullptr, nullptr);
GdkEventType type = gdk_event_get_event_type(event);
g_return_val_if_fail(type == GDK_KEY_PRESS || type == GDK_KEY_RELEASE,
nullptr);
FlKeyEvent* result = g_new(FlKeyEvent, 1);
guint16 keycode = 0;
gdk_event_get_keycode(event, &keycode);
guint keyval = 0;
gdk_event_get_keyval(event, &keyval);
GdkModifierType state = static_cast<GdkModifierType>(0);
gdk_event_get_state(event, &state);
result->time = gdk_event_get_time(event);
result->is_press = type == GDK_KEY_PRESS;
result->keycode = keycode;
result->keyval = keyval;
result->state = state;
result->group = event->key.group;
result->origin = event;
return result;
}
void fl_key_event_dispose(FlKeyEvent* event) {
if (event->origin != nullptr) {
gdk_event_free(event->origin);
}
g_free(event);
}
FlKeyEvent* fl_key_event_clone(const FlKeyEvent* event) {
FlKeyEvent* new_event = g_new(FlKeyEvent, 1);
*new_event = *event;
return new_event;
}
| engine/shell/platform/linux/fl_key_event.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_key_event.cc",
"repo_id": "engine",
"token_count": 508
} | 505 |
// 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_codec.h"
#include "flutter/shell/platform/linux/fl_method_codec_private.h"
#include <gmodule.h>
G_DEFINE_TYPE(FlMethodCodec, fl_method_codec, G_TYPE_OBJECT)
static void fl_method_codec_class_init(FlMethodCodecClass* klass) {}
static void fl_method_codec_init(FlMethodCodec* self) {}
GBytes* fl_method_codec_encode_method_call(FlMethodCodec* self,
const gchar* name,
FlValue* args,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CODEC(self), nullptr);
g_return_val_if_fail(name != nullptr, nullptr);
return FL_METHOD_CODEC_GET_CLASS(self)->encode_method_call(self, name, args,
error);
}
gboolean fl_method_codec_decode_method_call(FlMethodCodec* self,
GBytes* message,
gchar** name,
FlValue** args,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CODEC(self), FALSE);
g_return_val_if_fail(message != nullptr, FALSE);
g_return_val_if_fail(name != nullptr, FALSE);
g_return_val_if_fail(args != nullptr, FALSE);
return FL_METHOD_CODEC_GET_CLASS(self)->decode_method_call(self, message,
name, args, error);
}
GBytes* fl_method_codec_encode_success_envelope(FlMethodCodec* self,
FlValue* result,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CODEC(self), nullptr);
return FL_METHOD_CODEC_GET_CLASS(self)->encode_success_envelope(self, result,
error);
}
GBytes* fl_method_codec_encode_error_envelope(FlMethodCodec* self,
const gchar* code,
const gchar* message,
FlValue* details,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CODEC(self), nullptr);
g_return_val_if_fail(code != nullptr, nullptr);
return FL_METHOD_CODEC_GET_CLASS(self)->encode_error_envelope(
self, code, message, details, error);
}
FlMethodResponse* fl_method_codec_decode_response(FlMethodCodec* self,
GBytes* message,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CODEC(self), nullptr);
g_return_val_if_fail(message != nullptr, nullptr);
if (g_bytes_get_size(message) == 0) {
return FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
return FL_METHOD_CODEC_GET_CLASS(self)->decode_response(self, message, error);
}
| engine/shell/platform/linux/fl_method_codec.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_method_codec.cc",
"repo_id": "engine",
"token_count": 1751
} | 506 |
// 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_registry.h"
#include <gmodule.h>
G_DEFINE_INTERFACE(FlPluginRegistry, fl_plugin_registry, G_TYPE_OBJECT)
void fl_plugin_registry_default_init(FlPluginRegistryInterface* self) {}
G_MODULE_EXPORT FlPluginRegistrar* fl_plugin_registry_get_registrar_for_plugin(
FlPluginRegistry* self,
const gchar* name) {
g_return_val_if_fail(FL_IS_PLUGIN_REGISTRY(self), nullptr);
g_return_val_if_fail(name != nullptr, nullptr);
return FL_PLUGIN_REGISTRY_GET_IFACE(self)->get_registrar_for_plugin(self,
name);
}
| engine/shell/platform/linux/fl_plugin_registry.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_plugin_registry.cc",
"repo_id": "engine",
"token_count": 343
} | 507 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/fl_settings_plugin.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
#include "flutter/shell/platform/linux/fl_engine_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h"
#include "flutter/shell/platform/linux/testing/fl_test.h"
#include "flutter/shell/platform/linux/testing/mock_binary_messenger.h"
#include "flutter/shell/platform/linux/testing/mock_settings.h"
#include "flutter/testing/testing.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
MATCHER_P2(HasSetting, key, value, "") {
g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new();
g_autoptr(FlValue) message =
fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), arg, nullptr);
if (fl_value_equal(fl_value_lookup_string(message, key), value)) {
return true;
}
*result_listener << ::testing::PrintToString(message);
return false;
}
#define EXPECT_SETTING(messenger, key, value) \
EXPECT_CALL( \
messenger, \
fl_binary_messenger_send_on_channel( \
::testing::Eq<FlBinaryMessenger*>(messenger), \
::testing::StrEq("flutter/settings"), HasSetting(key, value), \
::testing::A<GCancellable*>(), ::testing::A<GAsyncReadyCallback>(), \
::testing::A<gpointer>()))
TEST(FlSettingsPluginTest, AlwaysUse24HourFormat) {
::testing::NiceMock<flutter::testing::MockSettings> settings;
::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger;
g_autoptr(FlEngine) engine =
FL_ENGINE(g_object_new(fl_engine_get_type(), "binary-messenger",
FL_BINARY_MESSENGER(messenger), nullptr));
g_autoptr(FlSettingsPlugin) plugin = fl_settings_plugin_new(engine);
g_autoptr(FlValue) use_12h = fl_value_new_bool(false);
g_autoptr(FlValue) use_24h = fl_value_new_bool(true);
EXPECT_CALL(settings, fl_settings_get_clock_format(
::testing::Eq<FlSettings*>(settings)))
.WillOnce(::testing::Return(FL_CLOCK_FORMAT_12H))
.WillOnce(::testing::Return(FL_CLOCK_FORMAT_24H));
EXPECT_SETTING(messenger, "alwaysUse24HourFormat", use_12h);
fl_settings_plugin_start(plugin, settings);
EXPECT_SETTING(messenger, "alwaysUse24HourFormat", use_24h);
fl_settings_emit_changed(settings);
}
TEST(FlSettingsPluginTest, PlatformBrightness) {
::testing::NiceMock<flutter::testing::MockSettings> settings;
::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger;
g_autoptr(FlEngine) engine =
FL_ENGINE(g_object_new(fl_engine_get_type(), "binary-messenger",
FL_BINARY_MESSENGER(messenger), nullptr));
g_autoptr(FlSettingsPlugin) plugin = fl_settings_plugin_new(engine);
g_autoptr(FlValue) light = fl_value_new_string("light");
g_autoptr(FlValue) dark = fl_value_new_string("dark");
EXPECT_CALL(settings, fl_settings_get_color_scheme(
::testing::Eq<FlSettings*>(settings)))
.WillOnce(::testing::Return(FL_COLOR_SCHEME_LIGHT))
.WillOnce(::testing::Return(FL_COLOR_SCHEME_DARK));
EXPECT_SETTING(messenger, "platformBrightness", light);
fl_settings_plugin_start(plugin, settings);
EXPECT_SETTING(messenger, "platformBrightness", dark);
fl_settings_emit_changed(settings);
}
TEST(FlSettingsPluginTest, TextScaleFactor) {
::testing::NiceMock<flutter::testing::MockSettings> settings;
::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger;
g_autoptr(FlEngine) engine =
FL_ENGINE(g_object_new(fl_engine_get_type(), "binary-messenger",
FL_BINARY_MESSENGER(messenger), nullptr));
g_autoptr(FlSettingsPlugin) plugin = fl_settings_plugin_new(engine);
g_autoptr(FlValue) one = fl_value_new_float(1.0);
g_autoptr(FlValue) two = fl_value_new_float(2.0);
EXPECT_CALL(settings, fl_settings_get_text_scaling_factor(
::testing::Eq<FlSettings*>(settings)))
.WillOnce(::testing::Return(1.0))
.WillOnce(::testing::Return(2.0));
EXPECT_SETTING(messenger, "textScaleFactor", one);
fl_settings_plugin_start(plugin, settings);
EXPECT_SETTING(messenger, "textScaleFactor", two);
fl_settings_emit_changed(settings);
}
// MOCK_ENGINE_PROC is leaky by design
// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape)
TEST(FlSettingsPluginTest, AccessibilityFeatures) {
g_autoptr(FlEngine) engine = make_mock_engine();
FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);
std::vector<FlutterAccessibilityFeature> calls;
embedder_api->UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
UpdateAccessibilityFeatures,
([&calls](auto engine, FlutterAccessibilityFeature features) {
calls.push_back(features);
return kSuccess;
}));
g_autoptr(FlSettingsPlugin) plugin = fl_settings_plugin_new(engine);
::testing::NiceMock<flutter::testing::MockSettings> settings;
EXPECT_CALL(settings, fl_settings_get_enable_animations(
::testing::Eq<FlSettings*>(settings)))
.WillOnce(::testing::Return(false))
.WillOnce(::testing::Return(true))
.WillOnce(::testing::Return(false))
.WillOnce(::testing::Return(true));
EXPECT_CALL(settings, fl_settings_get_high_contrast(
::testing::Eq<FlSettings*>(settings)))
.WillOnce(::testing::Return(true))
.WillOnce(::testing::Return(false))
.WillOnce(::testing::Return(false))
.WillOnce(::testing::Return(true));
fl_settings_plugin_start(plugin, settings);
EXPECT_THAT(calls, ::testing::SizeIs(1));
EXPECT_EQ(calls.back(), static_cast<FlutterAccessibilityFeature>(
kFlutterAccessibilityFeatureDisableAnimations |
kFlutterAccessibilityFeatureHighContrast));
fl_settings_emit_changed(settings);
EXPECT_THAT(calls, ::testing::SizeIs(2));
EXPECT_EQ(calls.back(), static_cast<FlutterAccessibilityFeature>(0));
fl_settings_emit_changed(settings);
EXPECT_THAT(calls, ::testing::SizeIs(3));
EXPECT_EQ(calls.back(), static_cast<FlutterAccessibilityFeature>(
kFlutterAccessibilityFeatureDisableAnimations));
fl_settings_emit_changed(settings);
EXPECT_THAT(calls, ::testing::SizeIs(4));
EXPECT_EQ(calls.back(), static_cast<FlutterAccessibilityFeature>(
kFlutterAccessibilityFeatureHighContrast));
}
// NOLINTEND(clang-analyzer-core.StackAddressEscape)
| engine/shell/platform/linux/fl_settings_plugin_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_settings_plugin_test.cc",
"repo_id": "engine",
"token_count": 2973
} | 508 |
// 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_VIEW_DELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXT_INPUT_VIEW_DELEGATE_H_
#include <gdk/gdk.h>
#include "flutter/shell/platform/embedder/embedder.h"
G_BEGIN_DECLS
G_DECLARE_INTERFACE(FlTextInputViewDelegate,
fl_text_input_view_delegate,
FL,
TEXT_INPUT_VIEW_DELEGATE,
GObject);
/**
* FlTextInputViewDelegate:
*
* An interface for a class that provides `FlTextInputPlugin` with
* view-related features.
*
* This interface is typically implemented by `FlView`.
*/
struct _FlTextInputViewDelegateInterface {
GTypeInterface g_iface;
void (*translate_coordinates)(FlTextInputViewDelegate* delegate,
gint view_x,
gint view_y,
gint* window_x,
gint* window_y);
};
void fl_text_input_view_delegate_translate_coordinates(
FlTextInputViewDelegate* delegate,
gint view_x,
gint view_y,
gint* window_x,
gint* window_y);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXT_INPUT_VIEW_DELEGATE_H_
| engine/shell/platform/linux/fl_text_input_view_delegate.h/0 | {
"file_path": "engine/shell/platform/linux/fl_text_input_view_delegate.h",
"repo_id": "engine",
"token_count": 647
} | 509 |
// 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_view.h"
#include "flutter/shell/platform/linux/testing/fl_test_gtk_logs.h"
#include "gtest/gtest.h"
TEST(FlViewTest, StateUpdateDoesNotHappenInInit) {
flutter::testing::fl_ensure_gtk_init();
g_autoptr(FlDartProject) project = fl_dart_project_new();
g_autoptr(FlView) view = fl_view_new(project);
// Check that creating a view doesn't try to query the window state in
// initialization, causing a critical log to be issued.
EXPECT_EQ(
flutter::testing::fl_get_received_gtk_log_levels() & G_LOG_LEVEL_CRITICAL,
(GLogLevelFlags)0x0);
g_object_ref_sink(view);
}
| engine/shell/platform/linux/fl_view_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_view_test.cc",
"repo_id": "engine",
"token_count": 295
} | 510 |
// 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_RESPONSE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_RESPONSE_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_value.h"
G_BEGIN_DECLS
/**
* FlMethodResponseError:
* @FL_METHOD_RESPONSE_ERROR_FAILED: Call failed due to an unspecified error.
* @FL_METHOD_RESPONSE_ERROR_REMOTE_ERROR: An error was returned by the other
* side of the channel.
* @FL_METHOD_RESPONSE_ERROR_NOT_IMPLEMENTED: The requested method is not
* implemented.
*
* Errors set by `fl_method_response_get_result` when the method call response
* is not #FlMethodSuccessResponse.
*/
#define FL_METHOD_RESPONSE_ERROR fl_method_response_error_quark()
typedef enum {
// NOLINTBEGIN(readability-identifier-naming)
FL_METHOD_RESPONSE_ERROR_FAILED,
FL_METHOD_RESPONSE_ERROR_REMOTE_ERROR,
FL_METHOD_RESPONSE_ERROR_NOT_IMPLEMENTED,
// NOLINTEND(readability-identifier-naming)
} FlMethodResponseError;
G_MODULE_EXPORT
GQuark fl_method_response_error_quark(void) G_GNUC_CONST;
G_MODULE_EXPORT
G_DECLARE_DERIVABLE_TYPE(FlMethodResponse,
fl_method_response,
FL,
METHOD_RESPONSE,
GObject)
struct _FlMethodResponseClass {
GObjectClass parent_class;
};
G_MODULE_EXPORT
G_DECLARE_FINAL_TYPE(FlMethodSuccessResponse,
fl_method_success_response,
FL,
METHOD_SUCCESS_RESPONSE,
FlMethodResponse)
G_MODULE_EXPORT
G_DECLARE_FINAL_TYPE(FlMethodErrorResponse,
fl_method_error_response,
FL,
METHOD_ERROR_RESPONSE,
FlMethodResponse)
G_MODULE_EXPORT
G_DECLARE_FINAL_TYPE(FlMethodNotImplementedResponse,
fl_method_not_implemented_response,
FL,
METHOD_NOT_IMPLEMENTED_RESPONSE,
FlMethodResponse)
/**
* FlMethodResponse:
*
* #FlMethodResponse contains the information returned when an #FlMethodChannel
* method call returns. If you expect the method call to be successful use
* fl_method_response_get_result(). If you want to handle error cases then you
* should use code like:
*
* |[<!-- language="C" -->
* if (FL_IS_METHOD_SUCCESS_RESPONSE (response)) {
* FlValue *result =
* fl_method_success_response_get_result(
* FL_METHOD_SUCCESS_RESPONSE (response));
* handle_result (result);
* } else if (FL_IS_METHOD_ERROR_RESPONSE (response)) {
* FlMethodErrorResponse *error_response =
* FL_METHOD_ERROR_RESPONSE (response);
* handle_error (fl_method_error_response_get_code (error_response),
* fl_method_error_response_get_message (error_response),
* fl_method_error_response_get_details (error_response));
* }
* else if (FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE (response)) {
* handle_not_implemented ();
* }
* }
* ]|
*/
/**
* FlMethodSuccessResponse:
*
* #FlMethodSuccessResponse is the #FlMethodResponse returned when a method call
* has successfully completed. The result of the method call is obtained using
* `fl_method_success_response_get_result`.
*/
/**
* FlMethodErrorResponse:
*
* #FlMethodErrorResponse is the #FlMethodResponse returned when a method call
* results in an error. The error details are obtained using
* `fl_method_error_response_get_code`, `fl_method_error_response_get_message`
* and `fl_method_error_response_get_details`.
*/
/**
* FlMethodNotImplementedResponse:
*
* #FlMethodNotImplementedResponse is the #FlMethodResponse returned when a
* method call is not implemented.
*/
/**
* fl_method_response_get_result:
* @response: an #FlMethodResponse.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Gets the result of a method call, or an error if the response wasn't
* successful.
*
* Returns: an #FlValue or %NULL on error.
*/
FlValue* fl_method_response_get_result(FlMethodResponse* response,
GError** error);
/**
* fl_method_success_response_new:
* @result: (allow-none): the #FlValue returned by the method call or %NULL.
*
* Creates a response to a method call when that method has successfully
* completed.
*
* Returns: a new #FlMethodResponse.
*/
FlMethodSuccessResponse* fl_method_success_response_new(FlValue* result);
/**
* fl_method_success_response_get_result:
* @response: an #FlMethodSuccessResponse.
*
* Gets the result of the method call.
*
* Returns: an #FlValue.
*/
FlValue* fl_method_success_response_get_result(
FlMethodSuccessResponse* response);
/**
* fl_method_error_response_new:
* @result: an #FlValue.
* @code: an error code.
* @message: (allow-none): an error message.
* @details: (allow-none): error details.
*
* Creates a response to a method call when that method has returned an error.
*
* Returns: a new #FlMethodErrorResponse.
*/
FlMethodErrorResponse* fl_method_error_response_new(const gchar* code,
const gchar* message,
FlValue* details);
/**
* fl_method_error_response_get_code:
* @response: an #FlMethodErrorResponse.
*
* Gets the error code reported.
*
* Returns: an error code.
*/
const gchar* fl_method_error_response_get_code(FlMethodErrorResponse* response);
/**
* fl_method_error_response_get_message:
* @response: an #FlMethodErrorResponse.
*
* Gets the error message reported.
*
* Returns: an error message or %NULL if no error message provided.
*/
const gchar* fl_method_error_response_get_message(
FlMethodErrorResponse* response);
/**
* fl_method_error_response_get_details:
* @response: an #FlMethodErrorResponse.
*
* Gets the details provided with this error.
*
* Returns: an #FlValue or %NULL if no details provided.
*/
FlValue* fl_method_error_response_get_details(FlMethodErrorResponse* response);
/**
* fl_method_not_implemented_response_new:
*
* Creates a response to a method call when that method does not exist.
*
* Returns: a new #FlMethodNotImplementedResponse.
*/
FlMethodNotImplementedResponse* fl_method_not_implemented_response_new();
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_RESPONSE_H_
| engine/shell/platform/linux/public/flutter_linux/fl_method_response.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_method_response.h",
"repo_id": "engine",
"token_count": 2635
} | 511 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_GTK_LOGS_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_GTK_LOGS_H_
#include <gtk/gtk.h>
namespace flutter {
namespace testing {
/**
* Ensures that GTK has been initialized. If GTK has not been initialized, it
* will be initialized using `gtk_init()`. It will also set the GTK log writer
* function to monitor the log output, recording the log levels that have been
* received in a bitfield accessible via {@link fl_get_received_gtk_log_levels}
*
* To retrieve the bitfield of recorded log levels, use
* `fl_get_received_gtk_log_levels()`.
*
* @param[in] writer The custom log writer function to use. If `nullptr`, or it
* returns G_LOG_WRITER_UNHANDLED, the default log writer function will be
* called.
*
* @brief Ensures that GTK has been initialized and starts monitoring logs.
*/
void fl_ensure_gtk_init(GLogWriterFunc writer = nullptr);
/**
* Resets the recorded GTK log levels to zero.
*
* @brief Resets the recorded log levels.
*/
void fl_reset_received_gtk_log_levels();
/**
* Returns a bitfield containing the GTK log levels that have been seen since
* the last time they were reset.
*
* @brief Returns the recorded log levels.
*
* @return A `GLogLevelFlags` bitfield representing the recorded log levels.
*/
GLogLevelFlags fl_get_received_gtk_log_levels();
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_GTK_LOGS_H_
| engine/shell/platform/linux/testing/fl_test_gtk_logs.h/0 | {
"file_path": "engine/shell/platform/linux/testing/fl_test_gtk_logs.h",
"repo_id": "engine",
"token_count": 541
} | 512 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SETTINGS_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SETTINGS_H_
#include "flutter/shell/platform/linux/fl_settings.h"
#include "gmock/gmock.h"
namespace flutter {
namespace testing {
// Mock for FlSettings.
class MockSettings {
public:
MockSettings();
~MockSettings();
// This was an existing use of operator overloading. It's against our style
// guide but enabling clang tidy on header files is a higher priority than
// fixing this.
// NOLINTNEXTLINE(google-explicit-constructor)
operator FlSettings*();
MOCK_METHOD(FlClockFormat,
fl_settings_get_clock_format,
(FlSettings * settings));
MOCK_METHOD(FlColorScheme,
fl_settings_get_color_scheme,
(FlSettings * settings));
MOCK_METHOD(bool, fl_settings_get_enable_animations, (FlSettings * settings));
MOCK_METHOD(bool, fl_settings_get_high_contrast, (FlSettings * settings));
MOCK_METHOD(gdouble,
fl_settings_get_text_scaling_factor,
(FlSettings * settings));
private:
FlSettings* instance_ = nullptr;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SETTINGS_H_
| engine/shell/platform/linux/testing/mock_settings.h/0 | {
"file_path": "engine/shell/platform/linux/testing/mock_settings.h",
"repo_id": "engine",
"token_count": 527
} | 513 |
# 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/zip_bundle.gni")
import("//flutter/shell/platform/common/client_wrapper/publish.gni")
import("//flutter/testing/testing.gni")
_wrapper_includes = [
"include/flutter/dart_project.h",
"include/flutter/flutter_engine.h",
"include/flutter/flutter_view_controller.h",
"include/flutter/flutter_view.h",
"include/flutter/plugin_registrar_windows.h",
]
_wrapper_sources = [
"flutter_engine.cc",
"flutter_view_controller.cc",
]
# This code will be merged into .../common/client_wrapper for client use,
# so uses header paths that assume the merged state. Include the header
# directories of the core wrapper files so these includes will work.
config("relative_core_wrapper_headers") {
include_dirs = [
"//flutter/shell/platform/common/client_wrapper",
"//flutter/shell/platform/common/client_wrapper/include/flutter",
]
}
# Windows client wrapper build for internal use by the shell implementation.
source_set("client_wrapper_windows") {
sources = _wrapper_sources
public = _wrapper_includes
deps = [
"//flutter/shell/platform/common:common_cpp_library_headers",
"//flutter/shell/platform/common/client_wrapper:client_wrapper",
"//flutter/shell/platform/windows:flutter_windows_headers",
]
configs +=
[ "//flutter/shell/platform/common:desktop_library_implementation" ]
public_configs = [
":relative_core_wrapper_headers",
"//flutter/shell/platform/common:relative_flutter_library_headers",
"//flutter/shell/platform/windows:relative_flutter_windows_headers",
]
}
# Copies the Windows client wrapper code to the output directory.
publish_client_wrapper_extension("publish_wrapper_windows") {
public = _wrapper_includes
sources = _wrapper_sources
}
source_set("client_wrapper_library_stubs_windows") {
sources = [
"testing/stub_flutter_windows_api.cc",
"testing/stub_flutter_windows_api.h",
]
defines = [ "FLUTTER_DESKTOP_LIBRARY" ]
public_deps = [ "//flutter/shell/platform/windows:flutter_windows_headers" ]
}
test_fixtures("client_wrapper_windows_fixtures") {
fixtures = []
}
executable("client_wrapper_windows_unittests") {
testonly = true
sources = [
"dart_project_unittests.cc",
"flutter_engine_unittests.cc",
"flutter_view_controller_unittests.cc",
"flutter_view_unittests.cc",
"plugin_registrar_windows_unittests.cc",
]
# Set embedder.h to export, not import, since the stubs are locally defined.
defines = [ "FLUTTER_DESKTOP_LIBRARY" ]
deps = [
":client_wrapper_library_stubs_windows",
":client_wrapper_windows",
":client_wrapper_windows_fixtures",
"//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs",
"//flutter/testing",
# TODO(chunhtai): Consider refactoring flutter_root/testing so that there's a testing
# target that doesn't require a Dart runtime to be linked in.
# https://github.com/flutter/flutter/issues/41414.
"$dart_src/runtime:libdart_jit",
]
}
client_wrapper_file_archive_list = [
"core_implementations.cc",
"engine_method_result.cc",
"plugin_registrar.cc",
"README",
"standard_codec.cc",
]
win_client_wrapper_file_archive_list = [
"flutter_engine.cc",
"flutter_view_controller.cc",
]
zip_bundle("client_wrapper_archive") {
output = "$full_target_platform_name/flutter-cpp-client-wrapper.zip"
deps = [
":client_wrapper_windows",
":publish_wrapper_windows",
"//flutter/shell/platform/common/client_wrapper:client_wrapper",
]
tmp_files = []
foreach(source_file, client_wrapper_file_archive_list) {
tmp_files += [
{
source = "//flutter/shell/platform/common/client_wrapper/$source_file"
destination = "cpp_client_wrapper/$source_file"
},
]
}
# Windows specific source code files
foreach(source_file, win_client_wrapper_file_archive_list) {
tmp_files += [
{
source = "//flutter/shell/platform/windows/client_wrapper/$source_file"
destination = "cpp_client_wrapper/$source_file"
},
]
}
# Headers
headers = core_cpp_client_wrapper_includes +
core_cpp_client_wrapper_internal_headers
foreach(header, headers) {
rebased_path =
rebase_path(header, "//flutter/shell/platform/common/client_wrapper")
tmp_files += [
{
source = header
destination = "cpp_client_wrapper/$rebased_path"
},
]
}
# Wrapper includes
foreach(header, _wrapper_includes) {
rebased_path =
rebase_path("//flutter/shell/platform/windows/client_wrapper/$header",
"//flutter/shell/platform/windows/client_wrapper")
tmp_files += [
{
source = header
destination = "cpp_client_wrapper/$rebased_path"
},
]
}
files = tmp_files
}
| engine/shell/platform/windows/client_wrapper/BUILD.gn/0 | {
"file_path": "engine/shell/platform/windows/client_wrapper/BUILD.gn",
"repo_id": "engine",
"token_count": 1826
} | 514 |
// 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/compositor_opengl.h"
#include "GLES3/gl3.h"
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
namespace flutter {
namespace {
constexpr uint32_t kWindowFrameBufferId = 0;
// The metadata for an OpenGL framebuffer backing store.
struct FramebufferBackingStore {
uint32_t framebuffer_id;
uint32_t texture_id;
};
// Based off Skia's logic:
// https://github.com/google/skia/blob/4738ed711e03212aceec3cd502a4adb545f38e63/src/gpu/ganesh/gl/GrGLCaps.cpp#L1963-L2116
int GetSupportedTextureFormat(const impeller::DescriptionGLES* description) {
if (description->HasExtension("GL_EXT_texture_format_BGRA8888")) {
return GL_BGRA8_EXT;
} else if (description->HasExtension("GL_APPLE_texture_format_BGRA8888") &&
description->GetGlVersion().IsAtLeast(impeller::Version(3, 0))) {
return GL_BGRA8_EXT;
} else {
return GL_RGBA8;
}
}
} // namespace
CompositorOpenGL::CompositorOpenGL(FlutterWindowsEngine* engine,
impeller::ProcTableGLES::Resolver resolver)
: engine_(engine), resolver_(resolver) {}
bool CompositorOpenGL::CreateBackingStore(
const FlutterBackingStoreConfig& config,
FlutterBackingStore* result) {
if (!is_initialized_ && !Initialize()) {
return false;
}
auto store = std::make_unique<FramebufferBackingStore>();
gl_->GenTextures(1, &store->texture_id);
gl_->GenFramebuffers(1, &store->framebuffer_id);
gl_->BindFramebuffer(GL_FRAMEBUFFER, store->framebuffer_id);
gl_->BindTexture(GL_TEXTURE_2D, store->texture_id);
gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
gl_->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, config.size.width,
config.size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
gl_->BindTexture(GL_TEXTURE_2D, 0);
gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0_EXT,
GL_TEXTURE_2D, store->texture_id, 0);
result->type = kFlutterBackingStoreTypeOpenGL;
result->open_gl.type = kFlutterOpenGLTargetTypeFramebuffer;
result->open_gl.framebuffer.name = store->framebuffer_id;
result->open_gl.framebuffer.target = format_;
result->open_gl.framebuffer.user_data = store.release();
result->open_gl.framebuffer.destruction_callback = [](void* user_data) {
// Backing store destroyed in `CompositorOpenGL::CollectBackingStore`, set
// on FlutterCompositor.collect_backing_store_callback during engine start.
};
return true;
}
bool CompositorOpenGL::CollectBackingStore(const FlutterBackingStore* store) {
FML_DCHECK(is_initialized_);
FML_DCHECK(store->type == kFlutterBackingStoreTypeOpenGL);
FML_DCHECK(store->open_gl.type == kFlutterOpenGLTargetTypeFramebuffer);
auto user_data = static_cast<FramebufferBackingStore*>(
store->open_gl.framebuffer.user_data);
gl_->DeleteFramebuffers(1, &user_data->framebuffer_id);
gl_->DeleteTextures(1, &user_data->texture_id);
delete user_data;
return true;
}
bool CompositorOpenGL::Present(FlutterViewId view_id,
const FlutterLayer** layers,
size_t layers_count) {
FlutterWindowsView* view = engine_->view(view_id);
if (!view) {
return false;
}
// Clear the view if there are no layers to present.
if (layers_count == 0) {
// Normally the compositor is initialized when the first backing store is
// created. However, on an empty frame no backing stores are created and
// the present needs to initialize the compositor.
if (!is_initialized_ && !Initialize()) {
return false;
}
return Clear(view);
}
// TODO: Support compositing layers and platform views.
// See: https://github.com/flutter/flutter/issues/31713
FML_DCHECK(is_initialized_);
FML_DCHECK(layers_count == 1);
FML_DCHECK(layers[0]->offset.x == 0 && layers[0]->offset.y == 0);
FML_DCHECK(layers[0]->type == kFlutterLayerContentTypeBackingStore);
FML_DCHECK(layers[0]->backing_store->type == kFlutterBackingStoreTypeOpenGL);
FML_DCHECK(layers[0]->backing_store->open_gl.type ==
kFlutterOpenGLTargetTypeFramebuffer);
auto width = layers[0]->size.width;
auto height = layers[0]->size.height;
// Check if this frame can be presented. This resizes the surface if a resize
// is pending and |width| and |height| match the target size.
if (!view->OnFrameGenerated(width, height)) {
return false;
}
// |OnFrameGenerated| should return false if the surface isn't valid.
FML_DCHECK(view->surface() != nullptr);
FML_DCHECK(view->surface()->IsValid());
egl::WindowSurface* surface = view->surface();
if (!surface->MakeCurrent()) {
return false;
}
auto source_id = layers[0]->backing_store->open_gl.framebuffer.name;
// Disable the scissor test as it can affect blit operations.
// Prevents regressions like: https://github.com/flutter/flutter/issues/140828
// See OpenGL specification version 4.6, section 18.3.1.
gl_->Disable(GL_SCISSOR_TEST);
gl_->BindFramebuffer(GL_READ_FRAMEBUFFER, source_id);
gl_->BindFramebuffer(GL_DRAW_FRAMEBUFFER, kWindowFrameBufferId);
gl_->BlitFramebuffer(0, // srcX0
0, // srcY0
width, // srcX1
height, // srcY1
0, // dstX0
0, // dstY0
width, // dstX1
height, // dstY1
GL_COLOR_BUFFER_BIT, // mask
GL_NEAREST // filter
);
if (!surface->SwapBuffers()) {
return false;
}
view->OnFramePresented();
return true;
}
bool CompositorOpenGL::Initialize() {
FML_DCHECK(!is_initialized_);
egl::Manager* manager = engine_->egl_manager();
if (!manager) {
return false;
}
if (!manager->render_context()->MakeCurrent()) {
return false;
}
gl_ = std::make_unique<impeller::ProcTableGLES>(resolver_);
if (!gl_->IsValid()) {
gl_.reset();
return false;
}
format_ = GetSupportedTextureFormat(gl_->GetDescription());
is_initialized_ = true;
return true;
}
bool CompositorOpenGL::Clear(FlutterWindowsView* view) {
FML_DCHECK(is_initialized_);
// Check if this frame can be presented. This resizes the surface if needed.
if (!view->OnEmptyFrameGenerated()) {
return false;
}
// |OnEmptyFrameGenerated| should return false if the surface isn't valid.
FML_DCHECK(view->surface() != nullptr);
FML_DCHECK(view->surface()->IsValid());
egl::WindowSurface* surface = view->surface();
if (!surface->MakeCurrent()) {
return false;
}
gl_->ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl_->Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
if (!surface->SwapBuffers()) {
return false;
}
view->OnFramePresented();
return true;
}
} // namespace flutter
| engine/shell/platform/windows/compositor_opengl.cc/0 | {
"file_path": "engine/shell/platform/windows/compositor_opengl.cc",
"repo_id": "engine",
"token_count": 2987
} | 515 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_CONTEXT_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_CONTEXT_H_
#include <EGL/egl.h>
#include "flutter/fml/macros.h"
namespace flutter {
namespace egl {
// An EGL context to interact with OpenGL.
//
// This enables automatic error logging and mocking.
//
// Flutter Windows uses this to create render and resource contexts.
class Context {
public:
Context(EGLDisplay display, EGLContext context);
~Context();
// Check if this context is currently bound to the thread.
virtual bool IsCurrent() const;
// Bind the context to the thread without any read or draw surfaces.
//
// Returns true on success.
virtual bool MakeCurrent() const;
// Unbind any context and surfaces from the thread.
//
// Returns true on success.
virtual bool ClearCurrent() const;
// Get the raw EGL context.
virtual const EGLContext& GetHandle() const;
private:
EGLDisplay display_ = EGL_NO_DISPLAY;
EGLContext context_ = EGL_NO_CONTEXT;
FML_DISALLOW_COPY_AND_ASSIGN(Context);
};
} // namespace egl
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_CONTEXT_H_
| engine/shell/platform/windows/egl/context.h/0 | {
"file_path": "engine/shell/platform/windows/egl/context.h",
"repo_id": "engine",
"token_count": 412
} | 516 |
// 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/external_texture_pixelbuffer.h"
namespace flutter {
ExternalTexturePixelBuffer::ExternalTexturePixelBuffer(
const FlutterDesktopPixelBufferTextureCallback texture_callback,
void* user_data,
std::shared_ptr<egl::ProcTable> gl)
: texture_callback_(texture_callback),
user_data_(user_data),
gl_(std::move(gl)) {}
ExternalTexturePixelBuffer::~ExternalTexturePixelBuffer() {
if (gl_texture_ != 0) {
gl_->DeleteTextures(1, &gl_texture_);
}
}
bool ExternalTexturePixelBuffer::PopulateTexture(
size_t width,
size_t height,
FlutterOpenGLTexture* opengl_texture) {
if (!CopyPixelBuffer(width, height)) {
return false;
}
// Populate the texture object used by the engine.
opengl_texture->target = GL_TEXTURE_2D;
opengl_texture->name = gl_texture_;
opengl_texture->format = GL_RGBA8_OES;
opengl_texture->destruction_callback = nullptr;
opengl_texture->user_data = nullptr;
opengl_texture->width = width;
opengl_texture->height = height;
return true;
}
bool ExternalTexturePixelBuffer::CopyPixelBuffer(size_t& width,
size_t& height) {
const FlutterDesktopPixelBuffer* pixel_buffer =
texture_callback_(width, height, user_data_);
if (!pixel_buffer || !pixel_buffer->buffer) {
return false;
}
width = pixel_buffer->width;
height = pixel_buffer->height;
if (gl_texture_ == 0) {
gl_->GenTextures(1, &gl_texture_);
gl_->BindTexture(GL_TEXTURE_2D, gl_texture_);
gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else {
gl_->BindTexture(GL_TEXTURE_2D, gl_texture_);
}
gl_->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pixel_buffer->width,
pixel_buffer->height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
pixel_buffer->buffer);
if (pixel_buffer->release_callback) {
pixel_buffer->release_callback(pixel_buffer->release_context);
}
return true;
}
} // namespace flutter
| engine/shell/platform/windows/external_texture_pixelbuffer.cc/0 | {
"file_path": "engine/shell/platform/windows/external_texture_pixelbuffer.cc",
"repo_id": "engine",
"token_count": 924
} | 517 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
#include "flutter/fml/logging.h"
#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_windows_view.h"
#include "flutter/shell/platform/windows/public/flutter_windows.h"
#include "flutter/shell/platform/windows/testing/egl/mock_manager.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h"
#include "flutter/shell/platform/windows/testing/mock_platform_view_manager.h"
#include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h"
#include "flutter/shell/platform/windows/testing/mock_windows_proc_table.h"
#include "flutter/shell/platform/windows/testing/test_keyboard.h"
#include "flutter/shell/platform/windows/testing/windows_test.h"
#include "flutter/shell/platform/windows/testing/windows_test_config_builder.h"
#include "flutter/third_party/accessibility/ax/platform/ax_platform_node_win.h"
#include "fml/synchronization/waitable_event.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
// winbase.h defines GetCurrentTime as a macro.
#undef GetCurrentTime
namespace flutter {
namespace testing {
using ::testing::NiceMock;
using ::testing::Return;
class FlutterWindowsEngineTest : public WindowsTest {};
// The engine can be run without any views.
TEST_F(FlutterWindowsEngineTest, RunHeadless) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
ASSERT_TRUE(engine->Run());
ASSERT_EQ(engine->view(kImplicitViewId), nullptr);
ASSERT_EQ(engine->view(123), nullptr);
}
TEST_F(FlutterWindowsEngineTest, RunDoesExpectedInitialization) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.AddDartEntrypointArgument("arg1");
builder.AddDartEntrypointArgument("arg2");
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
// The engine should be run with expected configuration values.
bool run_called = false;
modifier.embedder_api().Run = MOCK_ENGINE_PROC(
Run, ([&run_called, engine_instance = engine.get()](
size_t version, const FlutterRendererConfig* config,
const FlutterProjectArgs* args, void* user_data,
FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) {
run_called = true;
*engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
EXPECT_EQ(version, FLUTTER_ENGINE_VERSION);
EXPECT_NE(config, nullptr);
// We have an EGL manager, so this should be using OpenGL.
EXPECT_EQ(config->type, kOpenGL);
EXPECT_EQ(user_data, engine_instance);
// Spot-check arguments.
EXPECT_NE(args->assets_path, nullptr);
EXPECT_NE(args->icu_data_path, nullptr);
EXPECT_EQ(args->dart_entrypoint_argc, 2U);
EXPECT_EQ(strcmp(args->dart_entrypoint_argv[0], "arg1"), 0);
EXPECT_EQ(strcmp(args->dart_entrypoint_argv[1], "arg2"), 0);
EXPECT_NE(args->platform_message_callback, nullptr);
EXPECT_NE(args->custom_task_runners, nullptr);
EXPECT_NE(args->custom_task_runners->thread_priority_setter, nullptr);
EXPECT_EQ(args->custom_dart_entrypoint, nullptr);
EXPECT_NE(args->vsync_callback, nullptr);
EXPECT_EQ(args->update_semantics_callback, nullptr);
EXPECT_NE(args->update_semantics_callback2, nullptr);
EXPECT_EQ(args->update_semantics_node_callback, nullptr);
EXPECT_EQ(args->update_semantics_custom_action_callback, nullptr);
args->custom_task_runners->thread_priority_setter(
FlutterThreadPriority::kRaster);
EXPECT_EQ(GetThreadPriority(GetCurrentThread()),
THREAD_PRIORITY_ABOVE_NORMAL);
return kSuccess;
}));
// Accessibility updates must do nothing when the embedder engine is mocked
modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
UpdateAccessibilityFeatures,
[](FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterAccessibilityFeature flags) { return kSuccess; });
// It should send locale info.
bool update_locales_called = false;
modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
UpdateLocales,
([&update_locales_called](auto engine, const FlutterLocale** locales,
size_t locales_count) {
update_locales_called = true;
EXPECT_GT(locales_count, 0);
EXPECT_NE(locales, nullptr);
return kSuccess;
}));
// And it should send initial settings info.
bool settings_message_sent = false;
modifier.embedder_api().SendPlatformMessage = MOCK_ENGINE_PROC(
SendPlatformMessage,
([&settings_message_sent](auto engine, auto message) {
if (std::string(message->channel) == std::string("flutter/settings")) {
settings_message_sent = true;
}
return kSuccess;
}));
// And it should send display info.
bool notify_display_update_called = false;
modifier.SetFrameInterval(16600000); // 60 fps.
modifier.embedder_api().NotifyDisplayUpdate = MOCK_ENGINE_PROC(
NotifyDisplayUpdate,
([¬ify_display_update_called, engine_instance = engine.get()](
FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
const FlutterEngineDisplaysUpdateType update_type,
const FlutterEngineDisplay* embedder_displays,
size_t display_count) {
EXPECT_EQ(update_type, kFlutterEngineDisplaysUpdateTypeStartup);
EXPECT_EQ(display_count, 1);
FlutterEngineDisplay display = embedder_displays[0];
EXPECT_EQ(display.display_id, 0);
EXPECT_EQ(display.single_display, true);
EXPECT_EQ(std::floor(display.refresh_rate), 60.0);
notify_display_update_called = true;
return kSuccess;
}));
// Set the EGL manager to !nullptr to test ANGLE rendering.
modifier.SetEGLManager(std::make_unique<egl::MockManager>());
engine->Run();
EXPECT_TRUE(run_called);
EXPECT_TRUE(update_locales_called);
EXPECT_TRUE(settings_message_sent);
EXPECT_TRUE(notify_display_update_called);
// Ensure that deallocation doesn't call the actual Shutdown with the bogus
// engine pointer that the overridden Run returned.
modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
modifier.ReleaseEGLManager();
}
TEST_F(FlutterWindowsEngineTest, ConfiguresFrameVsync) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
bool on_vsync_called = false;
modifier.embedder_api().GetCurrentTime =
MOCK_ENGINE_PROC(GetCurrentTime, ([]() -> uint64_t { return 1; }));
modifier.embedder_api().OnVsync = MOCK_ENGINE_PROC(
OnVsync,
([&on_vsync_called, engine_instance = engine.get()](
FLUTTER_API_SYMBOL(FlutterEngine) engine, intptr_t baton,
uint64_t frame_start_time_nanos, uint64_t frame_target_time_nanos) {
EXPECT_EQ(baton, 1);
EXPECT_EQ(frame_start_time_nanos, 16600000);
EXPECT_EQ(frame_target_time_nanos, 33200000);
on_vsync_called = true;
return kSuccess;
}));
modifier.SetStartTime(0);
modifier.SetFrameInterval(16600000);
engine->OnVsync(1);
EXPECT_TRUE(on_vsync_called);
}
TEST_F(FlutterWindowsEngineTest, RunWithoutANGLEUsesSoftware) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
modifier.embedder_api().NotifyDisplayUpdate =
MOCK_ENGINE_PROC(NotifyDisplayUpdate,
([engine_instance = engine.get()](
FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
const FlutterEngineDisplaysUpdateType update_type,
const FlutterEngineDisplay* embedder_displays,
size_t display_count) { return kSuccess; }));
// The engine should be run with expected configuration values.
bool run_called = false;
modifier.embedder_api().Run = MOCK_ENGINE_PROC(
Run, ([&run_called, engine_instance = engine.get()](
size_t version, const FlutterRendererConfig* config,
const FlutterProjectArgs* args, void* user_data,
FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) {
run_called = true;
*engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
// We don't have an EGL Manager, so we should be using software.
EXPECT_EQ(config->type, kSoftware);
return kSuccess;
}));
// Accessibility updates must do nothing when the embedder engine is mocked
modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
UpdateAccessibilityFeatures,
[](FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterAccessibilityFeature flags) { return kSuccess; });
// Stub out UpdateLocales and SendPlatformMessage as we don't have a fully
// initialized engine instance.
modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
UpdateLocales, ([](auto engine, const FlutterLocale** locales,
size_t locales_count) { return kSuccess; }));
modifier.embedder_api().SendPlatformMessage =
MOCK_ENGINE_PROC(SendPlatformMessage,
([](auto engine, auto message) { return kSuccess; }));
// Set the EGL manager to nullptr to test software fallback path.
modifier.SetEGLManager(nullptr);
engine->Run();
EXPECT_TRUE(run_called);
// Ensure that deallocation doesn't call the actual Shutdown with the bogus
// engine pointer that the overridden Run returned.
modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
}
TEST_F(FlutterWindowsEngineTest, RunWithoutANGLEOnImpellerFailsToStart) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetSwitches({"--enable-impeller=true"});
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
modifier.embedder_api().NotifyDisplayUpdate =
MOCK_ENGINE_PROC(NotifyDisplayUpdate,
([engine_instance = engine.get()](
FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
const FlutterEngineDisplaysUpdateType update_type,
const FlutterEngineDisplay* embedder_displays,
size_t display_count) { return kSuccess; }));
// Accessibility updates must do nothing when the embedder engine is mocked
modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
UpdateAccessibilityFeatures,
[](FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterAccessibilityFeature flags) { return kSuccess; });
// Stub out UpdateLocales and SendPlatformMessage as we don't have a fully
// initialized engine instance.
modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
UpdateLocales, ([](auto engine, const FlutterLocale** locales,
size_t locales_count) { return kSuccess; }));
modifier.embedder_api().SendPlatformMessage =
MOCK_ENGINE_PROC(SendPlatformMessage,
([](auto engine, auto message) { return kSuccess; }));
// Set the EGL manager to nullptr to test software fallback path.
modifier.SetEGLManager(nullptr);
EXPECT_FALSE(engine->Run());
}
TEST_F(FlutterWindowsEngineTest, SendPlatformMessageWithoutResponse) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
const char* channel = "test";
const std::vector<uint8_t> test_message = {1, 2, 3, 4};
// Without a response, SendPlatformMessage should be a simple pass-through.
bool called = false;
modifier.embedder_api().SendPlatformMessage = MOCK_ENGINE_PROC(
SendPlatformMessage, ([&called, test_message](auto engine, auto message) {
called = true;
EXPECT_STREQ(message->channel, "test");
EXPECT_EQ(message->message_size, test_message.size());
EXPECT_EQ(memcmp(message->message, test_message.data(),
message->message_size),
0);
EXPECT_EQ(message->response_handle, nullptr);
return kSuccess;
}));
engine->SendPlatformMessage(channel, test_message.data(), test_message.size(),
nullptr, nullptr);
EXPECT_TRUE(called);
}
TEST_F(FlutterWindowsEngineTest, PlatformMessageRoundTrip) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("hiPlatformChannels");
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto binary_messenger =
std::make_unique<BinaryMessengerImpl>(engine->messenger());
engine->Run();
bool did_call_callback = false;
bool did_call_reply = false;
bool did_call_dart_reply = false;
std::string channel = "hi";
binary_messenger->SetMessageHandler(
channel,
[&did_call_callback, &did_call_dart_reply](
const uint8_t* message, size_t message_size, BinaryReply reply) {
if (message_size == 5) {
EXPECT_EQ(message[0], static_cast<uint8_t>('h'));
char response[] = {'b', 'y', 'e'};
reply(reinterpret_cast<uint8_t*>(response), 3);
did_call_callback = true;
} else {
EXPECT_EQ(message_size, 3);
EXPECT_EQ(message[0], static_cast<uint8_t>('b'));
did_call_dart_reply = true;
}
});
char payload[] = {'h', 'e', 'l', 'l', 'o'};
binary_messenger->Send(
channel, reinterpret_cast<uint8_t*>(payload), 5,
[&did_call_reply](const uint8_t* reply, size_t reply_size) {
EXPECT_EQ(reply_size, 5);
EXPECT_EQ(reply[0], static_cast<uint8_t>('h'));
did_call_reply = true;
});
// Rely on timeout mechanism in CI.
while (!did_call_callback || !did_call_reply || !did_call_dart_reply) {
engine->task_runner()->ProcessTasks();
}
}
TEST_F(FlutterWindowsEngineTest, PlatformMessageRespondOnDifferentThread) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("hiPlatformChannels");
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto binary_messenger =
std::make_unique<BinaryMessengerImpl>(engine->messenger());
engine->Run();
bool did_call_callback = false;
bool did_call_reply = false;
bool did_call_dart_reply = false;
std::string channel = "hi";
std::unique_ptr<std::thread> reply_thread;
binary_messenger->SetMessageHandler(
channel,
[&did_call_callback, &did_call_dart_reply, &reply_thread](
const uint8_t* message, size_t message_size, BinaryReply reply) {
if (message_size == 5) {
EXPECT_EQ(message[0], static_cast<uint8_t>('h'));
reply_thread.reset(new std::thread([reply = std::move(reply)]() {
char response[] = {'b', 'y', 'e'};
reply(reinterpret_cast<uint8_t*>(response), 3);
}));
did_call_callback = true;
} else {
EXPECT_EQ(message_size, 3);
EXPECT_EQ(message[0], static_cast<uint8_t>('b'));
did_call_dart_reply = true;
}
});
char payload[] = {'h', 'e', 'l', 'l', 'o'};
binary_messenger->Send(
channel, reinterpret_cast<uint8_t*>(payload), 5,
[&did_call_reply](const uint8_t* reply, size_t reply_size) {
EXPECT_EQ(reply_size, 5);
EXPECT_EQ(reply[0], static_cast<uint8_t>('h'));
did_call_reply = true;
});
// Rely on timeout mechanism in CI.
while (!did_call_callback || !did_call_reply || !did_call_dart_reply) {
engine->task_runner()->ProcessTasks();
}
ASSERT_TRUE(reply_thread);
reply_thread->join();
}
TEST_F(FlutterWindowsEngineTest, SendPlatformMessageWithResponse) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
const char* channel = "test";
const std::vector<uint8_t> test_message = {1, 2, 3, 4};
auto* dummy_response_handle =
reinterpret_cast<FlutterPlatformMessageResponseHandle*>(5);
const FlutterDesktopBinaryReply reply_handler = [](auto... args) {};
void* reply_user_data = reinterpret_cast<void*>(6);
// When a response is requested, a handle should be created, passed as part
// of the message, and then released.
bool create_response_handle_called = false;
modifier.embedder_api().PlatformMessageCreateResponseHandle =
MOCK_ENGINE_PROC(
PlatformMessageCreateResponseHandle,
([&create_response_handle_called, &reply_handler, reply_user_data,
dummy_response_handle](auto engine, auto reply, auto user_data,
auto response_handle) {
create_response_handle_called = true;
EXPECT_EQ(reply, reply_handler);
EXPECT_EQ(user_data, reply_user_data);
EXPECT_NE(response_handle, nullptr);
*response_handle = dummy_response_handle;
return kSuccess;
}));
bool release_response_handle_called = false;
modifier.embedder_api().PlatformMessageReleaseResponseHandle =
MOCK_ENGINE_PROC(
PlatformMessageReleaseResponseHandle,
([&release_response_handle_called, dummy_response_handle](
auto engine, auto response_handle) {
release_response_handle_called = true;
EXPECT_EQ(response_handle, dummy_response_handle);
return kSuccess;
}));
bool send_message_called = false;
modifier.embedder_api().SendPlatformMessage = MOCK_ENGINE_PROC(
SendPlatformMessage, ([&send_message_called, test_message,
dummy_response_handle](auto engine, auto message) {
send_message_called = true;
EXPECT_STREQ(message->channel, "test");
EXPECT_EQ(message->message_size, test_message.size());
EXPECT_EQ(memcmp(message->message, test_message.data(),
message->message_size),
0);
EXPECT_EQ(message->response_handle, dummy_response_handle);
return kSuccess;
}));
engine->SendPlatformMessage(channel, test_message.data(), test_message.size(),
reply_handler, reply_user_data);
EXPECT_TRUE(create_response_handle_called);
EXPECT_TRUE(release_response_handle_called);
EXPECT_TRUE(send_message_called);
}
TEST_F(FlutterWindowsEngineTest, DispatchSemanticsAction) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
bool called = false;
std::string message = "Hello";
modifier.embedder_api().DispatchSemanticsAction = MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&called, &message](auto engine, auto target, auto action, auto data,
auto data_length) {
called = true;
EXPECT_EQ(target, 42);
EXPECT_EQ(action, kFlutterSemanticsActionDismiss);
EXPECT_EQ(memcmp(data, message.c_str(), message.size()), 0);
EXPECT_EQ(data_length, message.size());
return kSuccess;
}));
auto data = fml::MallocMapping::Copy(message.c_str(), message.size());
engine->DispatchSemanticsAction(42, kFlutterSemanticsActionDismiss,
std::move(data));
EXPECT_TRUE(called);
}
TEST_F(FlutterWindowsEngineTest, SetsThreadPriority) {
WindowsPlatformThreadPrioritySetter(FlutterThreadPriority::kBackground);
EXPECT_EQ(GetThreadPriority(GetCurrentThread()),
THREAD_PRIORITY_BELOW_NORMAL);
WindowsPlatformThreadPrioritySetter(FlutterThreadPriority::kDisplay);
EXPECT_EQ(GetThreadPriority(GetCurrentThread()),
THREAD_PRIORITY_ABOVE_NORMAL);
WindowsPlatformThreadPrioritySetter(FlutterThreadPriority::kRaster);
EXPECT_EQ(GetThreadPriority(GetCurrentThread()),
THREAD_PRIORITY_ABOVE_NORMAL);
// FlutterThreadPriority::kNormal does not change thread priority, reset to 0
// here.
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
WindowsPlatformThreadPrioritySetter(FlutterThreadPriority::kNormal);
EXPECT_EQ(GetThreadPriority(GetCurrentThread()), THREAD_PRIORITY_NORMAL);
}
TEST_F(FlutterWindowsEngineTest, AddPluginRegistrarDestructionCallback) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
MockEmbedderApiForKeyboard(modifier,
std::make_shared<MockKeyResponseController>());
engine->Run();
// Verify that destruction handlers don't overwrite each other.
int result1 = 0;
int result2 = 0;
engine->AddPluginRegistrarDestructionCallback(
[](FlutterDesktopPluginRegistrarRef ref) {
auto result = reinterpret_cast<int*>(ref);
*result = 1;
},
reinterpret_cast<FlutterDesktopPluginRegistrarRef>(&result1));
engine->AddPluginRegistrarDestructionCallback(
[](FlutterDesktopPluginRegistrarRef ref) {
auto result = reinterpret_cast<int*>(ref);
*result = 2;
},
reinterpret_cast<FlutterDesktopPluginRegistrarRef>(&result2));
engine->Stop();
EXPECT_EQ(result1, 1);
EXPECT_EQ(result2, 2);
}
TEST_F(FlutterWindowsEngineTest, ScheduleFrame) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
bool called = false;
modifier.embedder_api().ScheduleFrame =
MOCK_ENGINE_PROC(ScheduleFrame, ([&called](auto engine) {
called = true;
return kSuccess;
}));
engine->ScheduleFrame();
EXPECT_TRUE(called);
}
TEST_F(FlutterWindowsEngineTest, SetNextFrameCallback) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
bool called = false;
modifier.embedder_api().SetNextFrameCallback = MOCK_ENGINE_PROC(
SetNextFrameCallback, ([&called](auto engine, auto callback, auto data) {
called = true;
return kSuccess;
}));
engine->SetNextFrameCallback([]() {});
EXPECT_TRUE(called);
}
TEST_F(FlutterWindowsEngineTest, GetExecutableName) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EXPECT_EQ(engine->GetExecutableName(), "flutter_windows_unittests.exe");
}
// Ensure that after setting or resetting the high contrast feature,
// the corresponding status flag can be retrieved from the engine.
TEST_F(FlutterWindowsEngineTest, UpdateHighContrastFeature) {
auto windows_proc_table = std::make_shared<MockWindowsProcTable>();
EXPECT_CALL(*windows_proc_table, GetHighContrastEnabled)
.WillOnce(Return(true))
.WillOnce(Return(false));
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetWindowsProcTable(windows_proc_table);
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
std::optional<FlutterAccessibilityFeature> engine_flags;
modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
UpdateAccessibilityFeatures, ([&engine_flags](auto engine, auto flags) {
engine_flags = flags;
return kSuccess;
}));
modifier.embedder_api().SendPlatformMessage = MOCK_ENGINE_PROC(
SendPlatformMessage,
[](auto engine, const auto message) { return kSuccess; });
// 1: High contrast is enabled.
engine->UpdateHighContrastMode();
EXPECT_TRUE(engine->high_contrast_enabled());
EXPECT_TRUE(engine_flags.has_value());
EXPECT_TRUE(
engine_flags.value() &
FlutterAccessibilityFeature::kFlutterAccessibilityFeatureHighContrast);
// 2: High contrast is disabled.
engine_flags.reset();
engine->UpdateHighContrastMode();
EXPECT_FALSE(engine->high_contrast_enabled());
EXPECT_TRUE(engine_flags.has_value());
EXPECT_FALSE(
engine_flags.value() &
FlutterAccessibilityFeature::kFlutterAccessibilityFeatureHighContrast);
}
TEST_F(FlutterWindowsEngineTest, PostRasterThreadTask) {
FlutterWindowsEngineBuilder builder{GetContext()};
std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
EngineModifier modifier(engine.get());
modifier.embedder_api().PostRenderThreadTask = MOCK_ENGINE_PROC(
PostRenderThreadTask, ([](auto engine, auto callback, auto context) {
callback(context);
return kSuccess;
}));
bool called = false;
engine->PostRasterThreadTask([&called]() { called = true; });
EXPECT_TRUE(called);
}
class MockFlutterWindowsView : public FlutterWindowsView {
public:
MockFlutterWindowsView(FlutterWindowsEngine* engine,
std::unique_ptr<WindowBindingHandler> wbh)
: FlutterWindowsView(kImplicitViewId, engine, std::move(wbh)) {}
~MockFlutterWindowsView() {}
MOCK_METHOD(void,
NotifyWinEventWrapper,
(ui::AXPlatformNodeWin*, ax::mojom::Event),
(override));
MOCK_METHOD(HWND, GetWindowHandle, (), (const, override));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockFlutterWindowsView);
};
// Verify the view is notified of accessibility announcements.
TEST_F(FlutterWindowsEngineTest, AccessibilityAnnouncement) {
auto& context = GetContext();
WindowsConfigBuilder builder{context};
builder.SetDartEntrypoint("sendAccessibilityAnnouncement");
bool done = false;
auto native_entry =
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { done = true; });
context.AddNativeFunction("Signal", native_entry);
EnginePtr engine{builder.RunHeadless()};
ASSERT_NE(engine, nullptr);
ui::AXPlatformNodeDelegateBase parent_delegate;
AlertPlatformNodeDelegate delegate{parent_delegate};
auto window_binding_handler =
std::make_unique<NiceMock<MockWindowBindingHandler>>();
EXPECT_CALL(*window_binding_handler, GetAlertDelegate)
.WillOnce(Return(&delegate));
auto windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
MockFlutterWindowsView view{windows_engine,
std::move(window_binding_handler)};
EngineModifier modifier{windows_engine};
modifier.SetImplicitView(&view);
windows_engine->UpdateSemanticsEnabled(true);
EXPECT_CALL(view, NotifyWinEventWrapper).Times(1);
// Rely on timeout mechanism in CI.
while (!done) {
windows_engine->task_runner()->ProcessTasks();
}
}
// Verify the app can send accessibility announcements while in headless mode.
TEST_F(FlutterWindowsEngineTest, AccessibilityAnnouncementHeadless) {
auto& context = GetContext();
WindowsConfigBuilder builder{context};
builder.SetDartEntrypoint("sendAccessibilityAnnouncement");
bool done = false;
auto native_entry =
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { done = true; });
context.AddNativeFunction("Signal", native_entry);
EnginePtr engine{builder.RunHeadless()};
ASSERT_NE(engine, nullptr);
auto windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
windows_engine->UpdateSemanticsEnabled(true);
// Rely on timeout mechanism in CI.
while (!done) {
windows_engine->task_runner()->ProcessTasks();
}
}
// Verify the engine does not crash if it receives an accessibility event
// it does not support yet.
TEST_F(FlutterWindowsEngineTest, AccessibilityTooltip) {
fml::testing::LogCapture log_capture;
auto& context = GetContext();
WindowsConfigBuilder builder{context};
builder.SetDartEntrypoint("sendAccessibilityTooltipEvent");
bool done = false;
auto native_entry =
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { done = true; });
context.AddNativeFunction("Signal", native_entry);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
auto engine = FlutterDesktopViewControllerGetEngine(controller.get());
auto windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine);
windows_engine->UpdateSemanticsEnabled(true);
// Rely on timeout mechanism in CI.
while (!done) {
windows_engine->task_runner()->ProcessTasks();
}
// Verify no error was logged.
// Regression test for:
// https://github.com/flutter/flutter/issues/144274
EXPECT_EQ(log_capture.str().find("tooltip"), std::string::npos);
}
class MockWindowsLifecycleManager : public WindowsLifecycleManager {
public:
MockWindowsLifecycleManager(FlutterWindowsEngine* engine)
: WindowsLifecycleManager(engine) {}
virtual ~MockWindowsLifecycleManager() {}
MOCK_METHOD(
void,
Quit,
(std::optional<HWND>, std::optional<WPARAM>, std::optional<LPARAM>, UINT),
(override));
MOCK_METHOD(void, DispatchMessage, (HWND, UINT, WPARAM, LPARAM), (override));
MOCK_METHOD(bool, IsLastWindowOfProcess, (), (override));
MOCK_METHOD(void, SetLifecycleState, (AppLifecycleState), (override));
void BeginProcessingLifecycle() override {
WindowsLifecycleManager::BeginProcessingLifecycle();
if (begin_processing_callback) {
begin_processing_callback();
}
}
std::function<void()> begin_processing_callback = nullptr;
};
TEST_F(FlutterWindowsEngineTest, TestExit) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("exitTestExit");
bool finished = false;
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, SetLifecycleState(AppLifecycleState::kResumed));
EXPECT_CALL(*handler, Quit)
.WillOnce([&finished](std::optional<HWND> hwnd,
std::optional<WPARAM> wparam,
std::optional<LPARAM> lparam,
UINT exit_code) { finished = exit_code == 0; });
EXPECT_CALL(*handler, IsLastWindowOfProcess).WillRepeatedly(Return(true));
modifier.SetLifecycleManager(std::move(handler));
engine->lifecycle_manager()->BeginProcessingExit();
engine->Run();
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
0);
// The test will only succeed when this while loop exits. Otherwise it will
// timeout.
while (!finished) {
engine->task_runner()->ProcessTasks();
}
}
TEST_F(FlutterWindowsEngineTest, TestExitCancel) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("exitTestCancel");
bool did_call = false;
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, SetLifecycleState(AppLifecycleState::kResumed));
EXPECT_CALL(*handler, IsLastWindowOfProcess).WillRepeatedly(Return(true));
EXPECT_CALL(*handler, Quit).Times(0);
modifier.SetLifecycleManager(std::move(handler));
engine->lifecycle_manager()->BeginProcessingExit();
auto binary_messenger =
std::make_unique<BinaryMessengerImpl>(engine->messenger());
binary_messenger->SetMessageHandler(
"flutter/platform", [&did_call](const uint8_t* message,
size_t message_size, BinaryReply reply) {
std::string contents(message, message + message_size);
EXPECT_NE(contents.find("\"method\":\"System.exitApplication\""),
std::string::npos);
EXPECT_NE(contents.find("\"type\":\"required\""), std::string::npos);
EXPECT_NE(contents.find("\"exitCode\":0"), std::string::npos);
did_call = true;
char response[] = "";
reply(reinterpret_cast<uint8_t*>(response), 0);
});
engine->Run();
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
0);
while (!did_call) {
engine->task_runner()->ProcessTasks();
}
}
// Flutter consumes the first WM_CLOSE message to allow the app to cancel the
// exit. If the app does not cancel the exit, Flutter synthesizes a second
// WM_CLOSE message.
TEST_F(FlutterWindowsEngineTest, TestExitSecondCloseMessage) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("exitTestExit");
bool second_close = false;
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, SetLifecycleState(AppLifecycleState::kResumed));
EXPECT_CALL(*handler, IsLastWindowOfProcess).WillOnce(Return(true));
EXPECT_CALL(*handler, Quit)
.WillOnce([handler_ptr = handler.get()](
std::optional<HWND> hwnd, std::optional<WPARAM> wparam,
std::optional<LPARAM> lparam, UINT exit_code) {
handler_ptr->WindowsLifecycleManager::Quit(hwnd, wparam, lparam,
exit_code);
});
EXPECT_CALL(*handler, DispatchMessage)
.WillRepeatedly(
[&engine](HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(
hwnd, msg, wparam, lparam);
});
modifier.SetLifecycleManager(std::move(handler));
engine->lifecycle_manager()->BeginProcessingExit();
engine->Run();
// This delegate will be registered after the lifecycle manager, so it will be
// called only when a message is not consumed by the lifecycle manager. This
// should be called on the second, synthesized WM_CLOSE message that the
// lifecycle manager posts.
engine->window_proc_delegate_manager()->RegisterTopLevelWindowProcDelegate(
[](HWND hwnd, UINT message, WPARAM wpar, LPARAM lpar, void* user_data,
LRESULT* result) {
switch (message) {
case WM_CLOSE: {
bool* called = reinterpret_cast<bool*>(user_data);
*called = true;
return true;
}
}
return false;
},
reinterpret_cast<void*>(&second_close));
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
0);
while (!second_close) {
engine->task_runner()->ProcessTasks();
}
}
TEST_F(FlutterWindowsEngineTest, TestExitCloseMultiWindow) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("exitTestExit");
bool finished = false;
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, SetLifecycleState(AppLifecycleState::kResumed));
EXPECT_CALL(*handler, IsLastWindowOfProcess).WillOnce([&finished]() {
finished = true;
return false;
});
// Quit should not be called when there is more than one window.
EXPECT_CALL(*handler, Quit).Times(0);
modifier.SetLifecycleManager(std::move(handler));
engine->lifecycle_manager()->BeginProcessingExit();
engine->Run();
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
0);
while (!finished) {
engine->task_runner()->ProcessTasks();
}
}
TEST_F(FlutterWindowsEngineTest, LifecycleManagerDisabledByDefault) {
FlutterWindowsEngineBuilder builder{GetContext()};
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, IsLastWindowOfProcess).Times(0);
modifier.SetLifecycleManager(std::move(handler));
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
0);
}
TEST_F(FlutterWindowsEngineTest, EnableApplicationLifecycle) {
FlutterWindowsEngineBuilder builder{GetContext()};
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, IsLastWindowOfProcess).WillOnce(Return(false));
modifier.SetLifecycleManager(std::move(handler));
engine->lifecycle_manager()->BeginProcessingExit();
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
0);
}
TEST_F(FlutterWindowsEngineTest, ApplicationLifecycleExternalWindow) {
FlutterWindowsEngineBuilder builder{GetContext()};
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, IsLastWindowOfProcess).WillOnce(Return(false));
modifier.SetLifecycleManager(std::move(handler));
engine->lifecycle_manager()->BeginProcessingExit();
engine->lifecycle_manager()->ExternalWindowMessage(0, WM_CLOSE, 0, 0);
}
TEST_F(FlutterWindowsEngineTest, AppStartsInResumedState) {
FlutterWindowsEngineBuilder builder{GetContext()};
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, SetLifecycleState(AppLifecycleState::kResumed))
.Times(1);
modifier.SetLifecycleManager(std::move(handler));
engine->Run();
}
TEST_F(FlutterWindowsEngineTest, LifecycleStateTransition) {
FlutterWindowsEngineBuilder builder{GetContext()};
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
engine->Run();
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(
(HWND)1, WM_SIZE, SIZE_RESTORED, 0);
EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
AppLifecycleState::kResumed);
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(
(HWND)1, WM_SIZE, SIZE_MINIMIZED, 0);
EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
AppLifecycleState::kHidden);
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(
(HWND)1, WM_SIZE, SIZE_RESTORED, 0);
EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
AppLifecycleState::kInactive);
}
TEST_F(FlutterWindowsEngineTest, ExternalWindowMessage) {
FlutterWindowsEngineBuilder builder{GetContext()};
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
// Sets lifecycle state to resumed.
engine->Run();
// Ensure HWND(1) is in the set of visible windows before hiding it.
engine->ProcessExternalWindowMessage(reinterpret_cast<HWND>(1), WM_SHOWWINDOW,
TRUE, NULL);
engine->ProcessExternalWindowMessage(reinterpret_cast<HWND>(1), WM_SHOWWINDOW,
FALSE, NULL);
EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
AppLifecycleState::kHidden);
}
TEST_F(FlutterWindowsEngineTest, InnerWindowHidden) {
FlutterWindowsEngineBuilder builder{GetContext()};
HWND outer = reinterpret_cast<HWND>(1);
HWND inner = reinterpret_cast<HWND>(2);
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
ON_CALL(view, GetWindowHandle).WillByDefault([=]() { return inner; });
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
// Sets lifecycle state to resumed.
engine->Run();
// Show both top-level and Flutter window.
engine->window_proc_delegate_manager()->OnTopLevelWindowProc(
outer, WM_SHOWWINDOW, TRUE, NULL);
view.OnWindowStateEvent(inner, WindowStateEvent::kShow);
view.OnWindowStateEvent(inner, WindowStateEvent::kFocus);
EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
AppLifecycleState::kResumed);
// Hide Flutter window, but not top level window.
view.OnWindowStateEvent(inner, WindowStateEvent::kHide);
// The top-level window is still visible, so we ought not enter hidden state.
EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
AppLifecycleState::kInactive);
}
TEST_F(FlutterWindowsEngineTest, EnableLifecycleState) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("enableLifecycleTest");
bool finished = false;
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, SetLifecycleState)
.WillRepeatedly([handler_ptr = handler.get()](AppLifecycleState state) {
handler_ptr->WindowsLifecycleManager::SetLifecycleState(state);
});
modifier.SetLifecycleManager(std::move(handler));
auto binary_messenger =
std::make_unique<BinaryMessengerImpl>(engine->messenger());
// Mark the test only as completed on receiving an inactive state message.
binary_messenger->SetMessageHandler(
"flutter/unittest", [&finished](const uint8_t* message,
size_t message_size, BinaryReply reply) {
std::string contents(message, message + message_size);
EXPECT_NE(contents.find("AppLifecycleState.inactive"),
std::string::npos);
finished = true;
char response[] = "";
reply(reinterpret_cast<uint8_t*>(response), 0);
});
engine->Run();
// Test that setting the state before enabling lifecycle does nothing.
HWND hwnd = reinterpret_cast<HWND>(1);
view.OnWindowStateEvent(hwnd, WindowStateEvent::kShow);
view.OnWindowStateEvent(hwnd, WindowStateEvent::kHide);
EXPECT_FALSE(finished);
// Test that we can set the state afterwards.
engine->lifecycle_manager()->BeginProcessingLifecycle();
view.OnWindowStateEvent(hwnd, WindowStateEvent::kShow);
while (!finished) {
engine->task_runner()->ProcessTasks();
}
}
TEST_F(FlutterWindowsEngineTest, LifecycleStateToFrom) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("enableLifecycleToFrom");
bool enabled_lifecycle = false;
bool dart_responded = false;
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, SetLifecycleState)
.WillRepeatedly([handler_ptr = handler.get()](AppLifecycleState state) {
handler_ptr->WindowsLifecycleManager::SetLifecycleState(state);
});
handler->begin_processing_callback = [&]() { enabled_lifecycle = true; };
modifier.SetLifecycleManager(std::move(handler));
auto binary_messenger =
std::make_unique<BinaryMessengerImpl>(engine->messenger());
binary_messenger->SetMessageHandler(
"flutter/unittest",
[&](const uint8_t* message, size_t message_size, BinaryReply reply) {
std::string contents(message, message + message_size);
EXPECT_NE(contents.find("AppLifecycleState."), std::string::npos);
dart_responded = true;
char response[] = "";
reply(reinterpret_cast<uint8_t*>(response), 0);
});
engine->Run();
while (!enabled_lifecycle) {
engine->task_runner()->ProcessTasks();
}
HWND hwnd = reinterpret_cast<HWND>(1);
view.OnWindowStateEvent(hwnd, WindowStateEvent::kShow);
view.OnWindowStateEvent(hwnd, WindowStateEvent::kHide);
while (!dart_responded) {
engine->task_runner()->ProcessTasks();
}
}
TEST_F(FlutterWindowsEngineTest, ChannelListenedTo) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("enableLifecycleToFrom");
auto engine = builder.Build();
auto window_binding_handler =
std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
EngineModifier modifier(engine.get());
modifier.SetImplicitView(&view);
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
bool lifecycle_began = false;
auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
EXPECT_CALL(*handler, SetLifecycleState).Times(1);
handler->begin_processing_callback = [&]() { lifecycle_began = true; };
modifier.SetLifecycleManager(std::move(handler));
engine->Run();
while (!lifecycle_began) {
engine->task_runner()->ProcessTasks();
}
}
TEST_F(FlutterWindowsEngineTest, ReceivePlatformViewMessage) {
FlutterWindowsEngineBuilder builder{GetContext()};
builder.SetDartEntrypoint("sendCreatePlatformViewMethod");
auto engine = builder.Build();
EngineModifier modifier{engine.get()};
modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
bool received_call = false;
auto manager = std::make_unique<MockPlatformViewManager>(engine.get());
EXPECT_CALL(*manager, AddPlatformView)
.WillOnce([&](PlatformViewId id, std::string_view type_name) {
received_call = true;
return true;
});
modifier.SetPlatformViewPlugin(std::move(manager));
engine->Run();
while (!received_call) {
engine->task_runner()->ProcessTasks();
}
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/flutter_windows_engine_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_windows_engine_unittests.cc",
"repo_id": "engine",
"token_count": 18515
} | 518 |
// 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_embedder_handler.h"
#include <string>
#include <vector>
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
#include "flutter/shell/platform/windows/keyboard_utils.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
constexpr SHORT kStateMaskToggled = 0x01;
constexpr SHORT kStateMaskPressed = 0x80;
class TestFlutterKeyEvent : public FlutterKeyEvent {
public:
TestFlutterKeyEvent(const FlutterKeyEvent& src,
FlutterKeyEventCallback callback,
void* user_data)
: character_str(src.character), callback(callback), user_data(user_data) {
struct_size = src.struct_size;
timestamp = src.timestamp;
type = src.type;
physical = src.physical;
logical = src.logical;
character = character_str.c_str();
synthesized = src.synthesized;
}
TestFlutterKeyEvent(TestFlutterKeyEvent&& source)
: FlutterKeyEvent(source),
callback(std::move(source.callback)),
user_data(source.user_data) {
character = character_str.c_str();
}
FlutterKeyEventCallback callback;
void* user_data;
private:
const std::string character_str;
};
class TestKeystate {
public:
void Set(int virtual_key, bool pressed, bool toggled_on = false) {
state_[virtual_key] = (pressed ? kStateMaskPressed : 0) |
(toggled_on ? kStateMaskToggled : 0);
}
SHORT Get(int virtual_key) { return state_[virtual_key]; }
KeyboardKeyEmbedderHandler::GetKeyStateHandler Getter() {
return [this](int virtual_key) { return Get(virtual_key); };
}
private:
std::map<int, SHORT> state_;
};
UINT DefaultMapVkToScan(UINT virtual_key, bool extended) {
return MapVirtualKey(virtual_key,
extended ? MAPVK_VK_TO_VSC_EX : MAPVK_VK_TO_VSC);
}
constexpr uint64_t kScanCodeKeyA = 0x1e;
constexpr uint64_t kScanCodeAltLeft = 0x38;
constexpr uint64_t kScanCodeNumpad1 = 0x4f;
constexpr uint64_t kScanCodeNumLock = 0x45;
constexpr uint64_t kScanCodeControl = 0x1d;
constexpr uint64_t kScanCodeShiftLeft = 0x2a;
constexpr uint64_t kScanCodeShiftRight = 0x36;
constexpr uint64_t kVirtualKeyA = 0x41;
} // namespace
using namespace ::flutter::testing::keycodes;
TEST(KeyboardKeyEmbedderHandlerTest, ConvertChar32ToUtf8) {
std::string result;
result = ConvertChar32ToUtf8(0x0024);
EXPECT_EQ(result.length(), 1);
EXPECT_EQ(result[0], '\x24');
result = ConvertChar32ToUtf8(0x00A2);
EXPECT_EQ(result.length(), 2);
EXPECT_EQ(result[0], '\xC2');
EXPECT_EQ(result[1], '\xA2');
result = ConvertChar32ToUtf8(0x0939);
EXPECT_EQ(result.length(), 3);
EXPECT_EQ(result[0], '\xE0');
EXPECT_EQ(result[1], '\xA4');
EXPECT_EQ(result[2], '\xB9');
result = ConvertChar32ToUtf8(0x10348);
EXPECT_EQ(result.length(), 4);
EXPECT_EQ(result[0], '\xF0');
EXPECT_EQ(result[1], '\x90');
EXPECT_EQ(result[2], '\x8D');
EXPECT_EQ(result[3], '\x88');
}
// Test the most basic key events.
//
// Press, hold, and release key A on an US keyboard.
TEST(KeyboardKeyEmbedderHandlerTest, BasicKeyPressingAndHolding) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Press KeyA.
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
key_state.Set(kVirtualKeyA, true);
// Hold KeyA.
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, true);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeRepeat);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
event->callback(false, event->user_data);
EXPECT_EQ(last_handled, false);
results.clear();
// Release KeyA.
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYUP, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(false, event->user_data);
}
// Press numpad 1, toggle NumLock, and release numpad 1 on an US
// keyboard.
//
// This is special because the virtual key for numpad 1 will
// change in this process.
TEST(KeyboardKeyEmbedderHandlerTest, ToggleNumLockDuringNumpadPress) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Press NumPad1.
key_state.Set(VK_NUMPAD1, true);
handler->KeyboardHook(
VK_NUMPAD1, kScanCodeNumpad1, WM_KEYDOWN, 0, false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumpad1);
EXPECT_EQ(event->logical, kLogicalNumpad1);
// EXPECT_STREQ(event->character, "1"); // TODO
EXPECT_EQ(event->synthesized, false);
results.clear();
// Press NumLock.
key_state.Set(VK_NUMLOCK, true, true);
handler->KeyboardHook(
VK_NUMLOCK, kScanCodeNumLock, WM_KEYDOWN, 0, true, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
results.clear();
// Release NumLock.
key_state.Set(VK_NUMLOCK, false, true);
handler->KeyboardHook(
VK_NUMLOCK, kScanCodeNumLock, WM_KEYUP, 0, true, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
results.clear();
// Release NumPad1. (The logical key is now NumpadEnd)
handler->KeyboardHook(
VK_END, kScanCodeNumpad1, WM_KEYUP, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalNumpad1);
EXPECT_EQ(event->logical, kLogicalNumpad1);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
results.clear();
}
// Key presses that trigger IME should be ignored by this API (and handled by
// compose API).
TEST(KeyboardKeyEmbedderHandlerTest, ImeEventsAreIgnored) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Press A in an IME
last_handled = false;
handler->KeyboardHook(
VK_PROCESSKEY, kScanCodeKeyA, WM_KEYDOWN, 0, true, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, true);
// The A key down should yield an empty event.
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->physical, 0);
EXPECT_EQ(event->logical, 0);
EXPECT_EQ(event->callback, nullptr);
results.clear();
// Release A in an IME
last_handled = false;
handler->KeyboardHook(
// The up event for an IME press has a normal virtual key.
kVirtualKeyA, kScanCodeKeyA, WM_KEYUP, 0, true, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, true);
// The A key up should yield an empty event.
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->physical, 0);
EXPECT_EQ(event->logical, 0);
EXPECT_EQ(event->callback, nullptr);
results.clear();
// Press A out of an IME
key_state.Set(kVirtualKeyA, true);
last_handled = false;
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 0, true, false,
[&last_handled](bool handled) { last_handled = handled; });
// Not decided yet
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
last_handled = false;
key_state.Set(kVirtualKeyA, false);
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYUP, 0, true, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
}
// Test if modifier keys that are told apart by the extended bit can be
// identified. (Their physical keys must be searched with the extended bit
// considered.)
TEST(KeyboardKeyEmbedderHandlerTest, ModifierKeysByExtendedBit) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Press Ctrl left.
last_handled = false;
key_state.Set(VK_LCONTROL, true);
handler->KeyboardHook(
VK_LCONTROL, kScanCodeControl, WM_KEYDOWN, 0, false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalControlLeft);
EXPECT_EQ(event->logical, kLogicalControlLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// Press Ctrl right.
last_handled = false;
key_state.Set(VK_RCONTROL, true);
handler->KeyboardHook(
VK_RCONTROL, kScanCodeControl, WM_KEYDOWN, 0, true, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalControlRight);
EXPECT_EQ(event->logical, kLogicalControlRight);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// Release Ctrl left.
last_handled = false;
key_state.Set(VK_LCONTROL, false);
handler->KeyboardHook(
VK_LCONTROL, kScanCodeControl, WM_KEYUP, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalControlLeft);
EXPECT_EQ(event->logical, kLogicalControlLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// Release Ctrl right.
last_handled = false;
key_state.Set(VK_RCONTROL, false);
handler->KeyboardHook(
VK_RCONTROL, kScanCodeControl, WM_KEYUP, 0, true, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalControlRight);
EXPECT_EQ(event->logical, kLogicalControlRight);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
}
// Test if modifier keys that are told apart by the virtual key
// can be identified.
TEST(KeyboardKeyEmbedderHandlerTest, ModifierKeysByVirtualKey) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Press Shift left.
last_handled = false;
key_state.Set(VK_LSHIFT, true);
handler->KeyboardHook(
VK_LSHIFT, kScanCodeShiftLeft, WM_KEYDOWN, 0, false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// Press Shift right.
last_handled = false;
key_state.Set(VK_RSHIFT, true);
handler->KeyboardHook(
VK_RSHIFT, kScanCodeShiftRight, WM_KEYDOWN, 0, false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftRight);
EXPECT_EQ(event->logical, kLogicalShiftRight);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// Release Shift left.
last_handled = false;
key_state.Set(VK_LSHIFT, false);
handler->KeyboardHook(
VK_LSHIFT, kScanCodeShiftLeft, WM_KEYUP, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// Release Shift right.
last_handled = false;
key_state.Set(VK_RSHIFT, false);
handler->KeyboardHook(
VK_RSHIFT, kScanCodeShiftRight, WM_KEYUP, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftRight);
EXPECT_EQ(event->logical, kLogicalShiftRight);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
}
// Test if modifiers left key down events are synthesized when left or right
// keys are not pressed.
TEST(KeyboardKeyEmbedderHandlerTest,
SynthesizeModifierLeftKeyDownWhenNotPressed) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Should synthesize shift left key down event.
handler->SyncModifiersIfNeeded(kShift);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
results.clear();
// Clear the pressing state.
handler->SyncModifiersIfNeeded(0);
results.clear();
// Should synthesize control left key down event.
handler->SyncModifiersIfNeeded(kControl);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalControlLeft);
EXPECT_EQ(event->logical, kLogicalControlLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
}
// Test if modifiers left key down events are not synthesized when left or right
// keys are pressed.
TEST(KeyboardKeyEmbedderHandlerTest, DoNotSynthesizeModifierDownWhenPressed) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Should not synthesize shift left key down event when shift left key
// is already pressed.
handler->KeyboardHook(
VK_LSHIFT, kScanCodeShiftLeft, WM_KEYDOWN, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
results.clear();
handler->SyncModifiersIfNeeded(kShift);
EXPECT_EQ(results.size(), 0);
// Should not synthesize shift left key down event when shift right key
// is already pressed.
handler->KeyboardHook(
VK_RSHIFT, kScanCodeShiftRight, WM_KEYDOWN, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
results.clear();
handler->SyncModifiersIfNeeded(kShift);
EXPECT_EQ(results.size(), 0);
// Should not synthesize control left key down event when control left key
// is already pressed.
handler->KeyboardHook(
VK_LCONTROL, kScanCodeControlLeft, WM_KEYDOWN, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
results.clear();
handler->SyncModifiersIfNeeded(kControl);
EXPECT_EQ(results.size(), 0);
// Should not synthesize control left key down event when control right key
// is already pressed .
handler->KeyboardHook(
VK_RCONTROL, kScanCodeControlRight, WM_KEYDOWN, 0, true, true,
[&last_handled](bool handled) { last_handled = handled; });
results.clear();
handler->SyncModifiersIfNeeded(kControl);
EXPECT_EQ(results.size(), 0);
}
// Test if modifiers keys up events are synthesized when left or right keys
// are pressed.
TEST(KeyboardKeyEmbedderHandlerTest, SynthesizeModifierUpWhenPressed) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Should synthesize shift left key up event when shift left key is
// already pressed and modifiers state is zero.
handler->KeyboardHook(
VK_LSHIFT, kScanCodeShiftLeft, WM_KEYDOWN, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
results.clear();
handler->SyncModifiersIfNeeded(0);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
results.clear();
// Should synthesize shift right key up event when shift right key is
// already pressed and modifiers state is zero.
handler->KeyboardHook(
VK_RSHIFT, kScanCodeShiftRight, WM_KEYDOWN, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
results.clear();
handler->SyncModifiersIfNeeded(0);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftRight);
EXPECT_EQ(event->logical, kLogicalShiftRight);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
results.clear();
// Should synthesize control left key up event when control left key is
// already pressed and modifiers state is zero.
handler->KeyboardHook(
VK_LCONTROL, kScanCodeControlLeft, WM_KEYDOWN, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
results.clear();
handler->SyncModifiersIfNeeded(0);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalControlLeft);
EXPECT_EQ(event->logical, kLogicalControlLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
results.clear();
// Should synthesize control right key up event when control right key is
// already pressed and modifiers state is zero.
handler->KeyboardHook(
VK_RCONTROL, kScanCodeControlRight, WM_KEYDOWN, 0, true, true,
[&last_handled](bool handled) { last_handled = handled; });
results.clear();
handler->SyncModifiersIfNeeded(0);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalControlRight);
EXPECT_EQ(event->logical, kLogicalControlRight);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
results.clear();
}
// Test if modifiers key up events are not synthesized when left or right
// keys are not pressed.
TEST(KeyboardKeyEmbedderHandlerTest, DoNotSynthesizeModifierUpWhenNotPressed) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Should not synthesize up events when no modifier key is pressed
// in pressing state and modifiers state is zero.
handler->SyncModifiersIfNeeded(0);
EXPECT_EQ(results.size(), 0);
}
TEST(KeyboardKeyEmbedderHandlerTest, RepeatedDownIsIgnored) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
last_handled = false;
// Press A (should yield a normal event)
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// KeyA's key up is missed.
// Press A again (should yield an empty event)
last_handled = false;
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, true);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->physical, 0);
EXPECT_EQ(event->logical, 0);
EXPECT_EQ(event->callback, nullptr);
results.clear();
}
TEST(KeyboardKeyEmbedderHandlerTest, AbruptRepeatIsConvertedToDown) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
last_handled = false;
key_state.Set(kVirtualKeyA, true);
// Press A (with was_down true)
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// Release A
last_handled = false;
key_state.Set(kVirtualKeyA, false);
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYUP, 'a', false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
}
TEST(KeyboardKeyEmbedderHandlerTest, AbruptUpIsIgnored) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
last_handled = false;
// KeyA's key down is missed.
key_state.Set(kVirtualKeyA, true);
// Press A again (should yield an empty event)
last_handled = false;
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYUP, 'a', false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, true);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->physical, 0);
EXPECT_EQ(event->logical, 0);
EXPECT_EQ(event->callback, nullptr);
results.clear();
}
TEST(KeyboardKeyEmbedderHandlerTest, SynthesizeForDesyncPressingState) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// A key down of control left is missed.
key_state.Set(VK_LCONTROL, true);
// Send a normal event
key_state.Set(kVirtualKeyA, true);
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 2);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalControlLeft);
EXPECT_EQ(event->logical, kLogicalControlLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
EXPECT_EQ(event->callback, nullptr);
event = &results[1];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
last_handled = true;
event->callback(false, event->user_data);
EXPECT_EQ(last_handled, false);
results.clear();
// A key down of control right is missed.
key_state.Set(VK_LCONTROL, false);
// Hold KeyA.
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 2);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalControlLeft);
EXPECT_EQ(event->logical, kLogicalControlLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
EXPECT_EQ(event->callback, nullptr);
event = &results[1];
EXPECT_EQ(event->type, kFlutterKeyEventTypeRepeat);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
last_handled = true;
event->callback(false, event->user_data);
EXPECT_EQ(last_handled, false);
results.clear();
// Release KeyA.
key_state.Set(kVirtualKeyA, false);
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYUP, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(false, event->user_data);
}
TEST(KeyboardKeyEmbedderHandlerTest, SynthesizeForDesyncToggledState) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// The NumLock is desynchronized by toggled on
key_state.Set(VK_NUMLOCK, false, true);
// Send a normal event
key_state.Set(kVirtualKeyA, true);
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 3);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
event = &results[1];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
event = &results[2];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// Test if the NumLock is mis-toggled while it should also be pressed
key_state.Set(VK_NUMLOCK, true, true);
// Send a normal event
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, true);
EXPECT_EQ(results.size(), 2);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
event = &results[1];
EXPECT_EQ(event->type, kFlutterKeyEventTypeRepeat);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
event->callback(false, event->user_data);
EXPECT_EQ(last_handled, false);
results.clear();
// Numlock is pressed at this moment.
// Test if the NumLock is mis-toggled while it should also be released
key_state.Set(VK_NUMLOCK, false, false);
// Send a normal event
key_state.Set(kVirtualKeyA, false);
handler->KeyboardHook(
kVirtualKeyA, kScanCodeKeyA, WM_KEYUP, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(results.size(), 4);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
EXPECT_EQ(event->callback, nullptr);
event = &results[1];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
EXPECT_EQ(event->callback, nullptr);
event = &results[2];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
EXPECT_EQ(event->callback, nullptr);
event = &results[3];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(false, event->user_data);
}
TEST(KeyboardKeyEmbedderHandlerTest,
SynthesizeForDesyncToggledStateByItselfsUp) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// When NumLock is down
key_state.Set(VK_NUMLOCK, true, true);
handler->KeyboardHook(
VK_NUMLOCK, kScanCodeNumLock, WM_KEYDOWN, 0, true, false,
[&last_handled](bool handled) { last_handled = handled; });
event = &results.back();
event->callback(false, event->user_data);
results.clear();
// Numlock is desynchronized by being off and released
key_state.Set(VK_NUMLOCK, false, false);
// Send a NumLock key up
handler->KeyboardHook(
VK_NUMLOCK, kScanCodeNumLock, WM_KEYUP, 0, true, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 3);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
EXPECT_EQ(event->callback, nullptr);
event = &results[1];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
EXPECT_EQ(event->callback, nullptr);
event = &results[2];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
last_handled = false;
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
}
TEST(KeyboardKeyEmbedderHandlerTest,
SynthesizeForDesyncToggledStateByItselfsDown) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
// NumLock is started up and disabled
key_state.Set(VK_NUMLOCK, false, false);
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// NumLock is toggled somewhere else
// key_state.Set(VK_NUMLOCK, false, true);
// NumLock is pressed
key_state.Set(VK_NUMLOCK, true, false);
handler->KeyboardHook(
VK_NUMLOCK, kScanCodeNumLock, WM_KEYDOWN, 0, true, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
// 4 total events should be fired:
// Pre-synchronization toggle, pre-sync press,
// main event, and post-sync press.
EXPECT_EQ(results.size(), 4);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
EXPECT_EQ(event->callback, nullptr);
event = &results[1];
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, true);
EXPECT_EQ(event->callback, nullptr);
event = &results[2];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
last_handled = false;
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
}
TEST(KeyboardKeyEmbedderHandlerTest, SynthesizeWithInitialTogglingState) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
// The app starts with NumLock toggled on
key_state.Set(VK_NUMLOCK, false, true);
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// NumLock key down
key_state.Set(VK_NUMLOCK, true, false);
handler->KeyboardHook(
VK_NUMLOCK, kScanCodeNumLock, WM_KEYDOWN, 0, true, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = &results[0];
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumLock);
EXPECT_EQ(event->logical, kLogicalNumLock);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
}
TEST(KeyboardKeyEmbedderHandlerTest, SysKeyPress) {
TestKeystate key_state;
std::vector<TestFlutterKeyEvent> results;
TestFlutterKeyEvent* event;
bool last_handled = false;
std::unique_ptr<KeyboardKeyEmbedderHandler> handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[&results](const FlutterKeyEvent& event,
FlutterKeyEventCallback callback, void* user_data) {
results.emplace_back(event, callback, user_data);
},
key_state.Getter(), DefaultMapVkToScan);
// Press KeyAltLeft.
key_state.Set(VK_LMENU, true);
handler->KeyboardHook(
VK_LMENU, kScanCodeAltLeft, WM_SYSKEYDOWN, 0, false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(results.size(), 1);
event = results.data();
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalAltLeft);
EXPECT_EQ(event->logical, kLogicalAltLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(true, event->user_data);
EXPECT_EQ(last_handled, true);
results.clear();
// Release KeyAltLeft.
key_state.Set(VK_LMENU, false);
handler->KeyboardHook(
VK_LMENU, kScanCodeAltLeft, WM_SYSKEYUP, 0, false, true,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(results.size(), 1);
event = results.data();
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalAltLeft);
EXPECT_EQ(event->logical, kLogicalAltLeft);
EXPECT_STREQ(event->character, "");
EXPECT_EQ(event->synthesized, false);
event->callback(false, event->user_data);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/keyboard_key_embedder_handler_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/keyboard_key_embedder_handler_unittests.cc",
"repo_id": "engine",
"token_count": 16989
} | 519 |
// 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_PLATFORM_VIEW_PLUGIN_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_PLATFORM_VIEW_PLUGIN_H_
#include "flutter/shell/platform/windows/platform_view_manager.h"
#include <functional>
#include <map>
#include <optional>
namespace flutter {
// The concrete implementation of PlatformViewManager that keeps track of
// existing platform view types and instances, and handles their instantiation.
class PlatformViewPlugin : public PlatformViewManager {
public:
PlatformViewPlugin(BinaryMessenger* messenger, TaskRunner* task_runner);
~PlatformViewPlugin();
// Find the HWND corresponding to a platform view id. Returns null if the id
// has no associated platform view.
std::optional<HWND> GetNativeHandleForId(PlatformViewId id) const;
// The runner-facing API calls this method to register a window type
// corresponding to a platform view identifier supplied to the widget tree.
void RegisterPlatformViewType(std::string_view type_name,
const FlutterPlatformViewTypeEntry& type);
// | PlatformViewManager |
// type_name must correspond to a string that has already been registered
// with RegisterPlatformViewType.
bool AddPlatformView(PlatformViewId id, std::string_view type_name) override;
// Create a queued platform view instance after it has been added.
// id must correspond to an identifier that has already been added with
// AddPlatformView.
// This method will create the platform view within a task queued to the
// engine's TaskRunner, which will run on the UI thread.
void InstantiatePlatformView(PlatformViewId id);
// | PlatformViewManager |
// id must correspond to an identifier that has already been added with
// AddPlatformView.
bool FocusPlatformView(PlatformViewId id,
FocusChangeDirection direction,
bool focus) override;
private:
std::unordered_map<std::string, FlutterPlatformViewTypeEntry>
platform_view_types_;
std::unordered_map<PlatformViewId, HWND> platform_views_;
std::unordered_map<PlatformViewId, std::function<HWND()>>
pending_platform_views_;
// Pointer to the task runner of the associated engine.
TaskRunner* task_runner_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_PLATFORM_VIEW_PLUGIN_H_
| engine/shell/platform/windows/platform_view_plugin.h/0 | {
"file_path": "engine/shell/platform/windows/platform_view_plugin.h",
"repo_id": "engine",
"token_count": 759
} | 520 |
// 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_EGL_MOCK_CONTEXT_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_CONTEXT_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/windows/egl/context.h"
#include "gmock/gmock.h"
namespace flutter {
namespace testing {
namespace egl {
/// Mock for the |Context| base class.
class MockContext : public flutter::egl::Context {
public:
MockContext() : Context(EGL_NO_DISPLAY, EGL_NO_CONTEXT) {}
MOCK_METHOD(bool, MakeCurrent, (), (const, override));
MOCK_METHOD(bool, ClearCurrent, (), (const, override));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockContext);
};
} // namespace egl
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_CONTEXT_H_
| engine/shell/platform/windows/testing/egl/mock_context.h/0 | {
"file_path": "engine/shell/platform/windows/testing/egl/mock_context.h",
"repo_id": "engine",
"token_count": 342
} | 521 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOWS_PROC_TABLE_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOWS_PROC_TABLE_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/windows/windows_proc_table.h"
#include "gmock/gmock.h"
namespace flutter {
namespace testing {
/// Mock for the |WindowsProcTable| base class.
class MockWindowsProcTable : public WindowsProcTable {
public:
MockWindowsProcTable() = default;
virtual ~MockWindowsProcTable() = default;
MOCK_METHOD(BOOL,
GetPointerType,
(UINT32 pointer_id, POINTER_INPUT_TYPE* pointer_type),
(const, override));
MOCK_METHOD(LRESULT,
GetThreadPreferredUILanguages,
(DWORD, PULONG, PZZWSTR, PULONG),
(const, override));
MOCK_METHOD(bool, GetHighContrastEnabled, (), (const, override));
MOCK_METHOD(bool, DwmIsCompositionEnabled, (), (const, override));
MOCK_METHOD(HRESULT, DwmFlush, (), (const, override));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockWindowsProcTable);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOWS_PROC_TABLE_H_
| engine/shell/platform/windows/testing/mock_windows_proc_table.h/0 | {
"file_path": "engine/shell/platform/windows/testing/mock_windows_proc_table.h",
"repo_id": "engine",
"token_count": 533
} | 522 |
// 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/text_input_plugin.h"
#include <windows.h>
#include <cstdint>
#include "flutter/fml/string_conversion.h"
#include "flutter/shell/platform/common/json_method_codec.h"
#include "flutter/shell/platform/common/text_editing_delta.h"
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
static constexpr char kSetEditingStateMethod[] = "TextInput.setEditingState";
static constexpr char kClearClientMethod[] = "TextInput.clearClient";
static constexpr char kSetClientMethod[] = "TextInput.setClient";
static constexpr char kShowMethod[] = "TextInput.show";
static constexpr char kHideMethod[] = "TextInput.hide";
static constexpr char kSetMarkedTextRect[] = "TextInput.setMarkedTextRect";
static constexpr char kSetEditableSizeAndTransform[] =
"TextInput.setEditableSizeAndTransform";
static constexpr char kMultilineInputType[] = "TextInputType.multiline";
static constexpr char kUpdateEditingStateMethod[] =
"TextInputClient.updateEditingState";
static constexpr char kUpdateEditingStateWithDeltasMethod[] =
"TextInputClient.updateEditingStateWithDeltas";
static constexpr char kPerformActionMethod[] = "TextInputClient.performAction";
static constexpr char kDeltaOldTextKey[] = "oldText";
static constexpr char kDeltaTextKey[] = "deltaText";
static constexpr char kDeltaStartKey[] = "deltaStart";
static constexpr char kDeltaEndKey[] = "deltaEnd";
static constexpr char kDeltasKey[] = "deltas";
static constexpr char kEnableDeltaModel[] = "enableDeltaModel";
static constexpr char kTextInputAction[] = "inputAction";
static constexpr char kTextInputType[] = "inputType";
static constexpr char kTextInputTypeName[] = "name";
static constexpr char kComposingBaseKey[] = "composingBase";
static constexpr char kComposingExtentKey[] = "composingExtent";
static constexpr char kSelectionAffinityKey[] = "selectionAffinity";
static constexpr char kAffinityDownstream[] = "TextAffinity.downstream";
static constexpr char kSelectionBaseKey[] = "selectionBase";
static constexpr char kSelectionExtentKey[] = "selectionExtent";
static constexpr char kSelectionIsDirectionalKey[] = "selectionIsDirectional";
static constexpr char kTextKey[] = "text";
static constexpr char kXKey[] = "x";
static constexpr char kYKey[] = "y";
static constexpr char kWidthKey[] = "width";
static constexpr char kHeightKey[] = "height";
static constexpr char kTransformKey[] = "transform";
static constexpr char kChannelName[] = "flutter/textinput";
static constexpr char kBadArgumentError[] = "Bad Arguments";
static constexpr char kInternalConsistencyError[] =
"Internal Consistency Error";
static constexpr char kInputActionNewline[] = "TextInputAction.newline";
namespace flutter {
void TextInputPlugin::TextHook(const std::u16string& text) {
if (active_model_ == nullptr) {
return;
}
std::u16string text_before_change =
fml::Utf8ToUtf16(active_model_->GetText());
TextRange selection_before_change = active_model_->selection();
active_model_->AddText(text);
if (enable_delta_model) {
TextEditingDelta delta =
TextEditingDelta(text_before_change, selection_before_change, text);
SendStateUpdateWithDelta(*active_model_, &delta);
} else {
SendStateUpdate(*active_model_);
}
}
void TextInputPlugin::KeyboardHook(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down) {
if (active_model_ == nullptr) {
return;
}
if (action == WM_KEYDOWN || action == WM_SYSKEYDOWN) {
// Most editing keys (arrow keys, backspace, delete, etc.) are handled in
// the framework, so don't need to be handled at this layer.
switch (key) {
case VK_RETURN:
EnterPressed(active_model_.get());
break;
default:
break;
}
}
}
TextInputPlugin::TextInputPlugin(flutter::BinaryMessenger* messenger,
FlutterWindowsEngine* engine)
: channel_(std::make_unique<flutter::MethodChannel<rapidjson::Document>>(
messenger,
kChannelName,
&flutter::JsonMethodCodec::GetInstance())),
engine_(engine),
active_model_(nullptr) {
channel_->SetMethodCallHandler(
[this](
const flutter::MethodCall<rapidjson::Document>& call,
std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result) {
HandleMethodCall(call, std::move(result));
});
}
TextInputPlugin::~TextInputPlugin() = default;
void TextInputPlugin::ComposeBeginHook() {
if (active_model_ == nullptr) {
return;
}
active_model_->BeginComposing();
if (enable_delta_model) {
std::string text = active_model_->GetText();
TextRange selection = active_model_->selection();
TextEditingDelta delta = TextEditingDelta(text);
SendStateUpdateWithDelta(*active_model_, &delta);
} else {
SendStateUpdate(*active_model_);
}
}
void TextInputPlugin::ComposeCommitHook() {
if (active_model_ == nullptr) {
return;
}
std::string text_before_change = active_model_->GetText();
TextRange selection_before_change = active_model_->selection();
TextRange composing_before_change = active_model_->composing_range();
std::string composing_text_before_change = text_before_change.substr(
composing_before_change.start(), composing_before_change.length());
active_model_->CommitComposing();
// We do not trigger SendStateUpdate here.
//
// Until a WM_IME_ENDCOMPOSING event, the user is still composing from the OS
// point of view. Commit events are always immediately followed by another
// composing event or an end composing event. However, in the brief window
// between the commit event and the following event, the composing region is
// collapsed. Notifying the framework of this intermediate state will trigger
// any framework code designed to execute at the end of composing, such as
// input formatters, which may try to update the text and send a message back
// to the engine with changes.
//
// This is a particular problem with Korean IMEs, which build up one
// character at a time in their composing region until a keypress that makes
// no sense for the in-progress character. At that point, the result
// character is committed and a compose event is immedidately received with
// the new composing region.
//
// In the case where this event is immediately followed by a composing event,
// the state will be sent in ComposeChangeHook.
//
// In the case where this event is immediately followed by an end composing
// event, the state will be sent in ComposeEndHook.
}
void TextInputPlugin::ComposeEndHook() {
if (active_model_ == nullptr) {
return;
}
std::string text_before_change = active_model_->GetText();
TextRange selection_before_change = active_model_->selection();
active_model_->CommitComposing();
active_model_->EndComposing();
if (enable_delta_model) {
std::string text = active_model_->GetText();
TextEditingDelta delta = TextEditingDelta(text);
SendStateUpdateWithDelta(*active_model_, &delta);
} else {
SendStateUpdate(*active_model_);
}
}
void TextInputPlugin::ComposeChangeHook(const std::u16string& text,
int cursor_pos) {
if (active_model_ == nullptr) {
return;
}
std::string text_before_change = active_model_->GetText();
TextRange composing_before_change = active_model_->composing_range();
active_model_->AddText(text);
active_model_->UpdateComposingText(text, TextRange(cursor_pos, cursor_pos));
std::string text_after_change = active_model_->GetText();
if (enable_delta_model) {
TextEditingDelta delta = TextEditingDelta(
fml::Utf8ToUtf16(text_before_change), composing_before_change, text);
SendStateUpdateWithDelta(*active_model_, &delta);
} else {
SendStateUpdate(*active_model_);
}
}
void TextInputPlugin::HandleMethodCall(
const flutter::MethodCall<rapidjson::Document>& method_call,
std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result) {
const std::string& method = method_call.method_name();
if (method.compare(kShowMethod) == 0 || method.compare(kHideMethod) == 0) {
// These methods are no-ops.
} else if (method.compare(kClearClientMethod) == 0) {
// TODO(loicsharma): Remove implicit view assumption.
// https://github.com/flutter/flutter/issues/142845
FlutterWindowsView* view = engine_->view(kImplicitViewId);
if (view == nullptr) {
result->Error(kInternalConsistencyError,
"Text input is not available in Windows headless mode");
return;
}
if (active_model_ != nullptr && active_model_->composing()) {
active_model_->CommitComposing();
active_model_->EndComposing();
SendStateUpdate(*active_model_);
}
view->OnResetImeComposing();
active_model_ = nullptr;
} else if (method.compare(kSetClientMethod) == 0) {
if (!method_call.arguments() || method_call.arguments()->IsNull()) {
result->Error(kBadArgumentError, "Method invoked without args");
return;
}
const rapidjson::Document& args = *method_call.arguments();
const rapidjson::Value& client_id_json = args[0];
const rapidjson::Value& client_config = args[1];
if (client_id_json.IsNull()) {
result->Error(kBadArgumentError, "Could not set client, ID is null.");
return;
}
if (client_config.IsNull()) {
result->Error(kBadArgumentError,
"Could not set client, missing arguments.");
return;
}
client_id_ = client_id_json.GetInt();
auto enable_delta_model_json = client_config.FindMember(kEnableDeltaModel);
if (enable_delta_model_json != client_config.MemberEnd() &&
enable_delta_model_json->value.IsBool()) {
enable_delta_model = enable_delta_model_json->value.GetBool();
}
input_action_ = "";
auto input_action_json = client_config.FindMember(kTextInputAction);
if (input_action_json != client_config.MemberEnd() &&
input_action_json->value.IsString()) {
input_action_ = input_action_json->value.GetString();
}
input_type_ = "";
auto input_type_info_json = client_config.FindMember(kTextInputType);
if (input_type_info_json != client_config.MemberEnd() &&
input_type_info_json->value.IsObject()) {
auto input_type_json =
input_type_info_json->value.FindMember(kTextInputTypeName);
if (input_type_json != input_type_info_json->value.MemberEnd() &&
input_type_json->value.IsString()) {
input_type_ = input_type_json->value.GetString();
}
}
active_model_ = std::make_unique<TextInputModel>();
} else if (method.compare(kSetEditingStateMethod) == 0) {
if (!method_call.arguments() || method_call.arguments()->IsNull()) {
result->Error(kBadArgumentError, "Method invoked without args");
return;
}
const rapidjson::Document& args = *method_call.arguments();
if (active_model_ == nullptr) {
result->Error(
kInternalConsistencyError,
"Set editing state has been invoked, but no client is set.");
return;
}
auto text = args.FindMember(kTextKey);
if (text == args.MemberEnd() || text->value.IsNull()) {
result->Error(kBadArgumentError,
"Set editing state has been invoked, but without text.");
return;
}
auto base = args.FindMember(kSelectionBaseKey);
auto extent = args.FindMember(kSelectionExtentKey);
if (base == args.MemberEnd() || base->value.IsNull() ||
extent == args.MemberEnd() || extent->value.IsNull()) {
result->Error(kInternalConsistencyError,
"Selection base/extent values invalid.");
return;
}
// Flutter uses -1/-1 for invalid; translate that to 0/0 for the model.
int selection_base = base->value.GetInt();
int selection_extent = extent->value.GetInt();
if (selection_base == -1 && selection_extent == -1) {
selection_base = selection_extent = 0;
}
active_model_->SetText(text->value.GetString());
active_model_->SetSelection(TextRange(selection_base, selection_extent));
base = args.FindMember(kComposingBaseKey);
extent = args.FindMember(kComposingExtentKey);
if (base == args.MemberEnd() || base->value.IsNull() ||
extent == args.MemberEnd() || extent->value.IsNull()) {
result->Error(kInternalConsistencyError,
"Composing base/extent values invalid.");
return;
}
int composing_base = base->value.GetInt();
int composing_extent = base->value.GetInt();
if (composing_base == -1 && composing_extent == -1) {
active_model_->EndComposing();
} else {
int composing_start = std::min(composing_base, composing_extent);
int cursor_offset = selection_base - composing_start;
active_model_->SetComposingRange(
TextRange(composing_base, composing_extent), cursor_offset);
}
} else if (method.compare(kSetMarkedTextRect) == 0) {
// TODO(loicsharma): Remove implicit view assumption.
// https://github.com/flutter/flutter/issues/142845
FlutterWindowsView* view = engine_->view(kImplicitViewId);
if (view == nullptr) {
result->Error(kInternalConsistencyError,
"Text input is not available in Windows headless mode");
return;
}
if (!method_call.arguments() || method_call.arguments()->IsNull()) {
result->Error(kBadArgumentError, "Method invoked without args");
return;
}
const rapidjson::Document& args = *method_call.arguments();
auto x = args.FindMember(kXKey);
auto y = args.FindMember(kYKey);
auto width = args.FindMember(kWidthKey);
auto height = args.FindMember(kHeightKey);
if (x == args.MemberEnd() || x->value.IsNull() || //
y == args.MemberEnd() || y->value.IsNull() || //
width == args.MemberEnd() || width->value.IsNull() || //
height == args.MemberEnd() || height->value.IsNull()) {
result->Error(kInternalConsistencyError,
"Composing rect values invalid.");
return;
}
composing_rect_ = {{x->value.GetDouble(), y->value.GetDouble()},
{width->value.GetDouble(), height->value.GetDouble()}};
Rect transformed_rect = GetCursorRect();
view->OnCursorRectUpdated(transformed_rect);
} else if (method.compare(kSetEditableSizeAndTransform) == 0) {
// TODO(loicsharma): Remove implicit view assumption.
// https://github.com/flutter/flutter/issues/142845
FlutterWindowsView* view = engine_->view(kImplicitViewId);
if (view == nullptr) {
result->Error(kInternalConsistencyError,
"Text input is not available in Windows headless mode");
return;
}
if (!method_call.arguments() || method_call.arguments()->IsNull()) {
result->Error(kBadArgumentError, "Method invoked without args");
return;
}
const rapidjson::Document& args = *method_call.arguments();
auto transform = args.FindMember(kTransformKey);
if (transform == args.MemberEnd() || transform->value.IsNull() ||
!transform->value.IsArray() || transform->value.Size() != 16) {
result->Error(kInternalConsistencyError,
"EditableText transform invalid.");
return;
}
size_t i = 0;
for (auto& entry : transform->value.GetArray()) {
if (entry.IsNull()) {
result->Error(kInternalConsistencyError,
"EditableText transform contains null value.");
return;
}
editabletext_transform_[i / 4][i % 4] = entry.GetDouble();
++i;
}
Rect transformed_rect = GetCursorRect();
view->OnCursorRectUpdated(transformed_rect);
} else {
result->NotImplemented();
return;
}
// All error conditions return early, so if nothing has gone wrong indicate
// success.
result->Success();
}
Rect TextInputPlugin::GetCursorRect() const {
Point transformed_point = {
composing_rect_.left() * editabletext_transform_[0][0] +
composing_rect_.top() * editabletext_transform_[1][0] +
editabletext_transform_[3][0],
composing_rect_.left() * editabletext_transform_[0][1] +
composing_rect_.top() * editabletext_transform_[1][1] +
editabletext_transform_[3][1]};
return {transformed_point, composing_rect_.size()};
}
void TextInputPlugin::SendStateUpdate(const TextInputModel& model) {
auto args = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = args->GetAllocator();
args->PushBack(client_id_, allocator);
TextRange selection = model.selection();
rapidjson::Value editing_state(rapidjson::kObjectType);
editing_state.AddMember(kSelectionAffinityKey, kAffinityDownstream,
allocator);
editing_state.AddMember(kSelectionBaseKey, selection.base(), allocator);
editing_state.AddMember(kSelectionExtentKey, selection.extent(), allocator);
editing_state.AddMember(kSelectionIsDirectionalKey, false, allocator);
int composing_base = model.composing() ? model.composing_range().base() : -1;
int composing_extent =
model.composing() ? model.composing_range().extent() : -1;
editing_state.AddMember(kComposingBaseKey, composing_base, allocator);
editing_state.AddMember(kComposingExtentKey, composing_extent, allocator);
editing_state.AddMember(
kTextKey, rapidjson::Value(model.GetText(), allocator).Move(), allocator);
args->PushBack(editing_state, allocator);
channel_->InvokeMethod(kUpdateEditingStateMethod, std::move(args));
}
void TextInputPlugin::SendStateUpdateWithDelta(const TextInputModel& model,
const TextEditingDelta* delta) {
auto args = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = args->GetAllocator();
args->PushBack(client_id_, allocator);
rapidjson::Value object(rapidjson::kObjectType);
rapidjson::Value deltas(rapidjson::kArrayType);
rapidjson::Value deltaJson(rapidjson::kObjectType);
deltaJson.AddMember(kDeltaOldTextKey, delta->old_text(), allocator);
deltaJson.AddMember(kDeltaTextKey, delta->delta_text(), allocator);
deltaJson.AddMember(kDeltaStartKey, delta->delta_start(), allocator);
deltaJson.AddMember(kDeltaEndKey, delta->delta_end(), allocator);
TextRange selection = model.selection();
deltaJson.AddMember(kSelectionAffinityKey, kAffinityDownstream, allocator);
deltaJson.AddMember(kSelectionBaseKey, selection.base(), allocator);
deltaJson.AddMember(kSelectionExtentKey, selection.extent(), allocator);
deltaJson.AddMember(kSelectionIsDirectionalKey, false, allocator);
int composing_base = model.composing() ? model.composing_range().base() : -1;
int composing_extent =
model.composing() ? model.composing_range().extent() : -1;
deltaJson.AddMember(kComposingBaseKey, composing_base, allocator);
deltaJson.AddMember(kComposingExtentKey, composing_extent, allocator);
deltas.PushBack(deltaJson, allocator);
object.AddMember(kDeltasKey, deltas, allocator);
args->PushBack(object, allocator);
channel_->InvokeMethod(kUpdateEditingStateWithDeltasMethod, std::move(args));
}
void TextInputPlugin::EnterPressed(TextInputModel* model) {
if (input_type_ == kMultilineInputType &&
input_action_ == kInputActionNewline) {
std::u16string text_before_change = fml::Utf8ToUtf16(model->GetText());
TextRange selection_before_change = model->selection();
model->AddText(u"\n");
if (enable_delta_model) {
TextEditingDelta delta(text_before_change, selection_before_change,
u"\n");
SendStateUpdateWithDelta(*model, &delta);
} else {
SendStateUpdate(*model);
}
}
auto args = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = args->GetAllocator();
args->PushBack(client_id_, allocator);
args->PushBack(rapidjson::Value(input_action_, allocator).Move(), allocator);
channel_->InvokeMethod(kPerformActionMethod, std::move(args));
}
} // namespace flutter
| engine/shell/platform/windows/text_input_plugin.cc/0 | {
"file_path": "engine/shell/platform/windows/text_input_plugin.cc",
"repo_id": "engine",
"token_count": 7451
} | 523 |
# This file is suitable for use within the tree. A different _embedder.yaml
# is generated by the BUILD.gn in this directory. Changes here must be
# mirrored there.
embedded_libs:
"dart:async": "../../../../../third_party/dart/sdk/lib/async/async.dart"
"dart:collection": "../../../../../third_party/dart/sdk/lib/collection/collection.dart"
"dart:convert": "../../../../../third_party/dart/sdk/lib/convert/convert.dart"
"dart:core": "../../../../../third_party/dart/sdk/lib/core/core.dart"
"dart:developer": "../../../../../third_party/dart/sdk/lib/developer/developer.dart"
"dart:ffi": "../../../../../third_party/dart/sdk/lib/ffi/ffi.dart"
"dart:html": "../../../../../third_party/dart/sdk/lib/html/html_dart2js.dart"
"dart:io": "../../../../../third_party/dart/sdk/lib/io/io.dart"
"dart:isolate": "../../../../../third_party/dart/sdk/lib/isolate/isolate.dart"
"dart:js": "../../../../../third_party/dart/sdk/lib/js/js.dart"
"dart:js_interop": "../../../../../third_party/dart/sdk/lib/js_interop/js_interop.dart"
"dart:js_interop_unsafe": "../../../../../third_party/dart/sdk/lib/js_interop_unsafe/js_interop_unsafe.dart"
"dart:js_util": "../../../../../third_party/dart/sdk/lib/js_util/js_util.dart"
"dart:math": "../../../../../third_party/dart/sdk/lib/math/math.dart"
"dart:typed_data": "../../../../../third_party/dart/sdk/lib/typed_data/typed_data.dart"
"dart:ui": "../../../../lib/ui/ui.dart"
"dart:ui_web": "../../../../lib/web_ui/lib/ui_web/src/ui_web.dart"
"dart:_http": "../../../../../third_party/dart/sdk/lib/_http/http.dart"
"dart:_interceptors": "../../../../../third_party/dart/sdk/lib/_interceptors/interceptors.dart"
# The _internal library is needed as some implementations bleed into the
# public API, e.g. List being Iterable by virtue of implementing
# EfficientLengthIterable. Not including this library yields analysis errors.
"dart:_internal": "../../../../../third_party/dart/sdk/lib/internal/internal.dart"
# The _js_annotations library is also needed for the same reasons as _internal.
"dart:_js_annotations": "../../../../../third_party/dart/sdk/lib/js/_js_annotations.dart"
# The _js_types library is also needed for the same reasons as _internal.
"dart:_js_types": "../../../../../third_party/dart/sdk/lib/_internal/js_shared/lib/js_types.dart"
"dart:nativewrappers": "_empty.dart"
| engine/sky/packages/sky_engine/lib/_embedder.yaml/0 | {
"file_path": "engine/sky/packages/sky_engine/lib/_embedder.yaml",
"repo_id": "engine",
"token_count": 964
} | 524 |
include: ../analysis_options.yaml
linter:
rules:
avoid_print: false
only_throw_errors: false
| engine/testing/analysis_options.yaml/0 | {
"file_path": "engine/testing/analysis_options.yaml",
"repo_id": "engine",
"token_count": 40
} | 525 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/testing/rules/android.gni")
_android_sources = [
"app/build.gradle",
"app/src/main/AndroidManifest.xml",
"app/src/main/java/dev/flutter/android_background_image/MainActivity.java",
"build.gradle",
]
gradle_task("android_lint") {
app_name = "android_background_image"
task = "lint"
gradle_project_dir = rebase_path(".")
sources = _android_sources
outputs =
[ "$root_out_dir/android_background_image/reports/lint-results.xml" ]
deps = [ "//flutter/testing/android_background_image:android_background_image_snapshot" ]
}
gradle_task("build_apk") {
app_name = "android_background_image"
task = "assembleDebug"
gradle_project_dir = rebase_path(".")
sources = _android_sources
outputs = [ "$root_out_dir/android_background_image/app/outputs/apk/debug/app-debug.apk" ]
deps = [
":android_lint",
"//flutter/testing/android_background_image:android_background_image_snapshot",
]
}
copy("android") {
sources = get_target_outputs(":build_apk")
outputs = [ "$root_out_dir/firebase_apks/android_background_image.apk" ]
deps = [ ":build_apk" ]
}
| engine/testing/android_background_image/android/BUILD.gn/0 | {
"file_path": "engine/testing/android_background_image/android/BUILD.gn",
"repo_id": "engine",
"token_count": 463
} | 526 |
// 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 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as path;
import 'impeller_enabled.dart';
void main() {
test('Animation metadata', () async {
Uint8List data = await _getSkiaResource('alphabetAnim.gif').readAsBytes();
ui.Codec codec = await ui.instantiateImageCodec(data);
expect(codec, isNotNull);
expect(codec.frameCount, 13);
expect(codec.repetitionCount, 0);
codec.dispose();
data = await _getSkiaResource('test640x479.gif').readAsBytes();
codec = await ui.instantiateImageCodec(data);
expect(codec.frameCount, 4);
expect(codec.repetitionCount, -1);
});
test('Fails with invalid data', () async {
final Uint8List data = Uint8List.fromList(<int>[1, 2, 3]);
try {
await ui.instantiateImageCodec(data);
fail('exception not thrown');
} on Exception catch (e) {
expect(e.toString(), contains('Invalid image data'));
}
});
test('getNextFrame fails with invalid data', () async {
Uint8List data = await _getSkiaResource('flutter_logo.jpg').readAsBytes();
data = Uint8List.view(data.buffer, 0, 4000);
final ui.Codec codec = await ui.instantiateImageCodec(data);
try {
await codec.getNextFrame();
fail('exception not thrown');
} on Exception catch (e) {
if (impellerEnabled) {
expect(e.toString(), contains('Could not decompress image.'));
} else {
expect(e.toString(), contains('Codec failed'));
}
}
});
test('nextFrame', () async {
final Uint8List data = await _getSkiaResource('test640x479.gif').readAsBytes();
final ui.Codec codec = await ui.instantiateImageCodec(data);
final List<List<int>> decodedFrameInfos = <List<int>>[];
for (int i = 0; i < 5; i++) {
final ui.FrameInfo frameInfo = await codec.getNextFrame();
decodedFrameInfos.add(<int>[
frameInfo.duration.inMilliseconds,
frameInfo.image.width,
frameInfo.image.height,
]);
}
expect(decodedFrameInfos, equals(<List<int>>[
<int>[200, 640, 479],
<int>[200, 640, 479],
<int>[200, 640, 479],
<int>[200, 640, 479],
<int>[200, 640, 479],
]));
});
test('non animated image', () async {
final Uint8List data = await _getSkiaResource('baby_tux.png').readAsBytes();
final ui.Codec codec = await ui.instantiateImageCodec(data);
final List<List<int>> decodedFrameInfos = <List<int>>[];
for (int i = 0; i < 2; i++) {
final ui.FrameInfo frameInfo = await codec.getNextFrame();
decodedFrameInfos.add(<int>[
frameInfo.duration.inMilliseconds,
frameInfo.image.width,
frameInfo.image.height,
]);
}
expect(decodedFrameInfos, equals(<List<int>>[
<int>[0, 240, 246],
<int>[0, 240, 246],
]));
});
test('with size', () async {
final Uint8List data = await _getSkiaResource('baby_tux.png').readAsBytes();
final ui.ImmutableBuffer buffer = await ui.ImmutableBuffer.fromUint8List(data);
final ui.Codec codec = await ui.instantiateImageCodecWithSize(
buffer,
getTargetSize: (int intrinsicWidth, int intrinsicHeight) {
return ui.TargetImageSize(
width: intrinsicWidth ~/ 2,
height: intrinsicHeight ~/ 2,
);
},
);
final List<List<int>> decodedFrameInfos = <List<int>>[];
for (int i = 0; i < 2; i++) {
final ui.FrameInfo frameInfo = await codec.getNextFrame();
decodedFrameInfos.add(<int>[
frameInfo.duration.inMilliseconds,
frameInfo.image.width,
frameInfo.image.height,
]);
}
expect(decodedFrameInfos, equals(<List<int>>[
<int>[0, 120, 123],
<int>[0, 120, 123],
]));
});
test('disposed decoded image', () async {
final Uint8List data = await _getSkiaResource('flutter_logo.jpg').readAsBytes();
final ui.Codec codec = await ui.instantiateImageCodec(data);
final ui.FrameInfo frameInfo = await codec.getNextFrame();
expect(frameInfo.image, isNotNull);
frameInfo.image.dispose();
try {
await codec.getNextFrame();
fail('exception not thrown');
} on Exception catch (e) {
expect(e.toString(), contains('Decoded image has been disposed'));
}
});
test('Animated gif can reuse across multiple frames', () async {
// Regression test for b/271947267 and https://github.com/flutter/flutter/issues/122134
final Uint8List data = File(
path.join('flutter', 'lib', 'ui', 'fixtures', 'four_frame_with_reuse.gif'),
).readAsBytesSync();
final ui.Codec codec = await ui.instantiateImageCodec(data);
// Capture the final frame of animation. If we have not composited
// correctly, it will be clipped strangely.
late ui.FrameInfo frameInfo;
for (int i = 0; i < 4; i++) {
frameInfo = await codec.getNextFrame();
}
final ui.Image image = frameInfo.image;
final ByteData imageData = (await image.toByteData(format: ui.ImageByteFormat.png))!;
final String fileName = impellerEnabled ? 'impeller_four_frame_with_reuse_end.png' : 'four_frame_with_reuse_end.png';
final Uint8List goldenData = File(
path.join('flutter', 'lib', 'ui', 'fixtures', fileName),
).readAsBytesSync();
expect(imageData.buffer.asUint8List(), goldenData);
});
test('Animated webp can reuse across multiple frames', () async {
// Regression test for https://github.com/flutter/flutter/issues/61150#issuecomment-679055858
final Uint8List data = File(
path.join('flutter', 'lib', 'ui', 'fixtures', 'heart.webp'),
).readAsBytesSync();
final ui.Codec codec = await ui.instantiateImageCodec(data);
// Capture the final frame of animation. If we have not composited
// correctly, the hearts will be incorrectly repeated in the image.
late ui.FrameInfo frameInfo;
for (int i = 0; i < 69; i++) {
frameInfo = await codec.getNextFrame();
}
final ui.Image image = frameInfo.image;
final ByteData imageData = (await image.toByteData(format: ui.ImageByteFormat.png))!;
final String fileName = impellerEnabled ? 'impeller_heart_end.png' : 'heart_end.png';
final Uint8List goldenData = File(
path.join('flutter', 'lib', 'ui', 'fixtures', fileName),
).readAsBytesSync();
expect(imageData.buffer.asUint8List(), goldenData);
});
test('Animated apng can reuse pre-pre-frame', () async {
// https://github.com/flutter/engine/pull/42153
final Uint8List data = File(
path.join('flutter', 'lib', 'ui', 'fixtures', '2_dispose_op_restore_previous.apng'),
).readAsBytesSync();
final ui.Codec codec = await ui.instantiateImageCodec(data);
// Capture the 67,68,69 frames of animation and then compare the pixels.
late ui.FrameInfo frameInfo;
for (int i = 0; i < 70; i++) {
frameInfo = await codec.getNextFrame();
if (i >= 67) {
final ui.Image image = frameInfo.image;
final ByteData imageData = (await image.toByteData(format: ui.ImageByteFormat.png))!;
final String fileName = impellerEnabled ? 'impeller_2_dispose_op_restore_previous.apng.$i.png' : '2_dispose_op_restore_previous.apng.$i.png';
final Uint8List goldenData = File(
path.join('flutter', 'lib', 'ui', 'fixtures', fileName),
).readAsBytesSync();
expect(imageData.buffer.asUint8List(), goldenData);
}
}
});
test('Animated apng alpha type handling', () async {
final Uint8List data = File(
path.join('flutter', 'lib', 'ui', 'fixtures', 'alpha_animated.apng'),
).readAsBytesSync();
final ui.Codec codec = await ui.instantiateImageCodec(data);
// The test image contains two frames of solid red. The first has
// alpha=0.2, and the second has alpha=0.6.
ui.Image image = (await codec.getNextFrame()).image;
ByteData imageData = (await image.toByteData())!;
expect(imageData.getUint32(0), 0x33000033);
image = (await codec.getNextFrame()).image;
imageData = (await image.toByteData())!;
expect(imageData.getUint32(0), 0x99000099);
});
test('Animated apng background color restore', () async {
final Uint8List data = File(
path.join('flutter', 'lib', 'ui', 'fixtures', 'dispose_op_background.apng'),
).readAsBytesSync();
final ui.Codec codec = await ui.instantiateImageCodec(data);
// First frame is solid red
ui.Image image = (await codec.getNextFrame()).image;
ByteData imageData = (await image.toByteData())!;
expect(imageData.getUint32(0), 0xFF0000FF);
// Third frame is blue in the lower right corner.
await codec.getNextFrame();
image = (await codec.getNextFrame()).image;
imageData = (await image.toByteData())!;
expect(imageData.getUint32(imageData.lengthInBytes - 4), 0x0000FFFF);
// Fourth frame is transparent in the lower right corner
image = (await codec.getNextFrame()).image;
imageData = (await image.toByteData())!;
expect(imageData.getUint32(imageData.lengthInBytes - 4), 0x00000000);
});
}
/// Returns a File handle to a file in the skia/resources directory.
File _getSkiaResource(String fileName) {
// As Platform.script is not working for flutter_tester
// (https://github.com/flutter/flutter/issues/12847), this is currently
// assuming the curent working directory is engine/src.
// This is fragile and should be changed once the Platform.script issue is
// resolved.
final String assetPath = path.join(
'flutter', 'third_party', 'skia', 'resources', 'images', fileName,
);
return File(assetPath);
}
| engine/testing/dart/codec_test.dart/0 | {
"file_path": "engine/testing/dart/codec_test.dart",
"repo_id": "engine",
"token_count": 3755
} | 527 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('Image constructor and dispose invokes onCreate once', () async {
// We test constructor and dispose in one test because
// litetest runs the tests in parallel and static handlers
// are shared between tests.
int onCreateInvokedCount = 0;
Image? createdImage;
int onDisposeInvokedCount = 0;
Image? disposedImage;
Image.onCreate = (Image image) {
onCreateInvokedCount++;
createdImage = image;
};
Image.onDispose = (Image image) {
onDisposeInvokedCount++;
disposedImage = image;
};
final Image image1 = await _createImage()..dispose();
expect(onCreateInvokedCount, 1);
expect(createdImage, image1);
expect(onDisposeInvokedCount, 1);
expect(disposedImage, image1);
final Image image2 = await _createImage()..dispose();
expect(onCreateInvokedCount, 2);
expect(createdImage, image2);
expect(onDisposeInvokedCount, 2);
expect(disposedImage, image2);
Image.onCreate = null;
Image.onDispose = null;
});
}
Future<Image> _createImage() => _createPicture().toImage(10, 10);
Picture _createPicture() {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0);
canvas.clipRect(rect);
return recorder.endRecording();
}
| engine/testing/dart/image_events_test.dart/0 | {
"file_path": "engine/testing/dart/image_events_test.dart",
"repo_id": "engine",
"token_count": 545
} | 528 |
// 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:developer' as developer;
import 'dart:typed_data';
import 'dart:ui' as 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('Setting invalid directory returns an error', () async {
vms.VmService? vmService;
try {
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 String viewId = await getViewId(vmService);
dynamic error;
try {
await vmService.callMethod(
'_flutter.setAssetBundlePath',
args: <String, Object>{'viewId': viewId, 'assetDirectory': ''},
);
} catch (err) {
error = err;
}
expect(error != null, true);
} finally {
await vmService?.dispose();
}
});
test('Can return whether or not impeller is enabled', () async {
vms.VmService? vmService;
try {
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 String? isolateId = await getIsolateId(vmService);
final vms.Response response = await vmService.callServiceExtension(
'ext.ui.window.impellerEnabled',
isolateId: isolateId,
);
expect(response.json!['enabled'], impellerEnabled);
} finally {
await vmService?.dispose();
}
});
test('Reload fonts request sends font change notification', () async {
vms.VmService? vmService;
try {
final developer.ServiceProtocolInfo info =
await developer.Service.getInfo();
if (info.serverUri == null) {
fail('This test must not be run with --disable-vm-service.');
}
final Completer<String> completer = Completer<String>();
ui.channelBuffers.setListener(
'flutter/system',
(ByteData? data, ui.PlatformMessageResponseCallback callback) {
final ByteBuffer buffer = data!.buffer;
final Uint8List list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
completer.complete(utf8.decode(list));
},
);
vmService = await vmServiceConnectUri(
'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws',
);
final String viewId = await getViewId(vmService);
final vms.Response fontChangeResponse = await vmService.callMethod(
'_flutter.reloadAssetFonts',
args: <String, Object>{'viewId': viewId},
);
expect(fontChangeResponse.type, 'Success');
expect(
await completer.future,
'{"type":"fontsChange"}',
);
} finally {
await vmService?.dispose();
ui.channelBuffers.clearListener('flutter/system');
}
});
}
Future<String> getViewId(vms.VmService vmService) async {
final vms.Response response = await vmService.callMethod('_flutter.listViews');
final List<Object?>? rawViews = response.json!['views'] as List<Object?>?;
return (rawViews![0]! as Map<String, Object?>?)!['id']! as String;
}
Future<String?> getIsolateId(vms.VmService vmService) async {
final vms.VM vm = await vmService.getVM();
for (final vms.IsolateRef isolate in vm.isolates!) {
if (isolate.isSystemIsolate ?? false) {
continue;
}
return isolate.id;
}
return null;
}
| engine/testing/dart/observatory/vmservice_methods_test.dart/0 | {
"file_path": "engine/testing/dart/observatory/vmservice_methods_test.dart",
"repo_id": "engine",
"token_count": 1580
} | 529 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ffi';
import 'dart:isolate';
import 'dart:ui';
import 'package:ffi/ffi.dart';
import 'package:litetest/litetest.dart';
// This import is used in a test, but not in a way that the analyzer can understand.
// ignore: unused_import
import 'spawn_helper.dart';
@Native<Handle Function(Pointer<Utf8>)>(symbol: 'LoadLibraryFromKernel')
external Object _loadLibraryFromKernel(Pointer<Utf8> path);
@Native<Handle Function(Pointer<Utf8>, Pointer<Utf8>)>(symbol: 'LookupEntryPoint')
external Object _lookupEntryPoint(Pointer<Utf8> library, Pointer<Utf8> name);
@Native<Void Function(Pointer<Utf8>, Pointer<Utf8>)>(symbol: 'Spawn')
external void _spawn(Pointer<Utf8> entrypoint, Pointer<Utf8> route);
void spawn({
required SendPort port,
String entrypoint = 'main',
String route = '/',
}) {
assert(
entrypoint != 'main' || route != '/',
'Spawn should not be used to spawn main with the default route name',
);
IsolateNameServer.registerPortWithName(port, route);
final Pointer<Utf8> nativeEntrypoint = entrypoint.toNativeUtf8();
final Pointer<Utf8> nativeRoute = route.toNativeUtf8();
_spawn(nativeEntrypoint, nativeRoute);
malloc.free(nativeEntrypoint);
malloc.free(nativeRoute);
}
const String kTestEntrypointRouteName = 'testEntrypoint';
@pragma('vm:entry-point')
void testEntrypoint() {
expect(PlatformDispatcher.instance.defaultRouteName, kTestEntrypointRouteName);
IsolateNameServer.lookupPortByName(kTestEntrypointRouteName)!.send(null);
}
void main() {
const bool kReleaseMode = bool.fromEnvironment('dart.vm.product');
const bool kProfileMode = bool.fromEnvironment('dart.vm.profile');
test('Spawn a different entrypoint with a special route name', () async {
final ReceivePort port = ReceivePort();
spawn(port: port.sendPort, entrypoint: 'testEntrypoint', route: kTestEntrypointRouteName);
expect(await port.first, isNull);
port.close();
});
test('Lookup entrypoint and execute', () {
final Pointer<Utf8> libraryPath = 'file://${const String.fromEnvironment('kFlutterSrcDirectory')}/testing/dart/spawn_helper.dart'.toNativeUtf8();
final Pointer<Utf8> entryPoint = 'echoInt'.toNativeUtf8();
expect(
(_lookupEntryPoint(
libraryPath,
entryPoint,
) as int Function(int))(42),
42,
);
malloc.free(libraryPath);
malloc.free(entryPoint);
});
test('Load from kernel', () {
final Pointer<Utf8> kernelPath = '${const String.fromEnvironment('kFlutterBuildDirectory')}/spawn_helper.dart.dill'.toNativeUtf8();
expect(
_loadLibraryFromKernel(kernelPath) is void Function(),
true,
);
malloc.free(kernelPath);
final Pointer<Utf8> fakePath = 'fake-path'.toNativeUtf8();
expect(_loadLibraryFromKernel(fakePath), null);
malloc.free(fakePath);
}, skip: kProfileMode || kReleaseMode); // ignore: avoid_redundant_argument_values
}
| engine/testing/dart/spawn_test.dart/0 | {
"file_path": "engine/testing/dart/spawn_test.dart",
"repo_id": "engine",
"token_count": 1063
} | 530 |
// 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_FIXTURE_TEST_H_
#define FLUTTER_TESTING_FIXTURE_TEST_H_
#include "flutter/testing/dart_fixture.h"
namespace flutter {
namespace testing {
class FixtureTest : public DartFixture, public ThreadTest {
public:
// Uses the default filenames from the fixtures generator.
FixtureTest();
// Allows to customize the kernel, ELF and split ELF filenames.
FixtureTest(std::string kernel_filename,
std::string elf_filename,
std::string elf_split_filename);
private:
FML_DISALLOW_COPY_AND_ASSIGN(FixtureTest);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_TESTING_FIXTURE_TEST_H_
| engine/testing/fixture_test.h/0 | {
"file_path": "engine/testing/fixture_test.h",
"repo_id": "engine",
"token_count": 292
} | 531 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
| engine/testing/ios/IosUnitTests/Tests/Info.plist/0 | {
"file_path": "engine/testing/ios/IosUnitTests/Tests/Info.plist",
"repo_id": "engine",
"token_count": 303
} | 532 |
#!/bin/bash
set -o pipefail -e;
BUILD_VARIANT="${1:-host_debug_unopt}"
CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
python3 "${CURRENT_DIR}/run_tests.py" --variant="${BUILD_VARIANT}" --type=engine,dart,benchmarks
# This does not run the web_ui tests. To run those, use:
# lib/web_ui/dev/felt test
| engine/testing/run_tests.sh/0 | {
"file_path": "engine/testing/run_tests.sh",
"repo_id": "engine",
"token_count": 147
} | 533 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.scenariosui;
import static org.junit.Assert.*;
import android.content.Intent;
import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import dev.flutter.scenarios.GetBitmapActivity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class GetBitmapTests {
@Rule @NonNull
public ActivityTestRule<GetBitmapActivity> activityRule =
new ActivityTestRule<>(
GetBitmapActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false);
@Test
public void getBitmap() throws Exception {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.putExtra("scenario_name", "get_bitmap");
GetBitmapActivity activity = activityRule.launchActivity(intent);
Bitmap bitmap = activity.getBitmap();
assertEquals(bitmap.getPixel(10, 10), 0xFFFF0000);
assertEquals(bitmap.getPixel(10, bitmap.getHeight() - 10), 0xFF0000FF);
}
}
| engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/GetBitmapTests.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/GetBitmapTests.java",
"repo_id": "engine",
"token_count": 421
} | 534 |
// 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 androidx.annotation.NonNull;
import io.flutter.embedding.engine.FlutterEngine;
public class PlatformViewsActivity extends TestActivity {
// WARNING: These strings must all be exactly the same length to avoid
// breaking the 'create' method's manual encoding in the test. See the
// TODO(stuartmorgan) about encoding alignment in platform_view.dart
public static final String TEXT_VIEW_PV = "scenarios/textPlatformView";
public static final String SURFACE_VIEW_PV = "scenarios/surfacePlatformV";
public static final String SURFACE_VIEW_BAD_CONTEXT_PV = "scenarios/surfaceVBadCntxt";
public static final String TEXTURE_VIEW_PV = "scenarios/texturePlatformV";
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
flutterEngine
.getPlatformViewsController()
.getRegistry()
.registerViewFactory(TEXT_VIEW_PV, new TextPlatformViewFactory());
flutterEngine
.getPlatformViewsController()
.getRegistry()
.registerViewFactory(SURFACE_VIEW_PV, new SurfacePlatformViewFactory(true));
flutterEngine
.getPlatformViewsController()
.getRegistry()
.registerViewFactory(SURFACE_VIEW_BAD_CONTEXT_PV, new SurfacePlatformViewFactory(false));
flutterEngine
.getPlatformViewsController()
.getRegistry()
.registerViewFactory(TEXTURE_VIEW_PV, new TexturePlatformViewFactory());
}
}
| engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/PlatformViewsActivity.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/PlatformViewsActivity.java",
"repo_id": "engine",
"token_count": 551
} | 535 |
org.gradle.jvmargs=-Xmx2048M
android.useAndroidX=true
android.enableJetifier=true
android.builder.sdkDownload=false
| engine/testing/scenario_app/android/gradle.properties/0 | {
"file_path": "engine/testing/scenario_app/android/gradle.properties",
"repo_id": "engine",
"token_count": 41
} | 536 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_TESTING_SCENARIO_APP_IOS_FLUTTERAPPEXTENSIONTESTHOST_FLUTTERAPPEXTENSIONTESTHOST_APPDELEGATE_H_
#define FLUTTER_TESTING_SCENARIO_APP_IOS_FLUTTERAPPEXTENSIONTESTHOST_FLUTTERAPPEXTENSIONTESTHOST_APPDELEGATE_H_
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@end
#endif // FLUTTER_TESTING_SCENARIO_APP_IOS_FLUTTERAPPEXTENSIONTESTHOST_FLUTTERAPPEXTENSIONTESTHOST_APPDELEGATE_H_
| engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/AppDelegate.h/0 | {
"file_path": "engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/AppDelegate.h",
"repo_id": "engine",
"token_count": 246
} | 537 |
//
// Generated file. Do not edit.
//
// clang-format off
#import "GeneratedPluginRegistrant.h"
@implementation GeneratedPluginRegistrant
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry {
}
@end
| engine/testing/scenario_app/ios/Runner/GeneratedPluginRegistrant.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Runner/GeneratedPluginRegistrant.m",
"repo_id": "engine",
"token_count": 78
} | 538 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_FLUTTERENGINE_SCENARIOSTEST_H_
#define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_FLUTTERENGINE_SCENARIOSTEST_H_
#import <Flutter/Flutter.h>
NS_ASSUME_NONNULL_BEGIN
@interface FlutterEngine (ScenariosTest)
- (instancetype)initWithScenario:(NSString*)scenario
withCompletion:(nullable void (^)(void))engineRunCompletion;
- (FlutterEngine*)spawnWithEntrypoint:(nullable NSString*)entrypoint
libraryURI:(nullable NSString*)libraryURI
initialRoute:(nullable NSString*)initialRoute
entrypointArgs:(nullable NSArray<NSString*>*)entrypointArgs;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_FLUTTERENGINE_SCENARIOSTEST_H_
| engine/testing/scenario_app/ios/Scenarios/Scenarios/FlutterEngine+ScenariosTest.h/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/FlutterEngine+ScenariosTest.h",
"repo_id": "engine",
"token_count": 422
} | 539 |
// 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>
#import "AppDelegate.h"
FLUTTER_ASSERT_ARC
@interface FlutterViewControllerTest : XCTestCase
@property(nonatomic, strong) FlutterViewController* flutterViewController;
@end
@implementation FlutterViewControllerTest
- (void)setUp {
[super setUp];
self.continueAfterFailure = NO;
}
- (void)tearDown {
if (self.flutterViewController) {
XCTestExpectation* vcDismissed = [self expectationWithDescription:@"dismiss"];
[self.flutterViewController dismissViewControllerAnimated:NO
completion:^{
[vcDismissed fulfill];
}];
[self waitForExpectationsWithTimeout:10.0 handler:nil];
}
[super tearDown];
}
- (void)testFirstFrameCallback {
XCTestExpectation* firstFrameRendered = [self expectationWithDescription:@"firstFrameRendered"];
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
self.flutterViewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
XCTAssertFalse(self.flutterViewController.isDisplayingFlutterUI);
XCTestExpectation* displayingFlutterUIExpectation =
[self keyValueObservingExpectationForObject:self.flutterViewController
keyPath:@"displayingFlutterUI"
expectedValue:@YES];
displayingFlutterUIExpectation.assertForOverFulfill = YES;
[self.flutterViewController setFlutterViewDidRenderCallback:^{
[firstFrameRendered fulfill];
}];
AppDelegate* appDelegate = (AppDelegate*)UIApplication.sharedApplication.delegate;
UIViewController* rootVC = appDelegate.window.rootViewController;
[rootVC presentViewController:self.flutterViewController animated:NO completion:nil];
[self waitForExpectationsWithTimeout:30.0 handler:nil];
}
- (void)testDrawLayer {
XCTestExpectation* firstFrameRendered = [self expectationWithDescription:@"firstFrameRendered"];
XCTestExpectation* imageRendered = [self expectationWithDescription:@"imageRendered"];
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
[engine.binaryMessenger
setMessageHandlerOnChannel:@"waiting_for_status"
binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply _Nonnull reply) {
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:@"driver"
binaryMessenger:engine.binaryMessenger
codec:[FlutterJSONMethodCodec sharedInstance]];
[channel invokeMethod:@"set_scenario" arguments:@{@"name" : @"solid_blue"}];
}];
self.flutterViewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
XCTAssertFalse(self.flutterViewController.isDisplayingFlutterUI);
[self.flutterViewController setFlutterViewDidRenderCallback:^{
[firstFrameRendered fulfill];
}];
AppDelegate* appDelegate = (AppDelegate*)UIApplication.sharedApplication.delegate;
UIViewController* rootVC = appDelegate.window.rootViewController;
[rootVC presentViewController:self.flutterViewController animated:NO completion:nil];
CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
__block dispatch_block_t callback;
callback = ^{
size_t width = 300u;
CGContextRef context =
CGBitmapContextCreate(nil, width, width, 8, 4 * width, color_space,
kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
[appDelegate.window.layer renderInContext:context];
uint32_t* image_data = (uint32_t*)CGBitmapContextGetData(context);
if (image_data[20] == 0xFF0000FF) {
[imageRendered fulfill];
return;
}
CGContextRelease(context);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(),
callback);
};
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(),
callback);
[self waitForExpectationsWithTimeout:30.0 handler:nil];
CGColorSpaceRelease(color_space);
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterViewControllerTest.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterViewControllerTest.m",
"repo_id": "engine",
"token_count": 2011
} | 540 |
# Golden UI Tests
This folder contains golden image tests. It renders UI (for instance, a platform
view) and does a screen shot comparison against a known good configuration.
The screen shots are named `golden_[scenario name]_[MODEL]`, with `_simulator`
appended for simulators. The model numbers for physical devices correspond
to the `hw.model` sys call, and will represent the model numbers. Simulator
names are taken from the environment.
New devices require running the test on the device, gathering the attachment
from the test result and verifying it manually. Then adding an appropriately
named file to this folder.
If the test is attempted on a new device, the log will contain a message
indicating the file name it expected to find. The test will continue and fail,
but will contain an attachment with the expected screen shot. If the screen
shot looks good, add it with the correct name to the project and run the test
again - it should pass this time.
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/README.md/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/README.md",
"repo_id": "engine",
"token_count": 222
} | 541 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'scenario.dart';
/// Fills the screen with a solid blue color.
class SolidBlueScenario extends Scenario {
/// Creates the SolidBlue scenario.
SolidBlueScenario(super.view);
@override
void onBeginFrame(Duration duration) {
final SceneBuilder builder = SceneBuilder();
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawPaint(Paint()..color = const Color(0xFF0000FF));
final Picture picture = recorder.endRecording();
builder.addPicture(
Offset.zero,
picture,
willChangeHint: true,
);
final Scene scene = builder.build();
view.render(scene);
scene.dispose();
}
}
| engine/testing/scenario_app/lib/src/solid_blue.dart/0 | {
"file_path": "engine/testing/scenario_app/lib/src/solid_blue.dart",
"repo_id": "engine",
"token_count": 282
} | 542 |
// 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:engine_repo_tools/engine_repo_tools.dart';
import 'package:path/path.dart' as path;
import 'package:skia_gold_client/skia_gold_client.dart';
/// An E2E test for the Skia Gold client.
///
/// Attempts to answer the question: "Does the Skia Gold client, and our custom
/// integration with it (GitHub, LUCI, etc), work as expected?" in an automated
/// way.
///
/// In a sibling directory, `e2e_fixtures`, there are static (checked-in) files
/// that represent (fake) generated output to be uploaded and verified by the
/// Skia Gold client. This test, when run on CI, will use these fixtures to
/// simulate the process of uploading and verifying real output.
///
/// For example, try changing the contents of a fixture file, and then uploading
/// a PR with this change. The CI will run this test, and it should fail (on
/// pre-submit), since the fixture file no longer matches the expected output.
///
/// Next, after the PR is merged, the CI will run this test again, and it should
/// pass (on post-submit), since the fixture file now matches the expected
/// output.
///
/// There are also tests for the "dimensions" feature of the Skia Gold client,
/// which live in `e2e_fixtures/dimensions`. These tests are similar to the
/// regular tests, but experiment with different fake dimensions to ensure that
/// our CI environment is correctly handling this feature.
void main() async {
// If the client is not available, we can't run the test.
if (!SkiaGoldClient.isAvailable()) {
stderr.writeln('Skia gold is unavailable in this environment.');
exitCode = 1;
return;
}
// If we're not in an engine repo, we can't run the test.
final Engine? engine = Engine.tryFindWithin();
if (engine == null) {
stderr.writeln('Must run within the engine repo.');
exitCode = 1;
return;
}
// Create a client.
final SkiaGoldClient skiaGoldClient = SkiaGoldClient(
engine.flutterDir,
);
// Authenticate the client.
await skiaGoldClient.auth();
const String prefix = 'SkiaGoldClientE2ETest';
const List<_Digest> digests = <_Digest>[
_Digest(
name: '${prefix}_SolidBlueSquare',
source: 'e2e_fixtures/solid_blue_square.png',
pixelCount: 512 * 512,
),
_Digest(
name: '${prefix}_SolidRedSquare',
source: 'e2e_fixtures/solid_red_square.png',
pixelCount: 768 * 768,
),
_Digest(
name: '${prefix}_SolidGreenSquare',
source: 'e2e_fixtures/solid_green_square.png',
pixelCount: 1200 * 1200,
),
];
// Upload the digests to Skia Gold.
final Set<_Digest> comparisonsFailed = <_Digest>{};
for (final _Digest digest in digests) {
final String digestPath = digest.source;
final String digestName = digest.name;
final File digestFile = File(path.join(
engine.flutterDir.path,
'testing',
'skia_gold_client',
'tool',
digestPath,
));
if (!digestFile.existsSync()) {
stderr.writeln('The digest file "$digestPath" does not exist.');
exitCode = 1;
return;
}
print('Uploading digest: $digestName ($digestPath): ${digest.pixelCount} pixels...');
try {
await skiaGoldClient.addImg(
digestName,
digestFile,
screenshotSize: 0,
);
stderr.writeln('Comparison success: $digestName');
} on Exception catch (e) {
stderr.writeln('Comparison failure: $digestName: $e');
comparisonsFailed.add(digest);
}
}
if (comparisonsFailed.isNotEmpty) {
stdout.writeln('${comparisonsFailed.length} digest(s) failed.');
for (final _Digest digest in comparisonsFailed) {
stderr.writeln(' ${digest.name} (${digest.source})');
}
exitCode = 1;
return;
}
}
final class _Digest {
const _Digest({
required this.name,
required this.source,
required this.pixelCount,
});
/// The name of the digest/test.
final String name;
/// The source of the digest (e.g. the path to the image file).
final String source;
/// The number of pixels in the image.
final int pixelCount;
@override
int get hashCode => source.hashCode;
@override
bool operator ==(Object other) {
return other is _Digest && other.source == source;
}
}
| engine/testing/skia_gold_client/tool/e2e_test.dart/0 | {
"file_path": "engine/testing/skia_gold_client/tool/e2e_test.dart",
"repo_id": "engine",
"token_count": 1522
} | 543 |
// 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_gl_surface.h"
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <EGL/eglplatform.h>
#include <GLES2/gl2.h>
#include <sstream>
#include <string>
#include "flutter/fml/build_config.h"
#include "flutter/fml/logging.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkColorType.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h"
#include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h"
#include "third_party/skia/include/gpu/ganesh/gl/GrGLDirectContext.h"
#include "third_party/skia/include/gpu/gl/GrGLAssembleInterface.h"
#include "third_party/skia/include/gpu/gl/GrGLTypes.h"
namespace flutter {
namespace testing {
static std::string GetEGLError() {
std::stringstream stream;
auto error = ::eglGetError();
stream << "EGL Result: '";
switch (error) {
case EGL_SUCCESS:
stream << "EGL_SUCCESS";
break;
case EGL_NOT_INITIALIZED:
stream << "EGL_NOT_INITIALIZED";
break;
case EGL_BAD_ACCESS:
stream << "EGL_BAD_ACCESS";
break;
case EGL_BAD_ALLOC:
stream << "EGL_BAD_ALLOC";
break;
case EGL_BAD_ATTRIBUTE:
stream << "EGL_BAD_ATTRIBUTE";
break;
case EGL_BAD_CONTEXT:
stream << "EGL_BAD_CONTEXT";
break;
case EGL_BAD_CONFIG:
stream << "EGL_BAD_CONFIG";
break;
case EGL_BAD_CURRENT_SURFACE:
stream << "EGL_BAD_CURRENT_SURFACE";
break;
case EGL_BAD_DISPLAY:
stream << "EGL_BAD_DISPLAY";
break;
case EGL_BAD_SURFACE:
stream << "EGL_BAD_SURFACE";
break;
case EGL_BAD_MATCH:
stream << "EGL_BAD_MATCH";
break;
case EGL_BAD_PARAMETER:
stream << "EGL_BAD_PARAMETER";
break;
case EGL_BAD_NATIVE_PIXMAP:
stream << "EGL_BAD_NATIVE_PIXMAP";
break;
case EGL_BAD_NATIVE_WINDOW:
stream << "EGL_BAD_NATIVE_WINDOW";
break;
case EGL_CONTEXT_LOST:
stream << "EGL_CONTEXT_LOST";
break;
default:
stream << "Unknown";
}
stream << "' (0x" << std::hex << error << std::dec << ").";
return stream.str();
}
static bool HasExtension(const char* extensions, const char* name) {
const char* r = strstr(extensions, name);
auto len = strlen(name);
// check that the extension name is terminated by space or null terminator
return r != nullptr && (r[len] == ' ' || r[len] == 0);
}
static void CheckSwanglekExtensions() {
const char* extensions = ::eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
FML_CHECK(HasExtension(extensions, "EGL_EXT_platform_base")) << extensions;
FML_CHECK(HasExtension(extensions, "EGL_ANGLE_platform_angle_vulkan"))
<< extensions;
FML_CHECK(HasExtension(extensions,
"EGL_ANGLE_platform_angle_device_type_swiftshader"))
<< extensions;
}
static EGLDisplay CreateSwangleDisplay() {
CheckSwanglekExtensions();
PFNEGLGETPLATFORMDISPLAYEXTPROC egl_get_platform_display_EXT =
reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(
eglGetProcAddress("eglGetPlatformDisplayEXT"));
FML_CHECK(egl_get_platform_display_EXT)
<< "eglGetPlatformDisplayEXT not available.";
const EGLint display_config[] = {
EGL_PLATFORM_ANGLE_TYPE_ANGLE,
EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE,
EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
EGL_PLATFORM_ANGLE_DEVICE_TYPE_SWIFTSHADER_ANGLE,
EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE,
EGL_PLATFORM_VULKAN_DISPLAY_MODE_HEADLESS_ANGLE,
EGL_NONE,
};
return egl_get_platform_display_EXT(
EGL_PLATFORM_ANGLE_ANGLE,
reinterpret_cast<EGLNativeDisplayType*>(EGL_DEFAULT_DISPLAY),
display_config);
}
TestGLSurface::TestGLSurface(SkISize surface_size)
: surface_size_(surface_size) {
display_ = CreateSwangleDisplay();
FML_CHECK(display_ != EGL_NO_DISPLAY);
auto result = ::eglInitialize(display_, nullptr, nullptr);
FML_CHECK(result == EGL_TRUE) << GetEGLError();
EGLConfig config = {0};
EGLint num_config = 0;
const EGLint attribute_list[] = {EGL_RED_SIZE,
8,
EGL_GREEN_SIZE,
8,
EGL_BLUE_SIZE,
8,
EGL_ALPHA_SIZE,
8,
EGL_SURFACE_TYPE,
EGL_PBUFFER_BIT,
EGL_CONFORMANT,
EGL_OPENGL_ES2_BIT,
EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES2_BIT,
EGL_NONE};
result = ::eglChooseConfig(display_, attribute_list, &config, 1, &num_config);
FML_CHECK(result == EGL_TRUE) << GetEGLError();
FML_CHECK(num_config == 1) << GetEGLError();
{
const EGLint onscreen_surface_attributes[] = {
EGL_WIDTH, surface_size_.width(), //
EGL_HEIGHT, surface_size_.height(), //
EGL_NONE,
};
onscreen_surface_ = ::eglCreatePbufferSurface(
display_, // display connection
config, // config
onscreen_surface_attributes // surface attributes
);
FML_CHECK(onscreen_surface_ != EGL_NO_SURFACE) << GetEGLError();
}
{
const EGLint offscreen_surface_attributes[] = {
EGL_WIDTH, 1, //
EGL_HEIGHT, 1, //
EGL_NONE,
};
offscreen_surface_ = ::eglCreatePbufferSurface(
display_, // display connection
config, // config
offscreen_surface_attributes // surface attributes
);
FML_CHECK(offscreen_surface_ != EGL_NO_SURFACE) << GetEGLError();
}
{
const EGLint context_attributes[] = {
EGL_CONTEXT_CLIENT_VERSION, //
2, //
EGL_NONE //
};
onscreen_context_ =
::eglCreateContext(display_, // display connection
config, // config
EGL_NO_CONTEXT, // sharegroup
context_attributes // context attributes
);
FML_CHECK(onscreen_context_ != EGL_NO_CONTEXT) << GetEGLError();
offscreen_context_ =
::eglCreateContext(display_, // display connection
config, // config
onscreen_context_, // sharegroup
context_attributes // context attributes
);
FML_CHECK(offscreen_context_ != EGL_NO_CONTEXT) << GetEGLError();
}
}
TestGLSurface::~TestGLSurface() {
context_ = nullptr;
auto result = ::eglDestroyContext(display_, onscreen_context_);
FML_CHECK(result == EGL_TRUE) << GetEGLError();
result = ::eglDestroyContext(display_, offscreen_context_);
FML_CHECK(result == EGL_TRUE) << GetEGLError();
result = ::eglDestroySurface(display_, onscreen_surface_);
FML_CHECK(result == EGL_TRUE) << GetEGLError();
result = ::eglDestroySurface(display_, offscreen_surface_);
FML_CHECK(result == EGL_TRUE) << GetEGLError();
result = ::eglTerminate(display_);
FML_CHECK(result == EGL_TRUE);
}
const SkISize& TestGLSurface::GetSurfaceSize() const {
return surface_size_;
}
bool TestGLSurface::MakeCurrent() {
auto result = ::eglMakeCurrent(display_, onscreen_surface_, onscreen_surface_,
onscreen_context_);
if (result == EGL_FALSE) {
FML_LOG(ERROR) << "Could not make the context current. " << GetEGLError();
}
return result == EGL_TRUE;
}
bool TestGLSurface::ClearCurrent() {
auto result = ::eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT);
if (result == EGL_FALSE) {
FML_LOG(ERROR) << "Could not clear the current context. " << GetEGLError();
}
return result == EGL_TRUE;
}
bool TestGLSurface::Present() {
auto result = ::eglSwapBuffers(display_, onscreen_surface_);
if (result == EGL_FALSE) {
FML_LOG(ERROR) << "Could not swap buffers. " << GetEGLError();
}
return result == EGL_TRUE;
}
uint32_t TestGLSurface::GetFramebuffer(uint32_t width, uint32_t height) const {
return GetWindowFBOId();
}
bool TestGLSurface::MakeResourceCurrent() {
auto result = ::eglMakeCurrent(display_, offscreen_surface_,
offscreen_surface_, offscreen_context_);
if (result == EGL_FALSE) {
FML_LOG(ERROR) << "Could not make the resource context current. "
<< GetEGLError();
}
return result == EGL_TRUE;
}
void* TestGLSurface::GetProcAddress(const char* name) const {
if (name == nullptr) {
return nullptr;
}
auto symbol = ::eglGetProcAddress(name);
if (symbol == NULL) {
FML_LOG(ERROR) << "Could not fetch symbol for name: " << name;
}
return reinterpret_cast<void*>(symbol);
}
sk_sp<GrDirectContext> TestGLSurface::GetGrContext() {
if (context_) {
return context_;
}
return CreateGrContext();
}
sk_sp<GrDirectContext> TestGLSurface::CreateGrContext() {
if (!MakeCurrent()) {
return nullptr;
}
auto get_string =
reinterpret_cast<PFNGLGETSTRINGPROC>(GetProcAddress("glGetString"));
if (!get_string) {
return nullptr;
}
auto c_version = reinterpret_cast<const char*>(get_string(GL_VERSION));
if (c_version == NULL) {
return nullptr;
}
GrGLGetProc get_proc = [](void* context, const char name[]) -> GrGLFuncPtr {
return reinterpret_cast<GrGLFuncPtr>(
reinterpret_cast<TestGLSurface*>(context)->GetProcAddress(name));
};
std::string version(c_version);
auto interface = version.find("OpenGL ES") == std::string::npos
? GrGLMakeAssembledGLInterface(this, get_proc)
: GrGLMakeAssembledGLESInterface(this, get_proc);
if (!interface) {
return nullptr;
}
context_ = GrDirectContexts::MakeGL(interface);
return context_;
}
sk_sp<SkSurface> TestGLSurface::GetOnscreenSurface() {
FML_CHECK(::eglGetCurrentContext() != EGL_NO_CONTEXT);
GrGLFramebufferInfo framebuffer_info = {};
const uint32_t width = surface_size_.width();
const uint32_t height = surface_size_.height();
framebuffer_info.fFBOID = GetFramebuffer(width, height);
#if FML_OS_MACOSX
framebuffer_info.fFormat = 0x8058; // GL_RGBA8
#else
framebuffer_info.fFormat = 0x93A1; // GL_BGRA8;
#endif
auto backend_render_target =
GrBackendRenderTargets::MakeGL(width, // width
height, // height
1, // sample count
8, // stencil bits
framebuffer_info // framebuffer info
);
SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
auto surface = SkSurfaces::WrapBackendRenderTarget(
GetGrContext().get(), // context
backend_render_target, // backend render target
kBottomLeft_GrSurfaceOrigin, // surface origin
kN32_SkColorType, // color type
SkColorSpace::MakeSRGB(), // color space
&surface_properties, // surface properties
nullptr, // release proc
nullptr // release context
);
if (!surface) {
FML_LOG(ERROR) << "Could not wrap the surface while attempting to "
"snapshot the GL surface.";
return nullptr;
}
return surface;
}
sk_sp<SkImage> TestGLSurface::GetRasterSurfaceSnapshot() {
auto surface = GetOnscreenSurface();
if (!surface) {
FML_LOG(ERROR) << "Aborting snapshot because of on-screen surface "
"acquisition failure.";
return nullptr;
}
auto device_snapshot = surface->makeImageSnapshot();
if (!device_snapshot) {
FML_LOG(ERROR) << "Could not create the device snapshot while attempting "
"to snapshot the GL surface.";
return nullptr;
}
auto host_snapshot = device_snapshot->makeRasterImage();
if (!host_snapshot) {
FML_LOG(ERROR) << "Could not create the host snapshot while attempting to "
"snapshot the GL surface.";
return nullptr;
}
return host_snapshot;
}
uint32_t TestGLSurface::GetWindowFBOId() const {
return 0u;
}
} // namespace testing
} // namespace flutter
| engine/testing/test_gl_surface.cc/0 | {
"file_path": "engine/testing/test_gl_surface.cc",
"repo_id": "engine",
"token_count": 5946
} | 544 |
// 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_VULKAN_SURFACE_H_
#define FLUTTER_TESTING_TEST_VULKAN_SURFACE_H_
#include <memory>
#include "flutter/testing/test_vulkan_context.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
namespace flutter {
namespace testing {
class TestVulkanSurface {
public:
static std::unique_ptr<TestVulkanSurface> Create(
const TestVulkanContext& context,
const SkISize& surface_size);
bool IsValid() const;
sk_sp<SkImage> GetSurfaceSnapshot() const;
VkImage GetImage();
private:
explicit TestVulkanSurface(TestVulkanImage&& image);
TestVulkanImage image_;
sk_sp<SkSurface> surface_;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_TESTING_TEST_VULKAN_SURFACE_H_
| engine/testing/test_vulkan_surface.h/0 | {
"file_path": "engine/testing/test_vulkan_surface.h",
"repo_id": "engine",
"token_count": 393
} | 545 |
// 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.
#include "ax_action_data.h"
#include "ax_enums.h"
namespace ui {
AXActionData::AXActionData()
: action(ax::mojom::Action::kNone),
hit_test_event_to_fire(ax::mojom::Event::kNone),
horizontal_scroll_alignment(ax::mojom::ScrollAlignment::kNone),
vertical_scroll_alignment(ax::mojom::ScrollAlignment::kNone),
scroll_behavior(ax::mojom::ScrollBehavior::kNone) {}
AXActionData::AXActionData(const AXActionData& other) = default;
AXActionData::~AXActionData() = default;
} // namespace ui
| engine/third_party/accessibility/ax/ax_action_data.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_action_data.cc",
"repo_id": "engine",
"token_count": 245
} | 546 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax_event_generator.h"
#include <algorithm>
#include "ax_enums.h"
#include "ax_node.h"
#include "ax_role_properties.h"
#include "base/container_utils.h"
namespace ui {
namespace {
bool IsActiveLiveRegion(const AXTreeObserver::Change& change) {
return change.node->data().HasStringAttribute(
ax::mojom::StringAttribute::kLiveStatus) &&
change.node->data().GetStringAttribute(
ax::mojom::StringAttribute::kLiveStatus) != "off";
}
bool IsContainedInLiveRegion(const AXTreeObserver::Change& change) {
return change.node->data().HasStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus) &&
change.node->data().HasStringAttribute(
ax::mojom::StringAttribute::kName);
}
bool HasEvent(const std::set<AXEventGenerator::EventParams>& node_events,
AXEventGenerator::Event event) {
for (auto& iter : node_events) {
if (iter.event == event)
return true;
}
return false;
}
void RemoveEvent(std::set<AXEventGenerator::EventParams>* node_events,
AXEventGenerator::Event event) {
for (auto& iter : *node_events) {
if (iter.event == event) {
node_events->erase(iter);
return;
}
}
}
// If a node toggled its ignored state, don't also fire children-changed because
// platforms likely will do that in response to ignored-changed.
// Suppress name- and description-changed because those can be emitted as a side
// effect of calculating alternative text values for a newly-displayed object.
// Ditto for text attributes such as foreground and background colors, or
// display changing from "none" to "block."
void RemoveEventsDueToIgnoredChanged(
std::set<AXEventGenerator::EventParams>* node_events) {
RemoveEvent(node_events,
AXEventGenerator::Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED);
RemoveEvent(node_events, AXEventGenerator::Event::CHILDREN_CHANGED);
RemoveEvent(node_events, AXEventGenerator::Event::DESCRIPTION_CHANGED);
RemoveEvent(node_events, AXEventGenerator::Event::NAME_CHANGED);
RemoveEvent(node_events, AXEventGenerator::Event::OBJECT_ATTRIBUTE_CHANGED);
RemoveEvent(node_events, AXEventGenerator::Event::SORT_CHANGED);
RemoveEvent(node_events, AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED);
RemoveEvent(node_events,
AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED);
}
// Add a particular AXEventGenerator::IgnoredChangedState to
// |ignored_changed_states|.
void AddIgnoredChangedState(
AXEventGenerator::IgnoredChangedStatesBitset& ignored_changed_states,
AXEventGenerator::IgnoredChangedState state) {
ignored_changed_states.set(static_cast<size_t>(state));
}
// Returns true if |ignored_changed_states| contains a particular
// AXEventGenerator::IgnoredChangedState.
bool HasIgnoredChangedState(
AXEventGenerator::IgnoredChangedStatesBitset& ignored_changed_states,
AXEventGenerator::IgnoredChangedState state) {
return ignored_changed_states[static_cast<size_t>(state)];
}
} // namespace
AXEventGenerator::EventParams::EventParams(
Event event,
ax::mojom::EventFrom event_from,
const std::vector<AXEventIntent>& event_intents)
: event(event), event_from(event_from), event_intents(event_intents) {}
AXEventGenerator::EventParams::~EventParams() = default;
AXEventGenerator::TargetedEvent::TargetedEvent(AXNode* node,
const EventParams& event_params)
: node(node), event_params(event_params) {
BASE_DCHECK(node);
}
bool AXEventGenerator::EventParams::operator==(const EventParams& rhs) {
return rhs.event == event;
}
bool AXEventGenerator::EventParams::operator<(const EventParams& rhs) const {
return event < rhs.event;
}
AXEventGenerator::Iterator::Iterator(
const std::map<AXNode*, std::set<EventParams>>& map,
const std::map<AXNode*, std::set<EventParams>>::const_iterator& head)
: map_(map), map_iter_(head) {
if (map_iter_ != map.end())
set_iter_ = map_iter_->second.begin();
}
AXEventGenerator::Iterator::Iterator(const AXEventGenerator::Iterator& other) =
default;
AXEventGenerator::Iterator::~Iterator() = default;
bool AXEventGenerator::Iterator::operator!=(
const AXEventGenerator::Iterator& rhs) const {
return map_iter_ != rhs.map_iter_ ||
(map_iter_ != map_.end() && set_iter_ != rhs.set_iter_);
}
AXEventGenerator::Iterator& AXEventGenerator::Iterator::operator++() {
if (map_iter_ == map_.end())
return *this;
set_iter_++;
while (map_iter_ != map_.end() && set_iter_ == map_iter_->second.end()) {
map_iter_++;
if (map_iter_ != map_.end())
set_iter_ = map_iter_->second.begin();
}
return *this;
}
AXEventGenerator::TargetedEvent AXEventGenerator::Iterator::operator*() const {
BASE_DCHECK(map_iter_ != map_.end() && set_iter_ != map_iter_->second.end());
return AXEventGenerator::TargetedEvent(map_iter_->first, *set_iter_);
}
AXEventGenerator::AXEventGenerator() = default;
AXEventGenerator::AXEventGenerator(AXTree* tree) : tree_(tree) {
if (tree_)
tree_->AddObserver(this);
}
AXEventGenerator::~AXEventGenerator() = default;
void AXEventGenerator::SetTree(AXTree* new_tree) {
if (tree_)
tree_->RemoveObserver(this);
tree_ = new_tree;
if (tree_)
tree_->AddObserver(this);
}
void AXEventGenerator::ReleaseTree() {
tree_->RemoveObserver(this);
tree_ = nullptr;
}
void AXEventGenerator::ClearEvents() {
tree_events_.clear();
}
void AXEventGenerator::AddEvent(AXNode* node, AXEventGenerator::Event event) {
BASE_DCHECK(node);
if (node->data().role == ax::mojom::Role::kInlineTextBox)
return;
std::set<EventParams>& node_events = tree_events_[node];
node_events.emplace(event, ax::mojom::EventFrom::kNone,
tree_->event_intents());
}
void AXEventGenerator::OnNodeDataChanged(AXTree* tree,
const AXNodeData& old_node_data,
const AXNodeData& new_node_data) {
BASE_DCHECK(tree_ == tree);
// Fire CHILDREN_CHANGED events when the list of children updates.
// Internally we store inline text box nodes as children of a static text
// node or a line break node, which enables us to determine character bounds
// and line layout. We don't expose those to platform APIs, though, so
// suppress CHILDREN_CHANGED events on static text nodes.
if (new_node_data.child_ids != old_node_data.child_ids &&
!ui::IsText(new_node_data.role)) {
AXNode* node = tree_->GetFromId(new_node_data.id);
tree_events_[node].emplace(Event::CHILDREN_CHANGED,
ax::mojom::EventFrom::kNone,
tree_->event_intents());
}
}
void AXEventGenerator::OnRoleChanged(AXTree* tree,
AXNode* node,
ax::mojom::Role old_role,
ax::mojom::Role new_role) {
BASE_DCHECK(tree_ == tree);
AddEvent(node, Event::ROLE_CHANGED);
}
void AXEventGenerator::OnStateChanged(AXTree* tree,
AXNode* node,
ax::mojom::State state,
bool new_value) {
BASE_DCHECK(tree_ == tree);
if (state != ax::mojom::State::kIgnored) {
AddEvent(node, Event::STATE_CHANGED);
AddEvent(node, Event::WIN_IACCESSIBLE_STATE_CHANGED);
}
switch (state) {
case ax::mojom::State::kExpanded:
AddEvent(node, new_value ? Event::EXPANDED : Event::COLLAPSED);
if (node->data().role == ax::mojom::Role::kRow ||
node->data().role == ax::mojom::Role::kTreeItem) {
AXNode* container = node;
while (container && !IsRowContainer(container->data().role))
container = container->parent();
if (container)
AddEvent(container, Event::ROW_COUNT_CHANGED);
}
break;
case ax::mojom::State::kIgnored: {
AXNode* unignored_parent = node->GetUnignoredParent();
if (unignored_parent)
AddEvent(unignored_parent, Event::CHILDREN_CHANGED);
AddEvent(node, Event::IGNORED_CHANGED);
if (!new_value)
AddEvent(node, Event::SUBTREE_CREATED);
break;
}
case ax::mojom::State::kMultiline:
AddEvent(node, Event::MULTILINE_STATE_CHANGED);
break;
case ax::mojom::State::kMultiselectable:
AddEvent(node, Event::MULTISELECTABLE_STATE_CHANGED);
break;
case ax::mojom::State::kRequired:
AddEvent(node, Event::REQUIRED_STATE_CHANGED);
break;
default:
break;
}
}
void AXEventGenerator::OnStringAttributeChanged(AXTree* tree,
AXNode* node,
ax::mojom::StringAttribute attr,
const std::string& old_value,
const std::string& new_value) {
BASE_DCHECK(tree_ == tree);
switch (attr) {
case ax::mojom::StringAttribute::kAccessKey:
AddEvent(node, Event::ACCESS_KEY_CHANGED);
break;
case ax::mojom::StringAttribute::kAriaInvalidValue:
AddEvent(node, Event::INVALID_STATUS_CHANGED);
break;
case ax::mojom::StringAttribute::kAutoComplete:
AddEvent(node, Event::AUTO_COMPLETE_CHANGED);
break;
case ax::mojom::StringAttribute::kClassName:
AddEvent(node, Event::CLASS_NAME_CHANGED);
break;
case ax::mojom::StringAttribute::kDescription:
AddEvent(node, Event::DESCRIPTION_CHANGED);
break;
case ax::mojom::StringAttribute::kKeyShortcuts:
AddEvent(node, Event::KEY_SHORTCUTS_CHANGED);
break;
case ax::mojom::StringAttribute::kLanguage:
AddEvent(node, Event::LANGUAGE_CHANGED);
break;
case ax::mojom::StringAttribute::kLiveRelevant:
AddEvent(node, Event::LIVE_RELEVANT_CHANGED);
break;
case ax::mojom::StringAttribute::kLiveStatus:
AddEvent(node, Event::LIVE_STATUS_CHANGED);
// Fire a LIVE_REGION_CREATED if the previous value was off, and the new
// value is not-off.
if (!IsAlert(node->data().role)) {
bool old_state = !old_value.empty() && old_value != "off";
bool new_state = !new_value.empty() && new_value != "off";
if (!old_state && new_state)
AddEvent(node, Event::LIVE_REGION_CREATED);
}
break;
case ax::mojom::StringAttribute::kName:
// If the name of the root node changes, we expect OnTreeDataChanged to
// add a DOCUMENT_TITLE_CHANGED event instead.
if (node != tree->root())
AddEvent(node, Event::NAME_CHANGED);
if (node->data().HasStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus)) {
FireLiveRegionEvents(node);
}
break;
case ax::mojom::StringAttribute::kPlaceholder:
AddEvent(node, Event::PLACEHOLDER_CHANGED);
break;
case ax::mojom::StringAttribute::kValue:
AddEvent(node, Event::VALUE_CHANGED);
break;
case ax::mojom::StringAttribute::kImageAnnotation:
// The image annotation is reported as part of the accessible name.
AddEvent(node, Event::IMAGE_ANNOTATION_CHANGED);
break;
case ax::mojom::StringAttribute::kFontFamily:
AddEvent(node, Event::TEXT_ATTRIBUTE_CHANGED);
break;
default:
AddEvent(node, Event::OTHER_ATTRIBUTE_CHANGED);
break;
}
}
void AXEventGenerator::OnIntAttributeChanged(AXTree* tree,
AXNode* node,
ax::mojom::IntAttribute attr,
int32_t old_value,
int32_t new_value) {
BASE_DCHECK(tree_ == tree);
switch (attr) {
case ax::mojom::IntAttribute::kActivedescendantId:
// Don't fire on invisible containers, as it confuses some screen readers,
// such as NVDA.
if (!node->data().HasState(ax::mojom::State::kInvisible)) {
AddEvent(node, Event::ACTIVE_DESCENDANT_CHANGED);
active_descendant_changed_.push_back(node);
}
break;
case ax::mojom::IntAttribute::kCheckedState:
AddEvent(node, Event::CHECKED_STATE_CHANGED);
AddEvent(node, Event::WIN_IACCESSIBLE_STATE_CHANGED);
break;
case ax::mojom::IntAttribute::kDropeffect:
AddEvent(node, Event::DROPEFFECT_CHANGED);
break;
case ax::mojom::IntAttribute::kHasPopup:
AddEvent(node, Event::HASPOPUP_CHANGED);
AddEvent(node, Event::WIN_IACCESSIBLE_STATE_CHANGED);
break;
case ax::mojom::IntAttribute::kHierarchicalLevel:
AddEvent(node, Event::HIERARCHICAL_LEVEL_CHANGED);
break;
case ax::mojom::IntAttribute::kInvalidState:
AddEvent(node, Event::INVALID_STATUS_CHANGED);
break;
case ax::mojom::IntAttribute::kPosInSet:
AddEvent(node, Event::POSITION_IN_SET_CHANGED);
break;
case ax::mojom::IntAttribute::kRestriction: {
bool was_enabled;
bool was_readonly;
GetRestrictionStates(static_cast<ax::mojom::Restriction>(old_value),
&was_enabled, &was_readonly);
bool is_enabled;
bool is_readonly;
GetRestrictionStates(static_cast<ax::mojom::Restriction>(new_value),
&is_enabled, &is_readonly);
if (was_enabled != is_enabled) {
AddEvent(node, Event::ENABLED_CHANGED);
AddEvent(node, Event::WIN_IACCESSIBLE_STATE_CHANGED);
}
if (was_readonly != is_readonly) {
AddEvent(node, Event::READONLY_CHANGED);
AddEvent(node, Event::WIN_IACCESSIBLE_STATE_CHANGED);
}
break;
}
case ax::mojom::IntAttribute::kScrollX:
AddEvent(node, Event::SCROLL_HORIZONTAL_POSITION_CHANGED);
break;
case ax::mojom::IntAttribute::kScrollY:
AddEvent(node, Event::SCROLL_VERTICAL_POSITION_CHANGED);
break;
case ax::mojom::IntAttribute::kSortDirection:
// Ignore sort direction changes on roles other than table headers and
// grid headers.
if (IsTableHeader(node->data().role))
AddEvent(node, Event::SORT_CHANGED);
break;
case ax::mojom::IntAttribute::kImageAnnotationStatus:
// The image annotation is reported as part of the accessible name.
AddEvent(node, Event::IMAGE_ANNOTATION_CHANGED);
break;
case ax::mojom::IntAttribute::kSetSize:
AddEvent(node, Event::SET_SIZE_CHANGED);
break;
case ax::mojom::IntAttribute::kBackgroundColor:
case ax::mojom::IntAttribute::kColor:
case ax::mojom::IntAttribute::kTextDirection:
case ax::mojom::IntAttribute::kTextPosition:
case ax::mojom::IntAttribute::kTextStyle:
case ax::mojom::IntAttribute::kTextOverlineStyle:
case ax::mojom::IntAttribute::kTextStrikethroughStyle:
case ax::mojom::IntAttribute::kTextUnderlineStyle:
AddEvent(node, Event::TEXT_ATTRIBUTE_CHANGED);
break;
case ax::mojom::IntAttribute::kTextAlign:
// Alignment is exposed as an object attribute because it cannot apply to
// a substring. However, for some platforms (e.g. ATK), alignment is a
// text attribute. Therefore fire both events to ensure platforms get the
// expected notifications.
AddEvent(node, Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED);
AddEvent(node, Event::OBJECT_ATTRIBUTE_CHANGED);
break;
default:
AddEvent(node, Event::OTHER_ATTRIBUTE_CHANGED);
break;
}
}
void AXEventGenerator::OnFloatAttributeChanged(AXTree* tree,
AXNode* node,
ax::mojom::FloatAttribute attr,
float old_value,
float new_value) {
BASE_DCHECK(tree_ == tree);
switch (attr) {
case ax::mojom::FloatAttribute::kMaxValueForRange:
AddEvent(node, Event::VALUE_MAX_CHANGED);
break;
case ax::mojom::FloatAttribute::kMinValueForRange:
AddEvent(node, Event::VALUE_MIN_CHANGED);
break;
case ax::mojom::FloatAttribute::kStepValueForRange:
AddEvent(node, Event::VALUE_STEP_CHANGED);
break;
case ax::mojom::FloatAttribute::kValueForRange:
AddEvent(node, Event::VALUE_CHANGED);
break;
case ax::mojom::FloatAttribute::kFontSize:
case ax::mojom::FloatAttribute::kFontWeight:
AddEvent(node, Event::TEXT_ATTRIBUTE_CHANGED);
break;
case ax::mojom::FloatAttribute::kTextIndent:
// Indentation is exposed as an object attribute because it cannot apply
// to a substring. However, for some platforms (e.g. ATK), alignment is a
// text attribute. Therefore fire both events to ensure platforms get the
// expected notifications.
AddEvent(node, Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED);
AddEvent(node, Event::OBJECT_ATTRIBUTE_CHANGED);
break;
default:
AddEvent(node, Event::OTHER_ATTRIBUTE_CHANGED);
break;
}
}
void AXEventGenerator::OnBoolAttributeChanged(AXTree* tree,
AXNode* node,
ax::mojom::BoolAttribute attr,
bool new_value) {
BASE_DCHECK(tree_ == tree);
switch (attr) {
case ax::mojom::BoolAttribute::kBusy:
AddEvent(node, Event::BUSY_CHANGED);
AddEvent(node, Event::WIN_IACCESSIBLE_STATE_CHANGED);
// Fire an 'invalidated' event when aria-busy becomes false
if (!new_value)
AddEvent(node, Event::LAYOUT_INVALIDATED);
break;
case ax::mojom::BoolAttribute::kGrabbed:
AddEvent(node, Event::GRABBED_CHANGED);
break;
case ax::mojom::BoolAttribute::kLiveAtomic:
AddEvent(node, Event::ATOMIC_CHANGED);
break;
case ax::mojom::BoolAttribute::kSelected: {
AddEvent(node, Event::SELECTED_CHANGED);
AddEvent(node, Event::WIN_IACCESSIBLE_STATE_CHANGED);
AXNode* container = node;
while (container &&
!IsContainerWithSelectableChildren(container->data().role))
container = container->parent();
if (container)
AddEvent(container, Event::SELECTED_CHILDREN_CHANGED);
break;
}
default:
AddEvent(node, Event::OTHER_ATTRIBUTE_CHANGED);
break;
}
}
void AXEventGenerator::OnIntListAttributeChanged(
AXTree* tree,
AXNode* node,
ax::mojom::IntListAttribute attr,
const std::vector<int32_t>& old_value,
const std::vector<int32_t>& new_value) {
BASE_DCHECK(tree_ == tree);
switch (attr) {
case ax::mojom::IntListAttribute::kControlsIds:
AddEvent(node, Event::CONTROLS_CHANGED);
break;
case ax::mojom::IntListAttribute::kDescribedbyIds:
AddEvent(node, Event::DESCRIBED_BY_CHANGED);
break;
case ax::mojom::IntListAttribute::kFlowtoIds: {
AddEvent(node, Event::FLOW_TO_CHANGED);
// Fire FLOW_FROM_CHANGED for all nodes added or removed
for (int32_t id : ComputeIntListDifference(old_value, new_value)) {
if (auto* target_node = tree->GetFromId(id))
AddEvent(target_node, Event::FLOW_FROM_CHANGED);
}
break;
}
case ax::mojom::IntListAttribute::kLabelledbyIds:
AddEvent(node, Event::LABELED_BY_CHANGED);
break;
case ax::mojom::IntListAttribute::kMarkerEnds:
case ax::mojom::IntListAttribute::kMarkerStarts:
case ax::mojom::IntListAttribute::kMarkerTypes:
// On a native text field, the spelling- and grammar-error markers are
// associated with children not exposed on any platform. Therefore, we
// adjust the node we fire that event on here.
if (AXNode* text_field = node->GetTextFieldAncestor())
AddEvent(text_field, Event::TEXT_ATTRIBUTE_CHANGED);
else
AddEvent(node, Event::TEXT_ATTRIBUTE_CHANGED);
break;
default:
AddEvent(node, Event::OTHER_ATTRIBUTE_CHANGED);
break;
}
}
void AXEventGenerator::OnTreeDataChanged(AXTree* tree,
const AXTreeData& old_tree_data,
const AXTreeData& new_tree_data) {
BASE_DCHECK(tree_ == tree);
if (new_tree_data.loaded && !old_tree_data.loaded &&
ShouldFireLoadEvents(tree->root())) {
AddEvent(tree->root(), Event::LOAD_COMPLETE);
}
if (new_tree_data.sel_is_backward != old_tree_data.sel_is_backward ||
new_tree_data.sel_anchor_object_id !=
old_tree_data.sel_anchor_object_id ||
new_tree_data.sel_anchor_offset != old_tree_data.sel_anchor_offset ||
new_tree_data.sel_anchor_affinity != old_tree_data.sel_anchor_affinity ||
new_tree_data.sel_focus_object_id != old_tree_data.sel_focus_object_id ||
new_tree_data.sel_focus_offset != old_tree_data.sel_focus_offset ||
new_tree_data.sel_focus_affinity != old_tree_data.sel_focus_affinity) {
AddEvent(tree->root(), Event::DOCUMENT_SELECTION_CHANGED);
}
if (new_tree_data.title != old_tree_data.title)
AddEvent(tree->root(), Event::DOCUMENT_TITLE_CHANGED);
if (new_tree_data.focus_id != old_tree_data.focus_id) {
AXNode* focus_node = tree->GetFromId(new_tree_data.focus_id);
if (focus_node) {
AddEvent(focus_node, Event::FOCUS_CHANGED);
}
}
}
void AXEventGenerator::OnNodeWillBeDeleted(AXTree* tree, AXNode* node) {
BASE_DCHECK(tree_ == tree);
tree_events_.erase(node);
}
void AXEventGenerator::OnSubtreeWillBeDeleted(AXTree* tree, AXNode* node) {
BASE_DCHECK(tree_ == tree);
}
void AXEventGenerator::OnNodeWillBeReparented(AXTree* tree, AXNode* node) {
BASE_DCHECK(tree_ == tree);
tree_events_.erase(node);
}
void AXEventGenerator::OnSubtreeWillBeReparented(AXTree* tree, AXNode* node) {
BASE_DCHECK(tree_ == tree);
}
void AXEventGenerator::OnAtomicUpdateFinished(
AXTree* tree,
bool root_changed,
const std::vector<Change>& changes) {
BASE_DCHECK(tree_ == tree);
if (root_changed && ShouldFireLoadEvents(tree->root())) {
if (tree->data().loaded)
AddEvent(tree->root(), Event::LOAD_COMPLETE);
else
AddEvent(tree->root(), Event::LOAD_START);
}
for (const auto& change : changes) {
if (change.type == SUBTREE_CREATED) {
AddEvent(change.node, Event::SUBTREE_CREATED);
} else if (change.type != NODE_CREATED) {
FireRelationSourceEvents(tree, change.node);
continue;
}
if (IsAlert(change.node->data().role))
AddEvent(change.node, Event::ALERT);
else if (IsActiveLiveRegion(change))
AddEvent(change.node, Event::LIVE_REGION_CREATED);
else if (IsContainedInLiveRegion(change))
FireLiveRegionEvents(change.node);
}
FireActiveDescendantEvents();
PostprocessEvents();
}
void AXEventGenerator::FireLiveRegionEvents(AXNode* node) {
AXNode* live_root = node;
while (live_root && !live_root->data().HasStringAttribute(
ax::mojom::StringAttribute::kLiveStatus))
live_root = live_root->parent();
if (live_root &&
!live_root->data().GetBoolAttribute(ax::mojom::BoolAttribute::kBusy) &&
live_root->data().GetStringAttribute(
ax::mojom::StringAttribute::kLiveStatus) != "off") {
// Fire LIVE_REGION_NODE_CHANGED on each node that changed.
if (!node->data()
.GetStringAttribute(ax::mojom::StringAttribute::kName)
.empty())
AddEvent(node, Event::LIVE_REGION_NODE_CHANGED);
// Fire LIVE_REGION_NODE_CHANGED on the root of the live region.
AddEvent(live_root, Event::LIVE_REGION_CHANGED);
}
}
void AXEventGenerator::FireActiveDescendantEvents() {
for (AXNode* node : active_descendant_changed_) {
AXNode* descendant = tree_->GetFromId(node->data().GetIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId));
if (!descendant)
continue;
switch (descendant->data().role) {
case ax::mojom::Role::kMenuItem:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kMenuItemRadio:
case ax::mojom::Role::kMenuListOption:
AddEvent(descendant, Event::MENU_ITEM_SELECTED);
break;
default:
break;
}
}
active_descendant_changed_.clear();
}
void AXEventGenerator::FireRelationSourceEvents(AXTree* tree,
AXNode* target_node) {
int32_t target_id = target_node->id();
std::set<AXNode*> source_nodes;
auto callback = [&](const auto& entry) {
const auto& target_to_sources = entry.second;
auto sources_it = target_to_sources.find(target_id);
if (sources_it == target_to_sources.end())
return;
auto sources = sources_it->second;
std::for_each(sources.begin(), sources.end(), [&](int32_t source_id) {
AXNode* source_node = tree->GetFromId(source_id);
if (!source_node || source_nodes.count(source_node) > 0)
return;
source_nodes.insert(source_node);
// GCC < 6.4 requires this pointer when calling a member
// function in anonymous function
this->AddEvent(source_node, Event::RELATED_NODE_CHANGED);
});
};
std::for_each(tree->int_reverse_relations().begin(),
tree->int_reverse_relations().end(), callback);
std::for_each(
tree->intlist_reverse_relations().begin(),
tree->intlist_reverse_relations().end(), [&](auto& entry) {
// Explicitly exclude relationships for which an additional event on the
// source node would cause extra noise. For example, kRadioGroupIds
// forms relations among all radio buttons and serves little value for
// AT to get events on the previous radio button in the group.
if (entry.first != ax::mojom::IntListAttribute::kRadioGroupIds)
callback(entry);
});
}
// Attempts to suppress load-related events that we presume no AT will be
// interested in under any circumstances, such as pages which have no size.
bool AXEventGenerator::ShouldFireLoadEvents(AXNode* node) {
if (always_fire_load_complete_)
return true;
const AXNodeData& data = node->data();
return data.relative_bounds.bounds.width() ||
data.relative_bounds.bounds.height();
}
void AXEventGenerator::TrimEventsDueToAncestorIgnoredChanged(
AXNode* node,
std::map<AXNode*, IgnoredChangedStatesBitset>&
ancestor_ignored_changed_map) {
BASE_DCHECK(node);
// Recursively compute and cache ancestor ignored changed results in
// |ancestor_ignored_changed_map|, if |node|'s ancestors have become ignored
// and the ancestor's ignored changed results have not been cached.
if (node->parent() &&
!base::Contains(ancestor_ignored_changed_map, node->parent())) {
TrimEventsDueToAncestorIgnoredChanged(node->parent(),
ancestor_ignored_changed_map);
}
// If an ancestor of |node| changed to ignored state (hide), append hide state
// to the corresponding entry in the map for |node|. Similarly, if an ancestor
// of |node| removed its ignored state (show), we append show state to the
// corresponding entry in map for |node| as well. If |node| flipped its
// ignored state as well, we want to remove various events related to
// IGNORED_CHANGED event.
const auto& parent_map_iter =
ancestor_ignored_changed_map.find(node->parent());
const auto& curr_events_iter = tree_events_.find(node);
// Initialize |ancestor_ignored_changed_map[node]| with an empty bitset,
// representing neither |node| nor its ancestor has IGNORED_CHANGED.
IgnoredChangedStatesBitset& ancestor_ignored_changed_states =
ancestor_ignored_changed_map[node];
// If |ancestor_ignored_changed_map| contains an entry for |node|'s
// ancestor's and the ancestor has either show/hide state, we want to populate
// |node|'s show/hide state in the map based on its cached ancestor result.
// An empty entry in |ancestor_ignored_changed_map| for |node| means that
// neither |node| nor its ancestor has IGNORED_CHANGED.
if (parent_map_iter != ancestor_ignored_changed_map.end()) {
// Propagate ancestor's show/hide states to |node|'s entry in the map.
if (HasIgnoredChangedState(parent_map_iter->second,
IgnoredChangedState::kHide)) {
AddIgnoredChangedState(ancestor_ignored_changed_states,
IgnoredChangedState::kHide);
}
if (HasIgnoredChangedState(parent_map_iter->second,
IgnoredChangedState::kShow)) {
AddIgnoredChangedState(ancestor_ignored_changed_states,
IgnoredChangedState::kShow);
}
// If |node| has IGNORED changed with show/hide state that matches one of
// its ancestors' IGNORED changed show/hide states, we want to remove
// |node|'s IGNORED_CHANGED related events.
if (curr_events_iter != tree_events_.end() &&
HasEvent(curr_events_iter->second, Event::IGNORED_CHANGED)) {
if ((HasIgnoredChangedState(parent_map_iter->second,
IgnoredChangedState::kHide) &&
node->IsIgnored()) ||
(HasIgnoredChangedState(parent_map_iter->second,
IgnoredChangedState::kShow) &&
!node->IsIgnored())) {
RemoveEvent(&(curr_events_iter->second), Event::IGNORED_CHANGED);
RemoveEventsDueToIgnoredChanged(&(curr_events_iter->second));
}
if (node->IsIgnored()) {
AddIgnoredChangedState(ancestor_ignored_changed_states,
IgnoredChangedState::kHide);
} else {
AddIgnoredChangedState(ancestor_ignored_changed_states,
IgnoredChangedState::kShow);
}
}
return;
}
// If ignored changed results for ancestors are not cached, calculate the
// corresponding entry for |node| in the map using the ignored states and
// events of |node|.
if (curr_events_iter != tree_events_.end() &&
HasEvent(curr_events_iter->second, Event::IGNORED_CHANGED)) {
if (node->IsIgnored()) {
AddIgnoredChangedState(ancestor_ignored_changed_states,
IgnoredChangedState::kHide);
} else {
AddIgnoredChangedState(ancestor_ignored_changed_states,
IgnoredChangedState::kShow);
}
return;
}
}
void AXEventGenerator::PostprocessEvents() {
std::map<AXNode*, IgnoredChangedStatesBitset> ancestor_ignored_changed_map;
std::set<AXNode*> removed_subtree_created_nodes;
auto iter = tree_events_.begin();
while (iter != tree_events_.end()) {
AXNode* node = iter->first;
std::set<EventParams>& node_events = iter->second;
// A newly created live region or alert should not *also* fire a
// live region changed event.
if (HasEvent(node_events, Event::ALERT) ||
HasEvent(node_events, Event::LIVE_REGION_CREATED)) {
RemoveEvent(&node_events, Event::LIVE_REGION_CHANGED);
}
if (HasEvent(node_events, Event::IGNORED_CHANGED)) {
// If a node toggled its ignored state, we only want to fire
// IGNORED_CHANGED event on the top most ancestor where this ignored state
// change takes place and suppress all the descendants's IGNORED_CHANGED
// events.
TrimEventsDueToAncestorIgnoredChanged(node, ancestor_ignored_changed_map);
RemoveEventsDueToIgnoredChanged(&node_events);
}
// When the selected option in an expanded select element changes, the
// foreground and background colors change. But we don't want to treat
// those as text attribute changes. This can also happen when a widget
// such as a button becomes enabled/disabled.
if (HasEvent(node_events, Event::SELECTED_CHANGED) ||
HasEvent(node_events, Event::ENABLED_CHANGED)) {
RemoveEvent(&node_events, Event::TEXT_ATTRIBUTE_CHANGED);
}
AXNode* parent = node->GetUnignoredParent();
// Don't fire text attribute changed on this node if its immediate parent
// also has text attribute changed.
if (parent && HasEvent(node_events, Event::TEXT_ATTRIBUTE_CHANGED) &&
tree_events_.find(parent) != tree_events_.end() &&
HasEvent(tree_events_[parent], Event::TEXT_ATTRIBUTE_CHANGED)) {
RemoveEvent(&node_events, Event::TEXT_ATTRIBUTE_CHANGED);
}
// Don't fire subtree created on this node if any of its ancestors also has
// subtree created.
if (HasEvent(node_events, Event::SUBTREE_CREATED)) {
while (parent &&
(tree_events_.find(parent) != tree_events_.end() ||
base::Contains(removed_subtree_created_nodes, parent))) {
if (base::Contains(removed_subtree_created_nodes, parent) ||
HasEvent(tree_events_[parent], Event::SUBTREE_CREATED)) {
RemoveEvent(&node_events, Event::SUBTREE_CREATED);
removed_subtree_created_nodes.insert(node);
break;
}
parent = parent->GetUnignoredParent();
}
}
// If this was the only event, remove the node entirely from the
// tree events.
if (node_events.empty())
iter = tree_events_.erase(iter);
else
++iter;
}
}
// static
void AXEventGenerator::GetRestrictionStates(ax::mojom::Restriction restriction,
bool* is_enabled,
bool* is_readonly) {
switch (restriction) {
case ax::mojom::Restriction::kDisabled:
*is_enabled = false;
*is_readonly = true;
break;
case ax::mojom::Restriction::kReadOnly:
*is_enabled = true;
*is_readonly = true;
break;
case ax::mojom::Restriction::kNone:
*is_enabled = true;
*is_readonly = false;
break;
}
}
// static
std::vector<int32_t> AXEventGenerator::ComputeIntListDifference(
const std::vector<int32_t>& lhs,
const std::vector<int32_t>& rhs) {
std::set<int32_t> sorted_lhs(lhs.cbegin(), lhs.cend());
std::set<int32_t> sorted_rhs(rhs.cbegin(), rhs.cend());
std::vector<int32_t> result;
std::set_symmetric_difference(sorted_lhs.cbegin(), sorted_lhs.cend(),
sorted_rhs.cbegin(), sorted_rhs.cend(),
std::back_inserter(result));
return result;
}
std::ostream& operator<<(std::ostream& os, AXEventGenerator::Event event) {
return os << ToString(event);
}
const char* ToString(AXEventGenerator::Event event) {
switch (event) {
case AXEventGenerator::Event::ACCESS_KEY_CHANGED:
return "ACCESS_KEY_CHANGED";
case AXEventGenerator::Event::ATOMIC_CHANGED:
return "ATOMIC_CHANGED";
case AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED:
return "ACTIVE_DESCENDANT_CHANGED";
case AXEventGenerator::Event::ALERT:
return "ALERT";
case AXEventGenerator::Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED:
return "ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED";
case AXEventGenerator::Event::BUSY_CHANGED:
return "BUSY_CHANGED";
case AXEventGenerator::Event::CHECKED_STATE_CHANGED:
return "CHECKED_STATE_CHANGED";
case AXEventGenerator::Event::CHILDREN_CHANGED:
return "CHILDREN_CHANGED";
case AXEventGenerator::Event::CLASS_NAME_CHANGED:
return "CLASS_NAME_CHANGED";
case AXEventGenerator::Event::COLLAPSED:
return "COLLAPSED";
case AXEventGenerator::Event::CONTROLS_CHANGED:
return "CONTROLS_CHANGED";
case AXEventGenerator::Event::DESCRIBED_BY_CHANGED:
return "DESCRIBED_BY_CHANGED";
case AXEventGenerator::Event::DESCRIPTION_CHANGED:
return "DESCRIPTION_CHANGED";
case AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED:
return "DOCUMENT_SELECTION_CHANGED";
case AXEventGenerator::Event::DOCUMENT_TITLE_CHANGED:
return "DOCUMENT_TITLE_CHANGED";
case AXEventGenerator::Event::DROPEFFECT_CHANGED:
return "DROPEFFECT_CHANGED";
case AXEventGenerator::Event::ENABLED_CHANGED:
return "ENABLED_CHANGED";
case AXEventGenerator::Event::EXPANDED:
return "EXPANDED";
case AXEventGenerator::Event::FLOW_FROM_CHANGED:
return "FLOW_FROM_CHANGED";
case AXEventGenerator::Event::FLOW_TO_CHANGED:
return "FLOW_TO_CHANGED";
case AXEventGenerator::Event::GRABBED_CHANGED:
return "GRABBED_CHANGED";
case AXEventGenerator::Event::HASPOPUP_CHANGED:
return "HASPOPUP_CHANGED";
case AXEventGenerator::Event::HIERARCHICAL_LEVEL_CHANGED:
return "HIERARCHICAL_LEVEL_CHANGED";
case ui::AXEventGenerator::Event::IGNORED_CHANGED:
return "IGNORED_CHANGED";
case AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED:
return "IMAGE_ANNOTATION_CHANGED";
case AXEventGenerator::Event::INVALID_STATUS_CHANGED:
return "INVALID_STATUS_CHANGED";
case AXEventGenerator::Event::KEY_SHORTCUTS_CHANGED:
return "KEY_SHORTCUTS_CHANGED";
case AXEventGenerator::Event::LABELED_BY_CHANGED:
return "LABELED_BY_CHANGED";
case AXEventGenerator::Event::LANGUAGE_CHANGED:
return "LANGUAGE_CHANGED";
case AXEventGenerator::Event::LAYOUT_INVALIDATED:
return "LAYOUT_INVALIDATED";
case AXEventGenerator::Event::LIVE_REGION_CHANGED:
return "LIVE_REGION_CHANGED";
case AXEventGenerator::Event::LIVE_REGION_CREATED:
return "LIVE_REGION_CREATED";
case AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED:
return "LIVE_REGION_NODE_CHANGED";
case AXEventGenerator::Event::LIVE_RELEVANT_CHANGED:
return "LIVE_RELEVANT_CHANGED";
case AXEventGenerator::Event::LIVE_STATUS_CHANGED:
return "LIVE_STATUS_CHANGED";
case AXEventGenerator::Event::LOAD_COMPLETE:
return "LOAD_COMPLETE";
case AXEventGenerator::Event::LOAD_START:
return "LOAD_START";
case AXEventGenerator::Event::MENU_ITEM_SELECTED:
return "MENU_ITEM_SELECTED";
case AXEventGenerator::Event::MULTILINE_STATE_CHANGED:
return "MULTILINE_STATE_CHANGED";
case AXEventGenerator::Event::MULTISELECTABLE_STATE_CHANGED:
return "MULTISELECTABLE_STATE_CHANGED";
case AXEventGenerator::Event::NAME_CHANGED:
return "NAME_CHANGED";
case AXEventGenerator::Event::OBJECT_ATTRIBUTE_CHANGED:
return "OBJECT_ATTRIBUTE_CHANGED";
case AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED:
return "OTHER_ATTRIBUTE_CHANGED";
case AXEventGenerator::Event::PLACEHOLDER_CHANGED:
return "PLACEHOLDER_CHANGED";
case AXEventGenerator::Event::PORTAL_ACTIVATED:
return "PORTAL_ACTIVATED";
case AXEventGenerator::Event::POSITION_IN_SET_CHANGED:
return "POSITION_IN_SET_CHANGED";
case AXEventGenerator::Event::READONLY_CHANGED:
return "READONLY_CHANGED";
case AXEventGenerator::Event::RELATED_NODE_CHANGED:
return "RELATED_NODE_CHANGED";
case AXEventGenerator::Event::REQUIRED_STATE_CHANGED:
return "REQUIRED_STATE_CHANGED";
case AXEventGenerator::Event::ROLE_CHANGED:
return "ROLE_CHANGED";
case AXEventGenerator::Event::ROW_COUNT_CHANGED:
return "ROW_COUNT_CHANGED";
case AXEventGenerator::Event::SCROLL_HORIZONTAL_POSITION_CHANGED:
return "SCROLL_HORIZONTAL_POSITION_CHANGED";
case AXEventGenerator::Event::SCROLL_VERTICAL_POSITION_CHANGED:
return "SCROLL_VERTICAL_POSITION_CHANGED";
case AXEventGenerator::Event::SELECTED_CHANGED:
return "SELECTED_CHANGED";
case AXEventGenerator::Event::SELECTED_CHILDREN_CHANGED:
return "SELECTED_CHILDREN_CHANGED";
case AXEventGenerator::Event::SET_SIZE_CHANGED:
return "SET_SIZE_CHANGED";
case AXEventGenerator::Event::STATE_CHANGED:
return "STATE_CHANGED";
case AXEventGenerator::Event::SUBTREE_CREATED:
return "SUBTREE_CREATED";
case AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED:
return "TEXT_ATTRIBUTE_CHANGED";
case AXEventGenerator::Event::VALUE_CHANGED:
return "VALUE_CHANGED";
case AXEventGenerator::Event::VALUE_MAX_CHANGED:
return "VALUE_MAX_CHANGED";
case AXEventGenerator::Event::VALUE_MIN_CHANGED:
return "VALUE_MIN_CHANGED";
case AXEventGenerator::Event::VALUE_STEP_CHANGED:
return "VALUE_STEP_CHANGED";
case AXEventGenerator::Event::AUTO_COMPLETE_CHANGED:
return "AUTO_COMPLETE_CHANGED";
case AXEventGenerator::Event::FOCUS_CHANGED:
return "FOCUS_CHANGED";
case AXEventGenerator::Event::SORT_CHANGED:
return "SORT_CHANGED";
case AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED:
return "WIN_IACCESSIBLE_STATE_CHANGED";
}
BASE_UNREACHABLE();
}
} // namespace ui
| engine/third_party/accessibility/ax/ax_event_generator.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_event_generator.cc",
"repo_id": "engine",
"token_count": 17142
} | 547 |
// 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.
#include <algorithm>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "ax/ax_enums.h"
#include "ax/ax_node.h"
#include "ax/ax_node_data.h"
#include "ax/ax_node_position.h"
#include "ax/ax_range.h"
#include "ax/ax_tree.h"
#include "ax/ax_tree_data.h"
#include "ax/ax_tree_id.h"
#include "ax/ax_tree_update.h"
#include "ax/test_ax_tree_manager.h"
#include "flutter/fml/platform/win/wstring_conversion.h"
#include "gtest/gtest.h"
namespace ui {
using TestPositionType = std::unique_ptr<AXPosition<AXNodePosition, AXNode>>;
using TestPositionRange = AXRange<AXPosition<AXNodePosition, AXNode>>;
namespace {
constexpr AXNode::AXID ROOT_ID = 1;
constexpr AXNode::AXID BUTTON_ID = 2;
constexpr AXNode::AXID CHECK_BOX_ID = 3;
constexpr AXNode::AXID TEXT_FIELD_ID = 4;
constexpr AXNode::AXID STATIC_TEXT1_ID = 5;
constexpr AXNode::AXID INLINE_BOX1_ID = 6;
constexpr AXNode::AXID LINE_BREAK_ID = 7;
constexpr AXNode::AXID STATIC_TEXT2_ID = 8;
constexpr AXNode::AXID INLINE_BOX2_ID = 9;
// A group of basic and extended characters.
constexpr const char16_t* kGraphemeClusters[] = {
// The English word "hey" consisting of four ASCII characters.
u"h",
u"e",
u"y",
// A Hindi word (which means "Hindi") consisting of two Devanagari
// grapheme clusters.
u"\x0939\x093F",
u"\x0928\x094D\x0926\x0940",
// A Thai word (which means "feel") consisting of three Thai grapheme
// clusters.
u"\x0E23\x0E39\x0E49",
u"\x0E2A\x0E36",
u"\x0E01",
};
class AXPositionTest : public testing::Test, public TestAXTreeManager {
public:
AXPositionTest() = default;
~AXPositionTest() override = default;
protected:
static const char* TEXT_VALUE;
void SetUp() override;
// Creates a document with three pages, adding any extra information to this
// basic document structure that has been provided as arguments.
std::unique_ptr<AXTree> CreateMultipageDocument(
AXNodeData& root_data,
AXNodeData& page_1_data,
AXNodeData& page_1_text_data,
AXNodeData& page_2_data,
AXNodeData& page_2_text_data,
AXNodeData& page_3_data,
AXNodeData& page_3_text_data) const;
// Creates a document with three static text objects each containing text in a
// different language.
std::unique_ptr<AXTree> CreateMultilingualDocument(
std::vector<int>* text_offsets) const;
void AssertTextLengthEquals(const AXTree* tree,
AXNode::AXID node_id,
int expected_text_length) const;
// Creates a new AXTree from a vector of nodes.
// Assumes the first node in the vector is the root.
std::unique_ptr<AXTree> CreateAXTree(
const std::vector<AXNodeData>& nodes) const;
AXNodeData root_;
AXNodeData button_;
AXNodeData check_box_;
AXNodeData text_field_;
AXNodeData static_text1_;
AXNodeData line_break_;
AXNodeData static_text2_;
AXNodeData inline_box1_;
AXNodeData inline_box2_;
private:
BASE_DISALLOW_COPY_AND_ASSIGN(AXPositionTest);
};
// Used by AXPositionExpandToEnclosingTextBoundaryTestWithParam.
//
// Every test instance starts from a pre-determined position and calls the
// ExpandToEnclosingTextBoundary method with the arguments provided in this
// struct.
struct ExpandToEnclosingTextBoundaryTestParam {
ExpandToEnclosingTextBoundaryTestParam() = default;
// Required by GTest framework.
ExpandToEnclosingTextBoundaryTestParam(
const ExpandToEnclosingTextBoundaryTestParam& other) = default;
ExpandToEnclosingTextBoundaryTestParam& operator=(
const ExpandToEnclosingTextBoundaryTestParam& other) = default;
~ExpandToEnclosingTextBoundaryTestParam() = default;
// The text boundary to expand to.
ax::mojom::TextBoundary boundary;
// Determines how to expand to the enclosing range when the starting position
// is already at a text boundary.
AXRangeExpandBehavior expand_behavior;
// The text position that should be returned for the anchor of the range.
std::string expected_anchor_position;
// The text position that should be returned for the focus of the range.
std::string expected_focus_position;
};
// This is a fixture for a set of parameterized tests that test the
// |ExpandToEnclosingTextBoundary| method with all possible input arguments.
class AXPositionExpandToEnclosingTextBoundaryTestWithParam
: public AXPositionTest,
public testing::WithParamInterface<
ExpandToEnclosingTextBoundaryTestParam> {
public:
AXPositionExpandToEnclosingTextBoundaryTestWithParam() = default;
~AXPositionExpandToEnclosingTextBoundaryTestWithParam() override = default;
BASE_DISALLOW_COPY_AND_ASSIGN(
AXPositionExpandToEnclosingTextBoundaryTestWithParam);
};
// Used by AXPositionCreatePositionAtTextBoundaryTestWithParam.
//
// Every test instance starts from a pre-determined position and calls the
// CreatePositionAtTextBoundary method with the arguments provided in this
// struct.
struct CreatePositionAtTextBoundaryTestParam {
CreatePositionAtTextBoundaryTestParam() = default;
// Required by GTest framework.
CreatePositionAtTextBoundaryTestParam(
const CreatePositionAtTextBoundaryTestParam& other) = default;
CreatePositionAtTextBoundaryTestParam& operator=(
const CreatePositionAtTextBoundaryTestParam& other) = default;
~CreatePositionAtTextBoundaryTestParam() = default;
// The text boundary to move to.
ax::mojom::TextBoundary boundary;
// The direction to move to.
ax::mojom::MoveDirection direction;
// What to do when the starting position is already at a text boundary, or
// when the movement operation will cause us to cross the starting object's
// boundary.
AXBoundaryBehavior boundary_behavior;
// The text position that should be returned, if the method was called on a
// text position instance.
std::string expected_text_position;
};
// This is a fixture for a set of parameterized tests that test the
// |CreatePositionAtTextBoundary| method with all possible input arguments.
class AXPositionCreatePositionAtTextBoundaryTestWithParam
: public AXPositionTest,
public testing::WithParamInterface<
CreatePositionAtTextBoundaryTestParam> {
public:
AXPositionCreatePositionAtTextBoundaryTestWithParam() = default;
~AXPositionCreatePositionAtTextBoundaryTestWithParam() override = default;
BASE_DISALLOW_COPY_AND_ASSIGN(
AXPositionCreatePositionAtTextBoundaryTestWithParam);
};
// Used by |AXPositionTextNavigationTestWithParam|.
//
// The test starts from a pre-determined position and repeats a text navigation
// operation, such as |CreateNextWordStartPosition|, until it runs out of
// expectations.
struct TextNavigationTestParam {
TextNavigationTestParam() = default;
// Required by GTest framework.
TextNavigationTestParam(const TextNavigationTestParam& other) = default;
TextNavigationTestParam& operator=(const TextNavigationTestParam& other) =
default;
~TextNavigationTestParam() = default;
// Stores the method that should be called repeatedly by the test to create
// the next position.
std::function<TestPositionType(const TestPositionType&)> TestMethod;
// The node at which the test should start.
AXNode::AXID start_node_id;
// The text offset at which the test should start.
int start_offset;
// A list of positions that should be returned from the method being tested,
// in stringified form.
std::vector<std::string> expectations;
};
// This is a fixture for a set of parameterized tests that ensure that text
// navigation operations, such as |CreateNextWordStartPosition|, work properly.
//
// Starting from a given position, test instances call a given text navigation
// method repeatedly and compare the return values to a set of expectations.
//
// TODO(nektar): Only text positions are tested for now.
class AXPositionTextNavigationTestWithParam
: public AXPositionTest,
public testing::WithParamInterface<TextNavigationTestParam> {
public:
AXPositionTextNavigationTestWithParam() = default;
~AXPositionTextNavigationTestWithParam() override = default;
BASE_DISALLOW_COPY_AND_ASSIGN(AXPositionTextNavigationTestWithParam);
};
const char* AXPositionTest::TEXT_VALUE = "Line 1\nLine 2";
void AXPositionTest::SetUp() {
// Most tests use kSuppressCharacter behavior.
g_ax_embedded_object_behavior = AXEmbeddedObjectBehavior::kSuppressCharacter;
// root_
// |
// +------------+-----------+
// | | |
// button_ check_box_ text_field_
// |
// +-----------+------------+
// | | |
// static_text1_ line_break_ static_text2_
// | |
// inline_box1_ inline_box2_
root_.id = ROOT_ID;
button_.id = BUTTON_ID;
check_box_.id = CHECK_BOX_ID;
text_field_.id = TEXT_FIELD_ID;
static_text1_.id = STATIC_TEXT1_ID;
inline_box1_.id = INLINE_BOX1_ID;
line_break_.id = LINE_BREAK_ID;
static_text2_.id = STATIC_TEXT2_ID;
inline_box2_.id = INLINE_BOX2_ID;
root_.role = ax::mojom::Role::kRootWebArea;
root_.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
button_.role = ax::mojom::Role::kButton;
button_.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
button_.SetHasPopup(ax::mojom::HasPopup::kMenu);
button_.SetName("Button");
button_.relative_bounds.bounds = gfx::RectF(20, 20, 200, 30);
root_.child_ids.push_back(button_.id);
check_box_.role = ax::mojom::Role::kCheckBox;
check_box_.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
check_box_.SetCheckedState(ax::mojom::CheckedState::kTrue);
check_box_.SetName("Check box");
check_box_.relative_bounds.bounds = gfx::RectF(20, 50, 200, 30);
root_.child_ids.push_back(check_box_.id);
text_field_.role = ax::mojom::Role::kTextField;
text_field_.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
text_field_.AddState(ax::mojom::State::kEditable);
text_field_.SetValue(TEXT_VALUE);
text_field_.SetName(TEXT_VALUE);
text_field_.AddIntListAttribute(
ax::mojom::IntListAttribute::kCachedLineStarts,
std::vector<int32_t>{0, 7});
text_field_.child_ids.push_back(static_text1_.id);
text_field_.child_ids.push_back(line_break_.id);
text_field_.child_ids.push_back(static_text2_.id);
root_.child_ids.push_back(text_field_.id);
static_text1_.role = ax::mojom::Role::kStaticText;
static_text1_.AddState(ax::mojom::State::kEditable);
static_text1_.SetName("Line 1");
static_text1_.child_ids.push_back(inline_box1_.id);
static_text1_.AddIntAttribute(
ax::mojom::IntAttribute::kTextStyle,
static_cast<int32_t>(ax::mojom::TextStyle::kBold));
inline_box1_.role = ax::mojom::Role::kInlineTextBox;
inline_box1_.AddState(ax::mojom::State::kEditable);
inline_box1_.SetName("Line 1");
inline_box1_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0, 5});
inline_box1_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{4, 6});
inline_box1_.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
line_break_.id);
line_break_.role = ax::mojom::Role::kLineBreak;
line_break_.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
line_break_.AddState(ax::mojom::State::kEditable);
line_break_.SetName("\n");
line_break_.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
inline_box1_.id);
static_text2_.role = ax::mojom::Role::kStaticText;
static_text2_.AddState(ax::mojom::State::kEditable);
static_text2_.SetName("Line 2");
static_text2_.child_ids.push_back(inline_box2_.id);
static_text2_.AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize, 1.0f);
inline_box2_.role = ax::mojom::Role::kInlineTextBox;
inline_box2_.AddState(ax::mojom::State::kEditable);
inline_box2_.SetName("Line 2");
inline_box2_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0, 5});
inline_box2_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{4, 6});
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes = {root_, button_, check_box_,
text_field_, static_text1_, inline_box1_,
line_break_, static_text2_, inline_box2_};
initial_state.has_tree_data = true;
initial_state.tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
initial_state.tree_data.title = "Dialog title";
// "SetTree" is defined in "TestAXTreeManager" and it passes ownership of the
// created AXTree to the manager.
SetTree(std::make_unique<AXTree>(initial_state));
}
std::unique_ptr<AXTree> AXPositionTest::CreateMultipageDocument(
AXNodeData& root_data,
AXNodeData& page_1_data,
AXNodeData& page_1_text_data,
AXNodeData& page_2_data,
AXNodeData& page_2_text_data,
AXNodeData& page_3_data,
AXNodeData& page_3_text_data) const {
root_data.id = 1;
root_data.role = ax::mojom::Role::kDocument;
page_1_data.id = 2;
page_1_data.role = ax::mojom::Role::kRegion;
page_1_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsPageBreakingObject,
true);
page_1_text_data.id = 3;
page_1_text_data.role = ax::mojom::Role::kStaticText;
page_1_text_data.SetName("some text on page 1");
page_1_text_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
page_1_data.child_ids = {3};
page_2_data.id = 4;
page_2_data.role = ax::mojom::Role::kRegion;
page_2_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsPageBreakingObject,
true);
page_2_text_data.id = 5;
page_2_text_data.role = ax::mojom::Role::kStaticText;
page_2_text_data.SetName("some text on page 2");
page_2_text_data.AddIntAttribute(
ax::mojom::IntAttribute::kTextStyle,
static_cast<int32_t>(ax::mojom::TextStyle::kBold));
page_2_data.child_ids = {5};
page_3_data.id = 6;
page_3_data.role = ax::mojom::Role::kRegion;
page_3_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsPageBreakingObject,
true);
page_3_text_data.id = 7;
page_3_text_data.role = ax::mojom::Role::kStaticText;
page_3_text_data.SetName("some more text on page 3");
page_3_data.child_ids = {7};
root_data.child_ids = {2, 4, 6};
return CreateAXTree({root_data, page_1_data, page_1_text_data, page_2_data,
page_2_text_data, page_3_data, page_3_text_data});
}
std::unique_ptr<AXTree> AXPositionTest::CreateMultilingualDocument(
std::vector<int>* text_offsets) const {
EXPECT_NE(nullptr, text_offsets);
text_offsets->push_back(0);
std::u16string english_text;
for (int i = 0; i < 3; ++i) {
std::u16string grapheme = kGraphemeClusters[i];
EXPECT_EQ(1u, grapheme.length())
<< "All English characters should be one UTF16 code unit in length.";
text_offsets->push_back(text_offsets->back() +
static_cast<int>(grapheme.length()));
english_text.append(grapheme);
}
std::u16string hindi_text;
for (int i = 3; i < 5; ++i) {
std::u16string grapheme = kGraphemeClusters[i];
EXPECT_LE(2u, grapheme.length()) << "All Hindi characters should be two "
"or more UTF16 code units in length.";
text_offsets->push_back(text_offsets->back() +
static_cast<int>(grapheme.length()));
hindi_text.append(grapheme);
}
std::u16string thai_text;
for (int i = 5; i < 8; ++i) {
std::u16string grapheme = kGraphemeClusters[i];
EXPECT_LT(0u, grapheme.length())
<< "One of the Thai characters should be one UTF16 code unit, "
"whilst others should be two or more.";
text_offsets->push_back(text_offsets->back() +
static_cast<int>(grapheme.length()));
thai_text.append(grapheme);
}
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData text_data1;
text_data1.id = 2;
text_data1.role = ax::mojom::Role::kStaticText;
text_data1.SetName(english_text);
AXNodeData text_data2;
text_data2.id = 3;
text_data2.role = ax::mojom::Role::kStaticText;
text_data2.SetName(hindi_text);
AXNodeData text_data3;
text_data3.id = 4;
text_data3.role = ax::mojom::Role::kStaticText;
text_data3.SetName(thai_text);
root_data.child_ids = {text_data1.id, text_data2.id, text_data3.id};
return CreateAXTree({root_data, text_data1, text_data2, text_data3});
}
void AXPositionTest::AssertTextLengthEquals(const AXTree* tree,
AXNode::AXID node_id,
int expected_text_length) const {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
tree->data().tree_id, node_id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(expected_text_length, text_position->MaxTextOffset());
ASSERT_EQ(expected_text_length,
static_cast<int>(text_position->GetText().length()));
}
std::unique_ptr<AXTree> AXPositionTest::CreateAXTree(
const std::vector<AXNodeData>& nodes) const {
EXPECT_FALSE(nodes.empty());
AXTreeUpdate update;
update.tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.has_tree_data = true;
update.root_id = nodes[0].id;
update.nodes = nodes;
return std::make_unique<AXTree>(update);
}
} // namespace
TEST_F(AXPositionTest, Clone) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType copy_position = null_position->Clone();
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsNullPosition());
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
copy_position = tree_position->Clone();
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsTreePosition());
EXPECT_EQ(root_.id, copy_position->anchor_id());
EXPECT_EQ(1, copy_position->child_index());
EXPECT_EQ(AXNodePosition::INVALID_OFFSET, copy_position->text_offset());
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_NE(nullptr, tree_position);
copy_position = tree_position->Clone();
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsTreePosition());
EXPECT_EQ(root_.id, copy_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, copy_position->child_index());
EXPECT_EQ(AXNodePosition::INVALID_OFFSET, copy_position->text_offset());
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
copy_position = text_position->Clone();
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsTextPosition());
EXPECT_EQ(text_field_.id, copy_position->anchor_id());
EXPECT_EQ(0, copy_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kUpstream, copy_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
copy_position = text_position->Clone();
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsTextPosition());
EXPECT_EQ(text_field_.id, copy_position->anchor_id());
EXPECT_EQ(0, copy_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, copy_position->affinity());
EXPECT_EQ(AXNodePosition::INVALID_INDEX, copy_position->child_index());
}
TEST_F(AXPositionTest, Serialize) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType copy_position =
AXNodePosition::Unserialize(null_position->Serialize());
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsNullPosition());
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
copy_position = AXNodePosition::Unserialize(tree_position->Serialize());
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsTreePosition());
EXPECT_EQ(root_.id, copy_position->anchor_id());
EXPECT_EQ(1, copy_position->child_index());
EXPECT_EQ(AXNodePosition::INVALID_OFFSET, copy_position->text_offset());
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_NE(nullptr, tree_position);
copy_position = AXNodePosition::Unserialize(tree_position->Serialize());
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsTreePosition());
EXPECT_EQ(root_.id, copy_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, copy_position->child_index());
EXPECT_EQ(AXNodePosition::INVALID_OFFSET, copy_position->text_offset());
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
copy_position = AXNodePosition::Unserialize(text_position->Serialize());
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsTextPosition());
EXPECT_EQ(text_field_.id, copy_position->anchor_id());
EXPECT_EQ(0, copy_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kUpstream, copy_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
copy_position = AXNodePosition::Unserialize(text_position->Serialize());
ASSERT_NE(nullptr, copy_position);
EXPECT_TRUE(copy_position->IsTextPosition());
EXPECT_EQ(text_field_.id, copy_position->anchor_id());
EXPECT_EQ(0, copy_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, copy_position->affinity());
EXPECT_EQ(AXNodePosition::INVALID_INDEX, copy_position->child_index());
}
TEST_F(AXPositionTest, ToString) {
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData static_text_data_1;
static_text_data_1.id = 2;
static_text_data_1.role = ax::mojom::Role::kStaticText;
static_text_data_1.SetName("some text");
AXNodeData static_text_data_2;
static_text_data_2.id = 3;
static_text_data_2.role = ax::mojom::Role::kStaticText;
static_text_data_2.SetName(u"\xfffc");
AXNodeData static_text_data_3;
static_text_data_3.id = 4;
static_text_data_3.role = ax::mojom::Role::kStaticText;
static_text_data_3.SetName("more text");
root_data.child_ids = {static_text_data_1.id, static_text_data_2.id,
static_text_data_3.id};
SetTree(CreateAXTree(
{root_data, static_text_data_1, static_text_data_2, static_text_data_3}));
TestPositionType text_position_1 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_1->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=1 text_offset=0 affinity=downstream "
"annotated_text=<s>ome text\xEF\xBF\xBCmore text",
text_position_1->ToString());
TestPositionType text_position_2 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_2->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=1 text_offset=5 affinity=downstream "
"annotated_text=some <t>ext\xEF\xBF\xBCmore text",
text_position_2->ToString());
TestPositionType text_position_3 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 9 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_3->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=1 text_offset=9 affinity=downstream "
"annotated_text=some text<\xEF\xBF\xBC>more text",
text_position_3->ToString());
TestPositionType text_position_4 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 10 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_4->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=1 text_offset=10 affinity=downstream "
"annotated_text=some text\xEF\xBF\xBC<m>ore text",
text_position_4->ToString());
TestPositionType text_position_5 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 19 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_5->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=1 text_offset=19 affinity=downstream "
"annotated_text=some text\xEF\xBF\xBCmore text<>",
text_position_5->ToString());
TestPositionType text_position_6 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text_data_2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_6->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=3 text_offset=0 affinity=downstream "
"annotated_text=<\xEF\xBF\xBC>",
text_position_6->ToString());
TestPositionType text_position_7 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text_data_2.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_7->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=3 text_offset=1 affinity=downstream "
"annotated_text=\xEF\xBF\xBC<>",
text_position_7->ToString());
TestPositionType text_position_8 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text_data_3.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_8->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<m>ore text",
text_position_8->ToString());
TestPositionType text_position_9 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text_data_3.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_9->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=4 text_offset=5 affinity=downstream "
"annotated_text=more <t>ext",
text_position_9->ToString());
TestPositionType text_position_10 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text_data_3.id, 9 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_10->IsTextPosition());
EXPECT_EQ(
"TextPosition anchor_id=4 text_offset=9 affinity=downstream "
"annotated_text=more text<>",
text_position_10->ToString());
}
TEST_F(AXPositionTest, IsIgnored) {
EXPECT_FALSE(AXNodePosition::CreateNullPosition()->IsIgnored());
// We now need to update the tree structure to test ignored tree and text
// positions.
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData static_text_data_1;
static_text_data_1.id = 2;
static_text_data_1.role = ax::mojom::Role::kStaticText;
static_text_data_1.SetName("One");
AXNodeData inline_box_data_1;
inline_box_data_1.id = 3;
inline_box_data_1.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_1.SetName("One");
inline_box_data_1.AddState(ax::mojom::State::kIgnored);
AXNodeData container_data;
container_data.id = 4;
container_data.role = ax::mojom::Role::kGenericContainer;
container_data.AddState(ax::mojom::State::kIgnored);
AXNodeData static_text_data_2;
static_text_data_2.id = 5;
static_text_data_2.role = ax::mojom::Role::kStaticText;
static_text_data_2.SetName("Two");
AXNodeData inline_box_data_2;
inline_box_data_2.id = 6;
inline_box_data_2.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_2.SetName("Two");
static_text_data_1.child_ids = {inline_box_data_1.id};
container_data.child_ids = {static_text_data_2.id};
static_text_data_2.child_ids = {inline_box_data_2.id};
root_data.child_ids = {static_text_data_1.id, container_data.id};
SetTree(
CreateAXTree({root_data, static_text_data_1, inline_box_data_1,
container_data, static_text_data_2, inline_box_data_2}));
//
// Text positions.
//
TestPositionType text_position_1 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_1->IsTextPosition());
// Since the leaf node containing the text that is pointed to is ignored, this
// position should be ignored.
EXPECT_TRUE(text_position_1->IsIgnored());
// Create a text position before the letter "e" in "One".
TestPositionType text_position_2 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 2 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_2->IsTextPosition());
// Same as above.
EXPECT_TRUE(text_position_2->IsIgnored());
// Create a text position before the letter "T" in "Two".
TestPositionType text_position_3 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 3 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_3->IsTextPosition());
// Since the leaf node containing the text that is pointed to is not ignored,
// but only a generic container that is in between this position and the leaf
// node, this position should not be ignored.
EXPECT_FALSE(text_position_3->IsIgnored());
// Create a text position before the letter "w" in "Two".
TestPositionType text_position_4 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_4->IsTextPosition());
// Same as above.
EXPECT_FALSE(text_position_4->IsIgnored());
// But a text position on the ignored generic container itself, should be
// ignored.
TestPositionType text_position_5 = AXNodePosition::CreateTextPosition(
GetTreeID(), container_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_5->IsTextPosition());
EXPECT_TRUE(text_position_5->IsIgnored());
// Whilst a text position on its static text child should not be ignored since
// there is nothing ignore below the generic container.
TestPositionType text_position_6 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text_data_2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_6->IsTextPosition());
EXPECT_FALSE(text_position_6->IsIgnored());
// A text position on an ignored leaf node should be ignored.
TestPositionType text_position_7 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_data_1.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position_7->IsTextPosition());
EXPECT_TRUE(text_position_7->IsIgnored());
//
// Tree positions.
//
// A "before children" position on the root should not be ignored, despite the
// fact that the leaf equivalent position is, because we can always adjust to
// an unignored position if asked to find the leaf equivalent unignored
// position.
TestPositionType tree_position_1 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_data.id, 0 /* child_index */);
ASSERT_TRUE(tree_position_1->IsTreePosition());
EXPECT_FALSE(tree_position_1->IsIgnored());
// A tree position pointing to an ignored child node should be ignored.
TestPositionType tree_position_2 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_data.id, 1 /* child_index */);
ASSERT_TRUE(tree_position_2->IsTreePosition());
EXPECT_TRUE(tree_position_2->IsIgnored());
// An "after text" tree position on an ignored leaf node should be ignored.
TestPositionType tree_position_3 = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box_data_1.id, 0 /* child_index */);
ASSERT_TRUE(tree_position_3->IsTreePosition());
EXPECT_TRUE(tree_position_3->IsIgnored());
// A "before text" tree position on an ignored leaf node should be ignored.
TestPositionType tree_position_4 = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box_data_1.id, AXNodePosition::BEFORE_TEXT);
ASSERT_TRUE(tree_position_4->IsTreePosition());
EXPECT_TRUE(tree_position_4->IsIgnored());
// An "after children" tree position on the root node, where the last child is
// ignored, should be ignored.
TestPositionType tree_position_5 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_data.id, 2 /* child_index */);
ASSERT_TRUE(tree_position_5->IsTreePosition());
EXPECT_TRUE(tree_position_5->IsIgnored());
// A "before text" position on an unignored node should not be ignored.
TestPositionType tree_position_6 = AXNodePosition::CreateTreePosition(
GetTreeID(), static_text_data_1.id, AXNodePosition::BEFORE_TEXT);
ASSERT_TRUE(tree_position_6->IsTreePosition());
EXPECT_FALSE(tree_position_6->IsIgnored());
}
TEST_F(AXPositionTest, GetTextFromNullPosition) {
TestPositionType text_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsNullPosition());
ASSERT_EQ(u"", text_position->GetText());
}
TEST_F(AXPositionTest, GetTextFromRoot) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(u"Line 1\nLine 2", text_position->GetText());
}
TEST_F(AXPositionTest, GetTextFromButton) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), button_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(u"", text_position->GetText());
}
TEST_F(AXPositionTest, GetTextFromCheckbox) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), check_box_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(u"", text_position->GetText());
}
TEST_F(AXPositionTest, GetTextFromTextField) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(u"Line 1\nLine 2", text_position->GetText());
}
TEST_F(AXPositionTest, GetTextFromStaticText) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(u"Line 1", text_position->GetText());
}
TEST_F(AXPositionTest, GetTextFromInlineTextBox) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(u"Line 1", text_position->GetText());
}
TEST_F(AXPositionTest, GetTextFromLineBreak) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(u"\n", text_position->GetText());
}
TEST_F(AXPositionTest, GetMaxTextOffsetFromNullPosition) {
TestPositionType text_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsNullPosition());
ASSERT_EQ(AXNodePosition::INVALID_OFFSET, text_position->MaxTextOffset());
}
TEST_F(AXPositionTest, GetMaxTextOffsetFromRoot) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(13, text_position->MaxTextOffset());
}
TEST_F(AXPositionTest, GetMaxTextOffsetFromButton) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), button_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(0, text_position->MaxTextOffset());
}
TEST_F(AXPositionTest, GetMaxTextOffsetFromCheckbox) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), check_box_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(0, text_position->MaxTextOffset());
}
TEST_F(AXPositionTest, GetMaxTextOffsetFromTextfield) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(13, text_position->MaxTextOffset());
}
TEST_F(AXPositionTest, GetMaxTextOffsetFromStaticText) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(6, text_position->MaxTextOffset());
}
TEST_F(AXPositionTest, GetMaxTextOffsetFromInlineTextBox) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(6, text_position->MaxTextOffset());
}
TEST_F(AXPositionTest, GetMaxTextOffsetFromLineBreak) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(1, text_position->MaxTextOffset());
}
TEST_F(AXPositionTest, GetMaxTextOffsetUpdate) {
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData more_text_data;
more_text_data.id = 3;
more_text_data.role = ax::mojom::Role::kStaticText;
more_text_data.SetName("more text");
root_data.child_ids = {2, 3};
SetTree(CreateAXTree({root_data, text_data, more_text_data}));
AssertTextLengthEquals(GetTree(), text_data.id, 9);
AssertTextLengthEquals(GetTree(), root_data.id, 18);
text_data.SetName("Adjusted line 1");
SetTree(CreateAXTree({root_data, text_data, more_text_data}));
AssertTextLengthEquals(GetTree(), text_data.id, 15);
AssertTextLengthEquals(GetTree(), root_data.id, 24);
// Value should override name
text_data.SetValue("Value should override name");
SetTree(CreateAXTree({root_data, text_data, more_text_data}));
AssertTextLengthEquals(GetTree(), text_data.id, 26);
AssertTextLengthEquals(GetTree(), root_data.id, 35);
// An empty value should fall back to name
text_data.SetValue("");
SetTree(CreateAXTree({root_data, text_data, more_text_data}));
AssertTextLengthEquals(GetTree(), text_data.id, 15);
AssertTextLengthEquals(GetTree(), root_data.id, 24);
}
TEST_F(AXPositionTest, GetMaxTextOffsetAndGetTextWithGeneratedContent) {
// ++1 kRootWebArea
// ++++2 kTextField
// ++++++3 kStaticText
// ++++++++4 kInlineTextBox
// ++++++5 kStaticText
// ++++++++6 kInlineTextBox
AXNodeData root_1;
AXNodeData text_field_2;
AXNodeData static_text_3;
AXNodeData inline_box_4;
AXNodeData static_text_5;
AXNodeData inline_box_6;
root_1.id = 1;
text_field_2.id = 2;
static_text_3.id = 3;
inline_box_4.id = 4;
static_text_5.id = 5;
inline_box_6.id = 6;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {text_field_2.id};
text_field_2.role = ax::mojom::Role::kGroup;
text_field_2.SetValue("3.14");
text_field_2.child_ids = {static_text_3.id, static_text_5.id};
static_text_3.role = ax::mojom::Role::kStaticText;
static_text_3.SetName("Placeholder from generated content");
static_text_3.child_ids = {inline_box_4.id};
inline_box_4.role = ax::mojom::Role::kInlineTextBox;
inline_box_4.SetName("Placeholder from generated content");
static_text_5.role = ax::mojom::Role::kStaticText;
static_text_5.SetName("3.14");
static_text_5.child_ids = {inline_box_6.id};
inline_box_6.role = ax::mojom::Role::kInlineTextBox;
inline_box_6.SetName("3.14");
SetTree(CreateAXTree({root_1, text_field_2, static_text_3, inline_box_4,
static_text_5, inline_box_6}));
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(38, text_position->MaxTextOffset());
EXPECT_EQ(u"Placeholder from generated content3.14",
text_position->GetText());
}
TEST_F(AXPositionTest, AtStartOfAnchorWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
EXPECT_FALSE(null_position->AtStartOfAnchor());
}
TEST_F(AXPositionTest, AtStartOfAnchorWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
EXPECT_TRUE(tree_position->AtStartOfAnchor());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
EXPECT_FALSE(tree_position->AtStartOfAnchor());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
3 /* child_index */);
ASSERT_NE(nullptr, tree_position);
EXPECT_FALSE(tree_position->AtStartOfAnchor());
// A "before text" position.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_NE(nullptr, tree_position);
EXPECT_TRUE(tree_position->AtStartOfAnchor());
// An "after text" position.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
EXPECT_FALSE(tree_position->AtStartOfAnchor());
}
TEST_F(AXPositionTest, AtStartOfAnchorWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfAnchor());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfAnchor());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfAnchor());
}
TEST_F(AXPositionTest, AtEndOfAnchorWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
EXPECT_FALSE(null_position->AtEndOfAnchor());
}
TEST_F(AXPositionTest, AtEndOfAnchorWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 3 /* child_index */);
ASSERT_NE(nullptr, tree_position);
EXPECT_TRUE(tree_position->AtEndOfAnchor());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
2 /* child_index */);
ASSERT_NE(nullptr, tree_position);
EXPECT_FALSE(tree_position->AtEndOfAnchor());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
EXPECT_FALSE(tree_position->AtEndOfAnchor());
}
TEST_F(AXPositionTest, AtEndOfAnchorWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtEndOfAnchor());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtEndOfAnchor());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtEndOfAnchor());
}
TEST_F(AXPositionTest, AtStartOfLineWithTextPosition) {
// An upstream affinity should not affect the outcome since there is no soft
// line break.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfLine());
// An "after text" position anchored at the line break should be equivalent to
// a "before text" position at the start of the next line.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfLine());
// An upstream affinity should not affect the outcome since there is no soft
// line break.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfLine());
}
TEST_F(AXPositionTest, AtStartOfLineStaticTextExtraPrecedingSpace) {
// Consider the following web content:
// <style>
// .required-label::after {
// content: " *";
// }
// </style>
// <label class="required-label">Required </label>
//
// Which has the following AXTree, where the static text (#3)
// contains an extra preceding space compared to its inline text (#4).
// ++1 kRootWebArea
// ++++2 kLabelText
// ++++++3 kStaticText name=" *"
// ++++++++4 kInlineTextBox name="*"
// This test ensures that this difference between static text and its inline
// text box does not cause a hang when AtStartOfLine is called on static text
// with text position " <*>".
AXNodeData root;
root.id = 1;
root.role = ax::mojom::Role::kRootWebArea;
// "kIsLineBreakingObject" is not strictly necessary but is added for
// completeness.
root.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData label_text;
label_text.id = 2;
label_text.role = ax::mojom::Role::kLabelText;
AXNodeData static_text1;
static_text1.id = 3;
static_text1.role = ax::mojom::Role::kStaticText;
static_text1.SetName(" *");
AXNodeData inline_text1;
inline_text1.id = 4;
inline_text1.role = ax::mojom::Role::kInlineTextBox;
inline_text1.SetName("*");
static_text1.child_ids = {inline_text1.id};
root.child_ids = {static_text1.id};
SetTree(CreateAXTree({root, static_text1, inline_text1}));
// Calling AtStartOfLine on |static_text1| with position " <*>",
// text_offset_=1, should not get into an infinite loop; it should be
// guaranteed to terminate.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text1.id, 1 /* child_index */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_FALSE(text_position->AtStartOfLine());
}
TEST_F(AXPositionTest, AtEndOfLineWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtEndOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtEndOfLine());
// A "before text" position anchored at the line break should visually be the
// same as a text position at the end of the previous line.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtEndOfLine());
// The following position comes after the soft line break, so it should not be
// marked as the end of the line.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtEndOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtEndOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtEndOfLine());
}
TEST_F(AXPositionTest, AtStartOfBlankLine) {
// Modify the test tree so that the line break will appear on a line of its
// own, i.e. as creating a blank line.
inline_box1_.RemoveIntAttribute(ax::mojom::IntAttribute::kNextOnLineId);
line_break_.RemoveIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId);
AXTreeUpdate update;
update.nodes = {inline_box1_, line_break_};
ASSERT_TRUE(GetTree()->Unserialize(update));
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
EXPECT_TRUE(tree_position->AtStartOfLine());
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfLine());
// A text position after a blank line should be equivalent to a "before text"
// position at the line that comes after it.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfLine());
}
TEST_F(AXPositionTest, AtEndOfBlankLine) {
// Modify the test tree so that the line break will appear on a line of its
// own, i.e. as creating a blank line.
inline_box1_.RemoveIntAttribute(ax::mojom::IntAttribute::kNextOnLineId);
line_break_.RemoveIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId);
AXTreeUpdate update;
update.nodes = {inline_box1_, line_break_};
ASSERT_TRUE(GetTree()->Unserialize(update));
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
EXPECT_FALSE(tree_position->AtEndOfLine());
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtEndOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtEndOfLine());
}
TEST_F(AXPositionTest, AtStartAndEndOfLineWhenAtEndOfTextSpan) {
// This test ensures that the "AtStartOfLine" and the "AtEndOfLine" methods
// return false and true respectively when we are at the end of a text span.
//
// A text span is defined by a series of inline text boxes that make up a
// single static text object. Lines always end at the end of static text
// objects, so there would never arise a situation when a position at the end
// of a text span would be at start of line. It should always be at end of
// line. On the contrary, if a position is at the end of an inline text box
// and the equivalent parent position is in the middle of a static text
// object, then the position would sometimes be at start of line, i.e., when
// the inline text box contains only white space that is used to separate
// lines in the case of lines being wrapped by a soft line break.
//
// Example accessibility tree:
// 0:kRootWebArea
// ++1:kStaticText "Hello testing "
// ++++2:kInlineTextBox "Hello" kNextOnLine=2
// ++++3:kInlineTextBox " " kPreviousOnLine=2
// ++++4:kInlineTextBox "testing" kNextOnLine=5
// ++++5:kInlineTextBox " " kPreviousOnLine=4
// ++6:kStaticText "here."
// ++++7:kInlineTextBox "here."
//
// Resulting text representation:
// "Hello<soft_line_break>testing <hard_line_break>here."
// Notice the extra space after the word "testing". This is not a line break.
// The hard line break is caused by the presence of the second static text
// object.
//
// A position at the end of inline text box 3 should be at start of line,
// whilst a position at the end of inline text box 5 should not.
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
// "kIsLineBreakingObject" is not strictly necessary but is added for
// completeness.
root_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
AXNodeData static_text_data_1;
static_text_data_1.id = 2;
static_text_data_1.role = ax::mojom::Role::kStaticText;
static_text_data_1.SetName("Hello testing ");
AXNodeData inline_box_data_1;
inline_box_data_1.id = 3;
inline_box_data_1.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_1.SetName("hello");
AXNodeData inline_box_data_2;
inline_box_data_2.id = 4;
inline_box_data_2.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_1.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
inline_box_data_2.id);
inline_box_data_2.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
inline_box_data_1.id);
// The name is a space character that we assume it turns into a soft line
// break by the layout engine.
inline_box_data_2.SetName(" ");
AXNodeData inline_box_data_3;
inline_box_data_3.id = 5;
inline_box_data_3.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_3.SetName("testing");
AXNodeData inline_box_data_4;
inline_box_data_4.id = 6;
inline_box_data_4.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_3.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
inline_box_data_4.id);
inline_box_data_4.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
inline_box_data_3.id);
inline_box_data_4.SetName(" "); // Just a space character - not a line break.
AXNodeData static_text_data_2;
static_text_data_2.id = 7;
static_text_data_2.role = ax::mojom::Role::kStaticText;
static_text_data_2.SetName("here.");
AXNodeData inline_box_data_5;
inline_box_data_5.id = 8;
inline_box_data_5.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_5.SetName("here.");
static_text_data_1.child_ids = {inline_box_data_1.id, inline_box_data_2.id,
inline_box_data_3.id, inline_box_data_4.id};
static_text_data_2.child_ids = {inline_box_data_5.id};
root_data.child_ids = {static_text_data_1.id, static_text_data_2.id};
SetTree(CreateAXTree({root_data, static_text_data_1, inline_box_data_1,
inline_box_data_2, inline_box_data_3, inline_box_data_4,
static_text_data_2, inline_box_data_5}));
// An "after text" tree position - after the soft line break.
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box_data_2.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
EXPECT_TRUE(tree_position->AtStartOfLine());
EXPECT_FALSE(tree_position->AtEndOfLine());
// An "after text" tree position - after the space character and before the
// hard line break caused by the second static text object.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box_data_4.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
EXPECT_FALSE(tree_position->AtStartOfLine());
EXPECT_TRUE(tree_position->AtEndOfLine());
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_data_2.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfLine());
EXPECT_FALSE(text_position->AtEndOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_data_4.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfLine());
EXPECT_TRUE(text_position->AtEndOfLine());
}
TEST_F(AXPositionTest, AtStartAndEndOfLineInsideTextField) {
// This test ensures that "AtStart/EndOfLine" methods work properly when at
// the start or end of a text field.
//
// We set up a test tree with two text fields. The first one has one line of
// text, and the second one three. There are inline text boxes containing only
// white space at the start and end of both text fields, which is a valid
// AXTree that might be generated by our renderer.
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
// "kIsLineBreakingObject" is not strictly necessary but is added for
// completeness.
root_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
AXNodeData text_field_data_1;
text_field_data_1.id = 2;
text_field_data_1.role = ax::mojom::Role::kGroup;
// "kIsLineBreakingObject" and the "kEditable" state are not strictly
// necessary but are added for completeness.
text_field_data_1.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
text_field_data_1.AddState(ax::mojom::State::kEditable);
// Notice that there is one space at the start and one at the end of the text
// field's value.
text_field_data_1.SetValue(" Text field one ");
AXNodeData static_text_data_1;
static_text_data_1.id = 3;
static_text_data_1.role = ax::mojom::Role::kStaticText;
static_text_data_1.SetName(" Text field one ");
AXNodeData inline_box_data_1;
inline_box_data_1.id = 4;
inline_box_data_1.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_1.SetName(" ");
AXNodeData inline_box_data_2;
inline_box_data_2.id = 5;
inline_box_data_2.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_1.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
inline_box_data_2.id);
inline_box_data_2.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
inline_box_data_1.id);
inline_box_data_2.SetName("Text field one");
AXNodeData inline_box_data_3;
inline_box_data_3.id = 6;
inline_box_data_3.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_2.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
inline_box_data_3.id);
inline_box_data_3.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
inline_box_data_2.id);
inline_box_data_3.SetName(" ");
AXNodeData text_field_data_2;
text_field_data_2.id = 7;
text_field_data_2.role = ax::mojom::Role::kGroup;
// "kIsLineBreakingObject" and the "kEditable" state are not strictly
// necessary but are added for completeness.
text_field_data_2.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
text_field_data_1.AddState(ax::mojom::State::kEditable);
// Notice that there are three lines, the first and the last one include only
// a single space.
text_field_data_2.SetValue(" Text field two ");
AXNodeData static_text_data_2;
static_text_data_2.id = 8;
static_text_data_2.role = ax::mojom::Role::kStaticText;
static_text_data_2.SetName(" Text field two ");
AXNodeData inline_box_data_4;
inline_box_data_4.id = 9;
inline_box_data_4.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_4.SetName(" ");
AXNodeData inline_box_data_5;
inline_box_data_5.id = 10;
inline_box_data_5.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_5.SetName("Text field two");
AXNodeData inline_box_data_6;
inline_box_data_6.id = 11;
inline_box_data_6.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_6.SetName(" ");
static_text_data_1.child_ids = {inline_box_data_1.id, inline_box_data_2.id,
inline_box_data_3.id};
static_text_data_2.child_ids = {inline_box_data_4.id, inline_box_data_5.id,
inline_box_data_6.id};
text_field_data_1.child_ids = {static_text_data_1.id};
text_field_data_2.child_ids = {static_text_data_2.id};
root_data.child_ids = {text_field_data_1.id, text_field_data_2.id};
SetTree(
CreateAXTree({root_data, text_field_data_1, static_text_data_1,
inline_box_data_1, inline_box_data_2, inline_box_data_3,
text_field_data_2, static_text_data_2, inline_box_data_4,
inline_box_data_5, inline_box_data_6}));
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_data_1.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
EXPECT_TRUE(tree_position->AtStartOfLine());
EXPECT_FALSE(tree_position->AtEndOfLine());
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_data_1.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
EXPECT_FALSE(tree_position->AtStartOfLine());
EXPECT_TRUE(tree_position->AtEndOfLine());
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_data_2.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
EXPECT_TRUE(tree_position->AtStartOfLine());
EXPECT_FALSE(tree_position->AtEndOfLine());
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_data_2.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
EXPECT_FALSE(tree_position->AtStartOfLine());
EXPECT_TRUE(tree_position->AtEndOfLine());
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_data_1.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfLine());
EXPECT_FALSE(text_position->AtEndOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_data_1.id, 16 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfLine());
EXPECT_TRUE(text_position->AtEndOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_data_2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfLine());
EXPECT_FALSE(text_position->AtEndOfLine());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_data_2.id, 16 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfLine());
EXPECT_TRUE(text_position->AtEndOfLine());
}
TEST_F(AXPositionTest, AtStartOfParagraphWithTextPosition) {
// An upstream affinity should not affect the outcome since there is no soft
// line break.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfParagraph());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfParagraph());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfParagraph());
// An "after text" position anchored at the line break should not be the same
// as a text position at the start of the next paragraph because in practice
// they should have resulted from two different ancestor positions. The former
// should have been an upstream position, whilst the latter a downstream one.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfParagraph());
// An upstream affinity should not affect the outcome since there is no soft
// line break.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtStartOfParagraph());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtStartOfParagraph());
}
TEST_F(AXPositionTest, AtEndOfParagraphWithTextPosition) {
// End of |inline_box1_| is not the end of paragraph since it's
// followed by a whitespace-only line breaking object
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// The start of |line_break_| is not the end of paragraph since it's
// not the end of its anchor.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// The end of |line_break_| is the end of paragraph since it's
// a line breaking object without additional trailing whitespace.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtEndOfParagraph());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// The end of |inline_box2_| is the end of paragraph since it's
// followed by the end of document.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->AtEndOfParagraph());
}
TEST_F(AXPositionTest, ParagraphEdgesWithPreservedNewLine) {
// This test ensures that "At{Start|End}OfParagraph" work correctly when a
// text position is on a preserved newline character.
//
// Newline characters are used to separate paragraphs. If there is a series of
// newline characters, a paragraph should start after the last newline
// character.
// ++1 kRootWebArea isLineBreakingObject
// ++++2 kStaticText "some text"
// ++++++3 kInlineTextBox "some text"
// ++++4 kGenericContainer isLineBreakingObject
// ++++++5 kStaticText "\nmore text"
// ++++++++6 kInlineTextBox "\n" isLineBreakingObject
// ++++++++7 kInlineTextBox "more text"
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
AXNodeData static_text_data_1;
static_text_data_1.id = 2;
static_text_data_1.role = ax::mojom::Role::kStaticText;
static_text_data_1.SetName("some text");
AXNodeData some_text_data;
some_text_data.id = 3;
some_text_data.role = ax::mojom::Role::kInlineTextBox;
some_text_data.SetName("some text");
AXNodeData container_data;
container_data.id = 4;
container_data.role = ax::mojom::Role::kGenericContainer;
container_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData static_text_data_2;
static_text_data_2.id = 5;
static_text_data_2.role = ax::mojom::Role::kStaticText;
static_text_data_2.SetName("\nmore text");
AXNodeData preserved_newline_data;
preserved_newline_data.id = 6;
preserved_newline_data.role = ax::mojom::Role::kInlineTextBox;
preserved_newline_data.SetName("\n");
preserved_newline_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData more_text_data;
more_text_data.id = 7;
more_text_data.role = ax::mojom::Role::kInlineTextBox;
more_text_data.SetName("more text");
static_text_data_1.child_ids = {some_text_data.id};
container_data.child_ids = {static_text_data_2.id};
static_text_data_2.child_ids = {preserved_newline_data.id, more_text_data.id};
root_data.child_ids = {static_text_data_1.id, container_data.id};
SetTree(CreateAXTree({root_data, static_text_data_1, some_text_data,
container_data, static_text_data_2,
preserved_newline_data, more_text_data}));
// Text position "some tex<t>\nmore text".
TestPositionType text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 8 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position1->AtEndOfParagraph());
EXPECT_FALSE(text_position1->AtStartOfParagraph());
// Text position "some text<\n>more text".
TestPositionType text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 9 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position2->AtEndOfParagraph());
EXPECT_FALSE(text_position2->AtStartOfParagraph());
// Text position "some text<\n>more text".
TestPositionType text_position3 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 9 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
EXPECT_FALSE(text_position3->AtEndOfParagraph());
EXPECT_FALSE(text_position3->AtStartOfParagraph());
// Text position "some text\n<m>ore text".
TestPositionType text_position4 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 10 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position4->AtEndOfParagraph());
EXPECT_TRUE(text_position4->AtStartOfParagraph());
// Text position "some text\n<m>ore text".
TestPositionType text_position5 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 10 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
EXPECT_TRUE(text_position5->AtEndOfParagraph());
EXPECT_FALSE(text_position5->AtStartOfParagraph());
// Text position "<\n>more text".
TestPositionType text_position6 = AXNodePosition::CreateTextPosition(
GetTreeID(), container_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position6->AtEndOfParagraph());
EXPECT_FALSE(text_position6->AtStartOfParagraph());
// Text position "\n<m>ore text".
TestPositionType text_position7 = AXNodePosition::CreateTextPosition(
GetTreeID(), container_data.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position7->AtEndOfParagraph());
EXPECT_TRUE(text_position7->AtStartOfParagraph());
// Text position "\n<m>ore text".
TestPositionType text_position8 = AXNodePosition::CreateTextPosition(
GetTreeID(), container_data.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
EXPECT_TRUE(text_position8->AtEndOfParagraph());
EXPECT_FALSE(text_position8->AtStartOfParagraph());
// Text position "\n<m>ore text".
TestPositionType text_position9 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text_data_2.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position9->AtEndOfParagraph());
EXPECT_TRUE(text_position9->AtStartOfParagraph());
// Text position "\n<m>ore text".
TestPositionType text_position10 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text_data_2.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
EXPECT_TRUE(text_position10->AtEndOfParagraph());
EXPECT_FALSE(text_position10->AtStartOfParagraph());
TestPositionType text_position11 = AXNodePosition::CreateTextPosition(
GetTreeID(), preserved_newline_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position11->AtEndOfParagraph());
EXPECT_FALSE(text_position11->AtStartOfParagraph());
TestPositionType text_position12 = AXNodePosition::CreateTextPosition(
GetTreeID(), preserved_newline_data.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(text_position12->AtEndOfParagraph());
EXPECT_FALSE(text_position12->AtStartOfParagraph());
TestPositionType text_position13 = AXNodePosition::CreateTextPosition(
GetTreeID(), more_text_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position13->AtEndOfParagraph());
EXPECT_TRUE(text_position13->AtStartOfParagraph());
TestPositionType text_position14 = AXNodePosition::CreateTextPosition(
GetTreeID(), more_text_data.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position14->AtEndOfParagraph());
EXPECT_FALSE(text_position14->AtStartOfParagraph());
}
TEST_F(
AXPositionTest,
PreviousParagraphEndStopAtAnchorBoundaryWithConsecutiveParentChildLineBreakingObjects) {
// This test updates the tree structure to test a specific edge case -
// CreatePreviousParagraphEndPosition(), stopping at an anchor boundary,
// with consecutive parent-child line breaking objects.
// ++1 rootWebArea
// ++++2 staticText name="first"
// ++++3 genericContainer isLineBreakingObject
// ++++++4 genericContainer isLineBreakingObject
// ++++++5 staticText name="second"
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData static_text_data_a;
static_text_data_a.id = 2;
static_text_data_a.role = ax::mojom::Role::kStaticText;
static_text_data_a.SetName("first");
AXNodeData container_data_a;
container_data_a.id = 3;
container_data_a.role = ax::mojom::Role::kGenericContainer;
container_data_a.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData container_data_b;
container_data_b.id = 4;
container_data_b.role = ax::mojom::Role::kGenericContainer;
container_data_b.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData static_text_data_b;
static_text_data_b.id = 5;
static_text_data_b.role = ax::mojom::Role::kStaticText;
static_text_data_b.SetName("second");
root_data.child_ids = {static_text_data_a.id, container_data_a.id};
container_data_a.child_ids = {container_data_b.id, static_text_data_b.id};
SetTree(CreateAXTree({root_data, static_text_data_a, container_data_a,
container_data_b, static_text_data_b}));
TestPositionType test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 11 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
test_position = test_position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(root_data.id, test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
}
TEST_F(AXPositionTest, AtStartOrEndOfParagraphOnAListMarker) {
// "AtStartOfParagraph" should return true before a list marker, either a
// Legacy Layout or an NG Layout one. It should return false on the next
// sibling of the list marker, i.e., before the list item's actual text
// contents.
//
// There are two list markers in the following test tree. The first one is a
// Legacy Layout one and the second an NG Layout one.
// ++1 kRootWebArea
// ++++2 kStaticText "Before list."
// ++++++3 kInlineTextBox "Before list."
// ++++4 kList
// ++++++5 kListItem
// ++++++++6 kListMarker
// ++++++++++7 kStaticText "1. "
// ++++++++++++8 kInlineTextBox "1. "
// ++++++++9 kStaticText "First item."
// ++++++++++10 kInlineTextBox "First item."
// ++++++11 kListItem
// ++++++++12 kListMarker "2. "
// ++++++++13 kStaticText "Second item."
// ++++++++++14 kInlineTextBox "Second item."
// ++15 kStaticText "After list."
// ++++16 kInlineTextBox "After list."
AXNodeData root;
AXNodeData list;
AXNodeData list_item1;
AXNodeData list_item2;
AXNodeData list_marker_legacy;
AXNodeData list_marker_ng;
AXNodeData static_text1;
AXNodeData static_text2;
AXNodeData static_text3;
AXNodeData static_text4;
AXNodeData static_text5;
AXNodeData inline_box1;
AXNodeData inline_box2;
AXNodeData inline_box3;
AXNodeData inline_box4;
AXNodeData inline_box5;
root.id = 1;
static_text1.id = 2;
inline_box1.id = 3;
list.id = 4;
list_item1.id = 5;
list_marker_legacy.id = 6;
static_text2.id = 7;
inline_box2.id = 8;
static_text3.id = 9;
inline_box3.id = 10;
list_item2.id = 11;
list_marker_ng.id = 12;
static_text4.id = 13;
inline_box4.id = 14;
static_text5.id = 15;
inline_box5.id = 16;
root.role = ax::mojom::Role::kRootWebArea;
root.child_ids = {static_text1.id, list.id, static_text5.id};
root.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
static_text1.role = ax::mojom::Role::kStaticText;
static_text1.child_ids = {inline_box1.id};
static_text1.SetName("Before list.");
inline_box1.role = ax::mojom::Role::kInlineTextBox;
inline_box1.SetName("Before list.");
list.role = ax::mojom::Role::kList;
list.child_ids = {list_item1.id, list_item2.id};
list_item1.role = ax::mojom::Role::kListItem;
list_item1.child_ids = {list_marker_legacy.id, static_text3.id};
list_item1.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
list_marker_legacy.role = ax::mojom::Role::kListMarker;
list_marker_legacy.child_ids = {static_text2.id};
static_text2.role = ax::mojom::Role::kStaticText;
static_text2.child_ids = {inline_box2.id};
static_text2.SetName("1. ");
inline_box2.role = ax::mojom::Role::kInlineTextBox;
inline_box2.SetName("1. ");
inline_box2.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
inline_box3.id);
static_text3.role = ax::mojom::Role::kStaticText;
static_text3.child_ids = {inline_box3.id};
static_text3.SetName("First item.");
inline_box3.role = ax::mojom::Role::kInlineTextBox;
inline_box3.SetName("First item.");
inline_box3.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
inline_box2.id);
list_item2.role = ax::mojom::Role::kListItem;
list_item2.child_ids = {list_marker_ng.id, static_text4.id};
list_item2.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
list_marker_ng.role = ax::mojom::Role::kListMarker;
list_marker_ng.SetName("2. ");
list_marker_ng.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
inline_box4.id);
static_text4.role = ax::mojom::Role::kStaticText;
static_text4.child_ids = {inline_box4.id};
static_text4.SetName("Second item.");
inline_box4.role = ax::mojom::Role::kInlineTextBox;
inline_box4.SetName("Second item.");
inline_box4.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
list_marker_ng.id);
static_text5.role = ax::mojom::Role::kStaticText;
static_text5.child_ids = {inline_box5.id};
static_text5.SetName("After list.");
inline_box5.role = ax::mojom::Role::kInlineTextBox;
inline_box5.SetName("After list.");
SetTree(CreateAXTree({root, static_text1, inline_box1, list, list_item1,
list_marker_legacy, static_text2, inline_box2,
static_text3, inline_box3, list_item2, list_marker_ng,
static_text4, inline_box4, static_text5, inline_box5}));
// A text position after the text "Before list.". It should not be equivalent
// to a position that is before the list itself, or before the first list
// bullet / item.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text1.id, 12 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_TRUE(text_position->AtEndOfParagraph());
// A text position after the text "Before list.". It should not be equivalent
// to a position that is before the list itself, or before the first list
// bullet / item.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1.id, 12 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_TRUE(text_position->AtEndOfParagraph());
// A text position before the list.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), list.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// A downstream text position after the list. It should resolve to a leaf
// position before the paragraph that comes after the list, so it should be
// "AtStartOfParagraph".
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), list.id, 14 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// An upstream text position after the list. It should be "AtEndOfParagraph".
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), list.id, 14 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_TRUE(text_position->AtEndOfParagraph());
// A text position before the first list bullet (the Legacy Layout one).
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), list_marker_legacy.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), list_marker_legacy.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// A text position before the first list bullet (the Legacy Layout one).
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text2.id, 2 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// A text position before the first list bullet (the Legacy Layout one).
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2.id, 3 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// A text position before the second list bullet (the NG Layout one).
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), list_marker_ng.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), list_marker_ng.id, 3 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// A text position before the text contents of the first list item - not the
// bullet.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text3.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// A text position before the text contents of the first list item - not the
// bullet.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box3.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// A text position after the text contents of the first list item.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text3.id, 11 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_TRUE(text_position->AtEndOfParagraph());
// A text position after the text contents of the first list item.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box3.id, 11 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_TRUE(text_position->AtEndOfParagraph());
// A text position before the text contents of the second list item - not the
// bullet.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text4.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// A text position before the text contents of the second list item - not the
// bullet.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box4.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
// A text position after the text contents of the second list item.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text4.id, 12 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_TRUE(text_position->AtEndOfParagraph());
// A text position after the text contents of the second list item.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box4.id, 12 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtStartOfParagraph());
EXPECT_TRUE(text_position->AtEndOfParagraph());
// A text position before the text "After list.".
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box5.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->AtStartOfParagraph());
EXPECT_FALSE(text_position->AtEndOfParagraph());
}
TEST_F(AXPositionTest,
AtStartOrEndOfParagraphWithLeadingAndTrailingDocumentWhitespace) {
// This test ensures that "At{Start|End}OfParagraph" work correctly when a
// text position is on a preserved newline character.
//
// Newline characters are used to separate paragraphs. If there is a series of
// newline characters, a paragraph should start after the last newline
// character.
// ++1 kRootWebArea isLineBreakingObject
// ++++2 kGenericContainer isLineBreakingObject
// ++++++3 kStaticText "\n"
// ++++++++4 kInlineTextBox "\n" isLineBreakingObject
// ++++5 kGenericContainer isLineBreakingObject
// ++++++6 kStaticText "some text"
// ++++++++7 kInlineTextBox "some"
// ++++++++8 kInlineTextBox " "
// ++++++++9 kInlineTextBox "text"
// ++++10 kGenericContainer isLineBreakingObject
// ++++++11 kStaticText "\n"
// ++++++++12 kInlineTextBox "\n" isLineBreakingObject
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
AXNodeData container_data_a;
container_data_a.id = 2;
container_data_a.role = ax::mojom::Role::kGenericContainer;
container_data_a.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData static_text_data_a;
static_text_data_a.id = 3;
static_text_data_a.role = ax::mojom::Role::kStaticText;
static_text_data_a.SetName("\n");
AXNodeData inline_text_data_a;
inline_text_data_a.id = 4;
inline_text_data_a.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_a.SetName("\n");
inline_text_data_a.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData container_data_b;
container_data_b.id = 5;
container_data_b.role = ax::mojom::Role::kGenericContainer;
container_data_b.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData static_text_data_b;
static_text_data_b.id = 6;
static_text_data_b.role = ax::mojom::Role::kStaticText;
static_text_data_b.SetName("some text");
AXNodeData inline_text_data_b_1;
inline_text_data_b_1.id = 7;
inline_text_data_b_1.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_b_1.SetName("some");
AXNodeData inline_text_data_b_2;
inline_text_data_b_2.id = 8;
inline_text_data_b_2.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_b_2.SetName(" ");
AXNodeData inline_text_data_b_3;
inline_text_data_b_3.id = 9;
inline_text_data_b_3.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_b_3.SetName("text");
AXNodeData container_data_c;
container_data_c.id = 10;
container_data_c.role = ax::mojom::Role::kGenericContainer;
container_data_c.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData static_text_data_c;
static_text_data_c.id = 11;
static_text_data_c.role = ax::mojom::Role::kStaticText;
static_text_data_c.SetName("\n");
AXNodeData inline_text_data_c;
inline_text_data_c.id = 12;
inline_text_data_c.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_c.SetName("\n");
inline_text_data_c.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
root_data.child_ids = {container_data_a.id, container_data_b.id,
container_data_c.id};
container_data_a.child_ids = {static_text_data_a.id};
static_text_data_a.child_ids = {inline_text_data_a.id};
container_data_b.child_ids = {static_text_data_b.id};
static_text_data_b.child_ids = {inline_text_data_b_1.id,
inline_text_data_b_2.id,
inline_text_data_b_3.id};
container_data_c.child_ids = {static_text_data_c.id};
static_text_data_c.child_ids = {inline_text_data_c.id};
SetTree(CreateAXTree(
{root_data, container_data_a, container_data_b, container_data_c,
static_text_data_a, static_text_data_b, static_text_data_c,
inline_text_data_a, inline_text_data_b_1, inline_text_data_b_2,
inline_text_data_b_3, inline_text_data_c}));
// Before the first "\n".
TestPositionType text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_a.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position1->AtEndOfParagraph());
EXPECT_TRUE(text_position1->AtStartOfParagraph());
// After the first "\n".
//
// Since the position is an "after text" position, it is similar to pressing
// the End key, (or Cmd-Right on Mac), while the caret is on the line break,
// so it should not be "AtStartOfParagraph".
TestPositionType text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_a.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(text_position2->AtEndOfParagraph());
EXPECT_FALSE(text_position2->AtStartOfParagraph());
// Before "some".
TestPositionType text_position3 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_1.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position3->AtEndOfParagraph());
EXPECT_TRUE(text_position3->AtStartOfParagraph());
// After "some".
TestPositionType text_position4 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_1.id, 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position4->AtEndOfParagraph());
EXPECT_FALSE(text_position4->AtStartOfParagraph());
// Before " ".
TestPositionType text_position5 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position5->AtEndOfParagraph());
EXPECT_FALSE(text_position5->AtStartOfParagraph());
// After " ".
TestPositionType text_position6 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_2.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position6->AtEndOfParagraph());
EXPECT_FALSE(text_position6->AtStartOfParagraph());
// Before "text".
TestPositionType text_position7 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_3.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position7->AtEndOfParagraph());
EXPECT_FALSE(text_position7->AtStartOfParagraph());
// After "text".
TestPositionType text_position8 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_3.id, 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position8->AtEndOfParagraph());
EXPECT_FALSE(text_position8->AtStartOfParagraph());
// Before the second "\n".
TestPositionType text_position9 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_c.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position9->AtEndOfParagraph());
EXPECT_FALSE(text_position9->AtStartOfParagraph());
// After the second "\n".
TestPositionType text_position10 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_c.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(text_position10->AtEndOfParagraph());
EXPECT_FALSE(text_position10->AtStartOfParagraph());
}
TEST_F(AXPositionTest, AtStartOrEndOfParagraphWithIgnoredNodes) {
// This test ensures that "At{Start|End}OfParagraph" work correctly when there
// are ignored nodes present near a paragraph boundary.
//
// An ignored node that is between a given position and a paragraph boundary
// should not be taken into consideration. The position should be interpreted
// as being on the boundary.
// ++1 kRootWebArea isLineBreakingObject
// ++++2 kGenericContainer ignored isLineBreakingObject
// ++++++3 kStaticText ignored "ignored text"
// ++++++++4 kInlineTextBox ignored "ignored text"
// ++++5 kGenericContainer isLineBreakingObject
// ++++++6 kStaticText "some text"
// ++++++++7 kInlineTextBox "some"
// ++++++++8 kInlineTextBox " "
// ++++++++9 kInlineTextBox "text"
// ++++10 kGenericContainer ignored isLineBreakingObject
// ++++++11 kStaticText ignored "ignored text"
// ++++++++12 kInlineTextBox ignored "ignored text"
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
AXNodeData container_data_a;
container_data_a.id = 2;
container_data_a.role = ax::mojom::Role::kGenericContainer;
container_data_a.AddState(ax::mojom::State::kIgnored);
container_data_a.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData static_text_data_a;
static_text_data_a.id = 3;
static_text_data_a.role = ax::mojom::Role::kStaticText;
static_text_data_a.SetName("ignored text");
static_text_data_a.AddState(ax::mojom::State::kIgnored);
AXNodeData inline_text_data_a;
inline_text_data_a.id = 4;
inline_text_data_a.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_a.SetName("ignored text");
inline_text_data_a.AddState(ax::mojom::State::kIgnored);
AXNodeData container_data_b;
container_data_b.id = 5;
container_data_b.role = ax::mojom::Role::kGenericContainer;
container_data_b.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData static_text_data_b;
static_text_data_b.id = 6;
static_text_data_b.role = ax::mojom::Role::kStaticText;
static_text_data_b.SetName("some text");
AXNodeData inline_text_data_b_1;
inline_text_data_b_1.id = 7;
inline_text_data_b_1.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_b_1.SetName("some");
AXNodeData inline_text_data_b_2;
inline_text_data_b_2.id = 8;
inline_text_data_b_2.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_b_2.SetName(" ");
AXNodeData inline_text_data_b_3;
inline_text_data_b_3.id = 9;
inline_text_data_b_3.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_b_3.SetName("text");
AXNodeData container_data_c;
container_data_c.id = 10;
container_data_c.role = ax::mojom::Role::kGenericContainer;
container_data_c.AddState(ax::mojom::State::kIgnored);
container_data_c.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData static_text_data_c;
static_text_data_c.id = 11;
static_text_data_c.role = ax::mojom::Role::kStaticText;
static_text_data_c.SetName("ignored text");
static_text_data_c.AddState(ax::mojom::State::kIgnored);
AXNodeData inline_text_data_c;
inline_text_data_c.id = 12;
inline_text_data_c.role = ax::mojom::Role::kInlineTextBox;
inline_text_data_c.SetName("ignored text");
inline_text_data_c.AddState(ax::mojom::State::kIgnored);
root_data.child_ids = {container_data_a.id, container_data_b.id,
container_data_c.id};
container_data_a.child_ids = {static_text_data_a.id};
static_text_data_a.child_ids = {inline_text_data_a.id};
container_data_b.child_ids = {static_text_data_b.id};
static_text_data_b.child_ids = {inline_text_data_b_1.id,
inline_text_data_b_2.id,
inline_text_data_b_3.id};
container_data_c.child_ids = {static_text_data_c.id};
static_text_data_c.child_ids = {inline_text_data_c.id};
SetTree(CreateAXTree(
{root_data, container_data_a, container_data_b, container_data_c,
static_text_data_a, static_text_data_b, static_text_data_c,
inline_text_data_a, inline_text_data_b_1, inline_text_data_b_2,
inline_text_data_b_3, inline_text_data_c}));
// Before "ignored text".
TestPositionType text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_a.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position1->AtEndOfParagraph());
EXPECT_FALSE(text_position1->AtStartOfParagraph());
// After "ignored text".
//
// Since the position is an "after text" position, it is similar to pressing
// the End key, (or Cmd-Right on Mac), while the caret is on "ignored text",
// so it should not be "AtStartOfParagraph". In practice, this situation
// should not arise in accessibility, because the node is ignored.
TestPositionType text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_a.id, 12 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position2->AtEndOfParagraph());
EXPECT_FALSE(text_position2->AtStartOfParagraph());
// Before "some".
TestPositionType text_position3 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_1.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position3->AtEndOfParagraph());
EXPECT_TRUE(text_position3->AtStartOfParagraph());
// After "some".
TestPositionType text_position4 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_1.id, 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position4->AtEndOfParagraph());
EXPECT_FALSE(text_position4->AtStartOfParagraph());
// Before " ".
TestPositionType text_position5 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position5->AtEndOfParagraph());
EXPECT_FALSE(text_position5->AtStartOfParagraph());
// After " ".
TestPositionType text_position6 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_2.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position6->AtEndOfParagraph());
EXPECT_FALSE(text_position6->AtStartOfParagraph());
// Before "text".
TestPositionType text_position7 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_3.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position7->AtEndOfParagraph());
EXPECT_FALSE(text_position7->AtStartOfParagraph());
// After "text".
TestPositionType text_position8 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_b_3.id, 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(text_position8->AtEndOfParagraph());
EXPECT_FALSE(text_position8->AtStartOfParagraph());
// Before "ignored text" - the second version.
TestPositionType text_position9 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_c.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position9->AtEndOfParagraph());
EXPECT_FALSE(text_position9->AtStartOfParagraph());
// After "ignored text" - the second version.
TestPositionType text_position10 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_text_data_c.id, 12 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position10->AtEndOfParagraph());
EXPECT_FALSE(text_position10->AtStartOfParagraph());
}
TEST_F(AXPositionTest, AtStartOrEndOfParagraphWithEmbeddedObjectCharacter) {
g_ax_embedded_object_behavior = AXEmbeddedObjectBehavior::kExposeCharacter;
// This test ensures that "At{Start|End}OfParagraph" work correctly when there
// are embedded objects present near a paragraph boundary.
//
// Nodes represented by an embedded object character, such as a plain text
// field or a check box, should create an implicit paragraph boundary for
// assistive software.
// ++1 kRootWebArea isLineBreakingObject
// ++++2 kLink
// ++++++3 kStaticText "hello"
// ++++++++4 kInlineTextBox "hello"
// ++++++5 kImage
// ++++++6 kStaticText "world"
// ++++++++7 kInlineTextBox "world"
AXNodeData root_1;
AXNodeData link_2;
AXNodeData static_text_3;
AXNodeData inline_box_4;
AXNodeData image_5;
AXNodeData static_text_6;
AXNodeData inline_box_7;
root_1.id = 1;
link_2.id = 2;
static_text_3.id = 3;
inline_box_4.id = 4;
image_5.id = 5;
static_text_6.id = 6;
inline_box_7.id = 7;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {link_2.id};
root_1.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
link_2.role = ax::mojom::Role::kLink;
link_2.child_ids = {static_text_3.id, image_5.id, static_text_6.id};
static_text_3.role = ax::mojom::Role::kStaticText;
static_text_3.child_ids = {inline_box_4.id};
static_text_3.SetName("Hello");
inline_box_4.role = ax::mojom::Role::kInlineTextBox;
inline_box_4.SetName("Hello");
image_5.role = ax::mojom::Role::kImage;
// The image's inner text should be an embedded object character.
static_text_6.role = ax::mojom::Role::kStaticText;
static_text_6.child_ids = {inline_box_7.id};
static_text_6.SetName("world");
inline_box_7.role = ax::mojom::Role::kInlineTextBox;
inline_box_7.SetName("world");
SetTree(CreateAXTree({root_1, link_2, static_text_3, inline_box_4, image_5,
static_text_6, inline_box_7}));
// Before "hello".
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_4.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position->AtEndOfParagraph());
EXPECT_TRUE(text_position->AtStartOfParagraph());
// After "hello".
//
// Note that even though this position and a position before the image's
// embedded object character are conceptually equivalent, in practice they
// should result from two different ancestor positions. The former should have
// been an upstream position, whilst the latter a downstream one.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_4.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(text_position->AtEndOfParagraph());
EXPECT_FALSE(text_position->AtStartOfParagraph());
// Before the image's embedded object character.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), image_5.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position->AtEndOfParagraph());
EXPECT_TRUE(text_position->AtStartOfParagraph());
// After the image's embedded object character.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), image_5.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(text_position->AtEndOfParagraph());
EXPECT_FALSE(text_position->AtStartOfParagraph());
// Before "world".
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_7.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_FALSE(text_position->AtEndOfParagraph());
EXPECT_TRUE(text_position->AtStartOfParagraph());
// After "world".
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_7.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(text_position->AtEndOfParagraph());
EXPECT_FALSE(text_position->AtStartOfParagraph());
}
TEST_F(AXPositionTest, LowestCommonAncestor) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
// An "after children" position.
TestPositionType root_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 3 /* child_index */);
ASSERT_NE(nullptr, root_position);
// A "before text" position.
TestPositionType button_position = AXNodePosition::CreateTreePosition(
GetTreeID(), button_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_NE(nullptr, button_position);
TestPositionType text_field_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 2 /* child_index */);
ASSERT_NE(nullptr, text_field_position);
TestPositionType static_text1_position = AXNodePosition::CreateTreePosition(
GetTreeID(), static_text1_.id, 0 /* child_index */);
ASSERT_NE(nullptr, static_text1_position);
TestPositionType static_text2_position = AXNodePosition::CreateTreePosition(
GetTreeID(), static_text2_.id, 0 /* child_index */);
ASSERT_NE(nullptr, static_text2_position);
TestPositionType inline_box1_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, inline_box1_position);
ASSERT_TRUE(inline_box1_position->IsTextPosition());
TestPositionType inline_box2_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, inline_box2_position);
ASSERT_TRUE(inline_box2_position->IsTextPosition());
TestPositionType test_position =
root_position->LowestCommonAncestor(*null_position.get());
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = root_position->LowestCommonAncestor(*root_position.get());
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(root_.id, test_position->anchor_id());
// The child index should be for an "after children" position, i.e. it should
// be unchanged.
EXPECT_EQ(3, test_position->child_index());
test_position =
button_position->LowestCommonAncestor(*text_field_position.get());
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(root_.id, test_position->anchor_id());
// The child index should point to the button.
EXPECT_EQ(0, test_position->child_index());
test_position =
static_text2_position->LowestCommonAncestor(*static_text1_position.get());
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
// The child index should point to the second static text node.
EXPECT_EQ(2, test_position->child_index());
test_position =
static_text1_position->LowestCommonAncestor(*text_field_position.get());
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
// The child index should point to the first static text node.
EXPECT_EQ(0, test_position->child_index());
test_position =
inline_box1_position->LowestCommonAncestor(*inline_box2_position.get());
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position =
inline_box2_position->LowestCommonAncestor(*inline_box1_position.get());
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
// The text offset should point to the second line.
EXPECT_EQ(7, test_position->text_offset());
}
TEST_F(AXPositionTest, AsTreePositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->AsTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, AsTreePositionWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position = tree_position->AsTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(root_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->child_index());
EXPECT_EQ(AXNodePosition::INVALID_OFFSET, test_position->text_offset());
}
TEST_F(AXPositionTest, AsTreePositionWithTextPosition) {
// Create a text position pointing to the last character in the text field.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 12 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position = text_position->AsTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
// The created tree position should point to the second static text node
// inside the text field.
EXPECT_EQ(2, test_position->child_index());
// But its text offset should be unchanged.
EXPECT_EQ(12, test_position->text_offset());
// Test for a "before text" position.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
EXPECT_EQ(0, test_position->text_offset());
// Test for an "after text" position.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
EXPECT_EQ(6, test_position->text_offset());
}
TEST_F(AXPositionTest, AsTextPositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->AsTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, AsTextPositionWithTreePosition) {
// Create a tree position pointing to the line break node inside the text
// field.
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position = tree_position->AsTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
// The created text position should point to the 6th character inside the text
// field, i.e. the line break.
EXPECT_EQ(6, test_position->text_offset());
// But its child index should be unchanged.
EXPECT_EQ(1, test_position->child_index());
// And the affinity cannot be anything other than downstream because we
// haven't moved up the tree and so there was no opportunity to introduce any
// ambiguity regarding the new position.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Test for a "before text" position.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->AsTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Test for an "after text" position.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->AsTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
EXPECT_EQ(0, test_position->child_index());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, AsTextPositionWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position = text_position->AsTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
EXPECT_EQ(AXNodePosition::INVALID_INDEX, test_position->child_index());
}
TEST_F(AXPositionTest, AsLeafTreePositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, AsLeafTreePositionWithTreePosition) {
// Create a tree position pointing to the first static text node inside the
// text field: a "before children" position.
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position = tree_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// Create a tree position pointing to the line break node inside the text
// field.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// Create a text position pointing to the second static text node inside the
// text field.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 2 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
}
TEST_F(AXPositionTest, AsLeafTreePositionWithTextPosition) {
// Create a text position pointing to the end of the root (an "after text"
// position).
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 13 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// Create a text position on the root, pointing to the line break character
// inside the text field but with an upstream affinity which will cause the
// leaf text position to be placed after the text of the first inline text
// box.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// Create a text position pointing to the line break character inside the text
// field but with an upstream affinity which will cause the leaf text position
// to be placed after the text of the first inline text box.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// Create a text position on the root, pointing to the line break character
// inside the text field.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// Create a text position pointing to the line break character inside the text
// field.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// Create a text position pointing to the offset after the last character in
// the text field, (an "after text" position).
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 13 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// Create a root text position that points to the middle of an equivalent leaf
// text position.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 10 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTreePosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTreePosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
}
TEST_F(AXPositionTest, AsLeafTextPositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, AsLeafTextPositionWithTreePosition) {
// Create a tree position pointing to the first static text node inside the
// text field.
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position = tree_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Create a tree position pointing to the line break node inside the text
// field.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Create a text position pointing to the second static text node inside the
// text field.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 2 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, AsLeafTextPositionWithTextPosition) {
// Create a text position pointing to the end of the root (an "after text"
// position).
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 13 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_FALSE(text_position->IsLeafTextPosition());
TestPositionType test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Create a text position on the root, pointing to the line break character
// inside the text field but with an upstream affinity which will cause the
// leaf text position to be placed after the text of the first inline text
// box.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Create a text position pointing to the line break character inside the text
// field but with an upstream affinity which will cause the leaf text position
// to be placed after the text of the first inline text box.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Create a text position on the root, pointing to the line break character
// inside the text field.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Create a text position pointing to the line break character inside the text
// field.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Create a text position pointing to the offset after the last character in
// the text field, (an "after text" position).
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 13 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Create a root text position that points to the middle of a leaf text
// position, should maintain its relative text_offset ("Lin<e> 2")
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 10 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(3, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// Create a root text position that points to the middle of an equivalent leaf
// text position. It should maintain its relative text_offset ("Lin<e> 2")
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 10 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(3, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, AsLeafTextPositionWithTextPositionAndEmptyTextSandwich) {
// This test updates the tree structure to test a specific edge case -
// AsLeafTextPosition when there is an empty leaf text node between
// two non-empty text nodes.
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kInlineTextBox;
text_data.SetName("some text");
AXNodeData button_data;
button_data.id = 3;
button_data.role = ax::mojom::Role::kButton;
button_data.SetName("");
AXNodeData more_text_data;
more_text_data.id = 4;
more_text_data.role = ax::mojom::Role::kInlineTextBox;
more_text_data.SetName("more text");
root_data.child_ids = {text_data.id, button_data.id, more_text_data.id};
SetTree(CreateAXTree({root_data, text_data, button_data, more_text_data}));
// Create a text position on the root pointing to just after the
// first static text leaf node.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 9 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_FALSE(text_position->IsLeafTextPosition());
TestPositionType test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(button_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 9 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->AsLeafTextPosition();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsLeafTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(text_data.id, test_position->anchor_id());
EXPECT_EQ(9, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, AsUnignoredPosition) {
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData static_text_data_1;
static_text_data_1.id = 2;
static_text_data_1.role = ax::mojom::Role::kStaticText;
static_text_data_1.SetName("12");
AXNodeData inline_box_data_1;
inline_box_data_1.id = 3;
inline_box_data_1.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_1.SetName("1");
AXNodeData inline_box_data_2;
inline_box_data_2.id = 4;
inline_box_data_2.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_2.SetName("2");
inline_box_data_2.AddState(ax::mojom::State::kIgnored);
AXNodeData container_data;
container_data.id = 5;
container_data.role = ax::mojom::Role::kGenericContainer;
container_data.AddState(ax::mojom::State::kIgnored);
AXNodeData static_text_data_2;
static_text_data_2.id = 6;
static_text_data_2.role = ax::mojom::Role::kStaticText;
static_text_data_2.SetName("3");
AXNodeData inline_box_data_3;
inline_box_data_3.id = 7;
inline_box_data_3.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_3.SetName("3");
static_text_data_1.child_ids = {inline_box_data_1.id, inline_box_data_2.id};
container_data.child_ids = {static_text_data_2.id};
static_text_data_2.child_ids = {inline_box_data_3.id};
root_data.child_ids = {static_text_data_1.id, container_data.id};
SetTree(CreateAXTree({root_data, static_text_data_1, inline_box_data_1,
inline_box_data_2, container_data, static_text_data_2,
inline_box_data_3}));
// 1. In the case of a text position, we move up the parent positions until we
// find the next unignored equivalent parent position. We don't do this for
// tree positions because, unlike text positions which maintain the
// corresponding text offset in the inner text of the parent node, tree
// positions would lose some information every time a parent position is
// computed. In other words, the parent position of a tree position is, in
// most cases, non-equivalent to the child position.
// "Before text" position.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), container_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsIgnored());
TestPositionType test_position = text_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(root_data.id, test_position->anchor_id());
EXPECT_EQ(2, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// "After text" position.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), container_data.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsIgnored());
// Changing the adjustment behavior should not affect the outcome.
test_position = text_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(root_data.id, test_position->anchor_id());
EXPECT_EQ(3, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
// "Before children" position.
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), container_data.id, 0 /* child_index */);
ASSERT_TRUE(tree_position->IsIgnored());
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// "After children" position.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), container_data.id, 1 /* child_index */);
ASSERT_TRUE(tree_position->IsIgnored());
// Changing the adjustment behavior should not affect the outcome.
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// "After children" tree positions that are anchored to an unignored node
// whose last child is ignored.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), static_text_data_1.id, 2 /* child_index */);
ASSERT_TRUE(tree_position->IsIgnored());
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_1.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// 2. If no equivalent and unignored parent position can be computed, we try
// computing the leaf equivalent position. If this is unignored, we return it.
// This can happen both for tree and text positions, provided that the leaf
// node and its inner text is visible to platform APIs, i.e. it's unignored.
root_data.AddState(ax::mojom::State::kIgnored);
SetTree(CreateAXTree({root_data, static_text_data_1, inline_box_data_1,
inline_box_data_2, container_data, static_text_data_2,
inline_box_data_3}));
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsIgnored());
test_position = text_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box_data_1.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsIgnored());
// Changing the adjustment behavior should not change the outcome.
test_position = text_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box_data_1.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_data.id,
1 /* child_index */);
ASSERT_TRUE(tree_position->IsIgnored());
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// Changing the adjustment behavior should not affect the outcome.
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// "After children" position.
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_data.id,
2 /* child_index */);
ASSERT_TRUE(tree_position->IsIgnored());
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// Changing the adjustment behavior should not affect the outcome.
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// "Before children" position.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), container_data.id, 0 /* child_index */);
ASSERT_TRUE(tree_position->IsIgnored());
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// "After children" position.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), container_data.id, 1 /* child_index */);
ASSERT_TRUE(tree_position->IsIgnored());
// Changing the adjustment behavior should not affect the outcome.
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// 3. As a last resort, we move either to the next or previous unignored
// position in the accessibility tree, based on the "adjustment_behavior".
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_data.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsIgnored());
test_position = text_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_data_2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsIgnored());
test_position = text_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_data_2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsIgnored());
test_position = text_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box_data_1.id, test_position->anchor_id());
// This should be an "after text" position.
EXPECT_EQ(1, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box_data_2.id, AXNodePosition::BEFORE_TEXT);
ASSERT_TRUE(tree_position->IsIgnored());
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
ASSERT_TRUE(tree_position->IsIgnored());
test_position = tree_position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box_data_1.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
}
TEST_F(AXPositionTest, CreatePositionAtTextBoundaryDocumentStartEndIsIgnored) {
// +-root_data
// +-static_text_data_1
// | +-inline_box_data_1 IGNORED
// +-static_text_data_2
// | +-inline_box_data_2
// +-static_text_data_3
// | +-inline_box_data_3
// +-static_text_data_4
// +-inline_box_data_4 IGNORED
constexpr AXNode::AXID ROOT_ID = 1;
constexpr AXNode::AXID STATIC_TEXT1_ID = 2;
constexpr AXNode::AXID STATIC_TEXT2_ID = 3;
constexpr AXNode::AXID STATIC_TEXT3_ID = 4;
constexpr AXNode::AXID STATIC_TEXT4_ID = 5;
constexpr AXNode::AXID INLINE_BOX1_ID = 6;
constexpr AXNode::AXID INLINE_BOX2_ID = 7;
constexpr AXNode::AXID INLINE_BOX3_ID = 8;
constexpr AXNode::AXID INLINE_BOX4_ID = 9;
AXNodeData root_data;
root_data.id = ROOT_ID;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData static_text_data_1;
static_text_data_1.id = STATIC_TEXT1_ID;
static_text_data_1.role = ax::mojom::Role::kStaticText;
static_text_data_1.SetName("One");
AXNodeData inline_box_data_1;
inline_box_data_1.id = INLINE_BOX1_ID;
inline_box_data_1.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_1.SetName("One");
inline_box_data_1.AddState(ax::mojom::State::kIgnored);
inline_box_data_1.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0});
inline_box_data_1.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{3});
inline_box_data_1.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
INLINE_BOX2_ID);
AXNodeData static_text_data_2;
static_text_data_2.id = STATIC_TEXT2_ID;
static_text_data_2.role = ax::mojom::Role::kStaticText;
static_text_data_2.SetName("Two");
AXNodeData inline_box_data_2;
inline_box_data_2.id = INLINE_BOX2_ID;
inline_box_data_2.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_2.SetName("Two");
inline_box_data_2.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0});
inline_box_data_2.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{3});
inline_box_data_2.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
INLINE_BOX1_ID);
inline_box_data_2.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
INLINE_BOX3_ID);
AXNodeData static_text_data_3;
static_text_data_3.id = STATIC_TEXT3_ID;
static_text_data_3.role = ax::mojom::Role::kStaticText;
static_text_data_3.SetName("Three");
AXNodeData inline_box_data_3;
inline_box_data_3.id = INLINE_BOX3_ID;
inline_box_data_3.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_3.SetName("Three");
inline_box_data_3.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0});
inline_box_data_3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{5});
inline_box_data_3.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
INLINE_BOX2_ID);
inline_box_data_3.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
INLINE_BOX4_ID);
AXNodeData static_text_data_4;
static_text_data_4.id = STATIC_TEXT4_ID;
static_text_data_4.role = ax::mojom::Role::kStaticText;
static_text_data_4.SetName("Four");
AXNodeData inline_box_data_4;
inline_box_data_4.id = INLINE_BOX4_ID;
inline_box_data_4.role = ax::mojom::Role::kInlineTextBox;
inline_box_data_4.SetName("Four");
inline_box_data_4.AddState(ax::mojom::State::kIgnored);
inline_box_data_3.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0});
inline_box_data_3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{4});
inline_box_data_3.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
INLINE_BOX3_ID);
root_data.child_ids = {static_text_data_1.id, static_text_data_2.id,
static_text_data_3.id, static_text_data_4.id};
static_text_data_1.child_ids = {inline_box_data_1.id};
static_text_data_2.child_ids = {inline_box_data_2.id};
static_text_data_3.child_ids = {inline_box_data_3.id};
static_text_data_4.child_ids = {inline_box_data_4.id};
SetTree(
CreateAXTree({root_data, static_text_data_1, static_text_data_2,
static_text_data_3, static_text_data_4, inline_box_data_1,
inline_box_data_2, inline_box_data_3, inline_box_data_4}));
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_data_2.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_FALSE(text_position->IsIgnored());
TestPositionType test_position = text_position->CreatePositionAtTextBoundary(
ax::mojom::TextBoundary::kWordStart, ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = text_position->CreatePositionAtTextBoundary(
ax::mojom::TextBoundary::kWordStart, ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box_data_2.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_data_3.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_FALSE(text_position->IsIgnored());
test_position = text_position->CreatePositionAtTextBoundary(
ax::mojom::TextBoundary::kWordStart, ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box_data_3.id, test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = text_position->CreatePositionAtTextBoundary(
ax::mojom::TextBoundary::kWordStart, ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box_data_2.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, CreatePositionAtInvalidGraphemeBoundary) {
std::vector<int> text_offsets;
SetTree(CreateMultilingualDocument(&text_offsets));
TestPositionType test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(4, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 10 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(10, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kUpstream, test_position->affinity());
}
TEST_F(AXPositionTest, CreatePositionAtStartOfAnchorWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position =
null_position->CreatePositionAtStartOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtStartOfAnchorWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position =
tree_position->CreatePositionAtStartOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(root_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->CreatePositionAtStartOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(root_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// An "after text" position.
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->CreatePositionAtStartOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
}
TEST_F(AXPositionTest, CreatePositionAtStartOfAnchorWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position =
text_position->CreatePositionAtStartOfAnchor();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreatePositionAtStartOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// Affinity should have been reset to the default value.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, CreatePositionAtEndOfAnchorWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->CreatePositionAtEndOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtEndOfAnchorWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 3 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position = tree_position->CreatePositionAtEndOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(root_.id, test_position->anchor_id());
EXPECT_EQ(3, test_position->child_index());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->CreatePositionAtEndOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(root_.id, test_position->anchor_id());
EXPECT_EQ(3, test_position->child_index());
}
TEST_F(AXPositionTest, CreatePositionAtEndOfAnchorWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position = text_position->CreatePositionAtEndOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreatePositionAtEndOfAnchor();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
// Affinity should have been reset to the default value.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, CreatePositionAtPreviousFormatStartWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position =
null_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtPreviousFormatStartWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), static_text1_.id, 1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
TestPositionType test_position =
tree_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(static_text1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// StopIfAlreadyAtBoundary shouldn't move, since it's already at a boundary.
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// StopAtLastAnchorBoundary should stop at the start of the document while
// CrossBoundary should return a null position when crossing it.
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtPreviousFormatStartWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 2 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position =
text_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// StopIfAlreadyAtBoundary shouldn't move, since it's already at a boundary.
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// StopAtLastAnchorBoundary should stop at the start of the document while
// CrossBoundary should return a null position when crossing it.
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtNextFormatEndWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtNextFormatEndWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), button_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
TestPositionType test_position = tree_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// StopIfAlreadyAtBoundary shouldn't move, since it's already at a boundary.
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// StopAtLastAnchorBoundary should stop at the end of the document while
// CrossBoundary should return a null position when crossing it.
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtNextFormatEndWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), button_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position = text_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
// StopIfAlreadyAtBoundary shouldn't move, since it's already at a boundary.
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
// StopAtLastAnchorBoundary should stop at the end of the document while
// CrossBoundary should return a null position when crossing it.
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
test_position = test_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtFormatBoundaryWithTextPosition) {
// This test updates the tree structure to test a specific edge case -
// CreatePositionAtFormatBoundary when text lies at the beginning and end
// of the AX tree.
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData more_text_data;
more_text_data.id = 3;
more_text_data.role = ax::mojom::Role::kStaticText;
more_text_data.SetName("more text");
root_data.child_ids = {text_data.id, more_text_data.id};
SetTree(CreateAXTree({root_data, text_data, more_text_data}));
// Test CreatePreviousFormatStartPosition at the start of the document.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_data.id, 8 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
TestPositionType test_position =
text_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// Test CreateNextFormatEndPosition at the end of the document.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), more_text_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(more_text_data.id, test_position->anchor_id());
EXPECT_EQ(9, test_position->text_offset());
}
TEST_F(AXPositionTest, MoveByFormatWithIgnoredNodes) {
// ++1 kRootWebArea
// ++++2 kGenericContainer
// ++++++3 kButton
// ++++++++4 kStaticText
// ++++++++++5 kInlineTextBox
// ++++++++6 kSvgRoot ignored
// ++++++++++7 kGenericContainer ignored
// ++++8 kGenericContainer
// ++++++9 kHeading
// ++++++++10 kStaticText
// ++++++++++11 kInlineTextBox
// ++++++12 kStaticText
// ++++++++13 kInlineTextBox
// ++++++14 kGenericContainer ignored
// ++++15 kGenericContainer
// ++++++16 kHeading
// ++++++++17 kStaticText
// ++++++++++18 kInlineTextBox
// ++++19 kGenericContainer
// ++++++20 kGenericContainer ignored
// ++++++21 kStaticText
// ++++++++22 kInlineTextBox
// ++++++23 kHeading
// ++++++++24 kStaticText
// ++++++++++25 kInlineTextBox
AXNodeData root_1;
AXNodeData generic_container_2;
AXNodeData button_3;
AXNodeData static_text_4;
AXNodeData inline_box_5;
AXNodeData svg_root_6;
AXNodeData generic_container_7;
AXNodeData generic_container_8;
AXNodeData heading_9;
AXNodeData static_text_10;
AXNodeData inline_box_11;
AXNodeData static_text_12;
AXNodeData inline_box_13;
AXNodeData generic_container_14;
AXNodeData generic_container_15;
AXNodeData heading_16;
AXNodeData static_text_17;
AXNodeData inline_box_18;
AXNodeData generic_container_19;
AXNodeData generic_container_20;
AXNodeData static_text_21;
AXNodeData inline_box_22;
AXNodeData heading_23;
AXNodeData static_text_24;
AXNodeData inline_box_25;
root_1.id = 1;
generic_container_2.id = 2;
button_3.id = 3;
static_text_4.id = 4;
inline_box_5.id = 5;
svg_root_6.id = 6;
generic_container_7.id = 7;
generic_container_8.id = 8;
heading_9.id = 9;
static_text_10.id = 10;
inline_box_11.id = 11;
static_text_12.id = 12;
inline_box_13.id = 13;
generic_container_14.id = 14;
generic_container_15.id = 15;
heading_16.id = 16;
static_text_17.id = 17;
inline_box_18.id = 18;
generic_container_19.id = 19;
generic_container_20.id = 20;
static_text_21.id = 21;
inline_box_22.id = 22;
heading_23.id = 23;
static_text_24.id = 24;
inline_box_25.id = 25;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {generic_container_2.id, generic_container_8.id,
generic_container_15.id, generic_container_19.id};
generic_container_2.role = ax::mojom::Role::kGenericContainer;
generic_container_2.child_ids = {button_3.id};
button_3.role = ax::mojom::Role::kButton;
button_3.child_ids = {static_text_4.id, svg_root_6.id};
static_text_4.role = ax::mojom::Role::kStaticText;
static_text_4.child_ids = {inline_box_5.id};
static_text_4.SetName("Button");
inline_box_5.role = ax::mojom::Role::kInlineTextBox;
inline_box_5.SetName("Button");
svg_root_6.role = ax::mojom::Role::kSvgRoot;
svg_root_6.child_ids = {generic_container_7.id};
svg_root_6.AddState(ax::mojom::State::kIgnored);
generic_container_7.role = ax::mojom::Role::kGenericContainer;
generic_container_7.AddState(ax::mojom::State::kIgnored);
generic_container_8.role = ax::mojom::Role::kGenericContainer;
generic_container_8.child_ids = {heading_9.id, static_text_12.id,
generic_container_14.id};
heading_9.role = ax::mojom::Role::kHeading;
heading_9.child_ids = {static_text_10.id};
static_text_10.role = ax::mojom::Role::kStaticText;
static_text_10.child_ids = {inline_box_11.id};
static_text_10.SetName("Heading");
inline_box_11.role = ax::mojom::Role::kInlineTextBox;
inline_box_11.SetName("Heading");
static_text_12.role = ax::mojom::Role::kStaticText;
static_text_12.child_ids = {inline_box_13.id};
static_text_12.SetName("3.14");
inline_box_13.role = ax::mojom::Role::kInlineTextBox;
inline_box_13.SetName("3.14");
generic_container_14.role = ax::mojom::Role::kGenericContainer;
generic_container_14.AddState(ax::mojom::State::kIgnored);
generic_container_15.role = ax::mojom::Role::kGenericContainer;
generic_container_15.child_ids = {heading_16.id};
heading_16.role = ax::mojom::Role::kHeading;
heading_16.child_ids = {static_text_17.id};
static_text_17.role = ax::mojom::Role::kStaticText;
static_text_17.child_ids = {inline_box_18.id};
static_text_17.SetName("Heading");
inline_box_18.role = ax::mojom::Role::kInlineTextBox;
inline_box_18.SetName("Heading");
generic_container_19.role = ax::mojom::Role::kGenericContainer;
generic_container_19.child_ids = {generic_container_20.id, static_text_21.id,
heading_23.id};
generic_container_20.role = ax::mojom::Role::kGenericContainer;
generic_container_20.AddState(ax::mojom::State::kIgnored);
static_text_21.role = ax::mojom::Role::kStaticText;
static_text_21.child_ids = {inline_box_22.id};
static_text_21.SetName("3.14");
inline_box_22.role = ax::mojom::Role::kInlineTextBox;
inline_box_22.SetName("3.14");
heading_23.role = ax::mojom::Role::kHeading;
heading_23.child_ids = {static_text_24.id};
static_text_24.role = ax::mojom::Role::kStaticText;
static_text_24.child_ids = {inline_box_25.id};
static_text_24.SetName("Heading");
inline_box_25.role = ax::mojom::Role::kInlineTextBox;
inline_box_25.SetName("Heading");
SetTree(CreateAXTree({root_1,
generic_container_2,
button_3,
static_text_4,
inline_box_5,
svg_root_6,
generic_container_7,
generic_container_8,
heading_9,
static_text_10,
inline_box_11,
static_text_12,
inline_box_13,
generic_container_14,
generic_container_15,
heading_16,
static_text_17,
inline_box_18,
generic_container_19,
generic_container_20,
static_text_21,
inline_box_22,
heading_23,
static_text_24,
inline_box_25}));
// There are two major cases to consider for format boundaries with ignored
// nodes:
// Case 1: When the ignored node is directly next to the current position.
// Case 2: When the ignored node is directly next to the next/previous format
// boundary.
// Case 1
// This test case spans nodes 2 to 11, inclusively.
{
// Forward movement
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_5.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(inline_box_5.id, text_position->anchor_id());
EXPECT_EQ(6, text_position->text_offset());
text_position = text_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(inline_box_11.id, text_position->anchor_id());
EXPECT_EQ(7, text_position->text_offset());
// Backward movement
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_11.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(inline_box_11.id, text_position->anchor_id());
EXPECT_EQ(0, text_position->text_offset());
text_position = text_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(inline_box_5.id, text_position->anchor_id());
EXPECT_EQ(0, text_position->text_offset());
}
// Case 2
// This test case spans nodes 8 to 25.
{
// Forward movement
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_11.id, 7 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(inline_box_11.id, text_position->anchor_id());
EXPECT_EQ(7, text_position->text_offset());
text_position = text_position->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(inline_box_13.id, text_position->anchor_id());
EXPECT_EQ(4, text_position->text_offset());
// Backward movement
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_25.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(inline_box_25.id, text_position->anchor_id());
EXPECT_EQ(0, text_position->text_offset());
text_position = text_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(inline_box_22.id, text_position->anchor_id());
EXPECT_EQ(0, text_position->text_offset());
}
}
TEST_F(AXPositionTest, CreatePositionAtPageBoundaryWithTextPosition) {
AXNodeData root_data, page_1_data, page_1_text_data, page_2_data,
page_2_text_data, page_3_data, page_3_text_data;
SetTree(CreateMultipageDocument(root_data, page_1_data, page_1_text_data,
page_2_data, page_2_text_data, page_3_data,
page_3_text_data));
// Test CreateNextPageStartPosition at the start of the document.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), page_1_text_data.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
// StopIfAlreadyAtBoundary shouldn't move at all since it's at a boundary.
TestPositionType test_position = text_position->CreateNextPageStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_1_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreateNextPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreateNextPageStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// Test CreateNextPageEndPosition until the end of document is reached.
test_position = test_position->CreateNextPageEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(19, test_position->text_offset());
test_position = test_position->CreateNextPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_3_text_data.id, test_position->anchor_id());
EXPECT_EQ(24, test_position->text_offset());
test_position = test_position->CreateNextPageEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_3_text_data.id, test_position->anchor_id());
EXPECT_EQ(24, test_position->text_offset());
// StopAtLastAnchorBoundary shouldn't move past the end of the document.
test_position = test_position->CreateNextPageStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_3_text_data.id, test_position->anchor_id());
EXPECT_EQ(24, test_position->text_offset());
test_position = test_position->CreateNextPageEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_3_text_data.id, test_position->anchor_id());
EXPECT_EQ(24, test_position->text_offset());
// Moving forward past the end should return a null position.
TestPositionType null_position = test_position->CreateNextPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, null_position);
EXPECT_TRUE(null_position->IsNullPosition());
null_position = test_position->CreateNextPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, null_position);
EXPECT_TRUE(null_position->IsNullPosition());
// Now move backward through the document.
text_position = test_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(page_3_text_data.id, text_position->anchor_id());
EXPECT_EQ(24, text_position->text_offset());
test_position = text_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(19, test_position->text_offset());
test_position = text_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(19, test_position->text_offset());
test_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_1_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_1_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// StopAtLastAnchorBoundary shouldn't move past the start of the document.
test_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_1_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(page_1_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// Moving before the start should return a null position.
null_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, null_position);
EXPECT_TRUE(null_position->IsNullPosition());
null_position = test_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, null_position);
EXPECT_TRUE(null_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtPageBoundaryWithTreePosition) {
AXNodeData root_data, page_1_data, page_1_text_data, page_2_data,
page_2_text_data, page_3_data, page_3_text_data;
SetTree(CreateMultipageDocument(root_data, page_1_data, page_1_text_data,
page_2_data, page_2_text_data, page_3_data,
page_3_text_data));
// Test CreateNextPageStartPosition at the start of the document.
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), page_1_data.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
ASSERT_TRUE(tree_position->IsTreePosition());
// StopIfAlreadyAtBoundary shouldn't move at all since it's at a boundary.
TestPositionType test_position = tree_position->CreateNextPageStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_1_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = tree_position->CreateNextPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
test_position = tree_position->CreateNextPageStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// Test CreateNextPageEndPosition until the end of document is reached.
test_position = tree_position->CreateNextPageEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_1_data.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->child_index());
test_position = test_position->CreateNextPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = test_position->CreateNextPageEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// StopAtLastAnchorBoundary shouldn't move past the end of the document.
test_position = test_position->CreateNextPageStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_3_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = test_position->CreateNextPageEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_3_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
// Moving forward past the end should return a null position.
TestPositionType null_position = test_position->CreateNextPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, null_position);
EXPECT_TRUE(null_position->IsNullPosition());
null_position = test_position->CreateNextPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, null_position);
EXPECT_TRUE(null_position->IsNullPosition());
// Now move backward through the document.
tree_position = test_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, tree_position);
EXPECT_TRUE(tree_position->IsTreePosition());
EXPECT_EQ(page_3_text_data.id, tree_position->anchor_id());
EXPECT_EQ(0, tree_position->child_index());
test_position = tree_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = tree_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->child_index());
test_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_2_text_data.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
test_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_1_text_data.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
test_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_1_text_data.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// StopAtLastAnchorBoundary shouldn't move past the start of the document.
test_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_1_text_data.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
test_position = test_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(page_1_text_data.id, test_position->anchor_id());
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
// Moving before the start should return a null position.
null_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, null_position);
EXPECT_TRUE(null_position->IsNullPosition());
null_position = test_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, null_position);
EXPECT_TRUE(null_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePagePositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position =
null_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreateNextPageStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtStartOfDocumentWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position =
null_position->CreatePositionAtStartOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePagePositionWithNonPaginatedDocument) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
// Non-paginated documents should move to the start of the document for
// CreatePreviousPageStartPosition (treating the entire document as a single
// page)
TestPositionType test_position =
text_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// Since there is no next page, CreateNextPageStartPosition should return a
// null position
test_position = text_position->CreateNextPageStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
// Since there is no previous page, CreatePreviousPageEndPosition should
// return a null position
test_position = text_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
// Since there are no distinct pages, CreateNextPageEndPosition should move
// to the end of the document, as if it's one large page.
test_position = text_position->CreateNextPageEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
// CreatePreviousPageStartPosition should move back to the beginning of the
// document
test_position = test_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// Since there's no next page, CreateNextPageStartPosition should return a
// null position
test_position = test_position->CreateNextPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
// Since there's no previous page, CreatePreviousPageEndPosition should return
// a null position
test_position = text_position->CreatePreviousPageEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
// Since there's no previous page, CreatePreviousPageStartPosition should
// return a null position
test_position = text_position->CreatePreviousPageStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtStartOfDocumentWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position =
tree_position->CreatePositionAtStartOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(root_.id, test_position->anchor_id());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->CreatePositionAtStartOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(root_.id, test_position->anchor_id());
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->CreatePositionAtStartOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(root_.id, test_position->anchor_id());
}
TEST_F(AXPositionTest, CreatePositionAtStartOfDocumentWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
TestPositionType test_position =
text_position->CreatePositionAtStartOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(root_.id, test_position->anchor_id());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->CreatePositionAtStartOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(root_.id, test_position->anchor_id());
// Affinity should have been reset to the default value.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, CreatePositionAtEndOfDocumentWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position =
null_position->CreatePositionAtEndOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreatePositionAtEndOfDocumentWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 3 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position =
tree_position->CreatePositionAtEndOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->CreatePositionAtEndOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->CreatePositionAtEndOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
}
TEST_F(AXPositionTest, CreatePositionAtEndOfDocumentWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
TestPositionType test_position =
text_position->CreatePositionAtEndOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
test_position = text_position->CreatePositionAtEndOfDocument();
EXPECT_NE(nullptr, test_position);
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
// Affinity should have been reset to the default value.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, AtLastNodeInTree) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_FALSE(text_position->AtLastNodeInTree());
EXPECT_FALSE(text_position->AsTreePosition()->AtLastNodeInTree());
TestPositionType test_position =
text_position->CreatePositionAtEndOfDocument();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->AtLastNodeInTree());
EXPECT_TRUE(test_position->AsTreePosition()->AtLastNodeInTree());
EXPECT_FALSE(text_position->CreateNullPosition()->AtLastNodeInTree());
TestPositionType on_last_node_but_not_at_maxtextoffset =
AXNodePosition::CreateTextPosition(GetTreeID(), inline_box2_.id,
1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, on_last_node_but_not_at_maxtextoffset);
EXPECT_TRUE(on_last_node_but_not_at_maxtextoffset->AtLastNodeInTree());
EXPECT_TRUE(on_last_node_but_not_at_maxtextoffset->AsTreePosition()
->AtLastNodeInTree());
}
TEST_F(AXPositionTest, CreateChildPositionAtWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->CreateChildPositionAt(0);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreateChildPositionAtWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 2 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position = tree_position->CreateChildPositionAt(1);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
// Since the anchor is a leaf node, |child_index| should signify that this is
// a "before text" position.
EXPECT_EQ(AXNodePosition::BEFORE_TEXT, test_position->child_index());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), button_.id,
0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->CreateChildPositionAt(0);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreateChildPositionAtWithTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text1_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position = text_position->CreateChildPositionAt(0);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text2_.id, 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreateChildPositionAt(1);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreateParentPositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->CreateParentPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreateParentPositionWithTreePosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), check_box_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position);
TestPositionType test_position = tree_position->CreateParentPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(root_.id, test_position->anchor_id());
// |child_index| should point to the check box node.
EXPECT_EQ(1, test_position->child_index());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
tree_position = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
1 /* child_index */);
ASSERT_NE(nullptr, tree_position);
test_position = tree_position->CreateParentPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreateParentPositionWithTextPosition) {
// Create a position that points at the end of the first line, right after the
// check box.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), check_box_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position = text_position->CreateParentPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(root_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// Since the same text offset in the root could be used to point to the
// beginning of the second line, affinity should have been adjusted to
// upstream.
EXPECT_EQ(ax::mojom::TextAffinity::kUpstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreateParentPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(static_text2_.id, test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = test_position->CreateParentPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
// |text_offset| should point to the same offset on the second line where the
// static text node position was pointing at.
EXPECT_EQ(12, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, CreateNextAndPreviousLeafTextPositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreateNextLeafTextPosition) {
TestPositionType check_box_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 1 /* child_index */);
ASSERT_NE(nullptr, check_box_position);
TestPositionType test_position =
check_box_position->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// The text offset on the root points to the button since it is the first
// available leaf text position, even though it has no text content.
TestPositionType root_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, root_position);
ASSERT_TRUE(root_position->IsTextPosition());
test_position = root_position->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
TestPositionType button_position = AXNodePosition::CreateTextPosition(
GetTreeID(), button_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, button_position);
ASSERT_TRUE(button_position->IsTextPosition());
test_position = button_position->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
TestPositionType text_field_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 2 /* child_index */);
ASSERT_NE(nullptr, text_field_position);
test_position = text_field_position->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// The root text position should resolve to its leaf text position,
// maintaining its text_offset
TestPositionType root_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 10 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, root_position2);
ASSERT_TRUE(root_position2->IsTextPosition());
test_position = root_position2->CreateNextLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(3, test_position->text_offset());
}
TEST_F(AXPositionTest, CreatePreviousLeafTextPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position =
text_position->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// Create a "before text" tree position on the second line of the text box.
TestPositionType before_text_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box2_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_NE(nullptr, before_text_position);
test_position = before_text_position->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = test_position->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
TestPositionType text_field_position = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 2 /* child_index */);
ASSERT_NE(nullptr, text_field_position);
test_position = text_field_position->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// The text offset on the root points to the text coming from inside the check
// box.
TestPositionType check_box_position = AXNodePosition::CreateTextPosition(
GetTreeID(), check_box_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, check_box_position);
ASSERT_TRUE(check_box_position->IsTextPosition());
test_position = check_box_position->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(button_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// The root text position should resolve to its leaf text position,
// maintaining its text_offset
TestPositionType root_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 10 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, root_position2);
ASSERT_TRUE(root_position2->IsTextPosition());
test_position = root_position2->CreatePreviousLeafTextPosition();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTreeID(), test_position->tree_id());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(3, test_position->text_offset());
}
TEST_F(AXPositionTest, CreateNextLeafTreePosition) {
TestPositionType root_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 0 /* child_index */);
ASSERT_TRUE(root_position->IsTreePosition());
TestPositionType button_position = AXNodePosition::CreateTreePosition(
GetTreeID(), button_.id, AXNodePosition::BEFORE_TEXT);
TestPositionType checkbox_position = AXNodePosition::CreateTreePosition(
GetTreeID(), check_box_.id, AXNodePosition::BEFORE_TEXT);
TestPositionType inline_box1_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, AXNodePosition::BEFORE_TEXT);
TestPositionType line_break_position = AXNodePosition::CreateTreePosition(
GetTreeID(), line_break_.id, AXNodePosition::BEFORE_TEXT);
TestPositionType inline_box2_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box2_.id, AXNodePosition::BEFORE_TEXT);
TestPositionType test_position = root_position->CreateNextLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *button_position);
test_position = test_position->CreateNextLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *checkbox_position);
test_position = test_position->CreateNextLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *inline_box1_position);
test_position = test_position->CreateNextLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *line_break_position);
test_position = test_position->CreateNextLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *inline_box2_position);
test_position = test_position->CreateNextLeafTreePosition();
EXPECT_TRUE(test_position->IsNullPosition());
TestPositionType root_text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 2 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(root_text_position->IsTextPosition());
test_position = root_text_position->CreateNextLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *inline_box1_position);
TestPositionType inline_box1_text_position =
AXNodePosition::CreateTextPosition(GetTreeID(), inline_box1_.id,
2 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(inline_box1_text_position->IsTextPosition());
test_position = inline_box1_text_position->CreateNextLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *line_break_position);
}
TEST_F(AXPositionTest, CreatePreviousLeafTreePosition) {
TestPositionType inline_box2_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box2_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_TRUE(inline_box2_position->IsTreePosition());
TestPositionType line_break_position = AXNodePosition::CreateTreePosition(
GetTreeID(), line_break_.id, AXNodePosition::BEFORE_TEXT);
TestPositionType inline_box1_position = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, AXNodePosition::BEFORE_TEXT);
TestPositionType checkbox_position = AXNodePosition::CreateTreePosition(
GetTreeID(), check_box_.id, AXNodePosition::BEFORE_TEXT);
TestPositionType button_position = AXNodePosition::CreateTreePosition(
GetTreeID(), button_.id, AXNodePosition::BEFORE_TEXT);
TestPositionType test_position =
inline_box2_position->CreatePreviousLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *line_break_position);
test_position = test_position->CreatePreviousLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *inline_box1_position);
test_position = test_position->CreatePreviousLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *checkbox_position);
test_position = test_position->CreatePreviousLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *button_position);
test_position = test_position->CreatePreviousLeafTreePosition();
EXPECT_TRUE(test_position->IsNullPosition());
TestPositionType inline_box2_text_position =
AXNodePosition::CreateTextPosition(GetTreeID(), inline_box2_.id,
2 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(inline_box2_text_position->IsTextPosition());
test_position = inline_box2_text_position->CreatePreviousLeafTreePosition();
EXPECT_TRUE(test_position->IsTreePosition());
EXPECT_EQ(*test_position, *line_break_position);
}
TEST_F(AXPositionTest,
AsLeafTextPositionBeforeAndAfterCharacterWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
ASSERT_TRUE(null_position->IsNullPosition());
TestPositionType test_position =
null_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest,
AsLeafTextPositionBeforeAndAfterCharacterAtInvalidGraphemeBoundary) {
#if true
GTEST_SKIP()
<< "Skipping, current accessibility library cannot handle grapheme";
#else
std::vector<int> text_offsets;
SetTree(CreateMultilingualDocument(&text_offsets));
TestPositionType test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
test_position = test_position->AsLeafTextPositionAfterCharacter();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->children()[1]->id(), test_position->anchor_id());
// "text_offset_" should have been adjusted to the next grapheme boundary.
EXPECT_EQ(2, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 10 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
test_position = test_position->AsLeafTextPositionBeforeCharacter();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->children()[2]->id(), test_position->anchor_id());
// "text_offset_" should have been adjusted to the previous grapheme boundary.
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 10 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
test_position = test_position->AsLeafTextPositionBeforeCharacter();
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->children()[2]->id(), test_position->anchor_id());
// The same as above, "text_offset_" should have been adjusted to the previous
// grapheme boundary.
EXPECT_EQ(0, test_position->text_offset());
// An upstream affinity should have had no effect on the outcome and so, it
// should have been reset in order to provide consistent output from the
// method regardless of input affinity.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
#endif // true
}
TEST_F(AXPositionTest, AsLeafTextPositionBeforeCharacterNoAdjustment) {
// A text offset that is on the line break right after "Line 1".
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position =
text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// A text offset that is before the line break right after "Line 1".
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 13 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
}
TEST_F(AXPositionTest, AsLeafTextPositionAfterCharacterNoAdjustment) {
// A text offset that is after "Line 2".
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 13 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position =
text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
// A text offset that is before "Line 2".
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 7 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
// A text offset that is on the line break right after "Line 1".
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 13 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
}
TEST_F(AXPositionTest, AsLeafTextPositionBeforeCharacter) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 3 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position =
text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(3, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 13 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionBeforeCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, AsLeafTextPositionAfterCharacter) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position =
text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->AsLeafTextPositionAfterCharacter();
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreateNextAndPreviousCharacterPositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, AsValidPosition) {
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
root_data.child_ids = {text_data.id};
SetTree(CreateAXTree({root_data, text_data}));
// Create a text position at MaxTextOffset.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_data.id, 9 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->IsValid());
EXPECT_EQ(9, text_position->text_offset());
// Test basic cases with static MaxTextOffset
TestPositionType test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_TRUE(test_position->IsValid());
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(text_data.id, test_position->anchor_id());
EXPECT_EQ(9, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
// AsValidPosition should not change any fields on already-valid positions.
EXPECT_TRUE(text_position->IsValid());
test_position = text_position->AsValidPosition();
EXPECT_TRUE(test_position->IsValid());
EXPECT_EQ(*test_position, *text_position);
// Now make a change to shorten MaxTextOffset. Ensure that this position is
// invalid, then call AsValidPosition and ensure that it is now valid.
text_data.SetName("some tex");
AXTreeUpdate shorten_text_update;
shorten_text_update.nodes = {text_data};
ASSERT_TRUE(GetTree()->Unserialize(shorten_text_update));
EXPECT_FALSE(text_position->IsValid());
text_position = text_position->AsValidPosition();
EXPECT_TRUE(text_position->IsValid());
EXPECT_EQ(8, text_position->text_offset());
// Now repeat the prior tests and ensure that we can create next character
// positions with the new, valid MaxTextOffset (8).
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_TRUE(test_position->IsValid());
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(text_data.id, test_position->anchor_id());
EXPECT_EQ(8, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
// AsValidPosition should create a NullPosition if a position's anchor is
// removed. This is true for both tree positions and text positions.
EXPECT_TRUE(text_position->IsValid());
TestPositionType tree_position = text_position->AsTreePosition();
ASSERT_NE(nullptr, tree_position);
EXPECT_TRUE(tree_position->IsTreePosition());
EXPECT_TRUE(tree_position->IsValid());
EXPECT_EQ(0, tree_position->child_index());
AXTreeUpdate remove_node_update;
root_data.child_ids = {};
remove_node_update.nodes = {root_data};
ASSERT_TRUE(GetTree()->Unserialize(remove_node_update));
EXPECT_FALSE(text_position->IsValid());
EXPECT_FALSE(tree_position->IsValid());
text_position = text_position->AsValidPosition();
EXPECT_TRUE(text_position->IsValid());
tree_position = tree_position->AsValidPosition();
EXPECT_TRUE(tree_position->IsValid());
EXPECT_TRUE(text_position->IsNullPosition());
EXPECT_TRUE(tree_position->IsNullPosition());
}
TEST_F(AXPositionTest, AsValidPositionInDescendantOfEmptyObject) {
g_ax_embedded_object_behavior = AXEmbeddedObjectBehavior::kExposeCharacter;
// ++1 kRootWebArea
// ++++2 kButton
// ++++++3 kStaticText "3.14" ignored
// ++++++++4 kInlineTextBox "3.14" ignored
AXNodeData root_1;
AXNodeData button_2;
AXNodeData static_text_3;
AXNodeData inline_box_4;
root_1.id = 1;
button_2.id = 2;
static_text_3.id = 3;
inline_box_4.id = 4;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {button_2.id};
button_2.role = ax::mojom::Role::kButton;
button_2.child_ids = {static_text_3.id};
static_text_3.role = ax::mojom::Role::kStaticText;
static_text_3.SetName("3.14");
static_text_3.child_ids = {inline_box_4.id};
inline_box_4.role = ax::mojom::Role::kInlineTextBox;
inline_box_4.SetName("3.14");
SetTree(CreateAXTree({root_1, button_2, static_text_3, inline_box_4}));
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_4.id, 3, ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->IsValid());
EXPECT_EQ(*text_position, *text_position->AsValidPosition());
TestPositionType tree_position =
AXNodePosition::CreateTreePosition(GetTreeID(), inline_box_4.id, 0);
ASSERT_NE(nullptr, tree_position);
EXPECT_TRUE(tree_position->IsTreePosition());
EXPECT_TRUE(tree_position->IsValid());
EXPECT_EQ(*tree_position, *tree_position->AsValidPosition());
static_text_3.AddState(ax::mojom::State::kIgnored);
inline_box_4.AddState(ax::mojom::State::kIgnored);
AXTreeUpdate update;
update.nodes = {static_text_3, inline_box_4};
ASSERT_TRUE(GetTree()->Unserialize(update));
EXPECT_FALSE(text_position->IsValid());
text_position = text_position->AsValidPosition();
EXPECT_TRUE(text_position->IsValid());
EXPECT_EQ(1, text_position->text_offset());
EXPECT_FALSE(tree_position->IsValid());
tree_position = tree_position->AsValidPosition();
EXPECT_TRUE(tree_position->IsValid());
EXPECT_EQ(0, tree_position->child_index());
}
TEST_F(AXPositionTest, CreateNextCharacterPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(4, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(6, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), check_box_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
// Affinity should have been reset to downstream.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 12 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
EXPECT_EQ(13, test_position->text_offset());
// Affinity should have been reset to downstream.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, CreatePreviousCharacterPosition) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType test_position =
text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(4, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(4, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(4, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(1, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box2_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(line_break_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(inline_box1_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), check_box_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(check_box_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
test_position = text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(text_field_.id, test_position->anchor_id());
EXPECT_EQ(0, test_position->text_offset());
// Affinity should have been reset to downstream.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
TEST_F(AXPositionTest, CreateNextCharacterPositionAtGraphemeBoundary) {
#if true
GTEST_SKIP()
<< "Skipping, current accessibility library cannot handle grapheme";
#else
std::vector<int> text_offsets;
SetTree(CreateMultilingualDocument(&text_offsets));
TestPositionType test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, test_position);
ASSERT_TRUE(test_position->IsTextPosition());
for (auto iter = (text_offsets.begin() + 1); iter != text_offsets.end();
++iter) {
const int text_offset = *iter;
test_position = test_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
testing::Message message;
message << "Expecting character boundary at " << text_offset << " in\n"
<< *test_position;
SCOPED_TRACE(message);
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(text_offset, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 3 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
test_position = test_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(3, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
test_position = test_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(5, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 9 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
test_position = test_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(9, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kUpstream, test_position->affinity());
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 10 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
test_position = test_position->CreateNextCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(12, test_position->text_offset());
// Affinity should have been reset to downstream because there was a move.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
#endif // true
}
TEST_F(AXPositionTest, CreatePreviousCharacterPositionAtGraphemeBoundary) {
#if true
GTEST_SKIP()
<< "Skipping, current accessibility library cannot handle grapheme";
#else
std::vector<int> text_offsets;
SetTree(CreateMultilingualDocument(&text_offsets));
TestPositionType test_position =
AXNodePosition::CreateTextPosition(GetTreeID(), GetTree()->root()->id(),
text_offsets.back() /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, test_position);
ASSERT_TRUE(test_position->IsTextPosition());
for (auto iter = (text_offsets.rbegin() + 1); iter != text_offsets.rend();
++iter) {
const int text_offset = *iter;
test_position = test_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
testing::Message message;
message << "Expecting character boundary at " << text_offset << " in\n"
<< *test_position;
SCOPED_TRACE(message);
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(text_offset, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
}
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 3 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
test_position = test_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(3, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 4 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
test_position = test_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(3, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 9 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
test_position = test_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(9, test_position->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kUpstream, test_position->affinity());
test_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetTree()->root()->id(), 10 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
test_position = test_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
ASSERT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsTextPosition());
EXPECT_EQ(GetTree()->root()->id(), test_position->anchor_id());
EXPECT_EQ(9, test_position->text_offset());
// Affinity should have been reset to downstream because there was a move.
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, test_position->affinity());
#endif // true
}
TEST_F(AXPositionTest, ReciprocalCreateNextAndPreviousCharacterPosition) {
TestPositionType tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 0 /* child_index */);
TestPositionType text_position = tree_position->AsTextPosition();
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
size_t next_character_moves = 0;
while (!text_position->IsNullPosition()) {
TestPositionType moved_position =
text_position->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
ASSERT_NE(nullptr, moved_position);
text_position = std::move(moved_position);
++next_character_moves;
}
tree_position = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, root_.child_ids.size() /* child_index */);
text_position = tree_position->AsTextPosition();
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
size_t previous_character_moves = 0;
while (!text_position->IsNullPosition()) {
TestPositionType moved_position =
text_position->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary);
ASSERT_NE(nullptr, moved_position);
text_position = std::move(moved_position);
++previous_character_moves;
}
EXPECT_EQ(next_character_moves, previous_character_moves);
EXPECT_EQ(strlen(TEXT_VALUE), next_character_moves - 1);
}
TEST_F(AXPositionTest, CreateNextAndPreviousWordStartPositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->CreateNextWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, CreateNextAndPreviousWordEndPositionWithNullPosition) {
TestPositionType null_position = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position);
TestPositionType test_position = null_position->CreateNextWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
test_position = null_position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
EXPECT_NE(nullptr, test_position);
EXPECT_TRUE(test_position->IsNullPosition());
}
TEST_F(AXPositionTest, OperatorEquals) {
TestPositionType null_position1 = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position1);
TestPositionType null_position2 = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position2);
EXPECT_EQ(*null_position1, *null_position2);
// Child indices must match.
TestPositionType button_position1 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 0 /* child_index */);
ASSERT_NE(nullptr, button_position1);
TestPositionType button_position2 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 0 /* child_index */);
ASSERT_NE(nullptr, button_position2);
EXPECT_EQ(*button_position1, *button_position2);
// Both child indices are invalid. It should result in equivalent null
// positions.
TestPositionType tree_position1 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 4 /* child_index */);
ASSERT_NE(nullptr, tree_position1);
TestPositionType tree_position2 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, AXNodePosition::INVALID_INDEX);
ASSERT_NE(nullptr, tree_position2);
EXPECT_EQ(*tree_position1, *tree_position2);
// An invalid position should not be equivalent to an "after children"
// position.
tree_position1 = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
3 /* child_index */);
ASSERT_NE(nullptr, tree_position1);
tree_position2 = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id,
-1 /* child_index */);
ASSERT_NE(nullptr, tree_position2);
EXPECT_NE(*tree_position1, *tree_position2);
// Two "after children" positions on the same node should be equivalent.
tree_position1 = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 3 /* child_index */);
ASSERT_NE(nullptr, tree_position1);
tree_position2 = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 3 /* child_index */);
ASSERT_NE(nullptr, tree_position2);
EXPECT_EQ(*tree_position1, *tree_position2);
// Two "before text" positions on the same node should be equivalent.
tree_position1 = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_NE(nullptr, tree_position1);
tree_position2 = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_NE(nullptr, tree_position2);
EXPECT_EQ(*tree_position1, *tree_position2);
// Both text offsets are invalid. It should result in equivalent null
// positions.
TestPositionType text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 15 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsNullPosition());
TestPositionType text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, -1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsNullPosition());
EXPECT_EQ(*text_position1, *text_position2);
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_EQ(*text_position1, *text_position2);
// Affinities should not matter.
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_EQ(*text_position1, *text_position2);
// Text offsets should match.
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
EXPECT_NE(*text_position1, *text_position2);
// Two "after text" positions on the same node should be equivalent.
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_EQ(*text_position1, *text_position2);
// Two text positions that are consecutive, one "before text" and one "after
// text".
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_EQ(*text_position1, *text_position2);
// Two "after text" positions on a parent and child should be equivalent, in
// the middle of the document...
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_EQ(*text_position1, *text_position2);
// ...and at the end of the document.
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text2_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
// Validate that we're actually at the end of the document by normalizing to
// the equivalent "before character" position.
EXPECT_TRUE(
text_position1->AsLeafTextPositionBeforeCharacter()->IsNullPosition());
EXPECT_TRUE(
text_position2->AsLeafTextPositionBeforeCharacter()->IsNullPosition());
// Now compare the positions.
EXPECT_EQ(*text_position1, *text_position2);
}
TEST_F(AXPositionTest, OperatorEqualsSameTextOffsetSameAnchorId) {
TestPositionType text_position_one = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position_one);
ASSERT_TRUE(text_position_one->IsTextPosition());
TestPositionType text_position_two = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position_two);
ASSERT_TRUE(text_position_two->IsTextPosition());
ASSERT_TRUE(*text_position_one == *text_position_two);
ASSERT_TRUE(*text_position_two == *text_position_one);
}
TEST_F(AXPositionTest, OperatorEqualsSameTextOffsetDifferentAnchorIdRoot) {
TestPositionType text_position_one = AXNodePosition::CreateTextPosition(
GetTreeID(), root_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position_one);
ASSERT_TRUE(text_position_one->IsTextPosition());
TestPositionType text_position_two = AXNodePosition::CreateTextPosition(
GetTreeID(), check_box_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position_two);
ASSERT_TRUE(text_position_two->IsTextPosition());
ASSERT_TRUE(*text_position_one == *text_position_two);
ASSERT_TRUE(*text_position_two == *text_position_one);
}
TEST_F(AXPositionTest, OperatorEqualsSameTextOffsetDifferentAnchorIdLeaf) {
TestPositionType text_position_one = AXNodePosition::CreateTextPosition(
GetTreeID(), button_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position_one);
ASSERT_TRUE(text_position_one->IsTextPosition());
TestPositionType text_position_two = AXNodePosition::CreateTextPosition(
GetTreeID(), check_box_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position_two);
ASSERT_TRUE(text_position_two->IsTextPosition());
ASSERT_TRUE(*text_position_one == *text_position_two);
ASSERT_TRUE(*text_position_two == *text_position_one);
}
TEST_F(AXPositionTest, OperatorsLessThanAndGreaterThan) {
TestPositionType null_position1 = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position1);
TestPositionType null_position2 = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position2);
EXPECT_FALSE(*null_position1 < *null_position2);
EXPECT_FALSE(*null_position1 > *null_position2);
TestPositionType button_position1 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 0 /* child_index */);
ASSERT_NE(nullptr, button_position1);
TestPositionType button_position2 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 1 /* child_index */);
ASSERT_NE(nullptr, button_position2);
EXPECT_LT(*button_position1, *button_position2);
EXPECT_GT(*button_position2, *button_position1);
TestPositionType tree_position1 = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 2 /* child_index */);
ASSERT_NE(nullptr, tree_position1);
// An "after children" position.
TestPositionType tree_position2 = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 3 /* child_index */);
ASSERT_NE(nullptr, tree_position2);
EXPECT_LT(*tree_position1, *tree_position2);
EXPECT_GT(*tree_position2, *tree_position1);
// A "before text" position.
tree_position1 = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, AXNodePosition::BEFORE_TEXT);
ASSERT_NE(nullptr, tree_position1);
// An "after text" position.
tree_position2 = AXNodePosition::CreateTreePosition(
GetTreeID(), inline_box1_.id, 0 /* child_index */);
ASSERT_NE(nullptr, tree_position2);
EXPECT_LT(*tree_position1, *tree_position2);
EXPECT_GT(*tree_position2, *tree_position1);
// Two text positions that share a common anchor.
TestPositionType text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 2 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
TestPositionType text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_GT(*text_position1, *text_position2);
EXPECT_LT(*text_position2, *text_position1);
// Affinities should not matter.
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_GT(*text_position1, *text_position2);
EXPECT_LT(*text_position2, *text_position1);
// An "after text" position.
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
// A "before text" position.
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kUpstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_GT(*text_position1, *text_position2);
EXPECT_LT(*text_position2, *text_position1);
// A text position that is an ancestor of another.
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1_.id, 5 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_GT(*text_position1, *text_position2);
EXPECT_LT(*text_position2, *text_position1);
// Two text positions that share a common ancestor.
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_GT(*text_position1, *text_position2);
EXPECT_LT(*text_position2, *text_position1);
// Two consecutive positions. One "before text" and one "after text".
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_EQ(*text_position1, *text_position2);
// A text position at the end of the document versus one that isn't.
text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box2_.id, 6 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_TRUE(text_position1->IsTextPosition());
// Validate that we're actually at the end of the document by normalizing to
// the equivalent "before character" position.
EXPECT_TRUE(
text_position1->AsLeafTextPositionBeforeCharacter()->IsNullPosition());
// Now create the not-at-end-of-document position and compare.
text_position2 = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position2);
ASSERT_TRUE(text_position2->IsTextPosition());
EXPECT_GT(*text_position1, *text_position2);
EXPECT_LT(*text_position2, *text_position1);
}
TEST_F(AXPositionTest, Swap) {
TestPositionType null_position1 = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position1);
TestPositionType null_position2 = AXNodePosition::CreateNullPosition();
ASSERT_NE(nullptr, null_position2);
swap(*null_position1, *null_position2);
EXPECT_TRUE(null_position1->IsNullPosition());
EXPECT_TRUE(null_position2->IsNullPosition());
TestPositionType tree_position1 = AXNodePosition::CreateTreePosition(
GetTreeID(), root_.id, 2 /* child_index */);
ASSERT_NE(nullptr, tree_position1);
TestPositionType tree_position2 = AXNodePosition::CreateTreePosition(
GetTreeID(), text_field_.id, 3 /* child_index */);
ASSERT_NE(nullptr, tree_position2);
swap(*tree_position1, *tree_position2);
EXPECT_TRUE(tree_position1->IsTreePosition());
EXPECT_EQ(GetTreeID(), tree_position1->tree_id());
EXPECT_EQ(text_field_.id, tree_position1->anchor_id());
EXPECT_EQ(3, tree_position1->child_index());
EXPECT_TRUE(tree_position1->IsTreePosition());
EXPECT_EQ(GetTreeID(), tree_position2->tree_id());
EXPECT_EQ(root_.id, tree_position2->anchor_id());
EXPECT_EQ(2, tree_position2->child_index());
swap(*tree_position1, *null_position1);
EXPECT_TRUE(tree_position1->IsNullPosition());
EXPECT_TRUE(null_position1->IsTreePosition());
EXPECT_EQ(GetTreeID(), null_position1->tree_id());
EXPECT_EQ(text_field_.id, null_position1->anchor_id());
EXPECT_EQ(3, null_position1->child_index());
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), line_break_.id, 1 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
swap(*text_position, *null_position1);
EXPECT_TRUE(null_position1->IsTextPosition());
EXPECT_EQ(GetTreeID(), text_position->tree_id());
EXPECT_EQ(line_break_.id, null_position1->anchor_id());
EXPECT_EQ(1, null_position1->text_offset());
EXPECT_EQ(ax::mojom::TextAffinity::kDownstream, null_position1->affinity());
EXPECT_TRUE(text_position->IsTreePosition());
EXPECT_EQ(GetTreeID(), text_position->tree_id());
EXPECT_EQ(text_field_.id, text_position->anchor_id());
EXPECT_EQ(3, text_position->child_index());
}
TEST_F(AXPositionTest, CreateNextAnchorPosition) {
// This test updates the tree structure to test a specific edge case -
// CreateNextAnchorPosition on an empty text field.
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData text_field_data;
text_field_data.id = 3;
text_field_data.role = ax::mojom::Role::kTextField;
AXNodeData empty_text_data;
empty_text_data.id = 4;
empty_text_data.role = ax::mojom::Role::kStaticText;
empty_text_data.SetName("");
AXNodeData more_text_data;
more_text_data.id = 5;
more_text_data.role = ax::mojom::Role::kStaticText;
more_text_data.SetName("more text");
root_data.child_ids = {text_data.id, text_field_data.id, more_text_data.id};
text_field_data.child_ids = {empty_text_data.id};
SetTree(CreateAXTree({root_data, text_data, text_field_data, empty_text_data,
more_text_data}));
// Test that CreateNextAnchorPosition will successfully navigate past the
// empty text field.
TestPositionType text_position1 = AXNodePosition::CreateTextPosition(
GetTreeID(), text_data.id, 8 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position1);
ASSERT_FALSE(text_position1->CreateNextAnchorPosition()
->CreateNextAnchorPosition()
->IsNullPosition());
}
TEST_F(AXPositionTest, CreateLinePositionsMultipleAnchorsInSingleLine) {
// This test updates the tree structure to test a specific edge case -
// Create next and previous line start/end positions on a single line composed
// by multiple anchors; only two line boundaries should be resolved: either
// the start of the "before" text or at the end of "after".
// ++1 kRootWebArea
// ++++2 kStaticText
// ++++++3 kInlineTextBox "before" kNextOnLineId=6
// ++++4 kGenericContainer
// ++++++5 kStaticText
// ++++++++6 kInlineTextBox "inside" kPreviousOnLineId=3 kNextOnLineId=8
// ++++7 kStaticText
// ++++++8 kInlineTextBox "after" kPreviousOnLineId=6
AXNodeData root;
AXNodeData inline_box1;
AXNodeData inline_box2;
AXNodeData inline_box3;
AXNodeData inline_block;
AXNodeData static_text1;
AXNodeData static_text2;
AXNodeData static_text3;
root.id = 1;
static_text1.id = 2;
inline_box1.id = 3;
inline_block.id = 4;
static_text2.id = 5;
inline_box2.id = 6;
static_text3.id = 7;
inline_box3.id = 8;
root.role = ax::mojom::Role::kRootWebArea;
root.child_ids = {static_text1.id, inline_block.id, static_text3.id};
static_text1.role = ax::mojom::Role::kStaticText;
static_text1.SetName("before");
static_text1.child_ids = {inline_box1.id};
inline_box1.role = ax::mojom::Role::kInlineTextBox;
inline_box1.SetName("before");
inline_box1.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
inline_box2.id);
inline_block.role = ax::mojom::Role::kGenericContainer;
inline_block.child_ids = {static_text2.id};
static_text2.role = ax::mojom::Role::kStaticText;
static_text2.SetName("inside");
static_text2.child_ids = {inline_box2.id};
inline_box2.role = ax::mojom::Role::kInlineTextBox;
inline_box2.SetName("inside");
inline_box2.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
inline_box1.id);
inline_box2.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
inline_box3.id);
static_text3.role = ax::mojom::Role::kStaticText;
static_text3.SetName("after");
static_text3.child_ids = {inline_box3.id};
inline_box3.role = ax::mojom::Role::kInlineTextBox;
inline_box3.SetName("after");
inline_box3.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
inline_box2.id);
SetTree(CreateAXTree({root, static_text1, inline_box1, inline_block,
static_text2, inline_box2, static_text3, inline_box3}));
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_block.id, 3 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionType next_line_start_position =
text_position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, next_line_start_position);
EXPECT_TRUE(next_line_start_position->IsTextPosition());
EXPECT_EQ(inline_box3.id, next_line_start_position->anchor_id());
EXPECT_EQ(5, next_line_start_position->text_offset());
TestPositionType previous_line_start_position =
text_position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, previous_line_start_position);
EXPECT_TRUE(previous_line_start_position->IsTextPosition());
EXPECT_EQ(inline_box1.id, previous_line_start_position->anchor_id());
EXPECT_EQ(0, previous_line_start_position->text_offset());
TestPositionType next_line_end_position =
text_position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, next_line_end_position);
EXPECT_TRUE(next_line_end_position->IsTextPosition());
EXPECT_EQ(inline_box3.id, next_line_end_position->anchor_id());
EXPECT_EQ(5, next_line_end_position->text_offset());
TestPositionType previous_line_end_position =
text_position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, previous_line_end_position);
EXPECT_TRUE(previous_line_end_position->IsTextPosition());
EXPECT_EQ(inline_box1.id, previous_line_end_position->anchor_id());
EXPECT_EQ(0, previous_line_end_position->text_offset());
}
TEST_F(AXPositionTest, CreateNextWordPositionInList) {
// This test updates the tree structure to test a specific edge case -
// next word navigation inside a list with AXListMarkers nodes.
// ++1 kRootWebArea
// ++++2 kList
// ++++++3 kListItem
// ++++++++4 kListMarker
// ++++++++++5 kStaticText
// ++++++++++++6 kInlineTextBox "1. "
// ++++++++7 kStaticText
// ++++++++++8 kInlineTextBox "first item"
// ++++++9 kListItem
// ++++++++10 kListMarker
// +++++++++++11 kStaticText
// ++++++++++++++12 kInlineTextBox "2. "
// ++++++++13 kStaticText
// ++++++++++14 kInlineTextBox "second item"
AXNodeData root;
AXNodeData list;
AXNodeData list_item1;
AXNodeData list_item2;
AXNodeData list_marker1;
AXNodeData list_marker2;
AXNodeData inline_box1;
AXNodeData inline_box2;
AXNodeData inline_box3;
AXNodeData inline_box4;
AXNodeData static_text1;
AXNodeData static_text2;
AXNodeData static_text3;
AXNodeData static_text4;
root.id = 1;
list.id = 2;
list_item1.id = 3;
list_marker1.id = 4;
static_text1.id = 5;
inline_box1.id = 6;
static_text2.id = 7;
inline_box2.id = 8;
list_item2.id = 9;
list_marker2.id = 10;
static_text3.id = 11;
inline_box3.id = 12;
static_text4.id = 13;
inline_box4.id = 14;
root.role = ax::mojom::Role::kRootWebArea;
root.child_ids = {list.id};
list.role = ax::mojom::Role::kList;
list.child_ids = {list_item1.id, list_item2.id};
list_item1.role = ax::mojom::Role::kListItem;
list_item1.child_ids = {list_marker1.id, static_text2.id};
list_item1.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
list_marker1.role = ax::mojom::Role::kListMarker;
list_marker1.child_ids = {static_text1.id};
static_text1.role = ax::mojom::Role::kStaticText;
static_text1.SetName("1. ");
static_text1.child_ids = {inline_box1.id};
inline_box1.role = ax::mojom::Role::kInlineTextBox;
inline_box1.SetName("1. ");
inline_box1.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0});
inline_box1.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{3});
static_text2.role = ax::mojom::Role::kStaticText;
static_text2.SetName("first item");
static_text2.child_ids = {inline_box2.id};
inline_box2.role = ax::mojom::Role::kInlineTextBox;
inline_box2.SetName("first item");
inline_box2.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0, 6});
inline_box2.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{5});
list_item2.role = ax::mojom::Role::kListItem;
list_item2.child_ids = {list_marker2.id, static_text4.id};
list_item2.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
list_marker2.role = ax::mojom::Role::kListMarker;
list_marker2.child_ids = {static_text3.id};
static_text3.role = ax::mojom::Role::kStaticText;
static_text3.SetName("2. ");
static_text3.child_ids = {inline_box3.id};
inline_box3.role = ax::mojom::Role::kInlineTextBox;
inline_box3.SetName("2. ");
inline_box3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0});
inline_box3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{3});
static_text4.role = ax::mojom::Role::kStaticText;
static_text4.SetName("second item");
static_text4.child_ids = {inline_box4.id};
inline_box4.role = ax::mojom::Role::kInlineTextBox;
inline_box4.SetName("second item");
inline_box4.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0, 7});
inline_box4.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{6});
SetTree(CreateAXTree({root, list, list_item1, list_marker1, static_text1,
inline_box1, static_text2, inline_box2, list_item2,
list_marker2, static_text3, inline_box3, static_text4,
inline_box4}));
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box1.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box1.id, text_position->anchor_id());
ASSERT_EQ(0, text_position->text_offset());
// "1. <f>irst item\n2. second item"
text_position = text_position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box2.id, text_position->anchor_id());
ASSERT_EQ(0, text_position->text_offset());
// "1. first <i>tem\n2. second item"
text_position = text_position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box2.id, text_position->anchor_id());
ASSERT_EQ(6, text_position->text_offset());
// "1. first item\n<2>. second item"
text_position = text_position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box3.id, text_position->anchor_id());
ASSERT_EQ(0, text_position->text_offset());
// "1. first item\n2. <s>econd item"
text_position = text_position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box4.id, text_position->anchor_id());
ASSERT_EQ(0, text_position->text_offset());
// "1. first item\n2. second <i>tem"
text_position = text_position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box4.id, text_position->anchor_id());
ASSERT_EQ(7, text_position->text_offset());
}
TEST_F(AXPositionTest, CreatePreviousWordPositionInList) {
// This test updates the tree structure to test a specific edge case -
// previous word navigation inside a list with AXListMarkers nodes.
// ++1 kRootWebArea
// ++++2 kList
// ++++++3 kListItem
// ++++++++4 kListMarker
// ++++++++++5 kStaticText
// ++++++++++++6 kInlineTextBox "1. "
// ++++++++7 kStaticText
// ++++++++++8 kInlineTextBox "first item"
// ++++++9 kListItem
// ++++++++10 kListMarker
// +++++++++++11 kStaticText
// ++++++++++++++12 kInlineTextBox "2. "
// ++++++++13 kStaticText
// ++++++++++14 kInlineTextBox "second item"
AXNodeData root;
AXNodeData list;
AXNodeData list_item1;
AXNodeData list_item2;
AXNodeData list_marker1;
AXNodeData list_marker2;
AXNodeData inline_box1;
AXNodeData inline_box2;
AXNodeData inline_box3;
AXNodeData inline_box4;
AXNodeData static_text1;
AXNodeData static_text2;
AXNodeData static_text3;
AXNodeData static_text4;
root.id = 1;
list.id = 2;
list_item1.id = 3;
list_marker1.id = 4;
static_text1.id = 5;
inline_box1.id = 6;
static_text2.id = 7;
inline_box2.id = 8;
list_item2.id = 9;
list_marker2.id = 10;
static_text3.id = 11;
inline_box3.id = 12;
static_text4.id = 13;
inline_box4.id = 14;
root.role = ax::mojom::Role::kRootWebArea;
root.child_ids = {list.id};
list.role = ax::mojom::Role::kList;
list.child_ids = {list_item1.id, list_item2.id};
list_item1.role = ax::mojom::Role::kListItem;
list_item1.child_ids = {list_marker1.id, static_text2.id};
list_item1.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
list_marker1.role = ax::mojom::Role::kListMarker;
list_marker1.child_ids = {static_text1.id};
static_text1.role = ax::mojom::Role::kStaticText;
static_text1.SetName("1. ");
static_text1.child_ids = {inline_box1.id};
inline_box1.role = ax::mojom::Role::kInlineTextBox;
inline_box1.SetName("1. ");
inline_box1.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0});
inline_box1.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{3});
static_text2.role = ax::mojom::Role::kStaticText;
static_text2.SetName("first item");
static_text2.child_ids = {inline_box2.id};
inline_box2.role = ax::mojom::Role::kInlineTextBox;
inline_box2.SetName("first item");
inline_box2.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0, 6});
inline_box2.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{5});
list_item2.role = ax::mojom::Role::kListItem;
list_item2.child_ids = {list_marker2.id, static_text4.id};
list_item2.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
list_marker2.role = ax::mojom::Role::kListMarker;
list_marker2.child_ids = {static_text3.id};
static_text3.role = ax::mojom::Role::kStaticText;
static_text3.SetName("2. ");
static_text3.child_ids = {inline_box3.id};
inline_box3.role = ax::mojom::Role::kInlineTextBox;
inline_box3.SetName("2. ");
inline_box3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0});
inline_box3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{3});
static_text4.role = ax::mojom::Role::kStaticText;
static_text4.SetName("second item");
static_text4.child_ids = {inline_box4.id};
inline_box4.role = ax::mojom::Role::kInlineTextBox;
inline_box4.SetName("second item");
inline_box4.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0, 7});
inline_box4.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{6});
SetTree(CreateAXTree({root, list, list_item1, list_marker1, static_text1,
inline_box1, static_text2, inline_box2, list_item2,
list_marker2, static_text3, inline_box3, static_text4,
inline_box4}));
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box4.id, 11 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box4.id, text_position->anchor_id());
ASSERT_EQ(11, text_position->text_offset());
// "1. first item\n2. second <i>tem"
text_position = text_position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box4.id, text_position->anchor_id());
ASSERT_EQ(7, text_position->text_offset());
// "1. first item\n2. <s>econd item"
text_position = text_position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box4.id, text_position->anchor_id());
ASSERT_EQ(0, text_position->text_offset());
// "1. first item\n<2>. second item"
text_position = text_position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box3.id, text_position->anchor_id());
ASSERT_EQ(0, text_position->text_offset());
// "1. first <i>tem\n2. <s>econd item"
text_position = text_position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box2.id, text_position->anchor_id());
ASSERT_EQ(6, text_position->text_offset());
// "1. <f>irst item\n2. second item"
text_position = text_position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box2.id, text_position->anchor_id());
ASSERT_EQ(0, text_position->text_offset());
// "<1>. first item\n2. second item"
text_position = text_position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, text_position);
ASSERT_TRUE(text_position->IsTextPosition());
ASSERT_EQ(inline_box1.id, text_position->anchor_id());
ASSERT_EQ(0, text_position->text_offset());
}
TEST_F(AXPositionTest, EmptyObjectReplacedByCharacterTextNavigation) {
g_ax_embedded_object_behavior = AXEmbeddedObjectBehavior::kExposeCharacter;
// ++1 kRootWebArea
// ++++2 kStaticText
// ++++++3 kInlineTextBox
// ++++4 kTextField
// ++++++5 kGenericContainer
// ++++6 kStaticText
// ++++++7 kInlineTextBox
// ++++8 kHeading
// ++++++9 kStaticText
// ++++++++10 kInlineTextBox
// ++++11 kGenericContainer ignored
// ++++12 kGenericContainer
// ++++13 kStaticText
// ++++14 kButton
// ++++++15 kGenericContainer ignored
AXNodeData root_1;
AXNodeData static_text_2;
AXNodeData inline_box_3;
AXNodeData text_field_4;
AXNodeData generic_container_5;
AXNodeData static_text_6;
AXNodeData inline_box_7;
AXNodeData heading_8;
AXNodeData static_text_9;
AXNodeData inline_box_10;
AXNodeData generic_container_11;
AXNodeData generic_container_12;
AXNodeData static_text_13;
AXNodeData button_14;
AXNodeData generic_container_15;
root_1.id = 1;
static_text_2.id = 2;
inline_box_3.id = 3;
text_field_4.id = 4;
generic_container_5.id = 5;
static_text_6.id = 6;
inline_box_7.id = 7;
heading_8.id = 8;
static_text_9.id = 9;
inline_box_10.id = 10;
generic_container_11.id = 11;
generic_container_12.id = 12;
static_text_13.id = 13;
button_14.id = 14;
generic_container_15.id = 15;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {static_text_2.id, text_field_4.id,
static_text_6.id, heading_8.id,
generic_container_11.id, generic_container_12.id,
static_text_13.id, button_14.id};
static_text_2.role = ax::mojom::Role::kStaticText;
static_text_2.SetName("Hello ");
static_text_2.child_ids = {inline_box_3.id};
inline_box_3.role = ax::mojom::Role::kInlineTextBox;
inline_box_3.SetName("Hello ");
inline_box_3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0});
inline_box_3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{6});
text_field_4.role = ax::mojom::Role::kGroup;
text_field_4.child_ids = {generic_container_5.id};
generic_container_5.role = ax::mojom::Role::kGenericContainer;
static_text_6.role = ax::mojom::Role::kStaticText;
static_text_6.SetName(" world");
static_text_6.child_ids = {inline_box_7.id};
inline_box_7.role = ax::mojom::Role::kInlineTextBox;
inline_box_7.SetName(" world");
inline_box_7.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{1});
inline_box_7.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{6});
heading_8.role = ax::mojom::Role::kHeading;
heading_8.child_ids = {static_text_9.id};
static_text_9.role = ax::mojom::Role::kStaticText;
static_text_9.child_ids = {inline_box_10.id};
static_text_9.SetName("3.14");
inline_box_10.role = ax::mojom::Role::kInlineTextBox;
inline_box_10.SetName("3.14");
generic_container_11.role = ax::mojom::Role::kGenericContainer;
generic_container_11.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
generic_container_11.AddState(ax::mojom::State::kIgnored);
generic_container_12.role = ax::mojom::Role::kGenericContainer;
generic_container_12.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
static_text_13.role = ax::mojom::Role::kStaticText;
static_text_13.SetName("hey");
button_14.role = ax::mojom::Role::kButton;
button_14.child_ids = {generic_container_15.id};
generic_container_15.role = ax::mojom::Role::kGenericContainer;
generic_container_15.AddState(ax::mojom::State::kIgnored);
SetTree(CreateAXTree({root_1, static_text_2, inline_box_3, text_field_4,
generic_container_5, static_text_6, inline_box_7,
heading_8, static_text_9, inline_box_10,
generic_container_11, generic_container_12,
static_text_13, button_14, generic_container_15}));
// CreateNextWordStartPosition tests.
TestPositionType position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_3.id, 0 /* child_index_or_text_offset */,
ax::mojom::TextAffinity::kDownstream);
TestPositionType result_position =
position->CreateNextWordStartPosition(AXBoundaryBehavior::CrossBoundary);
std::string expectations =
"TextPosition anchor_id=5 text_offset=0 affinity=downstream "
"annotated_text=<\xEF\xBF\xBC>";
ASSERT_EQ(result_position->ToString(), expectations);
position = std::move(result_position);
result_position =
position->CreateNextWordStartPosition(AXBoundaryBehavior::CrossBoundary);
expectations =
"TextPosition anchor_id=7 text_offset=1 affinity=downstream "
"annotated_text= <w>orld";
ASSERT_EQ(result_position->ToString(), expectations);
// CreatePreviousWordStartPosition tests.
position = std::move(result_position);
result_position = position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
expectations =
"TextPosition anchor_id=5 text_offset=0 affinity=downstream "
"annotated_text=<\xEF\xBF\xBC>";
ASSERT_EQ(result_position->ToString(), expectations);
position = std::move(result_position);
result_position = position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
expectations =
"TextPosition anchor_id=3 text_offset=0 affinity=downstream "
"annotated_text=<H>ello ";
ASSERT_EQ(result_position->ToString(), expectations);
// CreateNextWordEndPosition tests.
position = std::move(result_position);
result_position =
position->CreateNextWordEndPosition(AXBoundaryBehavior::CrossBoundary);
expectations =
"TextPosition anchor_id=3 text_offset=6 affinity=downstream "
"annotated_text=Hello <>";
ASSERT_EQ(result_position->ToString(), expectations);
position = std::move(result_position);
result_position =
position->CreateNextWordEndPosition(AXBoundaryBehavior::CrossBoundary);
expectations =
"TextPosition anchor_id=5 text_offset=1 affinity=downstream "
"annotated_text=\xEF\xBF\xBC<>";
ASSERT_EQ(result_position->ToString(), expectations);
position = std::move(result_position);
result_position =
position->CreateNextWordEndPosition(AXBoundaryBehavior::CrossBoundary);
expectations =
"TextPosition anchor_id=7 text_offset=6 affinity=downstream "
"annotated_text= world<>";
ASSERT_EQ(result_position->ToString(), expectations);
// CreatePreviousWordEndPosition tests.
position = std::move(result_position);
result_position = position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
expectations =
"TextPosition anchor_id=5 text_offset=1 affinity=downstream "
"annotated_text=\xEF\xBF\xBC<>";
ASSERT_EQ(result_position->ToString(), expectations);
position = std::move(result_position);
result_position = position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
expectations =
"TextPosition anchor_id=3 text_offset=6 affinity=downstream "
"annotated_text=Hello <>";
ASSERT_EQ(result_position->ToString(), expectations);
// GetText() with embedded object replacement character test.
position = AXNodePosition::CreateTextPosition(
GetTreeID(), generic_container_5.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
std::u16string expected_text;
expected_text += AXNodePosition::kEmbeddedCharacter;
ASSERT_EQ(expected_text, position->GetText());
// GetText() on a node parent of text nodes and an embedded object replacement
// character.
position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_1.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
expected_text =
std::u16string(u"Hello ") + AXNodePosition::kEmbeddedCharacter +
std::u16string(u" world3.14") + AXNodePosition::kEmbeddedCharacter +
std::u16string(u"hey") + AXNodePosition::kEmbeddedCharacter;
ASSERT_EQ(expected_text, position->GetText());
// MaxTextOffset() with an embedded object replacement character.
position = AXNodePosition::CreateTextPosition(
GetTreeID(), generic_container_5.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_EQ(1, position->MaxTextOffset());
// Parent positions created from a position inside a node represented by an
// embedded object replacement character.
position = position->CreateParentPosition();
expectations =
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<\xEF\xBF\xBC>";
ASSERT_EQ(position->ToString(), expectations);
ASSERT_EQ(1, position->MaxTextOffset());
position = position->CreateParentPosition();
expectations =
"TextPosition anchor_id=1 text_offset=6 affinity=downstream "
"annotated_text=Hello <\xEF\xBF\xBC> "
"world3.14\xEF\xBF\xBChey\xEF\xBF\xBC";
ASSERT_EQ(position->ToString(), expectations);
ASSERT_EQ(22, position->MaxTextOffset());
// MaxTextOffset() on a node parent of text nodes and an embedded object
// replacement character.
position = AXNodePosition::CreateTextPosition(
GetTreeID(), root_1.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_EQ(22, position->MaxTextOffset());
// The following is to test a specific edge case with heading navigation,
// occurring in AXPosition::CreatePreviousFormatStartPosition.
//
// When the position is at the beginning of an unignored empty object,
// preceded by an ignored empty object itself preceded by an heading node, the
// previous format start position should stay on this unignored empty object.
// It shouldn't move to the beginning of the heading.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), generic_container_12.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
text_position = text_position->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
EXPECT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_EQ(generic_container_12.id, text_position->anchor_id());
EXPECT_EQ(0, text_position->text_offset());
// The following is to test a specific edge case that occurs when all the
// children of a node are ignored and that node could be considered as an
// empty object replaced by character (e.g., a button).
//
// The button element should be treated as a leaf node even though it has a
// child. Because its only child is ignored, the button should be considered
// as an empty object replaced by character and we should be able to create a
// leaf position in the button node.
text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text_13.id, 3 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, text_position);
text_position = text_position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
EXPECT_NE(nullptr, text_position);
EXPECT_TRUE(text_position->IsTextPosition());
EXPECT_TRUE(text_position->IsLeafTextPosition());
EXPECT_EQ(button_14.id, text_position->anchor_id());
EXPECT_EQ(1, text_position->text_offset());
}
TEST_F(AXPositionTest, TextNavigationWithCollapsedCombobox) {
// On Windows, a <select> element is replaced by a combobox that contains
// an AXMenuListPopup parent of AXMenuListOptions. When the select dropdown is
// collapsed, the subtree of that combobox needs to be hidden and, when
// expanded, it must be accessible in the tree. This test ensures we can't
// navigate into the options of a collapsed menu list popup.
g_ax_embedded_object_behavior = AXEmbeddedObjectBehavior::kExposeCharacter;
// ++1 kRootWebArea
// ++++2 kStaticText "Hi"
// ++++++3 kInlineTextBox "Hi"
// ++++4 kPopUpButton
// ++++++5 kMenuListPopup
// ++++++++6 kMenuListOption "Option"
// ++++7 kStaticText "3.14"
// ++++++8 kInlineTextBox "3.14"
AXNodeData root_1;
AXNodeData static_text_2;
AXNodeData inline_box_3;
AXNodeData popup_button_4;
AXNodeData menu_list_popup_5;
AXNodeData menu_list_option_6;
AXNodeData static_text_7;
AXNodeData inline_box_8;
root_1.id = 1;
static_text_2.id = 2;
inline_box_3.id = 3;
popup_button_4.id = 4;
menu_list_popup_5.id = 5;
menu_list_option_6.id = 6;
static_text_7.id = 7;
inline_box_8.id = 8;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {static_text_2.id, popup_button_4.id, static_text_7.id};
static_text_2.role = ax::mojom::Role::kStaticText;
static_text_2.SetName("Hi");
static_text_2.child_ids = {inline_box_3.id};
inline_box_3.role = ax::mojom::Role::kInlineTextBox;
inline_box_3.SetName("Hi");
inline_box_3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
{0});
inline_box_3.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds, {2});
popup_button_4.role = ax::mojom::Role::kPopUpButton;
popup_button_4.child_ids = {menu_list_popup_5.id};
popup_button_4.AddState(ax::mojom::State::kCollapsed);
menu_list_popup_5.role = ax::mojom::Role::kMenuListPopup;
menu_list_popup_5.child_ids = {menu_list_option_6.id};
menu_list_option_6.role = ax::mojom::Role::kMenuListOption;
menu_list_option_6.SetName("Option");
static_text_7.role = ax::mojom::Role::kStaticText;
static_text_7.SetName("3.14");
static_text_7.child_ids = {inline_box_8.id};
inline_box_8.role = ax::mojom::Role::kInlineTextBox;
inline_box_8.SetName("3.14");
inline_box_8.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
{0});
inline_box_8.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds, {4});
SetTree(CreateAXTree({root_1, static_text_2, inline_box_3, popup_button_4,
menu_list_popup_5, menu_list_option_6, static_text_7,
inline_box_8}));
// Collapsed - Forward navigation.
TestPositionType position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_3.id, 0, ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, position);
position = position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, position);
EXPECT_EQ(popup_button_4.id, position->anchor_id());
EXPECT_EQ(0, position->text_offset());
position = position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, position);
EXPECT_EQ(inline_box_8.id, position->anchor_id());
EXPECT_EQ(0, position->text_offset());
// Collapsed - Backward navigation.
position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_8.id, 4, ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, position);
position = position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, position);
EXPECT_EQ(popup_button_4.id, position->anchor_id());
// The content of this popup button should be replaced with the empty object
// character of length 1.
EXPECT_EQ(1, position->text_offset());
position = position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, position);
EXPECT_EQ(inline_box_3.id, position->anchor_id());
EXPECT_EQ(2, position->text_offset());
// Expand the combobox for the rest of the test.
popup_button_4.RemoveState(ax::mojom::State::kCollapsed);
popup_button_4.AddState(ax::mojom::State::kExpanded);
AXTreeUpdate update;
update.nodes = {popup_button_4};
ASSERT_TRUE(GetTree()->Unserialize(update));
// Expanded - Forward navigation.
position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_3.id, 0, ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, position);
position = position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, position);
EXPECT_EQ(menu_list_option_6.id, position->anchor_id());
EXPECT_EQ(0, position->text_offset());
position = position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, position);
EXPECT_EQ(inline_box_8.id, position->anchor_id());
EXPECT_EQ(0, position->text_offset());
// Expanded- Backward navigation.
position = AXNodePosition::CreateTextPosition(
GetTreeID(), inline_box_8.id, 4, ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, position);
position = position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, position);
EXPECT_EQ(menu_list_option_6.id, position->anchor_id());
EXPECT_EQ(1, position->text_offset());
position = position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
ASSERT_NE(nullptr, position);
EXPECT_EQ(inline_box_3.id, position->anchor_id());
EXPECT_EQ(2, position->text_offset());
}
//
// Parameterized tests.
//
TEST_P(AXPositionExpandToEnclosingTextBoundaryTestWithParam,
TextPositionBeforeLine2) {
// Create a text position right before "Line 2". This should be at the start
// of many text boundaries, e.g. line, paragraph and word.
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), text_field_.id, 7 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsTextPosition());
TestPositionRange range = text_position->ExpandToEnclosingTextBoundary(
GetParam().boundary, GetParam().expand_behavior);
EXPECT_EQ(GetParam().expected_anchor_position, range.anchor()->ToString());
EXPECT_EQ(GetParam().expected_focus_position, range.focus()->ToString());
}
TEST_P(AXPositionCreatePositionAtTextBoundaryTestWithParam,
TextPositionBeforeStaticText) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), static_text2_.id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsTextPosition());
text_position = text_position->CreatePositionAtTextBoundary(
GetParam().boundary, GetParam().direction, GetParam().boundary_behavior);
EXPECT_NE(nullptr, text_position);
EXPECT_EQ(GetParam().expected_text_position, text_position->ToString());
}
TEST_P(AXPositionTextNavigationTestWithParam,
TraverseTreeStartingWithAffinityDownstream) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetParam().start_node_id, GetParam().start_offset,
ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(text_position->IsTextPosition());
for (const std::string& expectation : GetParam().expectations) {
text_position = GetParam().TestMethod(text_position);
EXPECT_NE(nullptr, text_position);
EXPECT_EQ(expectation, text_position->ToString());
}
}
TEST_P(AXPositionTextNavigationTestWithParam,
TraverseTreeStartingWithAffinityUpstream) {
TestPositionType text_position = AXNodePosition::CreateTextPosition(
GetTreeID(), GetParam().start_node_id, GetParam().start_offset,
ax::mojom::TextAffinity::kUpstream);
ASSERT_TRUE(text_position->IsTextPosition());
for (const std::string& expectation : GetParam().expectations) {
text_position = GetParam().TestMethod(text_position);
EXPECT_NE(nullptr, text_position);
EXPECT_EQ(expectation, text_position->ToString());
}
}
//
// Instantiations of parameterized tests.
//
INSTANTIATE_TEST_SUITE_P(
ExpandToEnclosingTextBoundary,
AXPositionExpandToEnclosingTextBoundaryTestWithParam,
testing::Values(
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kCharacter,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=6 affinity=downstream "
"annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kCharacter,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=8 affinity=downstream "
"annotated_text=Line 1\nL<i>ne 2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kFormat, AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kFormat,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineEnd,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=6 affinity=downstream "
"annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineEnd,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=6 affinity=downstream "
"annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineStart,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineStart,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineStartOrEnd,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=6 affinity=downstream "
"annotated_text=Line 1<\n>Line 2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineStartOrEnd,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kObject, AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kObject,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphEnd,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=7 affinity=upstream "
"annotated_text=Line 1\n<L>ine 2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphEnd,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=7 affinity=upstream "
"annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphStart,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphStart,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphStartOrEnd,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=7 affinity=upstream "
"annotated_text=Line 1\n<L>ine 2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphStartOrEnd,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 affinity=downstream "
"annotated_text=Line 1\nLine 2<>"},
// TODO(accessibility): Add tests for sentence boundary.
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kWebPage,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=1 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=9 text_offset=6 affinity=downstream "
"annotated_text=Line 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kWebPage,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=1 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=9 text_offset=6 affinity=downstream "
"annotated_text=Line 2<>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordEnd,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=6 affinity=downstream "
"annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=11 affinity=downstream "
"annotated_text=Line 1\nLine< >2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordEnd,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=6 affinity=downstream "
"annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=11 affinity=downstream "
"annotated_text=Line 1\nLine< >2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordStart,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=5 affinity=downstream "
"annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordStart,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=12 affinity=downstream "
"annotated_text=Line 1\nLine <2>"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordStartOrEnd,
AXRangeExpandBehavior::kLeftFirst,
"TextPosition anchor_id=4 text_offset=5 affinity=downstream "
"annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=4 text_offset=6 affinity=downstream "
"annotated_text=Line 1<\n>Line 2"},
ExpandToEnclosingTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordStartOrEnd,
AXRangeExpandBehavior::kRightFirst,
"TextPosition anchor_id=4 text_offset=7 affinity=downstream "
"annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=11 affinity=downstream "
"annotated_text=Line 1\nLine< >2"}));
// Only test with AXBoundaryBehavior::CrossBoundary for now.
// TODO(accessibility): Add more tests for other boundary behaviors if needed.
INSTANTIATE_TEST_SUITE_P(
CreatePositionAtTextBoundary,
AXPositionCreatePositionAtTextBoundaryTestWithParam,
testing::Values(
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kCharacter,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=7 text_offset=0 affinity=downstream "
"annotated_text=<\n>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kCharacter,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=1 affinity=downstream "
"annotated_text=L<i>ne 2"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kFormat,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=7 text_offset=0 affinity=downstream "
"annotated_text=<\n>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kFormat,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=6 affinity=downstream "
"annotated_text=Line 2<>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineEnd,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=7 text_offset=0 affinity=downstream "
"annotated_text=<\n>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineEnd,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=6 affinity=downstream "
"annotated_text=Line 2<>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineStart,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=6 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineStart,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary, "NullPosition"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineStartOrEnd,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=6 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kLineStartOrEnd,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=6 affinity=downstream "
"annotated_text=Line 2<>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kObject,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 2"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kObject,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=6 affinity=downstream "
"annotated_text=Line 2<>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphEnd,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=3 text_offset=0 affinity=downstream "
"annotated_text=<>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphEnd,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=6 affinity=downstream "
"annotated_text=Line 2<>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphStart,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=6 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphStart,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary, "NullPosition"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphStartOrEnd,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=6 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kParagraphStartOrEnd,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=6 affinity=downstream "
"annotated_text=Line 2<>"},
// TODO(accessibility): Add tests for sentence boundary.
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kWebPage,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=1 text_offset=0 affinity=downstream "
"annotated_text=<L>ine 1\nLine 2"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kWebPage,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=9 text_offset=6 affinity=downstream "
"annotated_text=Line 2<>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordEnd,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=6 text_offset=6 affinity=downstream "
"annotated_text=Line 1<>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordEnd,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=4 affinity=downstream "
"annotated_text=Line< >2"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordStart,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=6 text_offset=5 affinity=downstream "
"annotated_text=Line <1>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordStart,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=5 affinity=downstream "
"annotated_text=Line <2>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordStartOrEnd,
ax::mojom::MoveDirection::kBackward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=6 text_offset=5 affinity=downstream "
"annotated_text=Line <1>"},
CreatePositionAtTextBoundaryTestParam{
ax::mojom::TextBoundary::kWordStartOrEnd,
ax::mojom::MoveDirection::kForward,
AXBoundaryBehavior::CrossBoundary,
"TextPosition anchor_id=8 text_offset=4 affinity=downstream "
"annotated_text=Line< >2"}));
INSTANTIATE_TEST_SUITE_P(
CreateNextWordStartPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"NullPosition"}},
TextNavigationTestParam{[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=5 "
"affinity=downstream annotated_text=Line <1>",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=5 "
"affinity=downstream annotated_text=Line <2>",
"NullPosition"}},
TextNavigationTestParam{[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=5 "
"affinity=downstream annotated_text=Line <2>",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextWordStartPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=5 "
"affinity=downstream annotated_text=Line <1>",
"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=5 "
"affinity=downstream annotated_text=Line <2>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextWordStartPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=5 "
"affinity=downstream annotated_text=Line <1>",
"TextPosition anchor_id=5 text_offset=5 "
"affinity=downstream annotated_text=Line <1>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=5 "
"affinity=downstream annotated_text=Line <2>",
"TextPosition anchor_id=9 text_offset=5 "
"affinity=downstream annotated_text=Line <2>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextWordStartPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=5 "
"affinity=downstream annotated_text=Line <1>",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=5 "
"affinity=downstream annotated_text=Line <2>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=5 "
"affinity=downstream annotated_text=Line <2>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousWordStartPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=6 text_offset=5 "
"affinity=downstream annotated_text=Line <1>",
"TextPosition anchor_id=6 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousWordStartPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousWordStartPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=1 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=4 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=5 "
"affinity=downstream annotated_text=Line <1>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousWordStartPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
13 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=12 "
"affinity=downstream annotated_text=Line 1\nLine <2>",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=5 "
"affinity=downstream annotated_text=Line <1>\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=6 text_offset=5 "
"affinity=downstream annotated_text=Line <1>",
"TextPosition anchor_id=6 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=6 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextWordEndPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"NullPosition"}},
TextNavigationTestParam{[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=9 text_offset=4 "
"affinity=downstream annotated_text=Line< >2",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"NullPosition"}},
TextNavigationTestParam{[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextWordEndPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextWordEndPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=1 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=4 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=4 "
"affinity=downstream annotated_text=Line< >2"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextWordEndPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=9 text_offset=4 "
"affinity=downstream annotated_text=Line< >2",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextWordEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousWordEndPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=6 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=6 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousWordEndPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{
"TextPosition anchor_id=1 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousWordEndPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=4 "
"affinity=downstream annotated_text=Line< >2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousWordEndPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=11 "
"affinity=downstream annotated_text=Line 1\nLine< >2",
"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=4 "
"affinity=downstream annotated_text=Line< >1\nLine 2",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousWordEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=6 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=6 text_offset=4 "
"affinity=downstream annotated_text=Line< >1",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextLineStartPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"NullPosition"}},
TextNavigationTestParam{[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"NullPosition"}},
TextNavigationTestParam{[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextLineStartPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextLineStartPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextLineStartPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousLineStartPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
13 /* text_offset at the end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=6 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousLineStartPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at the end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousLineStartPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
13 /* text_offset at the end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousLineStartPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at the end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=6 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=6 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextLineEndPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"NullPosition"}},
TextNavigationTestParam{[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"NullPosition"}},
TextNavigationTestParam{[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextLineEndPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextLineEndPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextLineEndPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousLineEndPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
5 /* text_offset on the last character of "Line 1". */,
{"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
5 /* text_offset on the last character of "Line 1". */,
{"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=6 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
0 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=0 "
"affinity=downstream annotated_text=<\n>",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousLineEndPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
0 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousLineEndPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
12 /* text_offset one before the end of root. */,
{"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
12 /* text_offset one before the end of text field */,
{"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX1_ID,
2 /* text_offset */,
{"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=6 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=6 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
0 /* text_offset */,
{"TextPosition anchor_id=6 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=6 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousLineEndPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=6 "
"affinity=downstream annotated_text=Line 1<\n>Line 2",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=6 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousLineEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
0 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=0 "
"affinity=downstream annotated_text=<\n>",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=2 text_offset=0 "
"affinity=downstream annotated_text=<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextParagraphStartPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextParagraphStartPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextParagraphStartPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextParagraphStartPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousParagraphStartPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
13 /* text_offset at the end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=6 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousParagraphStartPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at the end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousParagraphStartPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
13 /* text_offset at the end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousParagraphStartPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at the end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=downstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
5 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=5 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=6 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1",
"TextPosition anchor_id=6 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextParagraphEndPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextParagraphEndPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>",
"TextPosition anchor_id=5 text_offset=6 "
"affinity=downstream annotated_text=Line 1<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextParagraphEndPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
LINE_BREAK_ID,
0 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
LINE_BREAK_ID,
1 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreateNextParagraphEndPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
0 /* text_offset */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=1 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
0 /* text_offset */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>",
"TextPosition anchor_id=4 text_offset=13 "
"affinity=downstream annotated_text=Line 1\nLine 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
STATIC_TEXT1_ID,
1 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreateNextParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>",
"TextPosition anchor_id=9 text_offset=6 "
"affinity=downstream annotated_text=Line 2<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousParagraphEndPositionWithBoundaryBehaviorCrossBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
ROOT_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
TEXT_FIELD_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"NullPosition"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::CrossBoundary);
},
INLINE_BOX2_ID,
0 /* text_offset */,
{"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"NullPosition"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousParagraphEndPositionWithBoundaryBehaviorStopAtAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
ROOT_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
TEXT_FIELD_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=4 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary);
},
INLINE_BOX2_ID,
0 /* text_offset */,
{"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2",
"TextPosition anchor_id=9 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 2"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousParagraphEndPositionWithBoundaryBehaviorStopIfAlreadyAtBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
ROOT_ID,
12 /* text_offset one before the end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
TEXT_FIELD_ID,
12 /* text_offset one before the end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX1_ID,
2 /* text_offset */,
{"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
INLINE_BOX2_ID,
0 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
LINE_BREAK_ID,
0 /* text_offset */,
{"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary);
},
LINE_BREAK_ID,
1 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>"}}));
INSTANTIATE_TEST_SUITE_P(
CreatePreviousParagraphEndPositionWithBoundaryBehaviorStopAtLastAnchorBoundary,
AXPositionTextNavigationTestWithParam,
testing::Values(
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
13 /* text_offset at end of root. */,
{"TextPosition anchor_id=1 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
13 /* text_offset at end of text field */,
{"TextPosition anchor_id=4 text_offset=7 "
"affinity=upstream annotated_text=Line 1\n<L>ine 2",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
ROOT_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2",
"TextPosition anchor_id=1 text_offset=0 "
"affinity=downstream annotated_text=<L>ine 1\nLine 2"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
TEXT_FIELD_ID,
5 /* text_offset on the last character of "Line 1". */,
{"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
4 /* text_offset */,
{"TextPosition anchor_id=7 text_offset=1 "
"affinity=downstream annotated_text=\n<>",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>"}},
TextNavigationTestParam{
[](const TestPositionType& position) {
return position->CreatePreviousParagraphEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary);
},
INLINE_BOX2_ID,
0 /* text_offset */,
{"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>",
"TextPosition anchor_id=3 text_offset=0 "
"affinity=downstream annotated_text=<>"}}));
} // namespace ui
| engine/third_party/accessibility/ax/ax_node_position_unittest.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_node_position_unittest.cc",
"repo_id": "engine",
"token_count": 196860
} | 548 |
// 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_H_
#define UI_ACCESSIBILITY_AX_TREE_H_
#include <cstdint>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "ax_enums.h"
#include "ax_export.h"
#include "ax_node.h"
#include "ax_node_data.h"
#include "ax_tree_data.h"
#include "ax_tree_update.h"
#include "gfx/geometry/rect.h"
namespace ui {
class AXTableInfo;
class AXTreeObserver;
struct AXTreeUpdateState;
// AXTree is a live, managed tree of AXNode objects that can receive
// updates from another AXTreeSource via AXTreeUpdates, and it can be
// used as a source for sending updates to another client tree.
// It's designed to be subclassed to implement support for native
// accessibility APIs on a specific platform.
class AX_EXPORT AXTree : public AXNode::OwnerTree {
public:
using IntReverseRelationMap =
std::map<ax::mojom::IntAttribute, std::map<int32_t, std::set<int32_t>>>;
using IntListReverseRelationMap =
std::map<ax::mojom::IntListAttribute,
std::map<int32_t, std::set<int32_t>>>;
AXTree();
explicit AXTree(const AXTreeUpdate& initial_state);
virtual ~AXTree();
// AXTree owns pointers so copying is non-trivial.
AXTree(const AXTree&) = delete;
AXTree& operator=(const AXTree&) = delete;
void AddObserver(AXTreeObserver* observer);
bool HasObserver(AXTreeObserver* observer);
void RemoveObserver(AXTreeObserver* observer);
std::vector<AXTreeObserver*>& observers() { return observers_; }
AXNode* root() const { return root_; }
const AXTreeData& data() const { return data_; }
// Destroys the tree and notifies all observers.
void Destroy();
// AXNode::OwnerTree override.
// Returns the globally unique ID of this accessibility tree.
AXTreeID GetAXTreeID() const override;
// AXNode::OwnerTree override.
// Returns the AXNode with the given |id| if it is part of this AXTree.
AXNode* GetFromId(int32_t id) const override;
// Returns true on success. If it returns false, it's a fatal error
// and this tree should be destroyed, and the source of the tree update
// should not be trusted any longer.
virtual bool Unserialize(const AXTreeUpdate& update);
virtual void UpdateData(const AXTreeData& data);
// Convert any rectangle from the local coordinate space of one node in
// the tree, to bounds in the coordinate space of the tree.
// If set, updates |offscreen| boolean to be true if the node is offscreen
// relative to its rootWebArea. Callers should initialize |offscreen|
// to false: this method may get called multiple times in a row and
// |offscreen| will be propagated.
// If |clip_bounds| is true, result bounds will be clipped.
gfx::RectF RelativeToTreeBounds(const AXNode* node,
gfx::RectF node_bounds,
bool* offscreen = nullptr,
bool clip_bounds = true) const;
// Get the bounds of a node in the coordinate space of the tree.
// If set, updates |offscreen| boolean to be true if the node is offscreen
// relative to its rootWebArea. Callers should initialize |offscreen|
// to false: this method may get called multiple times in a row and
// |offscreen| will be propagated.
// If |clip_bounds| is true, result bounds will be clipped.
gfx::RectF GetTreeBounds(const AXNode* node,
bool* offscreen = nullptr,
bool clip_bounds = true) const;
// Given a node ID attribute (one where IsNodeIdIntAttribute is true),
// and a destination node ID, return a set of all source node IDs that
// have that relationship attribute between them and the destination.
std::set<int32_t> GetReverseRelations(ax::mojom::IntAttribute attr,
int32_t dst_id) const;
// Given a node ID list attribute (one where
// IsNodeIdIntListAttribute is true), and a destination node ID,
// return a set of all source node IDs that have that relationship
// attribute between them and the destination.
std::set<int32_t> GetReverseRelations(ax::mojom::IntListAttribute attr,
int32_t dst_id) const;
// Given a child tree ID, return the node IDs of all nodes in the tree who
// have a kChildTreeId int attribute with that value.
std::set<int32_t> GetNodeIdsForChildTreeId(AXTreeID child_tree_id) const;
// Get all of the child tree IDs referenced by any node in this tree.
const std::set<AXTreeID> GetAllChildTreeIds() const;
// Map from a relation attribute to a map from a target id to source ids.
const IntReverseRelationMap& int_reverse_relations() {
return int_reverse_relations_;
}
const IntListReverseRelationMap& intlist_reverse_relations() {
return intlist_reverse_relations_;
}
// Return a multi-line indented string representation, for logging.
std::string ToString() const;
// A string describing the error from an unsuccessful Unserialize,
// for testing and debugging.
const std::string& error() const { return error_; }
int size() { return static_cast<int>(id_map_.size()); }
// Call this to enable support for extra Mac nodes - for each table,
// a table column header and a node for each column.
void SetEnableExtraMacNodes(bool enabled);
bool enable_extra_mac_nodes() const { return enable_extra_mac_nodes_; }
// Return a negative number that's suitable to use for a node ID for
// internal nodes created automatically by an AXTree, so as not to
// conflict with positive-numbered node IDs from tree sources.
int32_t GetNextNegativeInternalNodeId();
// Returns the PosInSet of |node|. Looks in node_set_size_pos_in_set_info_map_
// for cached value. Calls |ComputeSetSizePosInSetAndCache|if no value is
// present in the cache.
std::optional<int> GetPosInSet(const AXNode& node) override;
// Returns the SetSize of |node|. Looks in node_set_size_pos_in_set_info_map_
// for cached value. Calls |ComputeSetSizePosInSetAndCache|if no value is
// present in the cache.
std::optional<int> GetSetSize(const AXNode& node) override;
Selection GetUnignoredSelection() const override;
bool GetTreeUpdateInProgressState() const override;
void SetTreeUpdateInProgressState(bool set_tree_update_value);
// AXNode::OwnerTree override.
// Returns true if the tree represents a paginated document
bool HasPaginationSupport() const override;
// A list of intents active during a tree update/unserialization.
const std::vector<AXEventIntent>& event_intents() const {
return event_intents_;
}
private:
friend class AXTableInfoTest;
// AXNode::OwnerTree override.
//
// Given a node in this accessibility tree that corresponds to a table
// or grid, return an object containing information about the
// table structure. This object is computed lazily on-demand and
// cached until the next time the tree is updated. Clients should
// not retain this pointer, they should just request it every time
// it's needed.
//
// Returns nullptr if the node is not a valid table.
AXTableInfo* GetTableInfo(const AXNode* table_node) const override;
AXNode* CreateNode(AXNode* parent,
AXNode::AXID id,
size_t index_in_parent,
AXTreeUpdateState* update_state);
// Accumulates the work that will be required to update the AXTree.
// This allows us to notify observers of structure changes when the
// tree is still in a stable and unchanged state.
bool ComputePendingChanges(const AXTreeUpdate& update,
AXTreeUpdateState* update_state);
// Populates |update_state| with information about actions that will
// be performed on the tree during the update, such as adding or
// removing nodes in the tree. Returns true on success.
// Nothing within this call should modify tree structure or node data.
bool ComputePendingChangesToNode(const AXNodeData& new_data,
bool is_new_root,
AXTreeUpdateState* update_state);
// This is called from within Unserialize(), it returns true on success.
bool UpdateNode(const AXNodeData& src,
bool is_new_root,
AXTreeUpdateState* update_state);
// Notify the delegate that the subtree rooted at |node| will be
// destroyed or reparented.
void NotifySubtreeWillBeReparentedOrDeleted(
AXNode* node,
const AXTreeUpdateState* update_state);
// Notify the delegate that |node| will be destroyed or reparented.
void NotifyNodeWillBeReparentedOrDeleted(
AXNode* node,
const AXTreeUpdateState* update_state);
// Notify the delegate that |node| and all of its descendants will be
// destroyed. This function is called during AXTree teardown.
void RecursivelyNotifyNodeDeletedForTreeTeardown(AXNode* node);
// Notify the delegate that the node marked by |node_id| has been deleted.
// We are passing the node id instead of ax node is because by the time this
// function is called, the ax node in the tree will already have been
// destroyed.
void NotifyNodeHasBeenDeleted(AXNode::AXID node_id);
// Notify the delegate that |node| has been created or reparented.
void NotifyNodeHasBeenReparentedOrCreated(
AXNode* node,
const AXTreeUpdateState* update_state);
// Notify the delegate that a node will change its data.
void NotifyNodeDataWillChange(const AXNodeData& old_data,
const AXNodeData& new_data);
// Notify the delegate that |node| has changed its data.
void NotifyNodeDataHasBeenChanged(AXNode* node,
const AXNodeData& old_data,
const AXNodeData& new_data);
void UpdateReverseRelations(AXNode* node, const AXNodeData& new_data);
// Returns true if all pending changes in the |update_state| have been
// handled. If this returns false, the |error_| message will be populated.
// It's a fatal error to have pending changes after exhausting
// the AXTreeUpdate.
bool ValidatePendingChangesComplete(const AXTreeUpdateState& update_state);
// Modifies |update_state| so that it knows what subtree and nodes are
// going to be destroyed for the subtree rooted at |node|.
void MarkSubtreeForDestruction(AXNode::AXID node_id,
AXTreeUpdateState* update_state);
// Modifies |update_state| so that it knows what nodes are
// going to be destroyed for the subtree rooted at |node|.
void MarkNodesForDestructionRecursive(AXNode::AXID node_id,
AXTreeUpdateState* update_state);
// Validates that destroying the subtree rooted at |node| has required
// information in |update_state|, then calls DestroyNodeAndSubtree on it.
void DestroySubtree(AXNode* node, AXTreeUpdateState* update_state);
// Call Destroy() on |node|, and delete it from the id map, and then
// call recursively on all nodes in its subtree.
void DestroyNodeAndSubtree(AXNode* node, AXTreeUpdateState* update_state);
// Iterate over the children of |node| and for each child, destroy the
// child and its subtree if its id is not in |new_child_ids|.
void DeleteOldChildren(AXNode* node,
const std::vector<int32_t>& new_child_ids,
AXTreeUpdateState* update_state);
// Iterate over |new_child_ids| and populate |new_children| with
// pointers to child nodes, reusing existing nodes already in the tree
// if they exist, and creating otherwise. Reparenting is disallowed, so
// if the id already exists as the child of another node, that's an
// error. Returns true on success, false on fatal error.
bool CreateNewChildVector(AXNode* node,
const std::vector<int32_t>& new_child_ids,
std::vector<AXNode*>* new_children,
AXTreeUpdateState* update_state);
// Internal implementation of RelativeToTreeBounds. It calls itself
// recursively but ensures that it can only do so exactly once!
gfx::RectF RelativeToTreeBoundsInternal(const AXNode* node,
gfx::RectF node_bounds,
bool* offscreen,
bool clip_bounds,
bool allow_recursion) const;
std::vector<AXTreeObserver*> observers_;
AXNode* root_ = nullptr;
std::unordered_map<int32_t, AXNode*> id_map_;
std::string error_;
AXTreeData data_;
// Map from an int attribute (if IsNodeIdIntAttribute is true) to
// a reverse mapping from target nodes to source nodes.
IntReverseRelationMap int_reverse_relations_;
// Map from an int list attribute (if IsNodeIdIntListAttribute is true) to
// a reverse mapping from target nodes to source nodes.
IntListReverseRelationMap intlist_reverse_relations_;
// Map from child tree ID to the set of node IDs that contain that attribute.
std::map<AXTreeID, std::set<int32_t>> child_tree_id_reverse_map_;
// Map from node ID to cached table info, if the given node is a table.
// Invalidated every time the tree is updated.
mutable std::unordered_map<int32_t, std::unique_ptr<AXTableInfo>>
table_info_map_;
// The next negative node ID to use for internal nodes.
int32_t next_negative_internal_node_id_ = -1;
// Whether we should create extra nodes that
// are only useful on macOS. Implemented using this flag to allow
// this code to be unit-tested on other platforms (for example, more
// code sanitizers run on Linux).
bool enable_extra_mac_nodes_ = false;
// Contains pos_in_set and set_size data for an AXNode.
struct NodeSetSizePosInSetInfo {
NodeSetSizePosInSetInfo();
~NodeSetSizePosInSetInfo();
std::optional<int> pos_in_set;
std::optional<int> set_size;
std::optional<int> lowest_hierarchical_level;
};
// Represents the content of an ordered set which includes the ordered set
// items and the ordered set container if it exists.
struct OrderedSetContent;
// Maps a particular hierarchical level to a list of OrderedSetContents.
// Represents all ordered set items/container on a particular hierarchical
// level.
struct OrderedSetItemsMap;
// Populates |items_map_to_be_populated| with all items associated with
// |original_node| and within |ordered_set|. Only items whose roles match the
// role of the |ordered_set| will be added.
void PopulateOrderedSetItemsMap(
const AXNode& original_node,
const AXNode* ordered_set,
OrderedSetItemsMap* items_map_to_be_populated) const;
// Helper function for recursively populating ordered sets items map with
// all items associated with |original_node| and |ordered_set|. |local_parent|
// tracks the recursively passed in child nodes of |ordered_set|.
void RecursivelyPopulateOrderedSetItemsMap(
const AXNode& original_node,
const AXNode* ordered_set,
const AXNode* local_parent,
std::optional<int> ordered_set_min_level,
std::optional<int> prev_level,
OrderedSetItemsMap* items_map_to_be_populated) const;
// Computes the pos_in_set and set_size values of all items in ordered_set and
// caches those values. Called by GetPosInSet and GetSetSize.
void ComputeSetSizePosInSetAndCache(const AXNode& node,
const AXNode* ordered_set);
// Helper for ComputeSetSizePosInSetAndCache. Computes and caches the
// pos_in_set and set_size values for a given OrderedSetContent.
void ComputeSetSizePosInSetAndCacheHelper(
const OrderedSetContent& ordered_set_content);
// Map from node ID to OrderedSetInfo.
// Item-like and ordered-set-like objects will map to populated OrderedSetInfo
// objects.
// All other objects will map to default-constructed OrderedSetInfo objects.
// Invalidated every time the tree is updated.
mutable std::unordered_map<int32_t, NodeSetSizePosInSetInfo>
node_set_size_pos_in_set_info_map_;
// Indicates if the tree is updating.
bool tree_update_in_progress_ = false;
// Indicates if the tree represents a paginated document
bool has_pagination_support_ = false;
std::vector<AXEventIntent> event_intents_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_TREE_H_
| engine/third_party/accessibility/ax/ax_tree.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_tree.h",
"repo_id": "engine",
"token_count": 5691
} | 549 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_FRAGMENT_ROOT_WIN_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_FRAGMENT_ROOT_WIN_H_
#include "ax_platform_node_delegate_base.h"
#include <wrl/client.h>
namespace ui {
class AXFragmentRootDelegateWin;
class AXFragmentRootPlatformNodeWin;
class AXPlatformNodeWin;
// UI Automation on Windows requires the root of a multi-element provider to
// implement IRawElementProviderFragmentRoot. Our internal accessibility trees
// may not know their roots for right away; for example, web content may
// deserialize the document for an iframe before the host document. Because of
// this, and because COM rules require that the list of interfaces returned by
// QueryInterface remain static over the lifetime of an object instance, we
// implement IRawElementProviderFragmentRoot on its own node for each HWND, with
// the root of our internal accessibility tree for that HWND as its sole child.
//
// Since UIA derives some information from the underlying HWND hierarchy, we
// expose one fragment root per HWND. The class that owns the HWND is expected
// to own the corresponding AXFragmentRootWin.
class AX_EXPORT AXFragmentRootWin : public ui::AXPlatformNodeDelegateBase {
public:
AXFragmentRootWin(gfx::AcceleratedWidget widget,
AXFragmentRootDelegateWin* delegate);
~AXFragmentRootWin() override;
// Fragment roots register themselves in a map upon creation and unregister
// upon destruction. This method provides a lookup, which allows the internal
// accessibility root to navigate back to the corresponding fragment root.
static AXFragmentRootWin* GetForAcceleratedWidget(
gfx::AcceleratedWidget widget);
// If the given NativeViewAccessible is the direct descendant of a fragment
// root, return the corresponding fragment root.
static AXFragmentRootWin* GetFragmentRootParentOf(
gfx::NativeViewAccessible accessible);
// Returns the NativeViewAccessible for this fragment root.
gfx::NativeViewAccessible GetNativeViewAccessible() override;
// Assistive technologies will typically use UI Automation's control or
// content view rather than the raw view.
// Returns true if the fragment root should be included in the control and
// content views or false if it should be excluded.
bool IsControlElement();
// If a child node is available, return its delegate.
AXPlatformNodeDelegate* GetChildNodeDelegate() const;
// |AXPlatformNodeDelegate|
gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() override;
// alert_node is an AXPlatformNodeWin whose text value can be set by the
// application for the purposes of announcing messages to a screen reader.
// AXFragmentRootWin does not own its alert_node_; it is owned by the object
// with the responsibility of setting its text. In the case of flutter
// windows, this is the Window.
void SetAlertNode(AXPlatformNodeWin* alert_node);
private:
// AXPlatformNodeDelegate overrides.
gfx::NativeViewAccessible GetParent() override;
int GetChildCount() const override;
gfx::NativeViewAccessible ChildAtIndex(int index) override;
gfx::NativeViewAccessible GetNextSibling() override;
gfx::NativeViewAccessible GetPreviousSibling() override;
gfx::NativeViewAccessible HitTestSync(int x, int y) const override;
gfx::NativeViewAccessible GetFocus() override;
const ui::AXUniqueId& GetUniqueId() const override;
AXPlatformNode* GetFromTreeIDAndNodeID(const ui::AXTreeID& ax_tree_id,
int32_t id) override;
gfx::Rect GetBoundsRect(const AXCoordinateSystem acs,
const AXClippingBehavior acb,
AXOffscreenResult* result) const override;
// A fragment root does not correspond to any node in the platform neutral
// accessibility tree. Rather, the fragment root's child is a child of the
// fragment root's parent. This helper computes the child's index in the
// parent's array of children.
int GetIndexInParentOfChild() const;
// If a parent node is available, return its delegate.
AXPlatformNodeDelegate* GetParentNodeDelegate() const;
gfx::AcceleratedWidget widget_;
AXFragmentRootDelegateWin* const delegate_;
Microsoft::WRL::ComPtr<ui::AXFragmentRootPlatformNodeWin> platform_node_;
ui::AXUniqueId unique_id_;
// Node that presents the alert, if any.
AXPlatformNodeWin* alert_node_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_FRAGMENT_ROOT_WIN_H_
| engine/third_party/accessibility/ax/platform/ax_fragment_root_win.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_fragment_root_win.h",
"repo_id": "engine",
"token_count": 1362
} | 550 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax/platform/ax_platform_node_textprovider_win.h"
#include <wrl/client.h>
#include "base/win/scoped_safearray.h"
#include "ax/platform/ax_platform_node_textrangeprovider_win.h"
#define UIA_VALIDATE_TEXTPROVIDER_CALL() \
if (!owner()->GetDelegate()) \
return UIA_E_ELEMENTNOTAVAILABLE;
#define UIA_VALIDATE_TEXTPROVIDER_CALL_1_ARG(arg) \
if (!owner()->GetDelegate()) \
return UIA_E_ELEMENTNOTAVAILABLE; \
if (!arg) \
return E_INVALIDARG;
namespace ui {
AXPlatformNodeTextProviderWin::AXPlatformNodeTextProviderWin() {}
AXPlatformNodeTextProviderWin::~AXPlatformNodeTextProviderWin() {}
// static
AXPlatformNodeTextProviderWin* AXPlatformNodeTextProviderWin::Create(
AXPlatformNodeWin* owner) {
CComObject<AXPlatformNodeTextProviderWin>* text_provider = nullptr;
if (SUCCEEDED(CComObject<AXPlatformNodeTextProviderWin>::CreateInstance(
&text_provider))) {
BASE_DCHECK(text_provider);
text_provider->owner_ = owner;
text_provider->AddRef();
return text_provider;
}
return nullptr;
}
// static
void AXPlatformNodeTextProviderWin::CreateIUnknown(AXPlatformNodeWin* owner,
IUnknown** unknown) {
Microsoft::WRL::ComPtr<AXPlatformNodeTextProviderWin> text_provider(
Create(owner));
if (text_provider)
*unknown = text_provider.Detach();
}
//
// ITextProvider methods.
//
HRESULT AXPlatformNodeTextProviderWin::GetSelection(SAFEARRAY** selection) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*selection = nullptr;
AXPlatformNodeDelegate* delegate = owner()->GetDelegate();
AXTree::Selection unignored_selection = delegate->GetUnignoredSelection();
AXPlatformNode* anchor_object =
delegate->GetFromNodeID(unignored_selection.anchor_object_id);
AXPlatformNode* focus_object =
delegate->GetFromNodeID(unignored_selection.focus_object_id);
// anchor_offset corresponds to the selection start index
// and focus_offset is where the selection ends.
auto start_offset = unignored_selection.anchor_offset;
auto end_offset = unignored_selection.focus_offset;
// If there's no selected object, return success and don't fill the SAFEARRAY.
if (!anchor_object || !focus_object)
return S_OK;
AXNodePosition::AXPositionInstance start =
anchor_object->GetDelegate()->CreateTextPositionAt(start_offset);
AXNodePosition::AXPositionInstance end =
focus_object->GetDelegate()->CreateTextPositionAt(end_offset);
BASE_DCHECK(!start->IsNullPosition());
BASE_DCHECK(!end->IsNullPosition());
// Reverse start and end if the selection goes backwards
if (*start > *end)
std::swap(start, end);
Microsoft::WRL::ComPtr<ITextRangeProvider> text_range_provider =
AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
if (&text_range_provider == nullptr)
return E_OUTOFMEMORY;
// Since we don't support disjoint text ranges, the SAFEARRAY returned
// will always have one element
base::win::ScopedSafearray selections_to_return(
SafeArrayCreateVector(VT_UNKNOWN /* element type */, 0 /* lower bound */,
1 /* number of elements */));
if (!selections_to_return.Get())
return E_OUTOFMEMORY;
LONG index = 0;
HRESULT hr = SafeArrayPutElement(selections_to_return.Get(), &index,
text_range_provider.Get());
BASE_DCHECK(SUCCEEDED(hr));
// Since BASE_DCHECK only happens in debug builds, return immediately to
// ensure that we're not leaking the SAFEARRAY on release builds
if (FAILED(hr))
return E_FAIL;
*selection = selections_to_return.Release();
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::GetVisibleRanges(
SAFEARRAY** visible_ranges) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
const AXPlatformNodeDelegate* delegate = owner()->GetDelegate();
// Get the Clipped Frame Bounds of the current node, not from the root,
// so if this node is wrapped with overflow styles it will have the
// correct bounds
const gfx::Rect frame_rect = delegate->GetBoundsRect(
AXCoordinateSystem::kFrame, AXClippingBehavior::kClipped);
const auto start = delegate->CreateTextPositionAt(0);
const auto end = start->CreatePositionAtEndOfAnchor();
BASE_DCHECK(start->GetAnchor() == end->GetAnchor());
// SAFEARRAYs are not dynamic, so fill the visible ranges in a vector
// and then transfer to an appropriately-sized SAFEARRAY
std::vector<Microsoft::WRL::ComPtr<ITextRangeProvider>> ranges;
auto current_line_start = start->Clone();
while (!current_line_start->IsNullPosition() && *current_line_start < *end) {
auto current_line_end = current_line_start->CreateNextLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
if (current_line_end->IsNullPosition() || *current_line_end > *end)
current_line_end = end->Clone();
gfx::Rect current_rect = delegate->GetInnerTextRangeBoundsRect(
current_line_start->text_offset(), current_line_end->text_offset(),
AXCoordinateSystem::kFrame, AXClippingBehavior::kUnclipped);
if (frame_rect.Contains(current_rect)) {
Microsoft::WRL::ComPtr<ITextRangeProvider> text_range_provider =
AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
current_line_start->Clone(), current_line_end->Clone());
ranges.emplace_back(text_range_provider);
}
current_line_start = current_line_start->CreateNextLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
}
base::win::ScopedSafearray scoped_visible_ranges(
SafeArrayCreateVector(VT_UNKNOWN /* element type */, 0 /* lower bound */,
ranges.size() /* number of elements */));
if (!scoped_visible_ranges.Get())
return E_OUTOFMEMORY;
LONG index = 0;
for (Microsoft::WRL::ComPtr<ITextRangeProvider>& current_provider : ranges) {
HRESULT hr = SafeArrayPutElement(scoped_visible_ranges.Get(), &index,
current_provider.Get());
BASE_DCHECK(SUCCEEDED(hr));
// Since BASE_DCHECK only happens in debug builds, return immediately to
// ensure that we're not leaking the SAFEARRAY on release builds
if (FAILED(hr))
return E_FAIL;
++index;
}
*visible_ranges = scoped_visible_ranges.Release();
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::RangeFromChild(
IRawElementProviderSimple* child,
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL_1_ARG(child);
*range = nullptr;
Microsoft::WRL::ComPtr<ui::AXPlatformNodeWin> child_platform_node;
if (!SUCCEEDED(child->QueryInterface(IID_PPV_ARGS(&child_platform_node))))
return UIA_E_INVALIDOPERATION;
if (!owner()->IsDescendant(child_platform_node.Get()))
return E_INVALIDARG;
*range = GetRangeFromChild(owner(), child_platform_node.Get());
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::RangeFromPoint(
UiaPoint uia_point,
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*range = nullptr;
gfx::Point point(uia_point.x, uia_point.y);
// Retrieve the closest accessibility node. No coordinate unit conversion is
// needed, hit testing input is also in screen coordinates.
AXPlatformNodeWin* nearest_node =
static_cast<AXPlatformNodeWin*>(owner()->NearestLeafToPoint(point));
BASE_DCHECK(nearest_node);
BASE_DCHECK(nearest_node->IsLeaf());
AXNodePosition::AXPositionInstance start, end;
start = nearest_node->GetDelegate()->CreateTextPositionAt(
nearest_node->NearestTextIndexToPoint(point));
BASE_DCHECK(!start->IsNullPosition());
end = start->Clone();
*range = AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::get_DocumentRange(
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
// Get range from child, where child is the current node. In other words,
// getting the text range of the current owner AxPlatformNodeWin node.
*range = GetRangeFromChild(owner(), owner());
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::get_SupportedTextSelection(
enum SupportedTextSelection* text_selection) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*text_selection = SupportedTextSelection_Single;
return S_OK;
}
//
// ITextEditProvider methods.
//
HRESULT AXPlatformNodeTextProviderWin::GetActiveComposition(
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*range = nullptr;
return GetTextRangeProviderFromActiveComposition(range);
}
HRESULT AXPlatformNodeTextProviderWin::GetConversionTarget(
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*range = nullptr;
return GetTextRangeProviderFromActiveComposition(range);
}
ITextRangeProvider* AXPlatformNodeTextProviderWin::GetRangeFromChild(
ui::AXPlatformNodeWin* ancestor,
ui::AXPlatformNodeWin* descendant) {
BASE_DCHECK(ancestor);
BASE_DCHECK(descendant);
BASE_DCHECK(descendant->GetDelegate());
BASE_DCHECK(ancestor->IsDescendant(descendant));
// Start and end should be leaf text positions that span the beginning and end
// of text content within a node. The start position should be the directly
// first child and the end position should be the deepest last child node.
AXNodePosition::AXPositionInstance start =
descendant->GetDelegate()->CreateTextPositionAt(0)->AsLeafTextPosition();
AXNodePosition::AXPositionInstance end;
if (descendant->GetChildCount() == 0) {
end = descendant->GetDelegate()
->CreateTextPositionAt(0)
->CreatePositionAtEndOfAnchor()
->AsLeafTextPosition();
} else {
AXPlatformNodeBase* deepest_last_child = descendant->GetLastChild();
while (deepest_last_child && deepest_last_child->GetChildCount() > 0)
deepest_last_child = deepest_last_child->GetLastChild();
end = deepest_last_child->GetDelegate()
->CreateTextPositionAt(0)
->CreatePositionAtEndOfAnchor()
->AsLeafTextPosition();
}
return AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
}
ITextRangeProvider* AXPlatformNodeTextProviderWin::CreateDegenerateRangeAtStart(
ui::AXPlatformNodeWin* node) {
BASE_DCHECK(node);
BASE_DCHECK(node->GetDelegate());
// Create a degenerate range positioned at the node's start.
AXNodePosition::AXPositionInstance start, end;
start = node->GetDelegate()->CreateTextPositionAt(0)->AsLeafTextPosition();
end = start->Clone();
return AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
}
ui::AXPlatformNodeWin* AXPlatformNodeTextProviderWin::owner() const {
return owner_.Get();
}
HRESULT
AXPlatformNodeTextProviderWin::GetTextRangeProviderFromActiveComposition(
ITextRangeProvider** range) {
*range = nullptr;
// We fetch the start and end offset of an active composition only if
// this object has focus and TSF is in composition mode.
// The offsets here refer to the character positions in a plain text
// view of the DOM tree. Ex: if the active composition in an element
// has "abc" then the range will be (0,3) in both TSF and accessibility
if ((AXPlatformNode::FromNativeViewAccessible(
owner()->GetDelegate()->GetFocus()) ==
static_cast<AXPlatformNode*>(owner())) &&
owner()->HasActiveComposition()) {
gfx::Range active_composition_offset =
owner()->GetActiveCompositionOffsets();
AXNodePosition::AXPositionInstance start =
owner()->GetDelegate()->CreateTextPositionAt(
/*offset*/ active_composition_offset.start());
AXNodePosition::AXPositionInstance end =
owner()->GetDelegate()->CreateTextPositionAt(
/*offset*/ active_composition_offset.end());
*range = AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
}
return S_OK;
}
} // namespace ui
| engine/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win.cc",
"repo_id": "engine",
"token_count": 4328
} | 551 |
// 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_UNIQUE_ID_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_UNIQUE_ID_H_
#include <cstdint>
#include "ax/ax_export.h"
#include "base/macros.h"
namespace ui {
// AXUniqueID provides IDs for accessibility objects that are guaranteed to be
// unique for the entire Chrome instance. Instantiating the class is all that
// is required to generate the ID, and the ID is freed when the AXUniqueID is
// destroyed.
//
// The unique id that's guaranteed to be a positive number. Because some
// platforms want to negate it, we ensure the range is below the signed int max.
//
// These ids must not be conflated with the int id, that comes with web node
// data, which are only unique within their source frame.
class AX_EXPORT AXUniqueId {
public:
AXUniqueId();
virtual ~AXUniqueId();
int32_t Get() const { return id_; }
operator int32_t() const { return id_; }
bool operator==(const AXUniqueId& other) const;
bool operator!=(const AXUniqueId& other) const;
protected:
// Passing the max id is necessary for testing.
explicit AXUniqueId(const int32_t max_id);
private:
int32_t GetNextAXUniqueId(const int32_t max_id);
bool IsAssigned(int32_t) const;
int32_t id_;
BASE_DISALLOW_COPY_AND_ASSIGN(AXUniqueId);
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_UNIQUE_ID_H_
| engine/third_party/accessibility/ax/platform/ax_unique_id.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_unique_id.h",
"repo_id": "engine",
"token_count": 485
} | 552 |
// 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.
#ifndef BASE_BASE_EXPORT_H_
#define BASE_BASE_EXPORT_H_
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(BASE_IMPLEMENTATION)
#define BASE_EXPORT __declspec(dllexport)
#else
#define BASE_EXPORT __declspec(dllimport)
#endif // defined(BASE_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(BASE_IMPLEMENTATION)
#define BASE_EXPORT __attribute__((visibility("default")))
#else
#define BASE_EXPORT
#endif // defined(BASE_IMPLEMENTATION)
#endif
#else // defined(COMPONENT_BUILD)
#define BASE_EXPORT
#endif
#endif // BASE_BASE_EXPORT_H_
| engine/third_party/accessibility/base/base_export.h/0 | {
"file_path": "engine/third_party/accessibility/base/base_export.h",
"repo_id": "engine",
"token_count": 267
} | 553 |
// 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_RANGES_H_
#define BASE_NUMERICS_RANGES_H_
#include <algorithm>
#include <cmath>
namespace base {
// To be replaced with std::clamp() from C++17, someday.
template <class T>
constexpr const T& ClampToRange(const T& value, const T& min, const T& max) {
return std::min(std::max(value, min), max);
}
template <typename T>
constexpr bool IsApproximatelyEqual(T lhs, T rhs, T tolerance) {
static_assert(std::is_arithmetic<T>::value, "Argument must be arithmetic");
return std::abs(rhs - lhs) <= tolerance;
}
} // namespace base
#endif // BASE_NUMERICS_RANGES_H_
| engine/third_party/accessibility/base/numerics/ranges.h/0 | {
"file_path": "engine/third_party/accessibility/base/numerics/ranges.h",
"repo_id": "engine",
"token_count": 265
} | 554 |
// 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 BASE_WIN_ATL_H_
#define BASE_WIN_ATL_H_
// atlwin.h relies on std::void_t, but libc++ doesn't define it unless
// _LIBCPP_STD_VER > 14. Workaround this by manually defining it.
#include <type_traits>
#if defined(_LIBCPP_STD_VER) && _LIBCPP_STD_VER <= 14
namespace std {
template <class...>
using void_t = void;
}
#endif
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <atlhost.h>
#include <atlsecurity.h>
#include <atlwin.h>
#endif // BASE_WIN_ATL_H_
| engine/third_party/accessibility/base/win/atl.h/0 | {
"file_path": "engine/third_party/accessibility/base/win/atl.h",
"repo_id": "engine",
"token_count": 242
} | 555 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_WIN_SCOPED_VARIANT_H_
#define BASE_WIN_SCOPED_VARIANT_H_
#include <windows.h>
#include <oleauto.h>
#include <cstdint>
#include "base/base_export.h"
#include "base/macros.h"
namespace base {
namespace win {
// Scoped VARIANT class for automatically freeing a COM VARIANT at the
// end of a scope. Additionally provides a few functions to make the
// encapsulated VARIANT easier to use.
// Instead of inheriting from VARIANT, we take the containment approach
// in order to have more control over the usage of the variant and guard
// against memory leaks.
class BASE_EXPORT ScopedVariant {
public:
// Declaration of a global variant variable that's always VT_EMPTY
static const VARIANT kEmptyVariant;
// Default constructor.
ScopedVariant() {
// This is equivalent to what VariantInit does, but less code.
var_.vt = VT_EMPTY;
}
// Constructor to create a new VT_BSTR VARIANT.
// NOTE: Do not pass a BSTR to this constructor expecting ownership to
// be transferred
explicit ScopedVariant(const wchar_t* str);
// Creates a new VT_BSTR variant of a specified length.
ScopedVariant(const wchar_t* str, UINT length);
// Creates a new integral type variant and assigns the value to
// VARIANT.lVal (32 bit sized field).
explicit ScopedVariant(long value, VARTYPE vt = VT_I4);
// Creates a new integral type variant for the int type and assigns the value
// to VARIANT.lVal (32 bit sized field).
explicit ScopedVariant(int value);
// Creates a new boolean (VT_BOOL) variant and assigns the value to
// VARIANT.boolVal.
explicit ScopedVariant(bool value);
// Creates a new double-precision type variant. |vt| must be either VT_R8
// or VT_DATE.
explicit ScopedVariant(double value, VARTYPE vt = VT_R8);
// VT_DISPATCH
explicit ScopedVariant(IDispatch* dispatch);
// VT_UNKNOWN
explicit ScopedVariant(IUnknown* unknown);
// SAFEARRAY
explicit ScopedVariant(SAFEARRAY* safearray);
// Copies the variant.
explicit ScopedVariant(const VARIANT& var);
// Moves the wrapped variant into another ScopedVariant.
ScopedVariant(ScopedVariant&& var);
~ScopedVariant();
inline VARTYPE type() const { return var_.vt; }
// Give ScopedVariant ownership over an already allocated VARIANT.
void Reset(const VARIANT& var = kEmptyVariant);
// Releases ownership of the VARIANT to the caller.
VARIANT Release();
// Swap two ScopedVariant's.
void Swap(ScopedVariant& var);
// Returns a copy of the variant.
VARIANT Copy() const;
// The return value is 0 if the variants are equal, 1 if this object is
// greater than |other|, -1 if it is smaller.
// Comparison with an array VARIANT is not supported.
// 1. VT_NULL and VT_EMPTY is always considered less-than any other VARTYPE.
// 2. If both VARIANTS have either VT_UNKNOWN or VT_DISPATCH even if the
// VARTYPEs do not match, the address of its IID_IUnknown is compared to
// guarantee a logical ordering even though it is not a meaningful order.
// e.g. (a.Compare(b) != b.Compare(a)) unless (a == b).
// 3. If the VARTYPEs do not match, then the value of the VARTYPE is compared.
// 4. Comparing VT_BSTR values is a lexicographical comparison of the contents
// of the BSTR, taking into account |ignore_case|.
// 5. Otherwise returns the lexicographical comparison of the values held by
// the two VARIANTS that share the same VARTYPE.
int Compare(const VARIANT& other, bool ignore_case = false) const;
// Retrieves the pointer address.
// Used to receive a VARIANT as an out argument (and take ownership).
// The function DCHECKs on the current value being empty/null.
// Usage: GetVariant(var.receive());
VARIANT* Receive();
void Set(const wchar_t* str);
// Setters for simple types.
void Set(int8_t i8);
void Set(uint8_t ui8);
void Set(int16_t i16);
void Set(uint16_t ui16);
void Set(int32_t i32);
void Set(uint32_t ui32);
void Set(int64_t i64);
void Set(uint64_t ui64);
void Set(float r32);
void Set(double r64);
void Set(bool b);
// Creates a copy of |var| and assigns as this instance's value.
// Note that this is different from the Reset() method that's used to
// free the current value and assume ownership.
void Set(const VARIANT& var);
// COM object setters
void Set(IDispatch* disp);
void Set(IUnknown* unk);
// SAFEARRAY support
void Set(SAFEARRAY* array);
// Special setter for DATE since DATE is a double and we already have
// a setter for double.
void SetDate(DATE date);
// Allows const access to the contained variant without DCHECKs etc.
// This support is necessary for the V_XYZ (e.g. V_BSTR) set of macros to
// work properly but still doesn't allow modifications since we want control
// over that.
const VARIANT* ptr() const { return &var_; }
// Moves the ScopedVariant to another instance.
ScopedVariant& operator=(ScopedVariant&& var);
// Like other scoped classes (e.g. scoped_refptr, ScopedBstr,
// Microsoft::WRL::ComPtr) we support the assignment operator for the type we
// wrap.
ScopedVariant& operator=(const VARIANT& var);
// A hack to pass a pointer to the variant where the accepting
// function treats the variant as an input-only, read-only value
// but the function prototype requires a non const variant pointer.
// There's no DCHECK or anything here. Callers must know what they're doing.
VARIANT* AsInput() const {
// The nature of this function is const, so we declare
// it as such and cast away the constness here.
return const_cast<VARIANT*>(&var_);
}
// Allows the ScopedVariant instance to be passed to functions either by value
// or by const reference.
operator const VARIANT&() const { return var_; }
// Used as a debug check to see if we're leaking anything.
static bool IsLeakableVarType(VARTYPE vt);
protected:
VARIANT var_;
private:
// Comparison operators for ScopedVariant are not supported at this point.
// Use the Compare method instead.
bool operator==(const ScopedVariant& var) const;
bool operator!=(const ScopedVariant& var) const;
BASE_DISALLOW_COPY_AND_ASSIGN(ScopedVariant);
};
} // namespace win
} // namespace base
#endif // BASE_WIN_SCOPED_VARIANT_H_
| engine/third_party/accessibility/base/win/scoped_variant.h/0 | {
"file_path": "engine/third_party/accessibility/base/win/scoped_variant.h",
"repo_id": "engine",
"token_count": 2021
} | 556 |
// 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.
#ifndef UI_GFX_GEOMETRY_POINT_CONVERSIONS_H_
#define UI_GFX_GEOMETRY_POINT_CONVERSIONS_H_
#include "point.h"
#include "point_f.h"
namespace gfx {
// Returns a Point with each component from the input PointF floored.
GFX_EXPORT Point ToFlooredPoint(const PointF& point);
// Returns a Point with each component from the input PointF ceiled.
GFX_EXPORT Point ToCeiledPoint(const PointF& point);
// Returns a Point with each component from the input PointF rounded.
GFX_EXPORT Point ToRoundedPoint(const PointF& point);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_POINT_CONVERSIONS_H_
| engine/third_party/accessibility/gfx/geometry/point_conversions.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/point_conversions.h",
"repo_id": "engine",
"token_count": 255
} | 557 |
// 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.
#ifndef UI_GFX_GEOMETRY_SIZE_F_H_
#define UI_GFX_GEOMETRY_SIZE_F_H_
#include <iosfwd>
#include <string>
#include "base/compiler_specific.h"
#include "gfx/gfx_export.h"
#include "size.h"
namespace gfx {
// A floating version of gfx::Size.
class GFX_EXPORT SizeF {
public:
constexpr SizeF() : width_(0.f), height_(0.f) {}
constexpr SizeF(float width, float height)
: width_(clamp(width)), height_(clamp(height)) {}
constexpr explicit SizeF(const Size& size)
: SizeF(static_cast<float>(size.width()),
static_cast<float>(size.height())) {}
constexpr float width() const { return width_; }
constexpr float height() const { return height_; }
void set_width(float width) { width_ = clamp(width); }
void set_height(float height) { height_ = clamp(height); }
float GetArea() const;
void SetSize(float width, float height) {
set_width(width);
set_height(height);
}
void Enlarge(float grow_width, float grow_height);
void SetToMin(const SizeF& other);
void SetToMax(const SizeF& other);
bool IsEmpty() const { return !width() || !height(); }
void Scale(float scale) { Scale(scale, scale); }
void Scale(float x_scale, float y_scale) {
SetSize(width() * x_scale, height() * y_scale);
}
std::string ToString() const;
private:
static constexpr float kTrivial = 8.f * std::numeric_limits<float>::epsilon();
static constexpr float clamp(float f) { return f > kTrivial ? f : 0.f; }
float width_;
float height_;
};
inline bool operator==(const SizeF& lhs, const SizeF& rhs) {
return lhs.width() == rhs.width() && lhs.height() == rhs.height();
}
inline bool operator!=(const SizeF& lhs, const SizeF& rhs) {
return !(lhs == rhs);
}
GFX_EXPORT SizeF ScaleSize(const SizeF& p, float x_scale, float y_scale);
inline SizeF ScaleSize(const SizeF& p, float scale) {
return ScaleSize(p, scale, scale);
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const SizeF& size, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_SIZE_F_H_
| engine/third_party/accessibility/gfx/geometry/size_f.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/size_f.h",
"repo_id": "engine",
"token_count": 848
} | 558 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <sstream>
#include "gtest/gtest.h"
#include "range.h"
namespace {
template <typename T>
class RangeTest : public testing::Test {};
typedef testing::Types<gfx::Range> RangeTypes;
TYPED_TEST_SUITE(RangeTest, RangeTypes);
template <typename T>
void TestContainsAndIntersects(const T& r1, const T& r2, const T& r3) {
EXPECT_TRUE(r1.Intersects(r1));
EXPECT_TRUE(r1.Contains(r1));
EXPECT_EQ(T(10, 12), r1.Intersect(r1));
EXPECT_FALSE(r1.Intersects(r2));
EXPECT_FALSE(r1.Contains(r2));
EXPECT_TRUE(r1.Intersect(r2).is_empty());
EXPECT_FALSE(r2.Intersects(r1));
EXPECT_FALSE(r2.Contains(r1));
EXPECT_TRUE(r2.Intersect(r1).is_empty());
EXPECT_TRUE(r1.Intersects(r3));
EXPECT_TRUE(r3.Intersects(r1));
EXPECT_TRUE(r3.Contains(r1));
EXPECT_FALSE(r1.Contains(r3));
EXPECT_EQ(T(10, 12), r1.Intersect(r3));
EXPECT_EQ(T(10, 12), r3.Intersect(r1));
EXPECT_TRUE(r2.Intersects(r3));
EXPECT_TRUE(r3.Intersects(r2));
EXPECT_FALSE(r3.Contains(r2));
EXPECT_FALSE(r2.Contains(r3));
EXPECT_EQ(T(5, 8), r2.Intersect(r3));
EXPECT_EQ(T(5, 8), r3.Intersect(r2));
}
} // namespace
TYPED_TEST(RangeTest, EmptyInit) {
TypeParam r;
EXPECT_EQ(0U, r.start());
EXPECT_EQ(0U, r.end());
EXPECT_EQ(0U, r.length());
EXPECT_FALSE(r.is_reversed());
EXPECT_TRUE(r.is_empty());
EXPECT_TRUE(r.IsValid());
EXPECT_EQ(0U, r.GetMin());
EXPECT_EQ(0U, r.GetMax());
}
TYPED_TEST(RangeTest, StartEndInit) {
TypeParam r(10, 15);
EXPECT_EQ(10U, r.start());
EXPECT_EQ(15U, r.end());
EXPECT_EQ(5U, r.length());
EXPECT_FALSE(r.is_reversed());
EXPECT_FALSE(r.is_empty());
EXPECT_TRUE(r.IsValid());
EXPECT_EQ(10U, r.GetMin());
EXPECT_EQ(15U, r.GetMax());
}
TYPED_TEST(RangeTest, StartEndReversedInit) {
TypeParam r(10, 5);
EXPECT_EQ(10U, r.start());
EXPECT_EQ(5U, r.end());
EXPECT_EQ(5U, r.length());
EXPECT_TRUE(r.is_reversed());
EXPECT_FALSE(r.is_empty());
EXPECT_TRUE(r.IsValid());
EXPECT_EQ(5U, r.GetMin());
EXPECT_EQ(10U, r.GetMax());
}
TYPED_TEST(RangeTest, PositionInit) {
TypeParam r(12);
EXPECT_EQ(12U, r.start());
EXPECT_EQ(12U, r.end());
EXPECT_EQ(0U, r.length());
EXPECT_FALSE(r.is_reversed());
EXPECT_TRUE(r.is_empty());
EXPECT_TRUE(r.IsValid());
EXPECT_EQ(12U, r.GetMin());
EXPECT_EQ(12U, r.GetMax());
}
TYPED_TEST(RangeTest, InvalidRange) {
TypeParam r(TypeParam::InvalidRange());
EXPECT_EQ(0U, r.length());
EXPECT_EQ(r.start(), r.end());
EXPECT_EQ(r.GetMax(), r.GetMin());
EXPECT_FALSE(r.is_reversed());
EXPECT_TRUE(r.is_empty());
EXPECT_FALSE(r.IsValid());
EXPECT_EQ(r, TypeParam::InvalidRange());
EXPECT_TRUE(r.EqualsIgnoringDirection(TypeParam::InvalidRange()));
}
TYPED_TEST(RangeTest, Equality) {
TypeParam r1(10, 4);
TypeParam r2(10, 4);
TypeParam r3(10, 2);
EXPECT_EQ(r1, r2);
EXPECT_NE(r1, r3);
EXPECT_NE(r2, r3);
TypeParam r4(11, 4);
EXPECT_NE(r1, r4);
EXPECT_NE(r2, r4);
EXPECT_NE(r3, r4);
TypeParam r5(12, 5);
EXPECT_NE(r1, r5);
EXPECT_NE(r2, r5);
EXPECT_NE(r3, r5);
}
TYPED_TEST(RangeTest, EqualsIgnoringDirection) {
TypeParam r1(10, 5);
TypeParam r2(5, 10);
EXPECT_TRUE(r1.EqualsIgnoringDirection(r2));
}
TYPED_TEST(RangeTest, SetStart) {
TypeParam r(10, 20);
EXPECT_EQ(10U, r.start());
EXPECT_EQ(10U, r.length());
r.set_start(42);
EXPECT_EQ(42U, r.start());
EXPECT_EQ(20U, r.end());
EXPECT_EQ(22U, r.length());
EXPECT_TRUE(r.is_reversed());
}
TYPED_TEST(RangeTest, SetEnd) {
TypeParam r(10, 13);
EXPECT_EQ(10U, r.start());
EXPECT_EQ(3U, r.length());
r.set_end(20);
EXPECT_EQ(10U, r.start());
EXPECT_EQ(20U, r.end());
EXPECT_EQ(10U, r.length());
}
TYPED_TEST(RangeTest, SetStartAndEnd) {
TypeParam r;
r.set_end(5);
r.set_start(1);
EXPECT_EQ(1U, r.start());
EXPECT_EQ(5U, r.end());
EXPECT_EQ(4U, r.length());
EXPECT_EQ(1U, r.GetMin());
EXPECT_EQ(5U, r.GetMax());
}
TYPED_TEST(RangeTest, ReversedRange) {
TypeParam r(10, 5);
EXPECT_EQ(10U, r.start());
EXPECT_EQ(5U, r.end());
EXPECT_EQ(5U, r.length());
EXPECT_TRUE(r.is_reversed());
EXPECT_TRUE(r.IsValid());
EXPECT_EQ(5U, r.GetMin());
EXPECT_EQ(10U, r.GetMax());
}
TYPED_TEST(RangeTest, SetReversedRange) {
TypeParam r(10, 20);
r.set_start(25);
EXPECT_EQ(25U, r.start());
EXPECT_EQ(20U, r.end());
EXPECT_EQ(5U, r.length());
EXPECT_TRUE(r.is_reversed());
EXPECT_TRUE(r.IsValid());
r.set_end(21);
EXPECT_EQ(25U, r.start());
EXPECT_EQ(21U, r.end());
EXPECT_EQ(4U, r.length());
EXPECT_TRUE(r.IsValid());
EXPECT_EQ(21U, r.GetMin());
EXPECT_EQ(25U, r.GetMax());
}
TYPED_TEST(RangeTest, ContainAndIntersect) {
{
SCOPED_TRACE("contain and intersect");
TypeParam r1(10, 12);
TypeParam r2(1, 8);
TypeParam r3(5, 12);
TestContainsAndIntersects(r1, r2, r3);
}
{
SCOPED_TRACE("contain and intersect: reversed");
TypeParam r1(12, 10);
TypeParam r2(8, 1);
TypeParam r3(12, 5);
TestContainsAndIntersects(r1, r2, r3);
}
// Invalid rect tests
TypeParam r1(10, 12);
TypeParam r2(8, 1);
TypeParam invalid = r1.Intersect(r2);
EXPECT_FALSE(invalid.IsValid());
EXPECT_FALSE(invalid.Contains(invalid));
EXPECT_FALSE(invalid.Contains(r1));
EXPECT_FALSE(invalid.Intersects(invalid));
EXPECT_FALSE(invalid.Intersects(r1));
EXPECT_FALSE(r1.Contains(invalid));
EXPECT_FALSE(r1.Intersects(invalid));
}
TEST(RangeTest, RangeOperations) {
constexpr gfx::Range invalid_range = gfx::Range::InvalidRange();
constexpr gfx::Range ranges[] = {{0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1},
{1, 2}, {2, 0}, {2, 1}, {2, 2}};
// Ensures valid behavior over same range.
for (const auto& range : ranges) {
SCOPED_TRACE(range.ToString());
// A range should contain itself.
EXPECT_TRUE(range.Contains(range));
// A ranges should intersect with itself.
EXPECT_TRUE(range.Intersects(range));
}
// Ensures valid behavior with an invalid range.
for (const auto& range : ranges) {
SCOPED_TRACE(range.ToString());
EXPECT_FALSE(invalid_range.Contains(range));
EXPECT_FALSE(invalid_range.Intersects(range));
EXPECT_FALSE(range.Contains(invalid_range));
EXPECT_FALSE(range.Intersects(invalid_range));
}
EXPECT_FALSE(invalid_range.Contains(invalid_range));
EXPECT_FALSE(invalid_range.Intersects(invalid_range));
// Ensures consistent operations between Contains(...) and Intersects(...).
for (const auto& range1 : ranges) {
for (const auto& range2 : ranges) {
SCOPED_TRACE(testing::Message()
<< "range1=" << range1 << " range2=" << range2);
if (range1.Contains(range2)) {
EXPECT_TRUE(range1.Intersects(range2));
EXPECT_EQ(range2.Contains(range1),
range1.EqualsIgnoringDirection(range2));
}
EXPECT_EQ(range2.Intersects(range1), range1.Intersects(range2));
EXPECT_EQ(range1.Intersect(range2) != invalid_range,
range1.Intersects(range2));
}
}
// Ranges should behave the same way no matter the direction.
for (const auto& range1 : ranges) {
for (const auto& range2 : ranges) {
SCOPED_TRACE(testing::Message()
<< "range1=" << range1 << " range2=" << range2);
EXPECT_EQ(range1.Contains(range2),
range1.Contains(gfx::Range(range2.GetMax(), range2.GetMin())));
EXPECT_EQ(
range1.Intersects(range2),
range1.Intersects(gfx::Range(range2.GetMax(), range2.GetMin())));
}
}
}
TEST(RangeTest, ContainsAndIntersects) {
constexpr gfx::Range r1(0, 0);
constexpr gfx::Range r2(0, 1);
constexpr gfx::Range r3(1, 2);
constexpr gfx::Range r4(1, 0);
constexpr gfx::Range r5(2, 1);
constexpr gfx::Range r6(0, 2);
constexpr gfx::Range r7(2, 0);
constexpr gfx::Range r8(1, 1);
// Ensures Contains(...) handle the open range.
EXPECT_TRUE(r2.Contains(r1));
EXPECT_TRUE(r4.Contains(r1));
EXPECT_TRUE(r3.Contains(r5));
EXPECT_TRUE(r5.Contains(r3));
// Ensures larger ranges contains smaller ranges.
EXPECT_TRUE(r6.Contains(r1));
EXPECT_TRUE(r6.Contains(r2));
EXPECT_TRUE(r6.Contains(r3));
EXPECT_TRUE(r6.Contains(r4));
EXPECT_TRUE(r6.Contains(r5));
EXPECT_TRUE(r7.Contains(r1));
EXPECT_TRUE(r7.Contains(r2));
EXPECT_TRUE(r7.Contains(r3));
EXPECT_TRUE(r7.Contains(r4));
EXPECT_TRUE(r7.Contains(r5));
// Ensures Intersects(...) handle the open range.
EXPECT_TRUE(r2.Intersects(r1));
EXPECT_TRUE(r4.Intersects(r1));
// Ensures larger ranges intersects smaller ranges.
EXPECT_TRUE(r6.Intersects(r1));
EXPECT_TRUE(r6.Intersects(r2));
EXPECT_TRUE(r6.Intersects(r3));
EXPECT_TRUE(r6.Intersects(r4));
EXPECT_TRUE(r6.Intersects(r5));
EXPECT_TRUE(r7.Intersects(r1));
EXPECT_TRUE(r7.Intersects(r2));
EXPECT_TRUE(r7.Intersects(r3));
EXPECT_TRUE(r7.Intersects(r4));
EXPECT_TRUE(r7.Intersects(r5));
// Ensures adjacent ranges don't overlap.
EXPECT_FALSE(r2.Intersects(r3));
EXPECT_FALSE(r5.Intersects(r4));
// Ensures empty ranges are handled correctly.
EXPECT_FALSE(r1.Contains(r8));
EXPECT_FALSE(r2.Contains(r8));
EXPECT_TRUE(r3.Contains(r8));
EXPECT_TRUE(r8.Contains(r8));
EXPECT_FALSE(r1.Intersects(r8));
EXPECT_FALSE(r2.Intersects(r8));
EXPECT_TRUE(r3.Intersects(r8));
EXPECT_TRUE(r8.Intersects(r8));
}
TEST(RangeTest, Intersect) {
EXPECT_EQ(gfx::Range(0, 1).Intersect({0, 1}), gfx::Range(0, 1));
EXPECT_EQ(gfx::Range(0, 1).Intersect({0, 0}), gfx::Range(0, 0));
EXPECT_EQ(gfx::Range(0, 0).Intersect({1, 0}), gfx::Range(0, 0));
EXPECT_EQ(gfx::Range(0, 4).Intersect({2, 3}), gfx::Range(2, 3));
EXPECT_EQ(gfx::Range(0, 4).Intersect({2, 7}), gfx::Range(2, 4));
EXPECT_EQ(gfx::Range(0, 4).Intersect({3, 4}), gfx::Range(3, 4));
EXPECT_EQ(gfx::Range(0, 1).Intersect({1, 1}), gfx::Range::InvalidRange());
EXPECT_EQ(gfx::Range(1, 1).Intersect({1, 0}), gfx::Range::InvalidRange());
EXPECT_EQ(gfx::Range(0, 1).Intersect({1, 2}), gfx::Range::InvalidRange());
EXPECT_EQ(gfx::Range(0, 1).Intersect({2, 1}), gfx::Range::InvalidRange());
EXPECT_EQ(gfx::Range(2, 1).Intersect({1, 0}), gfx::Range::InvalidRange());
}
TEST(RangeTest, IsBoundedBy) {
constexpr gfx::Range r1(0, 0);
constexpr gfx::Range r2(0, 1);
EXPECT_TRUE(r1.IsBoundedBy(r1));
EXPECT_FALSE(r2.IsBoundedBy(r1));
constexpr gfx::Range r3(0, 2);
constexpr gfx::Range r4(2, 2);
EXPECT_TRUE(r4.IsBoundedBy(r3));
EXPECT_FALSE(r3.IsBoundedBy(r4));
}
TEST(RangeTest, ToString) {
gfx::Range range(4, 7);
EXPECT_EQ("{4,7}", range.ToString());
range = gfx::Range::InvalidRange();
std::ostringstream expected;
expected << "{" << range.start() << "," << range.end() << "}";
EXPECT_EQ(expected.str(), range.ToString());
}
| engine/third_party/accessibility/gfx/range/range_unittest.cc/0 | {
"file_path": "engine/third_party/accessibility/gfx/range/range_unittest.cc",
"repo_id": "engine",
"token_count": 5057
} | 559 |
// Directional glow GLSL fragment shader.
// Based on the "Let it Glow!" pen by "Selman Ay"
// (https://codepen.io/selmanays/pen/yLVmEqY)
precision highp float;
// Float uniforms
uniform float width; // Width of the canvas
uniform float height; // Height of the canvas
uniform float sourceX; // X position of the light source
uniform float
scrollFraction; // Scroll fraction of the page in relation to the canvas
uniform float density; // Density of the "smoke" effect
uniform float lightStrength; // Strength of the light
uniform float weight; // Weight of the "smoke" effect
// Sampler uniforms
uniform sampler2D tInput; // Input texture (the application canvas)
uniform sampler2D tNoise; // Some texture
out vec4 fragColor;
float sourceY = scrollFraction;
vec2 resolution = vec2(width, height);
vec2 lightSource = vec2(sourceX, sourceY);
const int samples = 20; // The number of "copies" of the canvas made to emulate
// the "smoke" effect
const float decay = 0.88; // Decay of the light in each sample
const float exposure = .9; // The exposure to the light
float random2d(vec2 uv) {
uv /= 256.;
vec4 tex = texture(tNoise, uv);
return mix(tex.r, tex.g, tex.a);
}
float random(vec3 xyz) {
return fract(sin(dot(xyz, vec3(12.9898, 78.233, 151.7182))) * 43758.5453);
}
vec4 sampleTexture(vec2 uv) {
vec4 textColor = texture(tInput, uv);
return textColor;
}
vec4 occlusion(vec2 uv, vec2 lightpos, vec4 objects) {
return (1. - smoothstep(0.0, lightStrength, length(lightpos - uv))) *
(objects);
}
vec4 fragment(vec2 uv, vec2 fragCoord) {
vec3 colour = vec3(0);
vec4 obj = sampleTexture(uv);
vec4 map = occlusion(uv, lightSource, obj);
float random = random(vec3(fragCoord, 1.0));
;
float exposure = exposure + (sin(random) * .5 + 1.) * .05;
vec2 _uv = uv;
vec2 distance = (_uv - lightSource) * (1. / float(samples) * density);
float illumination_decay = 1.;
for (int i = 0; i < samples; i++) {
_uv -= distance;
float movement = random * 20. * float(i + 1);
float dither =
random2d(uv +
mod(vec2(movement * sin(random * .5), -movement), 1000.)) *
2.;
vec4 stepped_map =
occlusion(uv, lightSource, sampleTexture(_uv + distance * dither));
stepped_map *= illumination_decay * weight;
illumination_decay *= decay;
map += stepped_map;
}
float lum = dot(map.rgb, vec3(0.2126, 0.7152, 0.0722));
colour += vec3(map.rgb * exposure);
return vec4(colour, lum);
}
void main() {
vec2 pos = gl_FragCoord.xy;
vec2 uv = pos / vec2(width, height);
fragColor = fragment(uv, pos);
}
| engine/third_party/test_shaders/selman/glow_shader.frag/0 | {
"file_path": "engine/third_party/test_shaders/selman/glow_shader.frag",
"repo_id": "engine",
"token_count": 1007
} | 560 |
// 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_CLASS_LIBRARY_H_
#define LIB_TONIC_DART_CLASS_LIBRARY_H_
#include <memory>
#include <string>
#include <unordered_map>
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/dart_class_provider.h"
namespace tonic {
struct DartWrapperInfo;
class DartClassLibrary {
public:
explicit DartClassLibrary();
~DartClassLibrary();
void add_provider(const std::string& library_name,
std::unique_ptr<DartClassProvider> provider) {
providers_.insert(std::make_pair(library_name, std::move(provider)));
}
Dart_PersistentHandle GetClass(const DartWrapperInfo& info);
Dart_PersistentHandle GetClass(const std::string& library_name,
const std::string& interface_name);
private:
Dart_PersistentHandle GetAndCacheClass(const char* library_name,
const char* interface_name,
Dart_PersistentHandle* cache_slot);
// TODO(abarth): Move this class somewhere more general.
// We should also use a more reasonable hash function, such as described in
// http://www.boost.org/doc/libs/1_35_0/doc/html/boost/hash_combine_id241013.html
struct PairHasher {
template <typename T, typename U>
std::size_t operator()(const std::pair<T, U>& pair) const {
return std::hash<T>()(pair.first) + 37 * std::hash<U>()(pair.second);
}
};
std::unordered_map<std::string, std::unique_ptr<DartClassProvider>>
providers_;
std::unordered_map<const DartWrapperInfo*, Dart_PersistentHandle> info_cache_;
std::unordered_map<std::pair<std::string, std::string>,
Dart_PersistentHandle,
PairHasher>
name_cache_;
TONIC_DISALLOW_COPY_AND_ASSIGN(DartClassLibrary);
};
} // namespace tonic
#endif // LIB_TONIC_DART_CLASS_LIBRARY_H_
| engine/third_party/tonic/dart_class_library.h/0 | {
"file_path": "engine/third_party/tonic/dart_class_library.h",
"repo_id": "engine",
"token_count": 824
} | 561 |
// 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_WEAK_PERSISTENT_VALUE_H_
#define LIB_TONIC_DART_WEAK_PERSISTENT_VALUE_H_
#include <memory>
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/common/macros.h"
namespace tonic {
class DartState;
// DartWeakPersistentValue is a bookkeeping class to help pair calls to
// Dart_NewWeakPersistentHandle with Dart_DeleteWeakPersistentHandle even in
// the case if IsolateGroup shutdown. Consider using this class instead of
// holding a Dart_PersistentHandle directly so that you don't leak the
// Dart_WeakPersistentHandle.
class DartWeakPersistentValue {
public:
DartWeakPersistentValue();
~DartWeakPersistentValue();
Dart_WeakPersistentHandle value() const { return handle_; }
bool is_empty() const { return handle_ == nullptr; }
void Set(DartState* dart_state,
Dart_Handle object,
void* peer,
intptr_t external_allocation_size,
Dart_HandleFinalizer callback);
void Clear();
Dart_Handle Get();
const std::weak_ptr<DartState>& dart_state() const { return dart_state_; }
private:
std::weak_ptr<DartState> dart_state_;
Dart_WeakPersistentHandle handle_;
TONIC_DISALLOW_COPY_AND_ASSIGN(DartWeakPersistentValue);
};
} // namespace tonic
#endif // LIB_TONIC_DART_WEAK_PERSISTENT_VALUE_H_
| engine/third_party/tonic/dart_weak_persistent_value.h/0 | {
"file_path": "engine/third_party/tonic/dart_weak_persistent_value.h",
"repo_id": "engine",
"token_count": 504
} | 562 |
// 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/path.h"
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <list>
#include <memory>
#include "tonic/common/build_config.h"
#include "tonic/filesystem/filesystem/portable_unistd.h"
namespace filesystem {
namespace {
size_t ResolveParentDirectoryTraversal(const std::string& path, size_t put) {
if (put >= 2) {
size_t previous_separator = path.rfind('/', put - 2);
if (previous_separator != std::string::npos)
return previous_separator + 1;
}
if (put == 1 && path[0] == '/') {
return put;
}
return 0;
}
std::string GetCurrentDirectory() {
char buffer[PATH_MAX];
if (getcwd(buffer, sizeof(buffer)) == NULL) {
return {};
}
return std::string(buffer);
}
} // namespace
std::string SimplifyPath(std::string path) {
if (path.empty())
return ".";
size_t put = 0;
size_t get = 0;
size_t traversal_root = 0;
size_t component_start = 0;
if (path[0] == '/') {
put = 1;
get = 1;
component_start = 1;
}
while (get < path.size()) {
char c = path[get];
if (c == '.' && (get == component_start || get == component_start + 1)) {
// We've seen "." or ".." so far in this component. We need to continue
// searching.
++get;
continue;
}
if (c == '/') {
if (get == component_start || get == component_start + 1) {
// We've found a "/" or a "./", which we can elide.
++get;
component_start = get;
continue;
}
if (get == component_start + 2) {
// We've found a "../", which means we need to remove the previous
// component.
if (put == traversal_root) {
path[put++] = '.';
path[put++] = '.';
path[put++] = '/';
traversal_root = put;
} else {
put = ResolveParentDirectoryTraversal(path, put);
}
++get;
component_start = get;
continue;
}
}
size_t next_separator = path.find('/', get);
if (next_separator == std::string::npos) {
// We've reached the last component.
break;
}
size_t next_component_start = next_separator + 1;
++next_separator;
size_t component_size = next_component_start - component_start;
if (put != component_start && component_size > 0) {
path.replace(put, component_size,
path.substr(component_start, component_size));
}
put += component_size;
get = next_component_start;
component_start = next_component_start;
}
size_t last_component_size = path.size() - component_start;
if (last_component_size == 1 && path[component_start] == '.') {
// The last component is ".", which we can elide.
} else if (last_component_size == 2 && path[component_start] == '.' &&
path[component_start + 1] == '.') {
// The last component is "..", which means we need to remove the previous
// component.
if (put == traversal_root) {
path[put++] = '.';
path[put++] = '.';
path[put++] = '/';
traversal_root = put;
} else {
put = ResolveParentDirectoryTraversal(path, put);
}
} else {
// Otherwise, we need to copy over the last component.
if (put != component_start && last_component_size > 0) {
path.replace(put, last_component_size,
path.substr(component_start, last_component_size));
}
put += last_component_size;
}
if (put >= 2 && path[put - 1] == '/')
--put; // Trim trailing /
else if (put == 0)
return "."; // Use . for otherwise empty paths to treat them as relative.
path.resize(put);
return path;
}
std::string AbsolutePath(const std::string& path) {
if (!path.empty()) {
if (path[0] == '/') {
// Path is already absolute.
return path;
}
return GetCurrentDirectory() + "/" + path;
} else {
// Path is empty.
return GetCurrentDirectory();
}
}
std::string GetDirectoryName(const std::string& path) {
size_t separator = path.rfind('/');
if (separator == 0u)
return "/";
if (separator == std::string::npos)
return std::string();
return path.substr(0, separator);
}
std::string GetBaseName(const std::string& path) {
size_t separator = path.rfind('/');
if (separator == std::string::npos)
return path;
return path.substr(separator + 1);
}
std::string GetAbsoluteFilePath(const std::string& path) {
#if defined(OS_FUCHSIA)
// realpath() isn't supported by Fuchsia. See MG-425.
return SimplifyPath(AbsolutePath(path));
#else
char buffer[PATH_MAX];
if (realpath(path.c_str(), buffer) == nullptr)
return std::string();
return buffer;
#endif // defined(OS_FUCHSIA)
}
} // namespace filesystem
| engine/third_party/tonic/filesystem/filesystem/path_posix.cc/0 | {
"file_path": "engine/third_party/tonic/filesystem/filesystem/path_posix.cc",
"repo_id": "engine",
"token_count": 1997
} | 563 |
// 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_SCOPES_DART_API_SCOPE_H_
#define LIB_TONIC_SCOPES_DART_API_SCOPE_H_
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/common/macros.h"
namespace tonic {
class DartApiScope {
public:
DartApiScope() { Dart_EnterScope(); }
~DartApiScope() {
if (Dart_CurrentIsolate())
Dart_ExitScope();
}
private:
TONIC_DISALLOW_COPY_AND_ASSIGN(DartApiScope);
};
} // namespace tonic
#endif // LIB_TONIC_SCOPES_DART_API_SCOPE_H_
| engine/third_party/tonic/scopes/dart_api_scope.h/0 | {
"file_path": "engine/third_party/tonic/scopes/dart_api_scope.h",
"repo_id": "engine",
"token_count": 257
} | 564 |
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "font_collection.h"
#include <algorithm>
#include <list>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "txt/platform.h"
#include "txt/text_style.h"
namespace txt {
FontCollection::FontCollection() : enable_font_fallback_(true) {}
FontCollection::~FontCollection() {
if (skt_collection_) {
skt_collection_->clearCaches();
}
}
size_t FontCollection::GetFontManagersCount() const {
return GetFontManagerOrder().size();
}
void FontCollection::SetupDefaultFontManager(
uint32_t font_initialization_data) {
default_font_manager_ = GetDefaultFontManager(font_initialization_data);
skt_collection_.reset();
}
void FontCollection::SetDefaultFontManager(sk_sp<SkFontMgr> font_manager) {
default_font_manager_ = font_manager;
skt_collection_.reset();
}
void FontCollection::SetAssetFontManager(sk_sp<SkFontMgr> font_manager) {
asset_font_manager_ = font_manager;
skt_collection_.reset();
}
void FontCollection::SetDynamicFontManager(sk_sp<SkFontMgr> font_manager) {
dynamic_font_manager_ = font_manager;
skt_collection_.reset();
}
void FontCollection::SetTestFontManager(sk_sp<SkFontMgr> font_manager) {
test_font_manager_ = font_manager;
skt_collection_.reset();
}
// Return the available font managers in the order they should be queried.
std::vector<sk_sp<SkFontMgr>> FontCollection::GetFontManagerOrder() const {
std::vector<sk_sp<SkFontMgr>> order;
if (dynamic_font_manager_)
order.push_back(dynamic_font_manager_);
if (asset_font_manager_)
order.push_back(asset_font_manager_);
if (test_font_manager_)
order.push_back(test_font_manager_);
if (default_font_manager_)
order.push_back(default_font_manager_);
return order;
}
void FontCollection::DisableFontFallback() {
enable_font_fallback_ = false;
if (skt_collection_) {
skt_collection_->disableFontFallback();
}
}
void FontCollection::ClearFontFamilyCache() {
if (skt_collection_) {
skt_collection_->clearCaches();
}
}
sk_sp<skia::textlayout::FontCollection>
FontCollection::CreateSktFontCollection() {
if (!skt_collection_) {
skt_collection_ = sk_make_sp<skia::textlayout::FontCollection>();
std::vector<SkString> default_font_families;
for (const std::string& family : GetDefaultFontFamilies()) {
default_font_families.emplace_back(family);
}
skt_collection_->setDefaultFontManager(default_font_manager_,
default_font_families);
skt_collection_->setAssetFontManager(asset_font_manager_);
skt_collection_->setDynamicFontManager(dynamic_font_manager_);
skt_collection_->setTestFontManager(test_font_manager_);
if (!enable_font_fallback_) {
skt_collection_->disableFontFallback();
}
}
return skt_collection_;
}
} // namespace txt
| engine/third_party/txt/src/txt/font_collection.cc/0 | {
"file_path": "engine/third_party/txt/src/txt/font_collection.cc",
"repo_id": "engine",
"token_count": 1223
} | 565 |
// 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 "txt/platform.h"
#if defined(SK_FONTMGR_ANDROID_AVAILABLE)
#include "third_party/skia/include/ports/SkFontMgr_android.h"
#endif
#if defined(SK_FONTMGR_FREETYPE_EMPTY_AVAILABLE)
#include "third_party/skia/include/ports/SkFontMgr_empty.h"
#endif
namespace txt {
std::vector<std::string> GetDefaultFontFamilies() {
return {"sans-serif"};
}
sk_sp<SkFontMgr> GetDefaultFontManager(uint32_t font_initialization_data) {
#if defined(SK_FONTMGR_ANDROID_AVAILABLE)
static sk_sp<SkFontMgr> mgr = SkFontMgr_New_Android(nullptr);
#elif defined(SK_FONTMGR_FREETYPE_EMPTY_AVAILABLE)
static sk_sp<SkFontMgr> mgr = SkFontMgr_New_Custom_Empty();
#else
static sk_sp<SkFontMgr> mgr = SkFontMgr::RefEmpty();
#endif
return mgr;
}
} // namespace txt
| engine/third_party/txt/src/txt/platform_android.cc/0 | {
"file_path": "engine/third_party/txt/src/txt/platform_android.cc",
"repo_id": "engine",
"token_count": 367
} | 566 |
/*
* 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.
*/
#include "txt/typeface_font_asset_provider.h"
#include "flutter/fml/logging.h"
#include "third_party/skia/include/core/SkString.h"
#include "third_party/skia/include/core/SkTypeface.h"
namespace txt {
TypefaceFontAssetProvider::TypefaceFontAssetProvider() = default;
TypefaceFontAssetProvider::~TypefaceFontAssetProvider() = default;
// |FontAssetProvider|
size_t TypefaceFontAssetProvider::GetFamilyCount() const {
return family_names_.size();
}
// |FontAssetProvider|
std::string TypefaceFontAssetProvider::GetFamilyName(int index) const {
return family_names_[index];
}
// |FontAssetProvider|
sk_sp<SkFontStyleSet> TypefaceFontAssetProvider::MatchFamily(
const std::string& family_name) {
auto found = registered_families_.find(CanonicalFamilyName(family_name));
if (found == registered_families_.end()) {
return nullptr;
}
return found->second;
}
void TypefaceFontAssetProvider::RegisterTypeface(sk_sp<SkTypeface> typeface) {
if (typeface == nullptr) {
return;
}
SkString sk_family_name;
typeface->getFamilyName(&sk_family_name);
std::string family_name(sk_family_name.c_str(), sk_family_name.size());
RegisterTypeface(std::move(typeface), std::move(family_name));
}
void TypefaceFontAssetProvider::RegisterTypeface(
sk_sp<SkTypeface> typeface,
std::string family_name_alias) {
if (family_name_alias.empty()) {
return;
}
std::string canonical_name = CanonicalFamilyName(family_name_alias);
auto family_it = registered_families_.find(canonical_name);
if (family_it == registered_families_.end()) {
family_names_.push_back(family_name_alias);
auto value =
std::make_pair(canonical_name, sk_make_sp<TypefaceFontStyleSet>());
family_it = registered_families_.emplace(value).first;
}
family_it->second->registerTypeface(std::move(typeface));
}
TypefaceFontStyleSet::TypefaceFontStyleSet() = default;
TypefaceFontStyleSet::~TypefaceFontStyleSet() = default;
void TypefaceFontStyleSet::registerTypeface(sk_sp<SkTypeface> typeface) {
if (typeface == nullptr) {
return;
}
typefaces_.emplace_back(std::move(typeface));
}
int TypefaceFontStyleSet::count() {
return typefaces_.size();
}
void TypefaceFontStyleSet::getStyle(int index,
SkFontStyle* style,
SkString* name) {
FML_DCHECK(static_cast<size_t>(index) < typefaces_.size());
if (style) {
*style = typefaces_[index]->fontStyle();
}
if (name) {
name->reset();
}
}
sk_sp<SkTypeface> TypefaceFontStyleSet::createTypeface(int i) {
size_t index = i;
if (index >= typefaces_.size()) {
return nullptr;
}
return typefaces_[index];
}
sk_sp<SkTypeface> TypefaceFontStyleSet::matchStyle(const SkFontStyle& pattern) {
return matchStyleCSS3(pattern);
}
} // namespace txt
| engine/third_party/txt/src/txt/typeface_font_asset_provider.cc/0 | {
"file_path": "engine/third_party/txt/src/txt/typeface_font_asset_provider.cc",
"repo_id": "engine",
"token_count": 1187
} | 567 |
## 0.1.1
* Initial release.
| engine/third_party/web_locale_keymap/CHANGELOG.md/0 | {
"file_path": "engine/third_party/web_locale_keymap/CHANGELOG.md",
"repo_id": "engine",
"token_count": 13
} | 568 |
// 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 groovy.json.JsonSlurper
// Configures the embedding dependencies.
ext.configureEmbedderDependencies = { engineRootDir, add ->
def filesJson = new File(engineRootDir, 'tools/androidx/files.json')
if (!filesJson.exists()) {
throw new Exception("${filesJson.absolutePath} not found. Did you provide the wrong engine root directory to configureDependencies?")
}
def dependencies = new JsonSlurper().parseText(filesJson.text)
assert dependencies instanceof List
dependencies.each { dependency ->
assert dependency.maven_dependency instanceof String
add(dependency.maven_dependency)
}
}
// Configures the embedding dependencies. To match the logic in
// generate_pom_file.py, this does not include transitive dependencies since
// they aren't used by the embedding.
ext.configureDependencies = { engineRootDir, add ->
def filesJson = new File(engineRootDir, 'tools/androidx/files.json')
if (!filesJson.exists()) {
throw new Exception("${filesJson.absolutePath} not found. Did you provide the wrong engine root directory to configureDependencies?")
}
def dependencies = new JsonSlurper().parseText(filesJson.text)
assert dependencies instanceof List
dependencies.each { dependency ->
assert dependency.maven_dependency instanceof String
if (dependency.provides) {
add(dependency.maven_dependency)
}
}
}
| engine/tools/androidx/configure.gradle/0 | {
"file_path": "engine/tools/androidx/configure.gradle",
"repo_id": "engine",
"token_count": 514
} | 569 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
bool _hasCommandOnPath(String name) {
final ProcessResult result = Process.runSync('which', <String>[name]);
return result.exitCode == 0;
}
List<String> _findPairs(Set<String> as, Set<String> bs) {
final List<String> result = <String>[];
for (final String a in as) {
if (bs.contains(a)) {
result.add(a);
} else {
print('Mix match file $a.');
}
}
for (final String b in bs) {
if (!as.contains(b)) {
print('Mix match file $b.');
}
}
return result;
}
String _basename(String path) {
return path.split(Platform.pathSeparator).last;
}
Set<String> _grabPngFilenames(Directory dir) {
return dir.listSync()
.map((FileSystemEntity e) => _basename(e.path))
.where((String e) => e.endsWith('.png'))
.toSet();
}
/// The main entry point to the tool, execute it like `main`. Returns the
/// `exitCode`.
int run(List<String> args) {
int returnCode = 0;
if (!_hasCommandOnPath('compare')) {
throw Exception(r'Could not find `compare` from ImageMagick on $PATH.');
}
if (args.length != 2) {
throw Exception('Usage: compare_goldens.dart <dir path> <dir path>');
}
final Directory dirA = Directory(args[0]);
if (!dirA.existsSync()) {
throw Exception('Unable to find $dirA');
}
final Directory dirB = Directory(args[1]);
if (!dirB.existsSync()) {
throw Exception('Unable to find $dirB');
}
final Set<String> filesA = _grabPngFilenames(dirA);
final Set<String> filesB = _grabPngFilenames(dirB);
final List<String> pairs = _findPairs(filesA, filesB);
if (filesA.length != pairs.length || filesB.length != pairs.length) {
returnCode = 1;
}
int count = 0;
for (final String name in pairs) {
count += 1;
final String pathA = <String>[dirA.path, name].join(Platform.pathSeparator);
final String pathB = <String>[dirB.path, name].join(Platform.pathSeparator);
final String output = 'diff_$name';
print('compare ($count / ${pairs.length}) $name');
final ProcessResult result = Process.runSync('compare',
<String>['-metric', 'RMSE', '-fuzz', '5%', pathA, pathB, output]);
if (result.exitCode != 0) {
print('DIFF FOUND: saved to $output');
returnCode = 1;
} else {
File(output).deleteSync();
}
}
return returnCode;
}
| engine/tools/compare_goldens/lib/compare_goldens.dart/0 | {
"file_path": "engine/tools/compare_goldens/lib/compare_goldens.dart",
"repo_id": "engine",
"token_count": 920
} | 570 |
// 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.
class Target {
const Target(this.stringValue, this.intValue, this.targetValue);
final String stringValue;
final int intValue;
final Target? targetValue;
void hit() {
print('$stringValue $intValue');
}
}
class ExtendsTarget extends Target {
const ExtendsTarget(super.stringValue, super.intValue, super.targetValue);
}
class ImplementsTarget implements Target {
const ImplementsTarget(this.stringValue, this.intValue, this.targetValue);
@override
final String stringValue;
@override
final int intValue;
@override
final Target? targetValue;
@override
void hit() {
print('ImplementsTarget - $stringValue $intValue');
}
}
mixin MixableTarget {
String get val;
void hit() {
print(val);
}
}
class MixedInTarget with MixableTarget {
const MixedInTarget(this.val);
@override
final String val;
}
| engine/tools/const_finder/test/fixtures/lib/target.dart/0 | {
"file_path": "engine/tools/const_finder/test/fixtures/lib/target.dart",
"repo_id": "engine",
"token_count": 317
} | 571 |
# The Engine Tool
[![Open `e: engine-tool` issues](https://img.shields.io/github/issues/flutter/flutter/e%3A%20engine-tool)](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3A%22e%3A+engine-tool%22)
This is a command line Dart program that automates workflows in the
`flutter/engine` repository.
> [!NOTE]
> This tool is under development and is not yet ready for general use. Consider
> filing a [feature request](https://github.com/flutter/flutter/issues/new?labels=e:engine-tool,team-engine).
## Prerequisites
The tool requires an initial `gclient sync -D` as described in the [repo setup
steps](https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment#getting-the-source)
before it will work.
## Status
The tool has the following commands.
- `help` - Prints helpful information about commands and usage.
- `build` - Builds the Flutter engine.
- `fetch` - Downloads Flutter engine dependencies.
- `format` - Formats files in the engine tree using various off-the-shelf
formatters.
- `run` - Runs a flutter application with a local build of the engine.
- `query builds` - Lists the CI builds described under `ci/builders` that the
host platform is capable of executing.
### Missing features
There are currently many missing features. Some overall goals are listed in the
GitHub issue [here](https://github.com/flutter/flutter/issues/132807). Some
desirable new features would do the following:
- Add a `doctor` command.
- Update the engine checkout so that engine developers no longer have to remember
to run `gclient sync -D`.
- Build and test the engine using CI configurations locally, with the
possibility to override or add new build options and targets.
- Build engines using options coming only from the command line.
- List tests and run them locally, automatically building their dependencies
first. Automatically start emulators or simulators if they're needed to run a
test.
- Spawn individual builders remotely using `led` from `depot_tools`.
- Encapsulate all code formatters, checkers, linters, etc. for all languages.
- Find a compatible version of the flutter/flutter repo, check it out, and spawn
tests from that repo with a locally built engine to run on an emulator,
simulator or device.
- Use a real logging package for prettier terminal output.
- Wire the tool up to a package providing autocomplete like
[cli_completion](https://pub.dev/packages/cli_completion.).
The way the current tooling in the engine repo works may need to be rewritten,
especially tests spawned by `run_tests.py`, in order to provide this interface.
## Contributing
- Follow the [Flutter style guide](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo)
for Dart code that are relevant outside of the framework repo. It contains
conventions that go beyond code formatting, which
we'll follow even if using `dart format` in the future.
- Do not call directly into `dart:io` except from `main.dart`. Instead access
the system only through the `Enviroment` object.
- All commands must have unit tests. If some functionality needs a fake
implementation, then write a fake implementation.
- When adding or changing functionality, update this README.md file.
- _Begin with the end in mind_ - Start working from what the interface provided
by this tool _should_ be, then modify underlying scripts and tools to provide
APIs to support that.
Run tests using `//flutter/testing/run_tests.py`:
```shell
testing/run_tests.py --type dart-host --dart-host-filter flutter/tools/engine_tool
```
| engine/tools/engine_tool/README.md/0 | {
"file_path": "engine/tools/engine_tool/README.md",
"repo_id": "engine",
"token_count": 978
} | 572 |
// 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';
void _appendTypeError(
Map<String, Object?> map,
String field,
String expected,
List<String> errors, {
Object? element,
}) {
if (element == null) {
final Type actual = map[field]!.runtimeType;
errors.add(
'For field "$field", expected type: $expected, actual type: $actual.',
);
} else {
final Type actual = element.runtimeType;
errors.add(
'For element "$element" of "$field", '
'expected type: $expected, actual type: $actual',
);
}
}
/// Type safe getter of a List<String> field from map.
List<String>? stringListOfJson(
Map<String, Object?> map,
String field,
List<String> errors,
) {
if (map[field] == null) {
return <String>[];
}
if (map[field]! is! List<Object?>) {
_appendTypeError(map, field, 'list', errors);
return null;
}
for (final Object? obj in map[field]! as List<Object?>) {
if (obj is! String) {
_appendTypeError(map, field, element: obj, 'string', errors);
return null;
}
}
return (map[field]! as List<Object?>).cast<String>();
}
/// Type safe getter of a String field from map.
String? stringOfJson(
Map<String, Object?> map,
String field,
List<String> errors,
) {
if (map[field] == null) {
return '<undef>';
}
if (map[field]! is! String) {
_appendTypeError(map, field, 'string', errors);
return null;
}
return map[field]! as String;
}
/// Type safe getter of an int field from map.
int? intOfJson(
Map<String, Object?> map,
String field,
List<String> errors, {
int fallback = 0,
}) {
if (map[field] == null) {
return fallback;
}
if (map[field]! is! int) {
_appendTypeError(map, field, 'int', errors);
return null;
}
return map[field]! as int;
}
const JsonEncoder _jsonEncoder = JsonEncoder.withIndent(' ');
/// Same as [jsonEncode] but is formatted to be human readable.
String jsonEncodePretty(Object? object) => _jsonEncoder.convert(object);
| engine/tools/engine_tool/lib/src/json_utils.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/json_utils.dart",
"repo_id": "engine",
"token_count": 787
} | 573 |
// 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/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';
class TestWorkerPoolProgressReporter implements WorkerPoolProgressReporter {
int _successCount = 0;
int _errorCount = 0;
final List<Object> _errors = <Object>[];
@override
void onRun(Set<WorkerTask> tasks) {}
@override
void onFinish() {}
@override
void onTaskStart(WorkerPool pool, WorkerTask task) {}
@override
void onTaskDone(WorkerPool pool, WorkerTask task, [Object? err]) {
if (err == null) {
_successCount++;
return;
}
_errorCount++;
_errors.add(err);
}
}
class SuccessfulTask extends WorkerTask {
SuccessfulTask() : super('s');
@override
Future<bool> run() async {
return true;
}
}
class FailureTask extends WorkerTask {
FailureTask() : super('f');
@override
Future<bool> run() async {
throw ArgumentError('test');
}
}
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),
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('worker pool success', () async {
final Logger logger = Logger.test();
final (Environment env, _) = macEnv(logger);
final TestWorkerPoolProgressReporter reporter =
TestWorkerPoolProgressReporter();
final WorkerPool wp = WorkerPool(env, reporter);
final WorkerTask task = SuccessfulTask();
final bool r = await wp.run(<WorkerTask>{task});
expect(r, equals(true));
expect(reporter._successCount, equals(1));
expect(reporter._errorCount, equals(0));
expect(reporter._errors.length, equals(0));
});
test('worker pool failure', () async {
final Logger logger = Logger.test();
final (Environment env, _) = macEnv(logger);
final TestWorkerPoolProgressReporter reporter =
TestWorkerPoolProgressReporter();
final WorkerPool wp = WorkerPool(env, reporter);
final WorkerTask task = FailureTask();
final bool r = await wp.run(<WorkerTask>{task});
expect(r, equals(false));
expect(reporter._successCount, equals(0));
expect(reporter._errorCount, equals(1));
expect(reporter._errors.length, equals(1));
});
}
| engine/tools/engine_tool/test/worker_pool_test.dart/0 | {
"file_path": "engine/tools/engine_tool/test/worker_pool_test.dart",
"repo_id": "engine",
"token_count": 1383
} | 574 |
[style]
based_on_style = chromium
| engine/tools/fuchsia/.style.yapf/0 | {
"file_path": "engine/tools/fuchsia/.style.yapf",
"repo_id": "engine",
"token_count": 13
} | 575 |
#!/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.
"""Reads the contents of a package config file generated by the build and
converts it to a real package_config.json file
"""
import argparse
import collections
import json
import os
import re
import sys
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path += [os.path.join(THIS_DIR, '..', '..', '..', 'third_party', 'pyyaml', 'lib3')]
import yaml
DEFAULT_LANGUAGE_VERSION = '2.8'
Package = collections.namedtuple('Package', ['name', 'rootUri', 'languageVersion', 'packageUri'])
class PackageConfig:
# The version of the package config.
VERSION = 2
# The name of the generator which gets written to the json output
GENERATOR_NAME = os.path.basename(__file__)
def __init__(self, packages):
self.packages = packages
def asdict(self):
"""Converts the package config to a dictionary"""
return {
'configVersion': self.VERSION,
'packages': [p._asdict() for p in sorted(self.packages)],
'generator': self.GENERATOR_NAME,
}
def language_version_from_pubspec(pubspec):
"""Parse the content of a pubspec.yaml"""
with open(pubspec) as pubspec:
parsed = yaml.safe_load(pubspec)
if not parsed:
return DEFAULT_LANGUAGE_VERSION
# If a format like sdk: '>=a.b' or sdk: 'a.b' is found, we'll use a.b.
# In all other cases we default to "2.8"
env_sdk = parsed.get('environment', {}).get('sdk', 'any')
match = re.search(r'^(>=)?((0|[1-9]\d*)\.(0|[1-9]\d*))', env_sdk)
if match:
min_sdk_version = match.group(2)
else:
min_sdk_version = DEFAULT_LANGUAGE_VERSION
return min_sdk_version
def collect_packages(items, relative_to):
"""Reads metadata produced by GN to create lists of packages and pubspecs.
- items: a list of objects collected from gn
- relative_to: The directory which the packages are relative to. This is
the location that contains the package_config.json file
Returns None if there was a problem parsing packages
"""
packages = []
pubspec_paths = []
for item in items:
if 'language_version' in item:
language_version = item['language_version']
elif 'pubspec_path' in item:
pubspec_paths.append(item['pubspec_path'])
language_version = language_version_from_pubspec(item['pubspec_path'])
else:
language_version = DEFAULT_LANGUAGE_VERSION
package = Package(
name=item['name'],
rootUri=os.path.relpath(item['root_uri'], relative_to),
languageVersion=language_version,
packageUri=item['package_uri']
)
# TODO(fxbug.dev/56428): enable once we sort out our duplicate packages
# for p in packages:
# if p.rootUri == package.rootUri:
# print('Failed to create package_config.json file')
# print('The following packages contain the same package root ' + p.rootUri)
# print(' - ' + p.rootUri)
# print(' - ' + package.rootUri)
# return None
packages.append(package)
return packages, pubspec_paths
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--input', help='Path to original package_config', required=True)
parser.add_argument('--output', help='Path to the updated package_config', required=True)
parser.add_argument('--root', help='Path to fuchsia root', required=True)
parser.add_argument('--depfile', help='Path to the depfile', required=True)
args = parser.parse_args()
with open(args.input, 'r') as input_file:
contents = json.load(input_file)
output_dir = os.path.dirname(os.path.abspath(args.output))
packages, pubspec_paths = collect_packages(contents, output_dir)
if packages is None:
return 1
with open(args.depfile, 'w') as depfile:
depfile.write('%s: %s' % (args.output, ' '.join(pubspec_paths)))
with open(args.output, 'w') as output_file:
package_config = PackageConfig(packages)
json.dump(
package_config.asdict(), output_file, indent=2, sort_keys=True, separators=(',', ': ')
)
return 0
if __name__ == '__main__':
sys.exit(main())
| engine/tools/fuchsia/dart/gen_dart_package_config.py/0 | {
"file_path": "engine/tools/fuchsia/dart/gen_dart_package_config.py",
"repo_id": "engine",
"token_count": 1557
} | 576 |
#!/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.
#
### Tests build_and_copy_to_fuchsia.sh by running it with various arguments.
### This script doesn't assert the results but just checks that the script runs
### successfully every time.
###
### This script doesn't run on CQ, it's only used for local testing.
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"/../lib/vars.sh || exit $?
ensure_fuchsia_dir
ensure_engine_dir
set -e # Fail on any error.
# TODO(akbiggs): Remove prebuilts before each build to check that the right set of
# prebuilts is being deployed. I tried this initially but gave up because
# build_and_copy_to_fuchsia.sh would fail when the prebuilt directories were missing.
engine-info "Testing build_and_copy_to_fuchsia.sh with no args..."
"$ENGINE_DIR"/flutter/tools/fuchsia/devshell/build_and_copy_to_fuchsia.sh
engine-info "Testing build_and_copy_to_fuchsia.sh --unoptimized..."
$ENGINE_DIR/flutter/tools/fuchsia/devshell/build_and_copy_to_fuchsia.sh --unoptimized
engine-info "Testing build_and_copy_to_fuchsia.sh --runtime-mode profile..."
$ENGINE_DIR/flutter/tools/fuchsia/devshell/build_and_copy_to_fuchsia.sh --runtime-mode profile
engine-info "Testing build_and_copy_to_fuchsia.sh --runtime-mode release..."
$ENGINE_DIR/flutter/tools/fuchsia/devshell/build_and_copy_to_fuchsia.sh --runtime-mode release
engine-info "Testing build_and_copy_to_fuchsia.sh --fuchsia-cpu arm64..."
$ENGINE_DIR/flutter/tools/fuchsia/devshell/build_and_copy_to_fuchsia.sh --fuchsia-cpu arm64
engine-info "Testing build_and_copy_to_fuchsia.sh --goma..."
$ENGINE_DIR/flutter/tools/fuchsia/devshell/build_and_copy_to_fuchsia.sh --goma
engine-info "Testing build_and_copy_to_fuchsia.sh --no-prebuilt-dart-sdk..."
$ENGINE_DIR/flutter/tools/fuchsia/devshell/build_and_copy_to_fuchsia.sh --no-prebuilt-dart-sdk
| engine/tools/fuchsia/devshell/test/test_build_and_copy_to_fuchsia.sh/0 | {
"file_path": "engine/tools/fuchsia/devshell/test/test_build_and_copy_to_fuchsia.sh",
"repo_id": "engine",
"token_count": 704
} | 577 |
#!/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.
""" Merges the debug symbols and uploads them to cipd.
"""
import argparse
import collections
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
# Path to the engine root checkout. This is used to calculate absolute
# paths if relative ones are passed to the script.
BUILD_ROOT_DIR = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..'))
def IsLinux():
return platform.system() == 'Linux'
# out_dir here is of the format "/b/s/w/ir/k/recipe_cleanup/tmpIbWDdp"
# we need to place the cipd definition in this directory.
def GetPackagingDir(out_dir):
return os.path.abspath(out_dir)
def CreateCIPDDefinition(target_arch, out_dir, symbol_dirs):
dir_name = os.path.basename(os.path.normpath(out_dir))
pkg_def = """
package: flutter/fuchsia-debug-symbols-%s
description: Flutter and Dart runner debug symbols for Fuchsia. Target architecture %s.
install_mode: copy
data:
""" % (target_arch, target_arch)
for symbol_dir in symbol_dirs:
symbol_dir_name = os.path.basename(os.path.normpath(symbol_dir))
data = '\n - dir: %s' % (symbol_dir_name)
pkg_def = pkg_def + data
return pkg_def
# CIPD CLI needs the definition and data directory to be relative to each other.
def WriteCIPDDefinition(target_arch, out_dir, symbol_dirs):
_packaging_dir = GetPackagingDir(out_dir)
yaml_file = os.path.join(_packaging_dir, 'debug_symbols.cipd.yaml')
with open(yaml_file, 'w') as f:
cipd_def = CreateCIPDDefinition(target_arch, out_dir, symbol_dirs)
f.write(cipd_def)
return yaml_file
def CheckCIPDPackageExists(package_name, tag):
'''Check to see if the current package/tag combo has been published'''
command = [
'cipd',
'search',
package_name,
'-tag',
tag,
]
stdout = subprocess.check_output(command)
stdout = stdout if isinstance(stdout, str) else stdout.decode('UTF-8')
match = re.search(r'No matching instances\.', stdout)
if match:
return False
else:
return True
def ProcessCIPDPackage(upload, cipd_yaml, engine_version, out_dir, target_arch):
_packaging_dir = GetPackagingDir(out_dir)
tag = 'git_revision:%s' % engine_version
package_name = 'flutter/fuchsia-debug-symbols-%s' % target_arch
already_exists = CheckCIPDPackageExists(package_name, tag)
if already_exists:
print('CIPD package %s tag %s already exists!' % (package_name, tag))
if upload and IsLinux() and not already_exists:
command = [
'cipd',
'create',
'-pkg-def',
cipd_yaml,
'-ref',
'latest',
'-tag',
tag,
'-verification-timeout',
'10m0s',
]
else:
command = [
'cipd', 'pkg-build', '-pkg-def', cipd_yaml, '-out',
os.path.join(_packaging_dir, 'fuchsia-debug-symbols-%s.cipd' % target_arch)
]
# Retry up to three times. We've seen CIPD fail on verification in some
# instances. Normally verification takes slightly more than 1 minute when
# it succeeds.
num_tries = 3
for tries in range(num_tries):
try:
subprocess.check_call(command, cwd=_packaging_dir)
break
except subprocess.CalledProcessError as error:
print('Failed %s times.\nError was: %s' % (tries + 1, error))
if tries == num_tries - 1:
raise
# Recursively hardlinks contents from one directory to another,
# skipping over collisions.
def HardlinkContents(dirA, dirB):
internal_symbol_dirs = []
for src_dir, _, filenames in os.walk(dirA):
for filename in filenames:
# if a file contains 'dbg_success' in its name, it is a stamp file.
# An example of this would be
# '._dart_jit_runner_dbg_symbols_unstripped_dbg_success' these
# are generated by GN and have to be ignored.
if 'dbg_success' in filename:
continue
src = os.path.join(src_dir, filename)
dest_dir = os.path.join(dirB, os.path.relpath(src_dir, dirA))
try:
os.makedirs(dest_dir)
internal_symbol_dirs.append(dest_dir)
except:
pass
dest = os.path.join(dest_dir, filename)
if os.path.exists(dest):
# The last two path components provide a content address for a .build-id entry.
tokens = os.path.split(dest)
name = os.path.join(tokens[-2], tokens[-1])
print('%s already exists in destination; skipping linking' % name)
continue
os.link(src, dest)
return internal_symbol_dirs
def CalculateAbsoluteDirs(dirs):
results = []
for directory in dirs:
if os.path.isabs(directory):
results.append(directory)
else:
results.append(os.path.join(BUILD_ROOT_DIR, directory))
return results
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--symbol-dirs',
required=True,
nargs='+',
help='Space separated list of directories that contain the debug symbols.'
)
parser.add_argument(
'--out-dir',
action='store',
dest='out_dir',
default=tempfile.mkdtemp(),
help=(
'Output directory where the executables will be placed defaults to an '
'empty temp directory'
)
)
parser.add_argument('--target-arch', type=str, choices=['x64', 'arm64'], required=True)
parser.add_argument('--engine-version', required=True, help='Specifies the flutter engine SHA.')
parser.add_argument('--upload', default=False, action='store_true')
args = parser.parse_args()
symbol_dirs = CalculateAbsoluteDirs(args.symbol_dirs)
for symbol_dir in symbol_dirs:
assert os.path.exists(symbol_dir) and os.path.isdir(symbol_dir)
out_dir = args.out_dir
if os.path.exists(out_dir):
print('Directory: %s is not empty, deleting it.' % out_dir)
shutil.rmtree(out_dir)
os.makedirs(out_dir)
internal_symbol_dirs = []
for symbol_dir in symbol_dirs:
internal_symbol_dirs += HardlinkContents(symbol_dir, out_dir)
# make these unique
internal_symbol_dirs = list(set(internal_symbol_dirs))
arch = args.target_arch
cipd_def = WriteCIPDDefinition(arch, out_dir, internal_symbol_dirs)
# Set revision to HEAD if empty and remove upload. This is to support
# presubmit workflows. An empty engine_version means this script is running
# on presubmit.
should_upload = args.upload
engine_version = args.engine_version
if not engine_version:
engine_version = 'HEAD'
should_upload = False
ProcessCIPDPackage(should_upload, cipd_def, engine_version, out_dir, arch)
return 0
if __name__ == '__main__':
sys.exit(main())
| engine/tools/fuchsia/merge_and_upload_debug_symbols.py/0 | {
"file_path": "engine/tools/fuchsia/merge_and_upload_debug_symbols.py",
"repo_id": "engine",
"token_count": 2616
} | 578 |
// 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 'common.dart';
import 'layout_types.dart';
// Maps all mandatory goals from the character to eventScanCode.
//
// Mandatory goals are all the alnum keys. These keys must be assigned at the
// end of layout planning.
final Map<String, String> _kMandatoryGoalsByChar = Map<String, String>.fromEntries(
kLayoutGoals
.entries
.where((MapEntry<String, String> entry) => isLetter(entry.value.codeUnitAt(0)))
.map((MapEntry<String, String?> entry) => MapEntry<String, String>(entry.value!, entry.key))
);
/// Plan a layout into a map from eventCode to logical key.
///
/// If a eventCode does not exist in this map, then this event's logical key
/// should be derived on the fly.
///
/// This function defines the benchmark planning algorithm if there were a way
/// to know the current keyboard layout.
Map<String, int> planLayout(Map<String, LayoutEntry> entries) {
// The logical key is derived in the following rules:
//
// 1. If any clue (the four possible printables) of the key is a mandatory
// goal (alnum), then the goal is the logical key.
// 2. If a mandatory goal is not assigned in the way of #1, then it is
// assigned to the physical key as mapped in the US layout.
// 3. Derived on the fly from key, code, and keyCode.
//
// The map returned from this function contains the first two rules.
// Unresolved mandatory goals, mapped from printables to KeyboardEvent.code.
// This map will be modified during this function and thus is a clone.
final Map<String, String> mandatoryGoalsByChar = <String, String>{..._kMandatoryGoalsByChar};
// The result mapping from KeyboardEvent.code to logical key.
final Map<String, int> result = <String, int>{};
entries.forEach((String eventCode, LayoutEntry entry) {
for (final String printable in entry.printables) {
if (mandatoryGoalsByChar.containsKey(printable)) {
result[eventCode] = printable.codeUnitAt(0);
mandatoryGoalsByChar.remove(printable);
break;
}
}
});
// Ensure all mandatory goals are assigned.
mandatoryGoalsByChar.forEach((String character, String code) {
assert(!result.containsKey(code), 'Code $code conflicts.');
result[code] = character.codeUnitAt(0);
});
return result;
}
bool _isLetterOrMappedToKeyCode(int charCode) {
return isLetterChar(charCode) || charCode == kUseKeyCode;
}
/// Plan all layouts, and summarize them into a huge table of EventCode ->
/// EventKey -> logicalKey.
///
/// The resulting logicalKey can also be kUseKeyCode.
///
/// If a eventCode does not exist in this map, then this event's logical key
/// should be derived on the fly.
///
/// Entries that can be derived using heuristics are omitted.
Map<String, Map<String, int>> combineLayouts(Iterable<Layout> layouts) {
final Map<String, Map<String, int>> result = <String, Map<String, int>>{};
for (final Layout layout in layouts) {
planLayout(layout.entries).forEach((String eventCode, int logicalKey) {
final Map<String, int> codeMap = result.putIfAbsent(eventCode, () => <String, int>{});
final LayoutEntry entry = layout.entries[eventCode]!;
for (final String eventKey in entry.printables) {
if (eventKey.isEmpty) {
continue;
}
// Found conflict. Assert that all such cases can be solved with
// keyCode.
if (codeMap.containsKey(eventKey) && codeMap[eventKey] != logicalKey) {
assert(isLetterChar(logicalKey));
assert(_isLetterOrMappedToKeyCode(codeMap[eventKey]!), '$eventCode, $eventKey, ${codeMap[eventKey]!}');
codeMap[eventKey] = kUseKeyCode;
} else {
codeMap[eventKey] = logicalKey;
}
}
});
}
// Remove mapping results that can be derived using heuristics.
result.removeWhere((String eventCode, Map<String, int> codeMap) {
codeMap.removeWhere((String eventKey, int logicalKey) =>
heuristicMapper(eventCode, eventKey) == logicalKey,
);
return codeMap.isEmpty;
});
return result;
}
| engine/tools/gen_web_locale_keymap/lib/benchmark_planner.dart/0 | {
"file_path": "engine/tools/gen_web_locale_keymap/lib/benchmark_planner.dart",
"repo_id": "engine",
"token_count": 1373
} | 579 |
#!/usr/bin/env vpython3
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
Runs the pre-push githooks.
'''
import os
import subprocess
import sys
SRC_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
FLUTTER_DIR = os.path.join(SRC_ROOT, 'flutter')
ENABLE_CLANG_TIDY = os.environ.get('PRE_PUSH_CLANG_TIDY')
def GetDartBin():
dart_bin = os.path.join(SRC_ROOT, 'flutter', 'third_party', 'dart', 'tools', 'sdks', 'dart-sdk', 'bin')
if not os.path.exists(dart_bin):
dart_bin = os.path.join(SRC_ROOT, 'third_party', 'dart', 'tools', 'sdks', 'dart-sdk', 'bin')
return dart_bin
def Main(argv):
githook_args = [
'--flutter',
FLUTTER_DIR,
]
if ENABLE_CLANG_TIDY is not None:
githook_args += [
'--enable-clang-tidy',
]
result = subprocess.run([
os.path.join(GetDartBin(), 'dart'),
'--disable-dart-dev',
os.path.join(FLUTTER_DIR, 'tools', 'githooks', 'bin', 'main.dart'),
] + githook_args + [
'pre-push',
] + argv[1:], cwd=SRC_ROOT)
return result.returncode
if __name__ == '__main__':
sys.exit(Main(sys.argv))
| engine/tools/githooks/pre-push/0 | {
"file_path": "engine/tools/githooks/pre-push",
"repo_id": "engine",
"token_count": 544
} | 580 |
// 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:io' as io;
import 'package:golden_tests_harvester/golden_tests_harvester.dart';
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as p;
void main() async {
Future<void> withTempDirectory(
FutureOr<void> Function(io.Directory) callback) async {
final io.Directory tempDirectory = await io.Directory.systemTemp
.createTemp('golden_tests_harvester_test.');
try {
await callback(tempDirectory);
} finally {
await tempDirectory.delete(recursive: true);
}
}
test('should fail on a missing directory', () async {
await withTempDirectory((io.Directory tempDirectory) async {
final StringSink stderr = StringBuffer();
final ArgumentError error = await _expectThrow<ArgumentError>(() async {
await Harvester.create(
io.Directory(p.join(tempDirectory.path, 'non_existent')),
stderr,
addImageToSkiaGold: _alwaysThrowsAddImg);
});
expect(error.message, contains('non_existent'));
expect(stderr.toString(), isEmpty);
});
});
test('should require a file named "digest.json" in the working directory',
() async {
await withTempDirectory((io.Directory tempDirectory) async {
final StringSink stderr = StringBuffer();
final StateError error = await _expectThrow<StateError>(() async {
await Harvester.create(
tempDirectory,
stderr,
addImageToSkiaGold: _alwaysThrowsAddImg);
});
expect(error.toString(), contains('digest.json'));
expect(stderr.toString(), isEmpty);
});
});
test('should throw if "digest.json" is in an unexpected format', () async {
await withTempDirectory((io.Directory tempDirectory) async {
final StringSink stderr = StringBuffer();
final io.File digestsFile =
io.File(p.join(tempDirectory.path, 'digest.json'));
await digestsFile
.writeAsString('{"dimensions": "not a map", "entries": []}');
final FormatException error =
await _expectThrow<FormatException>(() async {
await Harvester.create(
tempDirectory,
stderr,
addImageToSkiaGold: _alwaysThrowsAddImg);
});
expect(error.message, contains('dimensions'));
expect(stderr.toString(), isEmpty);
});
});
test('should fail eagerly if addImg fails', () async {
await withTempDirectory((io.Directory tempDirectory) async {
final io.File digestsFile =
io.File(p.join(tempDirectory.path, 'digest.json'));
final StringSink stderr = StringBuffer();
await digestsFile.writeAsString('''
{
"dimensions": {},
"entries": [
{
"filename": "test_name_1.png",
"width": 100,
"height": 100,
"maxDiffPixelsPercent": 0.01,
"maxColorDelta": 0
}
]
}
''');
final FailedComparisonException error =
await _expectThrow<FailedComparisonException>(() async {
final Harvester harvester = await Harvester.create(
tempDirectory,
stderr,
addImageToSkiaGold: _alwaysThrowsAddImg);
await harvest(harvester);
});
expect(error.testName, 'test_name_1.png');
expect(stderr.toString(), contains('IntentionalError'));
});
});
test('should invoke addImg per test', () async {
await withTempDirectory((io.Directory tempDirectory) async {
final io.File digestsFile =
io.File(p.join(tempDirectory.path, 'digest.json'));
await digestsFile.writeAsString('''
{
"dimensions": {},
"entries": [
{
"filename": "test_name_1.png",
"width": 100,
"height": 100,
"maxDiffPixelsPercent": 0.01,
"maxColorDelta": 0
},
{
"filename": "test_name_2.png",
"width": 200,
"height": 200,
"maxDiffPixelsPercent": 0.02,
"maxColorDelta": 1
}
]
}
''');
final List<String> addImgCalls = <String>[];
final StringSink stderr = StringBuffer();
final Harvester harvester =
await Harvester.create(tempDirectory, stderr, addImageToSkiaGold: (
String testName,
io.File goldenFile, {
required int screenshotSize,
double differentPixelsRate = 0.01,
int pixelColorDelta = 0,
}) async {
addImgCalls.add(
'$testName $screenshotSize $differentPixelsRate $pixelColorDelta');
});
await harvest(harvester);
expect(addImgCalls, <String>[
'test_name_1.png 10000 0.01 0',
'test_name_2.png 40000 0.02 1',
]);
});
});
test('client has dimensions', () async {
await withTempDirectory((io.Directory tempDirectory) async {
final StringSink stderr = StringBuffer();
final io.File digestsFile =
io.File(p.join(tempDirectory.path, 'digest.json'));
await digestsFile
.writeAsString('{"dimensions": {"key":"value"}, "entries": []}');
final Harvester harvester = await Harvester.create(tempDirectory, stderr);
expect(harvester is SkiaGoldHarvester, true);
final SkiaGoldHarvester skiaGoldHarvester =
harvester as SkiaGoldHarvester;
expect(skiaGoldHarvester.client.dimensions,
<String, String>{'key': 'value'});
});
});
test('throws without GOLDCTL', () async {
await withTempDirectory((io.Directory tempDirectory) async {
final StringSink stderr = StringBuffer();
final io.File digestsFile =
io.File(p.join(tempDirectory.path, 'digest.json'));
await digestsFile.writeAsString('''
{
"dimensions": {"key":"value"},
"entries": [
{
"filename": "foo.png",
"width": 100,
"height": 100,
"maxDiffPixelsPercent": 0.01,
"maxColorDelta": 0
}
]}
''');
final Harvester harvester = await Harvester.create(tempDirectory, stderr);
final StateError error = await _expectThrow<StateError>(() async {
await harvest(harvester);
});
expect(error.message, contains('GOLDCTL'));
expect(stderr.toString(), isEmpty);
});
});
}
FutureOr<T> _expectThrow<T extends Object>(
FutureOr<void> Function() callback) async {
try {
await callback();
fail('Expected an exception of type $T');
} on T catch (e) {
return e;
} catch (e) {
fail('Expected an exception of type $T, but got $e');
}
// fail(...) unfortunately does not return Never, but it does always throw.
throw UnsupportedError('Unreachable');
}
final class _IntentionalError extends Error {}
Future<void> _alwaysThrowsAddImg(
String testName,
io.File goldenFile, {
required int screenshotSize,
double differentPixelsRate = 0.01,
int pixelColorDelta = 0,
}) async {
throw _IntentionalError();
}
| engine/tools/golden_tests_harvester/test/golden_tests_harvester_test.dart/0 | {
"file_path": "engine/tools/golden_tests_harvester/test/golden_tests_harvester_test.dart",
"repo_id": "engine",
"token_count": 3048
} | 581 |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
| engine/tools/licenses/data/apache-license-2.0/0 | {
"file_path": "engine/tools/licenses/data/apache-license-2.0",
"repo_id": "engine",
"token_count": 3168
} | 582 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:core' hide RegExp;
import 'patterns.dart';
void _stripFullLines(List<String> lines) {
// Strip full-line decorations, e.g. horizontal lines, and trailing whitespace.
for (int index = 0; index < lines.length; index += 1) {
lines[index] = lines[index].trimRight();
if (fullDecorations.matchAsPrefix(lines[index]) != null) {
if (index == 0 || lines[index].length != lines[index - 1].length) {
// (we leave the decorations if it's just underlining the previous line)
lines[index] = '';
}
}
}
// Remove leading and trailing blank lines
while (lines.isNotEmpty && lines.first == '') {
lines.removeAt(0);
}
while (lines.isNotEmpty && lines.last == '') {
lines.removeLast();
}
}
bool _stripIndentation(List<String> lines) {
// Try stripping leading indentation.
String? prefix;
bool removeTrailingBlockEnd = false;
if (lines.first.startsWith('/*') && lines.last.startsWith(' *')) {
// In addition to the leadingDecorations, we also support one specific
// kind of multiline decoration, the /*...*/ block comment.
prefix = ' *';
removeTrailingBlockEnd = true;
} else {
prefix = leadingDecorations.matchAsPrefix(lines.first)?.group(0);
}
if (prefix != null && lines.skip(1).every((String line) => line.startsWith(prefix!) || prefix.startsWith(line))) {
final int prefixLength = prefix.length;
for (int index = 0; index < lines.length; index += 1) {
final String line = lines[index];
if (line.length > prefixLength) {
lines[index] = line.substring(prefixLength);
} else {
lines[index] = '';
}
}
if (removeTrailingBlockEnd) {
if (lines.last == '/') {
// This removes the line with the trailing "*/" when we had a "/*" at the top.
lines.removeLast();
}
}
return true;
}
return false;
}
bool _unindentLeadingParagraphs(List<String> lines) {
// Try removing leading spaces
// (we know that this loop terminates before the end of the block because
// otherwise the previous section would have stripped a common prefix across
// the entire block)
//
// For example, this will change:
//
// foo
// bar
//
// ...into:
//
// foo
// bar
//
assert(' '.startsWith(leadingDecorations));
if (lines.first.startsWith(' ')) {
int lineCount = 0;
String line = lines.first;
int leadingBlockIndent = line.length; // arbitrarily big number
do {
int indentWidth = 1;
while (indentWidth < line.length && line[indentWidth] == ' ') {
indentWidth += 1;
}
if (indentWidth < leadingBlockIndent) {
leadingBlockIndent = indentWidth;
}
lineCount += 1;
assert(lineCount < lines.length);
line = lines[lineCount];
} while (line.startsWith(' '));
assert(leadingBlockIndent > 0);
for (int index = 0; index < lineCount; index += 1) {
lines[index] = lines[index].substring(leadingBlockIndent, lines[index].length);
}
return true;
}
return false;
}
bool _minorRemovals(List<String> lines) {
bool didEdits = false;
// Try removing stray leading spaces (but only one space).
for (int index = 0; index < lines.length; index += 1) {
if (lines[index].startsWith(' ') && !lines[index].startsWith(' ')) {
lines[index] = lines[index].substring(1, lines[index].length);
didEdits = true;
}
}
// Try stripping HTML leading and trailing block (<!--/-->) comment markers.
if (lines.first.contains('<!--') || lines.last.contains('-->')) {
lines.first = lines[0].replaceFirst('<!--', '');
lines.last = lines[0].replaceFirst('-->', '');
didEdits = true;
}
// Try stripping C-style leading block comment markers.
// We don't do this earlier because if it's a multiline block comment
// we want to be careful about stripping the trailing aligned "*/".
if (lines.first.startsWith('/*')) {
lines.first = lines.first.substring(2, lines.first.length);
didEdits = true;
}
// Try stripping trailing decorations (specifically, stray "*/"s).
for (int index = 0; index < lines.length; index += 1) {
if (lines[index].endsWith('*/')) {
lines[index] = lines[index].substring(0, lines[index].length - 2);
didEdits = true;
}
}
return didEdits;
}
/// This function takes a block of text potentially decorated with leading
/// prefix indents, horizontal lines, C-style comment blocks, blank lines, etc,
/// and removes all such incidental material leaving only the significant text.
String reformat(String body) {
final List<String> lines = body.split('\n');
while (true) {
// The order of the following checks is important. If any test changes
// something that could affect an earlier test, then we should "continue" back
// to the top of the loop.
_stripFullLines(lines);
if (lines.isEmpty) {
// We've stripped everything, give up.
return '';
}
if (_stripIndentation(lines)) {
continue; // Go back to top since we may have more blank lines to strip now.
}
if (_unindentLeadingParagraphs(lines)) {
continue; // Go back to the top since we may have more indentation to strip now.
}
if (_minorRemovals(lines)) {
continue; // Go back to the top since we may have new stuff to strip.
}
// If we get here, we could not find anything else to do to the text to clean it up.
break;
}
return lines.join('\n');
}
String stripAsciiArt(String input) {
// Look for images so that we can remove them.
final List<String> lines = input.split('\n');
for (final List<String> image in asciiArtImages) {
assert(image.isNotEmpty);
// Look for the image starting on each line.
search: for (int index = 0; index < lines.length - image.length; index += 1) {
final int x = lines[index].indexOf(image[0]);
if (x >= 0) {
int width = image[0].length;
// Found the first line, check to see if we have a complete image.
for (int imageLine = 1; imageLine < image.length; imageLine += 1) {
if (lines[index + imageLine].indexOf(image[imageLine]) != x) {
continue search; // Not a complete image.
}
if (image[imageLine].length > width) {
width = image[imageLine].length;
}
}
// Now remove the image.
for (int imageLine = 0; imageLine < image.length; imageLine += 1) {
final String text = lines[index + imageLine];
assert(text.length > x);
if (text.length >= x + width) {
lines[index + imageLine] = text.substring(0, x) + text.substring(x + width, text.length);
} else {
lines[index + imageLine] = text.substring(0, x);
}
}
}
}
}
return lines.join('\n');
}
| engine/tools/licenses/lib/formatter.dart/0 | {
"file_path": "engine/tools/licenses/lib/formatter.dart",
"repo_id": "engine",
"token_count": 2557
} | 583 |
// 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_PATH_OPS_PATH_OPS_H_
#define FLUTTER_TOOLS_PATH_OPS_PATH_OPS_H_
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkPathBuilder.h"
#include "third_party/skia/include/core/SkPathTypes.h"
#include "third_party/skia/include/pathops/SkPathOps.h"
#ifdef _WIN32
#define API __declspec(dllexport)
#else
#define API __attribute__((visibility("default")))
#endif
extern "C" {
namespace flutter {
API SkPath* CreatePath(SkPathFillType fill_type);
API void DestroyPathBuilder(SkPath* path);
API void MoveTo(SkPath* path, SkScalar x, SkScalar y);
API void LineTo(SkPath* path, SkScalar x, SkScalar y);
API void CubicTo(SkPath* path,
SkScalar x1,
SkScalar y1,
SkScalar x2,
SkScalar y2,
SkScalar x3,
SkScalar y3);
API void Close(SkPath* path);
API void Reset(SkPath* path);
API void DestroyPath(SkPath* path);
API void Op(SkPath* one, SkPath* two, SkPathOp op);
API int GetFillType(SkPath* path);
struct API PathData {
uint8_t* verbs;
size_t verb_count;
float* points;
size_t point_count;
};
API struct PathData* Data(SkPath* path);
API void DestroyData(PathData* data);
} // namespace flutter
}
#endif // FLUTTER_TOOLS_PATH_OPS_PATH_OPS_H_
| engine/tools/path_ops/path_ops.h/0 | {
"file_path": "engine/tools/path_ops/path_ops.h",
"repo_id": "engine",
"token_count": 631
} | 584 |
# engine_repo_tools
This is a repo-internal library for `flutter/engine`, that contains shared code
for writing tools that operate on the engine repository. For example, finding
the latest compiled engine artifacts in the `out/` directory:
```dart
import 'package:engine_repo_tools/engine_repo_tools.dart';
void main() {
final engine = Engine.findWithin();
final latest = engine.latestOutput();
if (latest != null) {
print('Latest compile_commands.json: ${latest.compileCommandsJson?.path}');
}
}
```
| engine/tools/pkg/engine_repo_tools/README.md/0 | {
"file_path": "engine/tools/pkg/engine_repo_tools/README.md",
"repo_id": "engine",
"token_count": 156
} | 585 |
#!/usr/bin/env 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.
# ---------------------------------- NOTE ----------------------------------
#
# Please keep the logic in this file consistent with the logic in the
# `yapf.bat` script in the same directory to ensure that it continues to
# work across all platforms!
#
# --------------------------------------------------------------------------
# Generates objc docs for Flutter iOS libraries.
set -e
# On Mac OS, readlink -f doesn't work, so follow_links traverses the path one
# link at a time, and then cds into the link destination and find out where it
# ends up.
#
# The function is enclosed in a subshell to avoid changing the working directory
# of the caller.
function follow_links() (
cd -P "$(dirname -- "$1")"
file="$PWD/$(basename -- "$1")"
while [[ -h "$file" ]]; do
cd -P "$(dirname -- "$file")"
file="$(readlink -- "$file")"
cd -P "$(dirname -- "$file")"
file="$PWD/$(basename -- "$file")"
done
echo "$file"
)
SCRIPT_DIR=$(follow_links "$(dirname -- "${BASH_SOURCE[0]}")")
SRC_DIR="$(cd "$SCRIPT_DIR/../.."; pwd -P)"
YAPF_DIR="$(cd "$SRC_DIR/flutter/third_party/yapf"; pwd -P)"
PYTHONPATH="$YAPF_DIR" python3 "$YAPF_DIR/yapf" "$@"
| engine/tools/yapf.sh/0 | {
"file_path": "engine/tools/yapf.sh",
"repo_id": "engine",
"token_count": 438
} | 586 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_VULKAN_VULKAN_COMMAND_BUFFER_H_
#define FLUTTER_VULKAN_VULKAN_COMMAND_BUFFER_H_
#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/macros.h"
#include "flutter/vulkan/procs/vulkan_handle.h"
namespace vulkan {
class VulkanProcTable;
class VulkanCommandBuffer {
public:
VulkanCommandBuffer(const VulkanProcTable& vk,
const VulkanHandle<VkDevice>& device,
const VulkanHandle<VkCommandPool>& pool);
~VulkanCommandBuffer();
bool IsValid() const;
VkCommandBuffer Handle() const;
[[nodiscard]] bool Begin() const;
[[nodiscard]] bool End() const;
[[nodiscard]] bool InsertPipelineBarrier(
VkPipelineStageFlagBits src_stage_flags,
VkPipelineStageFlagBits dest_stage_flags,
uint32_t /* mask of VkDependencyFlagBits */ dependency_flags,
uint32_t memory_barrier_count,
const VkMemoryBarrier* memory_barriers,
uint32_t buffer_memory_barrier_count,
const VkBufferMemoryBarrier* buffer_memory_barriers,
uint32_t image_memory_barrier_count,
const VkImageMemoryBarrier* image_memory_barriers) const;
private:
const VulkanProcTable& vk_;
const VulkanHandle<VkDevice>& device_;
const VulkanHandle<VkCommandPool>& pool_;
VulkanHandle<VkCommandBuffer> handle_;
bool valid_;
FML_DISALLOW_COPY_AND_ASSIGN(VulkanCommandBuffer);
};
} // namespace vulkan
#endif // FLUTTER_VULKAN_VULKAN_COMMAND_BUFFER_H_
| engine/vulkan/vulkan_command_buffer.h/0 | {
"file_path": "engine/vulkan/vulkan_command_buffer.h",
"repo_id": "engine",
"token_count": 631
} | 587 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_VULKAN_VULKAN_SURFACE_H_
#define FLUTTER_VULKAN_VULKAN_SURFACE_H_
#include "flutter/fml/macros.h"
#include "flutter/vulkan/procs/vulkan_handle.h"
#include "third_party/skia/include/core/SkSize.h"
namespace vulkan {
class VulkanProcTable;
class VulkanApplication;
class VulkanNativeSurface;
class VulkanSurface {
public:
VulkanSurface(VulkanProcTable& vk,
VulkanApplication& application,
std::unique_ptr<VulkanNativeSurface> native_surface);
~VulkanSurface();
bool IsValid() const;
/// Returns the current size of the surface or (0, 0) if invalid.
SkISize GetSize() const;
const VulkanHandle<VkSurfaceKHR>& Handle() const;
const VulkanNativeSurface& GetNativeSurface() const;
private:
VulkanProcTable& vk;
VulkanApplication& application_;
std::unique_ptr<VulkanNativeSurface> native_surface_;
VulkanHandle<VkSurfaceKHR> surface_;
bool valid_;
FML_DISALLOW_COPY_AND_ASSIGN(VulkanSurface);
};
} // namespace vulkan
#endif // FLUTTER_VULKAN_VULKAN_SURFACE_H_
| engine/vulkan/vulkan_surface.h/0 | {
"file_path": "engine/vulkan/vulkan_surface.h",
"repo_id": "engine",
"token_count": 447
} | 588 |
// 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:test/test.dart';
import '../sdk_rewriter.dart';
void main() {
test('handles exports correctly in the engine library file', () {
const String source = '''
// Comment 1
library engine;
// Comment 2
export 'engine/file1.dart';
export'engine/file2.dart';
export 'engine/file3.dart';
''';
const String expected = '''
// Comment 1
@JS()
library dart._engine;
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;
import 'dart:extra';
// Comment 2
part 'engine/file1.dart';
part 'engine/file2.dart';
part 'engine/file3.dart';
''';
final String result = processSource(
source,
(String source) => validateApiFile(
'/path/to/lib/web_ui/lib/src/engine.dart',
source,
'engine'),
generateApiFilePatterns('engine', false, <String>["import 'dart:extra';"]),
);
expect(result, expected);
});
test('underscore is not added to library name for public library in API file', () {
const String source = '''
library engine;
''';
const String expected = '''
@JS()
library dart.engine;
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;
import 'dart:extra';
''';
final String result = processSource(
source,
(String source) => validateApiFile(
'/path/to/lib/web_ui/lib/src/engine.dart',
source,
'engine'),
generateApiFilePatterns('engine', true, <String>["import 'dart:extra';"]),
);
expect(result, expected);
});
test('complains about non-compliant engine.dart file', () {
const String source = '''
library engine;
import 'dart:something';
export 'engine/file1.dart';
export 'engine/file3.dart';
''';
Object? caught;
try {
processSource(
source,
(String source) => validateApiFile(
'/path/to/lib/web_ui/lib/src/engine.dart',
source,
'engine'),
generateApiFilePatterns('engine', false, <String>[]),
);
} catch(error) {
caught = error;
}
expect(caught, isA<Exception>());
expect(
'$caught',
'Exception: on line 3: unexpected code in /path/to/lib/web_ui/lib/src/engine.dart. '
'This file may only contain comments and exports. Found:\n'
"import 'dart:something';",
);
});
test('removes imports/exports from engine files', () {
const String source = '''
import 'package:some_package/some_package.dart';
import 'package:some_package/some_package/foo.dart';
import 'package:some_package/some_package' as some_package;
import 'file1.dart';
import'file2.dart';
import 'file3.dart';
export 'file4.dart';
export'file5.dart';
export 'file6.dart';
void printSomething() {
print('something');
}
''';
const String expected = '''
part of dart._engine;
void printSomething() {
print('something');
}
''';
final String result = processSource(
source,
(String source) => preprocessPartFile(source, 'engine'),
generatePartsPatterns('engine', false),
);
expect(result, expected);
});
test('gets correct extra imports', () {
// Root libraries.
expect(getExtraImportsForLibrary('engine'), <String>[
"import 'dart:_skwasm_stub' if (dart.library.ffi) 'dart:_skwasm_impl';",
"import 'dart:ui_web' as ui_web;",
"import 'dart:_web_unicode';",
"import 'dart:_web_test_fonts';",
"import 'dart:_web_locale_keymap' as locale_keymap;",
]);
expect(getExtraImportsForLibrary('skwasm_stub'), <String>[
"import 'dart:ui_web' as ui_web;",
"import 'dart:_engine';",
"import 'dart:_web_unicode';",
"import 'dart:_web_test_fonts';",
"import 'dart:_web_locale_keymap' as locale_keymap;",
]);
expect(getExtraImportsForLibrary('skwasm_impl'), <String>[
"import 'dart:ui_web' as ui_web;",
"import 'dart:_engine';",
"import 'dart:_web_unicode';",
"import 'dart:_web_test_fonts';",
"import 'dart:_web_locale_keymap' as locale_keymap;",
"import 'dart:_wasm';",
]);
// Other libraries (should not have extra imports).
expect(getExtraImportsForLibrary('web_unicode'), isEmpty);
expect(getExtraImportsForLibrary('web_test_fonts'), isEmpty);
expect(getExtraImportsForLibrary('web_locale_keymap'), isEmpty);
});
}
| engine/web_sdk/test/sdk_rewriter_test.dart/0 | {
"file_path": "engine/web_sdk/test/sdk_rewriter_test.dart",
"repo_id": "engine",
"token_count": 1991
} | 589 |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="17" />
</component>
</project> | flutter-intellij/.idea/compiler.xml/0 | {
"file_path": "flutter-intellij/.idea/compiler.xml",
"repo_id": "flutter-intellij",
"token_count": 55
} | 590 |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
<item class="com.intellij.openapi.ui.TextFieldWithBrowseButton" icon="/com/intellij/uiDesigner/icons/panel.png" removable="true" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="0" />
</item>
</group>
</component>
</project> | flutter-intellij/.idea/uiDesigner.xml/0 | {
"file_path": "flutter-intellij/.idea/uiDesigner.xml",
"repo_id": "flutter-intellij",
"token_count": 3701
} | 591 |
# Flutter Plugin Integration Testing
On the advice of Jetbrains engineers, we have switched the integration testing module to be
a Gradle-built plugin. This allows the tests to run from anywhere; previously they only ran
when copied into the GUI testing framework module. Thanks to karashevich@jetbrains for
creating the plugin.
## Usage
1. Prepare the flutter-intellij plugin. Run `bin/plugin build` in a terminal. If you do not
want to wait for all the distros to be build, consult product-matrix.json to find which version
sets isTestTarget to true. Then you can use it as the value of the -o option to the build command.
For example: `bin/plugin build -o3.5`
2. Check that the buildPlugin task works normally. Open the Gradle
tool view: View -> Tool Windows -> Gradle. Expamd `Tasks`, then expand `intellij`.
Select `buildPliugin`, right-click and choose `Run ...`. This may take a while initially
as it may have to download some files.
3. For now, we use the built-in terminal to run tests. Open the terminal emulator in IntelliJ, then:
```bash
cd flutter-gui-tests
./gradlew -Dtest.single=TestSuite clean test
```
## Editing
Currently, the tests need to be edited in a minimal flutter-intellij project. Open the flutter-intellij
project in IntelliJ 2019.1 for stand-alone editing, without Dart or IntelliJ sources (see CONTRIBUTING.md).
If you want to test recent changes be sure to repeat Step 1 in Usage so you are testing the latest build.
## Notes
If the buildPlugin task fails, check for a new version of the Gradle plugin with id org.jetbrains.intellij.
This is likely to be needed if a new version of IntelliJ is downloaded automatically.
On a Mac, you must grant permission to control your computer to the JVM. Open System Preferences then select
Security & Privacy. Unlock it and click the + button. Navigate to the JVM used to run the integration tests
and add it to the list. One way to find the JVM is to run the tests, let it hang, and search the output of
`ps xa` for LATEST-EAP. If that points to a JVM in a .gradle directory (which the Mac will not allow you to
navigate to) you can hard link to it in some random directory then add that file.
If you get errors from Gradle sync failing try using Java 11 instead of Java 8 in the project that manages
the test plugin. For example, create an IntelliJ platform plugin SDK in Project Structure and point its base
SDK to a Java 11 installation. Then set that as the default SDK for the project. | flutter-intellij/flutter-gui-tests/README.md/0 | {
"file_path": "flutter-intellij/flutter-gui-tests/README.md",
"repo_id": "flutter-intellij",
"token_count": 658
} | 592 |
/*
* 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.execution.ui.layout.impl.JBRunnerTabs
import com.intellij.testGuiFramework.fixtures.JComponentFixture
import com.intellij.testGuiFramework.impl.GuiRobotHolder
import com.intellij.ui.content.Content
import com.intellij.ui.tabs.TabInfo
import com.intellij.ui.tabs.newImpl.TabLabel
import org.fest.swing.core.Robot
fun showTab(index: Int, contents: Array<Content>) {
val tabs: JBRunnerTabs = contents[0].component.components[0] as JBRunnerTabs
val info: TabInfo = tabs.getTabAt(index)
val label = tabs.getTabLabel(info)
TabLabelFixture(GuiRobotHolder.robot, label).click()
}
// A clickable fixture for the three tabs in the inspector: Widgets, Render Tree, and Performance.
class TabLabelFixture(robot: Robot, target: TabLabel)
: JComponentFixture<TabLabelFixture, TabLabel>(TabLabelFixture::class.java, robot, target)
| flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/fixtures/Utils.kt/0 | {
"file_path": "flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/fixtures/Utils.kt",
"repo_id": "flutter-intellij",
"token_count": 349
} | 593 |
/*
* 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.actions;
import com.intellij.execution.*;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionEnvironmentBuilder;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.util.ThreeState;
import com.intellij.util.messages.MessageBusConnection;
import io.flutter.FlutterConstants;
import io.flutter.FlutterInitializer;
import io.flutter.bazel.Workspace;
import io.flutter.pub.PubRoot;
import io.flutter.run.FlutterLaunchMode;
import io.flutter.run.SdkAttachConfig;
import io.flutter.run.SdkRunConfig;
import io.flutter.run.bazel.BazelAttachConfig;
import io.flutter.run.bazel.BazelRunConfig;
import io.flutter.sdk.FlutterSdk;
import io.flutter.sdk.FlutterSdkUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
import java.util.function.Consumer;
public class AttachDebuggerAction extends FlutterSdkAction {
// Is 'flutter attach' running for a project?
// The three states are true, false, and non-existent (null).
// true = run automatically via the debug listener in FlutterStudioStartupActivity
// false = run from button press here
// null = no attach process is running
// The button is still required because there may be multiple Flutter run configs.
public static final Key<ThreeState> ATTACH_IS_ACTIVE = new Key<>("attach-is-active");
public @NotNull ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.BGT;
}
@Override
public void startCommand(@NotNull Project project, @NotNull FlutterSdk sdk, @Nullable PubRoot root, @NotNull DataContext context) {
// NOTE: When making changes here, consider making similar changes to RunFlutterAction.
FlutterInitializer.sendAnalyticsAction(this);
RunConfiguration configuration = findRunConfig(project);
if (configuration == null) {
final RunnerAndConfigurationSettings settings = RunManagerEx.getInstanceEx(project).getSelectedConfiguration();
if (settings == null) {
showSelectConfigDialog();
return;
}
configuration = settings.getConfiguration();
if (!(configuration instanceof SdkRunConfig)) {
if (project.isDefault() || !FlutterSdkUtil.hasFlutterModules(project)) {
return;
}
showSelectConfigDialog();
return;
}
}
final SdkAttachConfig sdkRunConfig = new SdkAttachConfig((SdkRunConfig)configuration);
sdkRunConfig.pubRoot = root;
final Executor executor = RunFlutterAction.getExecutor(ToolWindowId.DEBUG);
if (executor == null) {
return;
}
final ExecutionEnvironmentBuilder builder = ExecutionEnvironmentBuilder.create(executor, sdkRunConfig);
final ExecutionEnvironment env = builder.activeTarget().dataContext(context).build();
FlutterLaunchMode.addToEnvironment(env, FlutterLaunchMode.DEBUG);
if (project.getUserData(ATTACH_IS_ACTIVE) == null) {
project.putUserData(ATTACH_IS_ACTIVE, ThreeState.fromBoolean(false));
onAttachTermination(project, (p) -> p.putUserData(ATTACH_IS_ACTIVE, null));
}
ProgramRunnerUtil.executeConfiguration(env, false, true);
}
public void startCommandInBazelContext(@NotNull Project project, @NotNull Workspace workspace, @NotNull AnActionEvent event) {
FlutterInitializer.sendAnalyticsAction(this);
RunConfiguration configuration = findRunConfig(project);
if (configuration == null) {
final RunnerAndConfigurationSettings settings = RunManagerEx.getInstanceEx(project).getSelectedConfiguration();
if (settings == null) {
showSelectConfigDialog();
return;
}
configuration = settings.getConfiguration();
if (!(configuration instanceof BazelRunConfig)) {
return;
}
}
final BazelAttachConfig sdkRunConfig = new BazelAttachConfig((BazelRunConfig)configuration);
final Executor executor = RunFlutterAction.getExecutor(ToolWindowId.DEBUG);
if (executor == null) {
return;
}
final ExecutionEnvironmentBuilder builder = ExecutionEnvironmentBuilder.create(executor, sdkRunConfig);
final ExecutionEnvironment env = builder.activeTarget().dataContext(event.getDataContext()).build();
FlutterLaunchMode.addToEnvironment(env, FlutterLaunchMode.DEBUG);
ProgramRunnerUtil.executeConfiguration(env, false, true);
}
public boolean enableActionInBazelContext() {
return true;
}
@Override
public void update(AnActionEvent e) {
final Project project = e.getProject();
if (project == null || project.isDefault()) {
super.update(e);
return;
}
if (!FlutterSdkUtil.hasFlutterModules(project)) {
// Hide this button in Android projects.
e.getPresentation().setVisible(false);
return;
}
RunConfiguration configuration = findRunConfig(project);
boolean enabled;
if (configuration == null) {
final RunnerAndConfigurationSettings settings = RunManagerEx.getInstanceEx(project).getSelectedConfiguration();
if (settings == null) {
enabled = false;
}
else {
configuration = settings.getConfiguration();
enabled = configuration instanceof SdkRunConfig || configuration instanceof BazelRunConfig;
}
}
else {
enabled = true;
}
if (enabled && (project.getUserData(ATTACH_IS_ACTIVE) != null)) {
enabled = false;
}
e.getPresentation().setVisible(true);
e.getPresentation().setEnabled(enabled);
}
@Nullable
public static RunConfiguration findRunConfig(Project project) {
// Look for a Flutter run config. If exactly one is found then return it otherwise return null.
final RunManagerEx mgr = RunManagerEx.getInstanceEx(project);
final List<RunConfiguration> configs = mgr.getAllConfigurationsList();
int count = 0;
RunConfiguration sdkConfig = null;
for (RunConfiguration config : configs) {
if (config instanceof SdkRunConfig) {
count += 1;
sdkConfig = config;
}
}
return count == 1 ? sdkConfig : null;
}
private static void onAttachTermination(@NotNull Project project, @NotNull Consumer<Project> runner) {
final MessageBusConnection connection = project.getMessageBus().connect();
// Need an ExecutionListener to clean up project-scoped state when the Stop button is clicked.
connection.subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() {
Object handler;
@Override
public void processStarted(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler) {
if (env.getRunProfile() instanceof SdkAttachConfig) {
this.handler = handler;
}
}
@Override
public void processTerminated(@NotNull String executorId,
@NotNull ExecutionEnvironment env,
@NotNull ProcessHandler handler,
int exitCode) {
if (this.handler == handler) {
runner.accept(project);
connection.disconnect();
}
}
});
}
private static void showSelectConfigDialog() {
ApplicationManager.getApplication().invokeLater(() -> new SelectConfigDialog().show(), ModalityState.NON_MODAL);
}
private static class SelectConfigDialog extends DialogWrapper {
private JPanel myPanel;
private JTextPane myTextPane;
SelectConfigDialog() {
super(null, false, false);
setTitle("Run Configuration");
myPanel = new JPanel();
myTextPane = new JTextPane();
Messages.installHyperlinkSupport(myTextPane);
final String selectConfig = "<html><body>" +
"<p>The run configuration for the Flutter module must be selected." +
"<p>Please change the run configuration to the one created when the<br>" +
"module was created. See <a href=\"" +
FlutterConstants.URL_RUN_AND_DEBUG +
"\">the Flutter documentation</a> for more information.</body></html>";
myTextPane.setText(selectConfig);
myPanel.add(myTextPane);
init();
//noinspection ConstantConditions
getButton(getCancelAction()).setVisible(false);
}
@Nullable
@Override
protected JComponent createCenterPanel() {
return myPanel;
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/AttachDebuggerAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/AttachDebuggerAction.java",
"repo_id": "flutter-intellij",
"token_count": 3206
} | 594 |
/*
* Copyright 2016 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.actions;
import com.intellij.ide.browsers.BrowserLauncher;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import io.flutter.FlutterInitializer;
import org.jetbrains.annotations.NotNull;
public class FlutterSubmitFeedback extends DumbAwareAction {
@Override
public void actionPerformed(@NotNull final AnActionEvent e) {
FlutterInitializer.sendAnalyticsAction(this);
final String url = "https://github.com/flutter/flutter-intellij/issues/new";
BrowserLauncher.getInstance().browse(url, null);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterSubmitFeedback.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterSubmitFeedback.java",
"repo_id": "flutter-intellij",
"token_count": 241
} | 595 |
/*
* Copyright 2016 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.actions;
import com.intellij.openapi.actionSystem.ActionPlaces;
/**
* A keystroke or tool-bar invoked {@link RestartFlutterApp} action.
*/
public class RestartFlutterAppRetarget extends FlutterRetargetAppAction {
public RestartFlutterAppRetarget() {
super(RestartFlutterApp.ID,
RestartFlutterApp.TEXT,
RestartFlutterApp.DESCRIPTION,
ActionPlaces.MAIN_TOOLBAR,
ActionPlaces.NAVIGATION_BAR_TOOLBAR,
ActionPlaces.MAIN_MENU);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/RestartFlutterAppRetarget.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/RestartFlutterAppRetarget.java",
"repo_id": "flutter-intellij",
"token_count": 254
} | 596 |
/*
* 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.android;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
public class IntellijGradleSyncProvider implements GradleSyncProvider {
@Override
public void scheduleSync(@NotNull Project project) {
// TODO(messick): Restore the next line after Android Q sources are published; it cannot be compiled until then.
//GradleSyncInvoker.getInstance().requestProjectSync(project, GradleSyncInvoker.Request.userRequest());
}
}
| flutter-intellij/flutter-idea/src/io/flutter/android/IntellijGradleSyncProvider.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/android/IntellijGradleSyncProvider.java",
"repo_id": "flutter-intellij",
"token_count": 184
} | 597 |
/*
* Copyright 2021 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.devtools;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.sdk.FlutterSdkUtil;
import io.flutter.sdk.FlutterSdkVersion;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class DevToolsUrl {
private String devtoolsHost;
private int devtoolsPort;
private String vmServiceUri;
private String page;
private boolean embed;
public String colorHexCode;
public String widgetId;
public Float fontSize;
private final FlutterSdkVersion flutterSdkVersion;
private final FlutterSdkUtil sdkUtil;
private final boolean canUseDevToolsPathUrl;
public final DevToolsIdeFeature ideFeature;
public DevToolsUrl(String devtoolsHost,
int devtoolsPort,
String vmServiceUri,
String page,
boolean embed,
String colorHexCode,
Float fontSize,
@Nullable FlutterSdkVersion flutterSdkVersion,
WorkspaceCache workspaceCache,
DevToolsIdeFeature ideFeature) {
this(devtoolsHost, devtoolsPort, vmServiceUri, page, embed, colorHexCode, fontSize, flutterSdkVersion, workspaceCache, ideFeature, new FlutterSdkUtil());
}
public DevToolsUrl(String devtoolsHost,
int devtoolsPort,
String vmServiceUri,
String page,
boolean embed,
String colorHexCode,
Float fontSize,
FlutterSdkVersion flutterSdkVersion,
WorkspaceCache workspaceCache,
DevToolsIdeFeature ideFeature,
FlutterSdkUtil flutterSdkUtil) {
this.devtoolsHost = devtoolsHost;
this.devtoolsPort = devtoolsPort;
this.vmServiceUri = vmServiceUri;
this.page = page;
this.embed = embed;
this.colorHexCode = colorHexCode;
this.fontSize = fontSize;
this.flutterSdkVersion = flutterSdkVersion;
this.ideFeature = ideFeature;
this.sdkUtil = flutterSdkUtil;
if (workspaceCache != null && workspaceCache.isBazel()) {
this.canUseDevToolsPathUrl = true;
} else if (flutterSdkVersion != null) {
this.canUseDevToolsPathUrl = flutterSdkVersion.canUseDevToolsPathUrls();
} else {
this.canUseDevToolsPathUrl = false;
}
}
@NotNull
public String getUrlString() {
final List<String> params = new ArrayList<>();
params.add("ide=" + sdkUtil.getFlutterHostEnvValue());
if (page != null && !this.canUseDevToolsPathUrl) {
params.add("page=" + page);
}
if (colorHexCode != null) {
params.add("backgroundColor=" + colorHexCode);
}
if (embed) {
params.add("embed=true");
}
if (fontSize != null) {
params.add("fontSize=" + fontSize);
}
if (ideFeature != null) {
params.add("ideFeature=" + ideFeature.value);
}
if (vmServiceUri != null) {
final String urlParam = URLEncoder.encode(vmServiceUri, StandardCharsets.UTF_8);
params.add("uri=" + urlParam);
}
if (widgetId != null) {
params.add("inspectorRef=" + widgetId);
}
if (this.canUseDevToolsPathUrl) {
return "http://" + devtoolsHost + ":" + devtoolsPort + "/" + ( page != null ? page : "" ) + "?" + String.join("&", params);
} else {
return "http://" + devtoolsHost + ":" + devtoolsPort + "/#/?" + String.join("&", params);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/devtools/DevToolsUrl.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/devtools/DevToolsUrl.java",
"repo_id": "flutter-intellij",
"token_count": 1603
} | 598 |
/*
* Copyright 2021 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.editor;
import com.intellij.codeInsight.daemon.GutterName;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.LineMarkerProviderDescriptor;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.source.tree.AstBufferUtil;
import com.jetbrains.lang.dart.DartTokenTypes;
import com.jetbrains.lang.dart.psi.*;
import com.jetbrains.lang.dart.psi.impl.DartCallExpressionImpl;
import com.jetbrains.lang.dart.util.DartPsiImplUtil;
import com.jetbrains.lang.dart.util.DartResolveUtil;
import gnu.trove.THashSet;
import info.debatty.java.stringsimilarity.JaroWinkler;
import io.flutter.FlutterBundle;
import io.flutter.sdk.FlutterSdk;
import io.flutter.sdk.FlutterSdkUtil;
import io.flutter.utils.IconPreviewGenerator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.VisibleForTesting;
import javax.swing.*;
import java.util.*;
import static io.flutter.dart.DartPsiUtil.*;
// Style note: Normally we put control flow changing statements on a separate line in a block.
// When working with PSI elements nearly everything can return null. There are a lot of null checks
// that could return null, but they seldom trigger, so the return is on the same line as the if statement.
public class FlutterIconLineMarkerProvider extends LineMarkerProviderDescriptor {
public static final Map<String, Set<String>> KnownPaths = new HashMap<>();
private static final Map<String, String> BuiltInPaths = new HashMap<>();
private static final Logger LOG = Logger.getInstance(FlutterIconLineMarkerProvider.class);
private static final String MaterialRelativeAssetPath = "/bin/cache/artifacts/material_fonts/MaterialIcons-Regular.otf";
private static final String MaterialRelativeIconsPath = "/packages/flutter/lib/src/material/icons.dart";
private static final String CupertinoRelativeAssetPath = "/assets/CupertinoIcons.ttf";
private static final String CupertinoRelativeIconsPath = "/packages/flutter/lib/src/cupertino/icons.dart";
static {
initialize();
}
public static void initialize() {
KnownPaths.clear();
KnownPaths.put("Icons", new THashSet<>(Collections.singleton("packages/flutter/lib/src/material")));
KnownPaths.put("IconData", new THashSet<>(Collections.singleton("packages/flutter/lib/src/widgets")));
KnownPaths.put("CupertinoIcons", new THashSet<>(Collections.singleton("packages/flutter/lib/src/cupertino")));
BuiltInPaths.clear();
BuiltInPaths.put("Icons", MaterialRelativeIconsPath);
BuiltInPaths.put("IconData", MaterialRelativeIconsPath);
BuiltInPaths.put("CupertinoIcons", CupertinoRelativeIconsPath);
}
@Nullable("null means disabled")
@Override
public @GutterName String getName() {
return FlutterBundle.message("flutter.icon.preview.title");
}
@Override
@Nullable
public LineMarkerInfo<?> getLineMarkerInfo(@NotNull PsiElement element) {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(element.getProject());
return sdk == null ? null : getLineMarkerInfo(element, sdk);
}
@VisibleForTesting
@Nullable
LineMarkerInfo<?> getLineMarkerInfo(@NotNull PsiElement element, @NotNull FlutterSdk sdk) {
if ((element.getNode() != null ? element.getNode().getElementType() : null) != DartTokenTypes.IDENTIFIER) return null;
final String name = element.getText();
assert name != null;
if (!KnownPaths.containsKey(name)) return null;
final PsiElement refExpr = topmostReferenceExpression(element);
if (refExpr == null) return null;
PsiElement parent = refExpr.getParent();
if (parent == null) return null;
String knownPath = null;
assert ApplicationManager.getApplication() != null;
if (!ApplicationManager.getApplication().isUnitTestMode()) {
// Resolve the class reference and check that it is one of the known, cached classes.
final PsiElement symbol = "IconData".equals(name) ? refExpr : refExpr.getFirstChild();
if (!(symbol instanceof DartReference)) return null;
final PsiElement result = ((DartReference)symbol).resolve();
if (result == null) return null;
assert result.getContainingFile() != null;
final List<VirtualFile> library = DartResolveUtil.findLibrary(result.getContainingFile());
for (VirtualFile file : library) {
assert file != null;
final VirtualFile dir = file.getParent();
assert dir != null;
if (dir.isInLocalFileSystem()) {
final String path = dir.getPath();
String trimmedPath = path;
if (!path.endsWith("lib")) {
final int index = path.indexOf("lib");
if (index >= 0) {
trimmedPath = path.substring(0, index + 3);
}
}
final Set<String> knownPaths = KnownPaths.get(name);
assert knownPaths != null; // Due to guard clause above.
if (knownPaths.contains(path) || knownPaths.contains(trimmedPath)) {
knownPath = file.getPath();
break;
}
for (String aPath : knownPaths) {
assert aPath != null;
if (path.endsWith(aPath) || aPath.contains(path) || trimmedPath.endsWith(aPath) || aPath.contains(trimmedPath)) {
knownPath = file.getPath();
break;
}
}
}
}
if (knownPath == null) return null;
}
final ASTNode parentNode = parent.getNode();
assert parentNode != null;
if (parentNode.getElementType() == DartTokenTypes.CALL_EXPRESSION) {
// Check font family and package
final DartArguments arguments = DartPsiImplUtil.getArguments((DartCallExpression)parent);
if (arguments == null) return null;
final String family = getValueOfNamedArgument(arguments, "fontFamily");
final PsiElement fontPackage = getNamedArgumentExpression(arguments, "fontPackage");
final String argument = getValueOfPositionalArgument(arguments, 0);
if (argument == null) return null;
final Icon icon = getIconFromPackage(fontPackage, family, argument, element.getProject(), sdk, parent);
if (icon != null) {
return createLineMarker(element, icon);
}
}
else if (parentNode.getElementType() == DartTokenTypes.SIMPLE_TYPE) {
parent = getNewExprFromType(parent);
if (parent == null) return null;
final DartArguments arguments = DartPsiImplUtil.getArguments((DartNewExpression)parent);
if (arguments == null) return null;
final String family = getValueOfNamedArgument(arguments, "fontFamily");
final PsiElement fontPackage = getNamedArgumentExpression(arguments, "fontPackage");
final String argument = getValueOfPositionalArgument(arguments, 0);
if (argument == null) return null;
final Icon icon = getIconFromPackage(fontPackage, family, argument, element.getProject(), sdk, parent);
if (icon != null) {
return createLineMarker(element, icon);
}
}
else {
final PsiElement idNode = refExpr.getFirstChild();
if (idNode == null) return null;
if (name.equals(idNode.getText())) {
final PsiElement selectorNode = refExpr.getLastChild();
if (selectorNode == null) return null;
assert selectorNode.getNode() != null;
final String selector = AstBufferUtil.getTextSkippingWhitespaceComments(selectorNode.getNode());
final Icon icon;
if (name.equals("Icons")) {
if (sdk.getVersion().canUseDistributedIcons()) {
icon = FlutterMaterialIcons.getIconForName(selector);
}
else {
final IconInfo iconDef = findStandardDefinition(name, selector, element.getProject(), knownPath, sdk);
if (iconDef == null) return null;
// <flutter-sdk>/bin/cache/artifacts/material_fonts/MaterialIcons-Regular.otf
icon = findStandardIconFromDef(name, iconDef, sdk.getHomePath() + MaterialRelativeAssetPath);
}
}
else if (name.equals("CupertinoIcons")) {
if (sdk.getVersion().canUseDistributedIcons()) {
icon = FlutterCupertinoIcons.getIconForName(selector);
}
else {
final IconInfo iconDef = findStandardDefinition(name, selector, element.getProject(), knownPath, sdk);
if (iconDef == null) return null;
final String path = FlutterSdkUtil.getPathToCupertinoIconsPackage(element.getProject());
// <pub_cache>/hosted/pub.dartlang.org/cupertino_icons-v.m.n/assets/CupertinoIcons.ttf
icon = findStandardIconFromDef(name, iconDef, path + CupertinoRelativeAssetPath);
}
}
else {
// Note: I want to keep this code until I'm sure we won't use pubspec.yaml.
//final DartComponent result = DartResolveUtil.findReferenceAndComponentTarget(idNode);
//if (result != null) {
// final VirtualFile map = IconPreviewGenerator.findAssetMapFor(result);
// if (map == null) {
// return null;
// }
// final FileViewProvider provider = PsiManager.getInstance(result.getProject()).findViewProvider(map);
// if (provider != null) {
// final PsiFile psi = provider.getPsi(YAMLLanguage.INSTANCE);
// final YamlAssetMapVisitor visitor = new YamlAssetMapVisitor();
// psi.accept(visitor);
// final HashMap<String, String> assetMap = visitor.assetMap;
// }
//}
final PsiElement iconElement = refExpr.getLastChild();
if (iconElement == null) return null; // TODO check for instance creation with codepoint
final String iconName = iconElement.getText();
assert iconName != null;
assert knownPath != null;
final IconInfo iconDef = findDefinition(name, iconName, element.getProject(), knownPath);
if (iconDef == null) return null;
icon = findIconFromDef(name, iconDef, knownPath);
}
if (icon != null) {
return createLineMarker(element, icon);
}
}
}
return null;
}
@Nullable
private IconInfo findStandardDefinition(@NotNull String className,
@NotNull String iconName,
@NotNull Project project,
@Nullable String path,
@NotNull FlutterSdk sdk) {
if (path != null) {
return findDefinition(className, iconName, project, path);
}
assert Objects.requireNonNull(ApplicationManager.getApplication()).isUnitTestMode();
return findDefinition(className, iconName, project, sdk.getHomePath() + BuiltInPaths.get(className));
}
@Nullable
private Icon findStandardIconFromDef(@NotNull String name, @NotNull IconInfo iconDef, @NotNull String path) {
assert LocalFileSystem.getInstance() != null;
final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path);
if (virtualFile == null) return null;
final IconPreviewGenerator generator = new IconPreviewGenerator(virtualFile.getPath());
return generator.convert(iconDef.codepoint);
}
// Note: package flutter_icons is not currently supported because it takes forever to analyze it.
@Nullable
private Icon getIconFromPackage(@Nullable PsiElement aPackage, @Nullable String family, @NotNull String argument,
@NotNull Project project, @NotNull FlutterSdk sdk, @NotNull PsiElement parent) {
final int code;
try {
code = parseLiteralNumber(argument);
}
catch (NumberFormatException ignored) {
return null;
}
if (family == null) {
family = "MaterialIcons";
}
else if (family.isEmpty()) {
// We have to work harder to determine the family. It was probably specified as a constant value, not a string literal.
final PsiElement parent2 = parent.getParent();
if (parent2 == null) return null;
final PsiElement varDecl = parent2.getParent();
if (varDecl == null) return null;
final ASTNode node = varDecl.getNode();
if (node == null) return null;
final ASTNode firstChild = node.getFirstChildNode();
if (firstChild == null) return null;
final ASTNode lastChild = firstChild.getLastChildNode();
if (lastChild == null) return null;
final String iconName = lastChild.getFirstChildNode().getText();
final FlutterIconLineMarkerProvider.IconInfo iconDef =
findDefinition("", iconName, project, parent.getContainingFile().getVirtualFile().getPath());
if (iconDef == null) return null;
family = iconDef.familyName;
if (family == null) return null;
aPackage = null; // TODO Allow package to be specified.
}
if (aPackage == null) {
// Looking for IconData with no package -- package specification not currently supported.
final String relativeAssetPath = family.equals("MaterialIcons") ? MaterialRelativeAssetPath : CupertinoRelativeAssetPath;
final String base = getBasePathForFamily(family, sdk, project);
if (base == null) return null;
final IconPreviewGenerator generator = new IconPreviewGenerator(base + relativeAssetPath);
return generator.convert(code);
}
return null;
}
@Nullable
private String getBasePathForFamily(@NotNull String family, @NotNull FlutterSdk sdk, @NotNull Project project) {
if (family.equals("MaterialIcons")) {
return sdk.getHomePath();
}
// TODO Generalize this to work with other icon packages from pub.
return FlutterSdkUtil.getPathToCupertinoIconsPackage(project);
}
@Nullable
private LineMarkerInfo<PsiElement> createLineMarker(@Nullable PsiElement element, @NotNull Icon icon) {
if (element == null) return null;
assert element.getTextRange() != null;
//noinspection MissingRecentApi
return new LineMarkerInfo<>(element, element.getTextRange(), icon, null, null,
GutterIconRenderer.Alignment.LEFT, () -> "");
}
@Nullable
private IconInfo findDefinition(@NotNull String className, @NotNull String iconName, @NotNull Project project, @NotNull String path) {
assert LocalFileSystem.getInstance() != null;
final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path);
if (virtualFile == null) return null;
final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
if (psiFile == null) {
return null;
}
final IconInfoVisitor visitor = new IconInfoVisitor(iconName);
psiFile.accept(visitor);
return visitor.info;
}
@Nullable
private Icon findIconFromDef(@NotNull String iconClassName, @NotNull IconInfo iconDef, @NotNull String path) {
assert LocalFileSystem.getInstance() != null;
final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path);
if (virtualFile == null) return null;
VirtualFile parent = virtualFile;
while (parent != null && !parent.getName().equals("lib")) {
parent = parent.getParent();
}
if (parent != null) parent = parent.getParent(); // We have to search the entire project.
if (parent == null) {
return null;
}
final List<VirtualFile> ttfFiles = new ArrayList<>();
VfsUtilCore.visitChildrenRecursively(parent, new VirtualFileVisitor<Void>() {
@Override
public boolean visitFile(@NotNull VirtualFile file) {
final String ext = file.getExtension();
if ("ttf".equals(ext)) {
ttfFiles.add(file);
return false;
}
else {
return super.visitFile(file);
}
}
});
double match = -1;
final String family = iconDef.familyName;
VirtualFile bestFileMatch = null;
if (family != null) {
for (VirtualFile file : ttfFiles) {
assert file != null;
final double n = findPattern(file.getNameWithoutExtension(), family);
if (n > match) {
match = n;
bestFileMatch = file;
}
}
} // If the family is null we could do a search for font files named similar to the package.
if (bestFileMatch != null) {
final IconPreviewGenerator generator = new IconPreviewGenerator(bestFileMatch.getPath());
final Icon icon = generator.convert(iconDef.codepoint);
if (icon != null) return icon;
}
for (VirtualFile file : ttfFiles) {
assert file != null;
final IconPreviewGenerator generator = new IconPreviewGenerator(file.getPath());
final Icon icon = generator.convert(iconDef.codepoint);
if (icon != null) return icon;
}
return null;
}
public double findPattern(@NotNull String t, @NotNull String p) {
// This is from https://github.com/tdebatty/java-string-similarity
// It's MIT license file is: https://github.com/tdebatty/java-string-similarity/blob/master/LICENSE.md
final JaroWinkler jw = new JaroWinkler();
return jw.similarity(t, p);
}
static class IconInfo {
final @NotNull String iconName;
final @NotNull String className;
final @Nullable String familyName;
final @NotNull String codepoint;
IconInfo(@NotNull String className, @NotNull String iconName, @Nullable String familyName, @NotNull String codepoint) {
this.className = className;
this.iconName = iconName;
this.familyName = familyName;
this.codepoint = codepoint;
}
}
static class IconInfoVisitor extends DartRecursiveVisitor {
final HashMap<String, String> staticVars = new HashMap<>();
final String iconName;
IconInfo info;
IconInfoVisitor(String iconName) {
this.iconName = iconName;
}
@Nullable
private String findFamilyName(@Nullable PsiElement expression, @Nullable DartType type) {
if (expression == null && type != null) {
LOG.info("Check superclass constructor for font family: " + type.getName());
return null; // TODO Check superclass of <type> for a constructor that includes the family.
}
else if (expression instanceof DartStringLiteralExpression) {
//noinspection ConstantConditions
final Pair<String, TextRange> pair = DartPsiImplUtil.getUnquotedDartStringAndItsRange(expression.getText().trim());
return pair.first;
}
else {
if (expression != null) {
assert expression.getNode() != null;
if (expression.getNode().getElementType() == DartTokenTypes.REFERENCE_EXPRESSION) {
assert expression.getText() != null;
final Pair<String, TextRange> pair = DartPsiImplUtil.getUnquotedDartStringAndItsRange(expression.getText().trim());
final String varName = pair.first;
return staticVars.get(varName);
}
}
}
return null;
}
@Override
public void visitVarAccessDeclaration(@NotNull DartVarAccessDeclaration o) {
if (Objects.requireNonNull(o.getComponentName().getText()).trim().equals(iconName)) {
assert o.getParent() != null;
final DartVarInit init = (DartVarInit)o.getParent().getLastChild();
assert init != null;
final DartExpression expression = init.getExpression();
String className = null;
DartArguments arguments = null;
DartType type = null;
if (expression instanceof DartNewExpression) {
final DartNewExpression newExpr = (DartNewExpression)expression;
type = newExpr.getType();
if (type != null) {
className = type.getText();
arguments = newExpr.getArguments();
}
}
else if (expression instanceof DartCallExpression) {
// The Dart parser sometimes generates a call expression where we expect a new expression.
final DartCallExpressionImpl callExpr = (DartCallExpressionImpl)expression;
arguments = callExpr.getArguments();
className = callExpr.getExpression().getText();
}
if (KnownPaths.containsKey(className)) {
if (arguments != null) {
final DartArgumentList argumentList = arguments.getArgumentList();
if (argumentList != null) {
final List<DartExpression> list = argumentList.getExpressionList();
if (!list.isEmpty()) {
final DartExpression dartExpression = list.get(0);
assert dartExpression != null;
final String codepoint = dartExpression.getText();
final PsiElement family = getNamedArgumentExpression(arguments, "fontFamily");
final String familyName = findFamilyName(family, type);
assert className != null;
assert codepoint != null;
info = new IconInfo(className, iconName, familyName, codepoint);
}
}
}
}
}
else {
final PsiElement firstChild = o.getFirstChild();
assert firstChild != null;
assert firstChild.getText() != null;
if (firstChild.getText().trim().equals("static")) {
// Fortunately, in all packages checked so far, static variables defining font family and
// package names appear at the beginning of the file. So this simple visitor works, but it
// will fail if the static variables are defined at the end of the file.
final String varName = Objects.requireNonNull(o.getComponentName().getText()).trim();
assert o.getParent() != null;
final DartVarInit init = (DartVarInit)o.getParent().getLastChild();
assert init != null;
final DartExpression expression = init.getExpression();
if (expression instanceof DartStringLiteralExpression) {
assert expression.getText() != null;
final Pair<String, TextRange> pair = DartPsiImplUtil.getUnquotedDartStringAndItsRange(expression.getText());
staticVars.put(varName, pair.first);
}
}
}
}
}
//@Deprecated // This might be useful if we eliminate the preference pane that defines packages to analyze.
//static class YamlAssetMapVisitor extends YamlRecursivePsiElementVisitor {
// final HashMap<String, String> assetMap = new HashMap<>();
// final List<String> iconClassNames = new ArrayList<>();
//
// @Override
// public void visitCompoundValue(@NotNull YAMLCompoundValue compoundValue) {
// final PsiElement[] children = compoundValue.getChildren();
// if (children.length == 2 && Objects.requireNonNull(children[0].getFirstChild()).textMatches("asset")) {
// assert children[0].getLastChild() != null;
// final String fontFilePath = children[0].getLastChild().getText();
// assert children[1] != null;
// assert children[1].getLastChild() != null;
// final String className = children[1].getLastChild().getText();
// iconClassNames.add(className);
// assetMap.put(className, fontFilePath);
// }
// else {
// super.visitCompoundValue(compoundValue);
// }
// }
//
// @Override
// public void visitKeyValue(@NotNull YAMLKeyValue keyValue) {
// if (keyValue.getKeyText().equals("icons")) {
// iconClassNames.add(keyValue.getValueText());
// }
// else {
// super.visitKeyValue(keyValue);
// }
// }
//}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterIconLineMarkerProvider.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterIconLineMarkerProvider.java",
"repo_id": "flutter-intellij",
"token_count": 9170
} | 599 |