text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/keyboard_key_embedder_handler.h"
#include <map>
// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT
// This file is generated by
// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not
// be edited directly.
//
// Edit the template
// flutter/flutter:dev/tools/gen_keycodes/data/windows_flutter_key_map_cc.tmpl
// instead.
//
// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information.
namespace flutter {
std::map<uint64_t, uint64_t> KeyboardKeyEmbedderHandler::windowsToPhysicalMap_ =
{
{0x00000001, 0x00070029}, // escape
{0x00000002, 0x0007001e}, // digit1
{0x00000003, 0x0007001f}, // digit2
{0x00000004, 0x00070020}, // digit3
{0x00000005, 0x00070021}, // digit4
{0x00000006, 0x00070022}, // digit5
{0x00000007, 0x00070023}, // digit6
{0x00000008, 0x00070024}, // digit7
{0x00000009, 0x00070025}, // digit8
{0x0000000a, 0x00070026}, // digit9
{0x0000000b, 0x00070027}, // digit0
{0x0000000c, 0x0007002d}, // minus
{0x0000000d, 0x0007002e}, // equal
{0x0000000e, 0x0007002a}, // backspace
{0x0000000f, 0x0007002b}, // tab
{0x00000010, 0x00070014}, // keyQ
{0x00000011, 0x0007001a}, // keyW
{0x00000012, 0x00070008}, // keyE
{0x00000013, 0x00070015}, // keyR
{0x00000014, 0x00070017}, // keyT
{0x00000015, 0x0007001c}, // keyY
{0x00000016, 0x00070018}, // keyU
{0x00000017, 0x0007000c}, // keyI
{0x00000018, 0x00070012}, // keyO
{0x00000019, 0x00070013}, // keyP
{0x0000001a, 0x0007002f}, // bracketLeft
{0x0000001b, 0x00070030}, // bracketRight
{0x0000001c, 0x00070028}, // enter
{0x0000001d, 0x000700e0}, // controlLeft
{0x0000001e, 0x00070004}, // keyA
{0x0000001f, 0x00070016}, // keyS
{0x00000020, 0x00070007}, // keyD
{0x00000021, 0x00070009}, // keyF
{0x00000022, 0x0007000a}, // keyG
{0x00000023, 0x0007000b}, // keyH
{0x00000024, 0x0007000d}, // keyJ
{0x00000025, 0x0007000e}, // keyK
{0x00000026, 0x0007000f}, // keyL
{0x00000027, 0x00070033}, // semicolon
{0x00000028, 0x00070034}, // quote
{0x00000029, 0x00070035}, // backquote
{0x0000002a, 0x000700e1}, // shiftLeft
{0x0000002b, 0x00070031}, // backslash
{0x0000002c, 0x0007001d}, // keyZ
{0x0000002d, 0x0007001b}, // keyX
{0x0000002e, 0x00070006}, // keyC
{0x0000002f, 0x00070019}, // keyV
{0x00000030, 0x00070005}, // keyB
{0x00000031, 0x00070011}, // keyN
{0x00000032, 0x00070010}, // keyM
{0x00000033, 0x00070036}, // comma
{0x00000034, 0x00070037}, // period
{0x00000035, 0x00070038}, // slash
{0x00000036, 0x000700e5}, // shiftRight
{0x00000037, 0x00070055}, // numpadMultiply
{0x00000038, 0x000700e2}, // altLeft
{0x00000039, 0x0007002c}, // space
{0x0000003a, 0x00070039}, // capsLock
{0x0000003b, 0x0007003a}, // f1
{0x0000003c, 0x0007003b}, // f2
{0x0000003d, 0x0007003c}, // f3
{0x0000003e, 0x0007003d}, // f4
{0x0000003f, 0x0007003e}, // f5
{0x00000040, 0x0007003f}, // f6
{0x00000041, 0x00070040}, // f7
{0x00000042, 0x00070041}, // f8
{0x00000043, 0x00070042}, // f9
{0x00000044, 0x00070043}, // f10
{0x00000045, 0x00070048}, // pause
{0x00000046, 0x00070047}, // scrollLock
{0x00000047, 0x0007005f}, // numpad7
{0x00000048, 0x00070060}, // numpad8
{0x00000049, 0x00070061}, // numpad9
{0x0000004a, 0x00070056}, // numpadSubtract
{0x0000004b, 0x0007005c}, // numpad4
{0x0000004c, 0x0007005d}, // numpad5
{0x0000004d, 0x0007005e}, // numpad6
{0x0000004e, 0x00070057}, // numpadAdd
{0x0000004f, 0x00070059}, // numpad1
{0x00000050, 0x0007005a}, // numpad2
{0x00000051, 0x0007005b}, // numpad3
{0x00000052, 0x00070062}, // numpad0
{0x00000053, 0x00070063}, // numpadDecimal
{0x00000056, 0x00070064}, // intlBackslash
{0x00000057, 0x00070044}, // f11
{0x00000058, 0x00070045}, // f12
{0x00000059, 0x00070067}, // numpadEqual
{0x00000064, 0x00070068}, // f13
{0x00000065, 0x00070069}, // f14
{0x00000066, 0x0007006a}, // f15
{0x00000067, 0x0007006b}, // f16
{0x00000068, 0x0007006c}, // f17
{0x00000069, 0x0007006d}, // f18
{0x0000006a, 0x0007006e}, // f19
{0x0000006b, 0x0007006f}, // f20
{0x0000006c, 0x00070070}, // f21
{0x0000006d, 0x00070071}, // f22
{0x0000006e, 0x00070072}, // f23
{0x00000070, 0x00070088}, // kanaMode
{0x00000071, 0x00070091}, // lang2
{0x00000072, 0x00070090}, // lang1
{0x00000073, 0x00070087}, // intlRo
{0x00000076, 0x00070073}, // f24
{0x00000077, 0x00070093}, // lang4
{0x00000078, 0x00070092}, // lang3
{0x00000079, 0x0007008a}, // convert
{0x0000007b, 0x0007008b}, // nonConvert
{0x0000007d, 0x00070089}, // intlYen
{0x0000007e, 0x00070085}, // numpadComma
{0x000000fc, 0x00070002}, // usbPostFail
{0x000000ff, 0x00070001}, // usbErrorRollOver
{0x0000e008, 0x0007007a}, // undo
{0x0000e00a, 0x0007007d}, // paste
{0x0000e010, 0x000c00b6}, // mediaTrackPrevious
{0x0000e017, 0x0007007b}, // cut
{0x0000e018, 0x0007007c}, // copy
{0x0000e019, 0x000c00b5}, // mediaTrackNext
{0x0000e01c, 0x00070058}, // numpadEnter
{0x0000e01d, 0x000700e4}, // controlRight
{0x0000e020, 0x0007007f}, // audioVolumeMute
{0x0000e021, 0x000c0192}, // launchApp2
{0x0000e022, 0x000c00cd}, // mediaPlayPause
{0x0000e024, 0x000c00b7}, // mediaStop
{0x0000e02c, 0x000c00b8}, // eject
{0x0000e02e, 0x00070081}, // audioVolumeDown
{0x0000e030, 0x00070080}, // audioVolumeUp
{0x0000e032, 0x000c0223}, // browserHome
{0x0000e035, 0x00070054}, // numpadDivide
{0x0000e037, 0x00070046}, // printScreen
{0x0000e038, 0x000700e6}, // altRight
{0x0000e03b, 0x00070075}, // help
{0x0000e045, 0x00070053}, // numLock
{0x0000e047, 0x0007004a}, // home
{0x0000e048, 0x00070052}, // arrowUp
{0x0000e049, 0x0007004b}, // pageUp
{0x0000e04b, 0x00070050}, // arrowLeft
{0x0000e04d, 0x0007004f}, // arrowRight
{0x0000e04f, 0x0007004d}, // end
{0x0000e050, 0x00070051}, // arrowDown
{0x0000e051, 0x0007004e}, // pageDown
{0x0000e052, 0x00070049}, // insert
{0x0000e053, 0x0007004c}, // delete
{0x0000e05b, 0x000700e3}, // metaLeft
{0x0000e05c, 0x000700e7}, // metaRight
{0x0000e05d, 0x00070065}, // contextMenu
{0x0000e05e, 0x00070066}, // power
{0x0000e05f, 0x00010082}, // sleep
{0x0000e063, 0x00010083}, // wakeUp
{0x0000e065, 0x000c0221}, // browserSearch
{0x0000e066, 0x000c022a}, // browserFavorites
{0x0000e067, 0x000c0227}, // browserRefresh
{0x0000e068, 0x000c0226}, // browserStop
{0x0000e069, 0x000c0225}, // browserForward
{0x0000e06a, 0x000c0224}, // browserBack
{0x0000e06b, 0x000c0194}, // launchApp1
{0x0000e06c, 0x000c018a}, // launchMail
{0x0000e06d, 0x000c0183}, // mediaSelect
};
std::map<uint64_t, uint64_t> KeyboardKeyEmbedderHandler::windowsToLogicalMap_ =
{
{0x00000003, 0x00100000504}, // CANCEL -> cancel
{0x00000008, 0x00100000008}, // BACK -> backspace
{0x00000009, 0x00100000009}, // TAB -> tab
{0x0000000c, 0x00100000401}, // CLEAR -> clear
{0x0000000d, 0x0010000000d}, // RETURN -> enter
{0x00000010, 0x00200000102}, // SHIFT -> shiftLeft
{0x00000011, 0x00200000100}, // CONTROL -> controlLeft
{0x00000013, 0x00100000509}, // PAUSE -> pause
{0x00000014, 0x00100000104}, // CAPITAL -> capsLock
{0x00000015, 0x00200000010}, // KANA, HANGEUL, HANGUL -> lang1
{0x00000017, 0x00100000713}, // JUNJA -> junjaMode
{0x00000018, 0x00100000706}, // FINAL -> finalMode
{0x00000019, 0x00100000719}, // HANJA, KANJI -> kanjiMode
{0x0000001b, 0x0010000001b}, // ESCAPE -> escape
{0x0000001c, 0x00100000705}, // CONVERT -> convert
{0x0000001e, 0x00100000501}, // ACCEPT -> accept
{0x0000001f, 0x0010000070b}, // MODECHANGE -> modeChange
{0x00000020, 0x00000000020}, // SPACE -> space
{0x00000021, 0x00100000308}, // PRIOR -> pageUp
{0x00000022, 0x00100000307}, // NEXT -> pageDown
{0x00000023, 0x00100000305}, // END -> end
{0x00000024, 0x00100000306}, // HOME -> home
{0x00000025, 0x00100000302}, // LEFT -> arrowLeft
{0x00000026, 0x00100000304}, // UP -> arrowUp
{0x00000027, 0x00100000303}, // RIGHT -> arrowRight
{0x00000028, 0x00100000301}, // DOWN -> arrowDown
{0x00000029, 0x0010000050c}, // SELECT -> select
{0x0000002a, 0x00100000a0c}, // PRINT -> print
{0x0000002b, 0x00100000506}, // EXECUTE -> execute
{0x0000002c, 0x00100000608}, // SNAPSHOT -> printScreen
{0x0000002d, 0x00100000407}, // INSERT -> insert
{0x0000002e, 0x0010000007f}, // DELETE -> delete
{0x0000002f, 0x00100000508}, // HELP -> help
{0x0000005b, 0x00200000106}, // LWIN -> metaLeft
{0x0000005c, 0x00200000107}, // RWIN -> metaRight
{0x0000005d, 0x00100000505}, // APPS -> contextMenu
{0x0000005f, 0x00200000002}, // SLEEP -> sleep
{0x00000060, 0x00200000230}, // NUMPAD0 -> numpad0
{0x00000061, 0x00200000231}, // NUMPAD1 -> numpad1
{0x00000062, 0x00200000232}, // NUMPAD2 -> numpad2
{0x00000063, 0x00200000233}, // NUMPAD3 -> numpad3
{0x00000064, 0x00200000234}, // NUMPAD4 -> numpad4
{0x00000065, 0x00200000235}, // NUMPAD5 -> numpad5
{0x00000066, 0x00200000236}, // NUMPAD6 -> numpad6
{0x00000067, 0x00200000237}, // NUMPAD7 -> numpad7
{0x00000068, 0x00200000238}, // NUMPAD8 -> numpad8
{0x00000069, 0x00200000239}, // NUMPAD9 -> numpad9
{0x0000006a, 0x0020000022a}, // MULTIPLY -> numpadMultiply
{0x0000006b, 0x0020000022b}, // ADD -> numpadAdd
{0x0000006c, 0x0020000022c}, // SEPARATOR -> numpadComma
{0x0000006d, 0x0020000022d}, // SUBTRACT -> numpadSubtract
{0x0000006e, 0x0020000022e}, // DECIMAL -> numpadDecimal
{0x0000006f, 0x0020000022f}, // DIVIDE -> numpadDivide
{0x00000070, 0x00100000801}, // F1 -> f1
{0x00000071, 0x00100000802}, // F2 -> f2
{0x00000072, 0x00100000803}, // F3 -> f3
{0x00000073, 0x00100000804}, // F4 -> f4
{0x00000074, 0x00100000805}, // F5 -> f5
{0x00000075, 0x00100000806}, // F6 -> f6
{0x00000076, 0x00100000807}, // F7 -> f7
{0x00000077, 0x00100000808}, // F8 -> f8
{0x00000078, 0x00100000809}, // F9 -> f9
{0x00000079, 0x0010000080a}, // F10 -> f10
{0x0000007a, 0x0010000080b}, // F11 -> f11
{0x0000007b, 0x0010000080c}, // F12 -> f12
{0x0000007c, 0x0010000080d}, // F13 -> f13
{0x0000007d, 0x0010000080e}, // F14 -> f14
{0x0000007e, 0x0010000080f}, // F15 -> f15
{0x0000007f, 0x00100000810}, // F16 -> f16
{0x00000080, 0x00100000811}, // F17 -> f17
{0x00000081, 0x00100000812}, // F18 -> f18
{0x00000082, 0x00100000813}, // F19 -> f19
{0x00000083, 0x00100000814}, // F20 -> f20
{0x00000084, 0x00100000815}, // F21 -> f21
{0x00000085, 0x00100000816}, // F22 -> f22
{0x00000086, 0x00100000817}, // F23 -> f23
{0x00000087, 0x00100000818}, // F24 -> f24
{0x00000090, 0x0010000010a}, // NUMLOCK -> numLock
{0x00000091, 0x0010000010c}, // SCROLL -> scrollLock
{0x00000092, 0x0020000023d}, // OEM_NEC_EQUAL -> numpadEqual
{0x000000a0, 0x00200000102}, // LSHIFT -> shiftLeft
{0x000000a1, 0x00200000103}, // RSHIFT -> shiftRight
{0x000000a2, 0x00200000100}, // LCONTROL -> controlLeft
{0x000000a3, 0x00200000101}, // RCONTROL -> controlRight
{0x000000a4, 0x00200000104}, // LMENU -> altLeft
{0x000000a5, 0x00200000105}, // RMENU -> altRight
{0x000000a6, 0x00100000c01}, // BROWSER_BACK -> browserBack
{0x000000a7, 0x00100000c03}, // BROWSER_FORWARD -> browserForward
{0x000000a8, 0x00100000c05}, // BROWSER_REFRESH -> browserRefresh
{0x000000a9, 0x00100000c07}, // BROWSER_STOP -> browserStop
{0x000000aa, 0x00100000c06}, // BROWSER_SEARCH -> browserSearch
{0x000000ab, 0x00100000c02}, // BROWSER_FAVORITES -> browserFavorites
{0x000000ac, 0x00100000c04}, // BROWSER_HOME -> browserHome
{0x000000ad, 0x00100000a11}, // VOLUME_MUTE -> audioVolumeMute
{0x000000ae, 0x00100000a0f}, // VOLUME_DOWN -> audioVolumeDown
{0x000000af, 0x00100000a10}, // VOLUME_UP -> audioVolumeUp
{0x000000b2, 0x00100000a07}, // MEDIA_STOP -> mediaStop
{0x000000b3, 0x00100000a05}, // MEDIA_PLAY_PAUSE -> mediaPlayPause
{0x000000b4, 0x00100000b03}, // LAUNCH_MAIL -> launchMail
{0x000000ba, 0x0000000003b}, // OEM_1 -> semicolon
{0x000000bb, 0x0000000003d}, // OEM_PLUS -> equal
{0x000000bc, 0x0000000002c}, // OEM_COMMA -> comma
{0x000000bd, 0x0000000002d}, // OEM_MINUS -> minus
{0x000000be, 0x0000000002e}, // OEM_PERIOD -> period
{0x000000bf, 0x0000000002f}, // OEM_2 -> slash
{0x000000c0, 0x00000000060}, // OEM_3 -> backquote
{0x000000c3, 0x00200000308}, // GAMEPAD_A -> gameButton8
{0x000000c4, 0x00200000309}, // GAMEPAD_B -> gameButton9
{0x000000c5, 0x0020000030a}, // GAMEPAD_X -> gameButton10
{0x000000c6, 0x0020000030b}, // GAMEPAD_Y -> gameButton11
{0x000000c7, 0x0020000030c}, // GAMEPAD_RIGHT_SHOULDER -> gameButton12
{0x000000c8, 0x0020000030d}, // GAMEPAD_LEFT_SHOULDER -> gameButton13
{0x000000c9, 0x0020000030e}, // GAMEPAD_LEFT_TRIGGER -> gameButton14
{0x000000ca, 0x0020000030f}, // GAMEPAD_RIGHT_TRIGGER -> gameButton15
{0x000000cb, 0x00200000310}, // GAMEPAD_DPAD_UP -> gameButton16
{0x000000db, 0x0000000005b}, // OEM_4 -> bracketLeft
{0x000000dc, 0x0000000005c}, // OEM_5 -> backslash
{0x000000dd, 0x0000000005d}, // OEM_6 -> bracketRight
{0x000000de, 0x00000000022}, // OEM_7 -> quote
{0x000000f6, 0x00100000503}, // ATTN -> attn
{0x000000fa, 0x0010000050a}, // PLAY -> play
};
std::map<uint64_t, uint64_t> KeyboardKeyEmbedderHandler::scanCodeToLogicalMap_ =
{
{0x00000037, 0x0020000022a}, // numpadMultiply -> numpadMultiply
{0x00000047, 0x00200000237}, // numpad7 -> numpad7
{0x00000048, 0x00200000238}, // numpad8 -> numpad8
{0x00000049, 0x00200000239}, // numpad9 -> numpad9
{0x0000004a, 0x0020000022d}, // numpadSubtract -> numpadSubtract
{0x0000004b, 0x00200000234}, // numpad4 -> numpad4
{0x0000004c, 0x00200000235}, // numpad5 -> numpad5
{0x0000004d, 0x00200000236}, // numpad6 -> numpad6
{0x0000004e, 0x0020000022b}, // numpadAdd -> numpadAdd
{0x0000004f, 0x00200000231}, // numpad1 -> numpad1
{0x00000050, 0x00200000232}, // numpad2 -> numpad2
{0x00000051, 0x00200000233}, // numpad3 -> numpad3
{0x00000052, 0x00200000230}, // numpad0 -> numpad0
{0x00000053, 0x0020000022e}, // numpadDecimal -> numpadDecimal
{0x00000059, 0x0020000023d}, // numpadEqual -> numpadEqual
{0x0000e01d, 0x00200000101}, // controlRight -> controlRight
{0x0000e035, 0x0020000022f}, // numpadDivide -> numpadDivide
{0x0000e038, 0x00200000105}, // altRight -> altRight
};
const uint64_t KeyboardKeyEmbedderHandler::valueMask = 0x000ffffffff;
const uint64_t KeyboardKeyEmbedderHandler::unicodePlane = 0x00000000000;
const uint64_t KeyboardKeyEmbedderHandler::windowsPlane = 0x01600000000;
} // namespace flutter
| engine/shell/platform/windows/flutter_key_map.g.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_key_map.g.cc",
"repo_id": "engine",
"token_count": 8588
} | 412 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
#include "flutter/shell/platform/windows/egl/proc_table.h"
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
#include "flutter/shell/platform/windows/flutter_windows_texture_registrar.h"
#include "flutter/shell/platform/windows/testing/egl/mock_proc_table.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
using ::testing::_;
using ::testing::AtLeast;
using Microsoft::WRL::ComPtr;
namespace {
// Returns an engine instance configured with dummy project path values.
std::unique_ptr<FlutterWindowsEngine> GetTestEngine() {
FlutterDesktopEngineProperties properties = {};
properties.assets_path = L"C:\\foo\\flutter_assets";
properties.icu_data_path = L"C:\\foo\\icudtl.dat";
properties.aot_library_path = L"C:\\foo\\aot.so";
FlutterProjectBundle project(properties);
auto engine = std::make_unique<FlutterWindowsEngine>(project);
EngineModifier modifier(engine.get());
modifier.embedder_api().RegisterExternalTexture =
MOCK_ENGINE_PROC(RegisterExternalTexture,
([](auto engine, auto texture_id) { return kSuccess; }));
return engine;
}
// Creates a ID3D11Texture2D with the specified size.
ComPtr<ID3D11Texture2D> CreateD3dTexture(FlutterWindowsEngine* engine,
UINT width,
UINT height) {
ComPtr<ID3D11Device> d3d_device;
ComPtr<ID3D11Texture2D> d3d_texture;
if (engine->egl_manager()->GetDevice(d3d_device.GetAddressOf())) {
D3D11_TEXTURE2D_DESC texture_description = {};
texture_description.MipLevels = 1;
texture_description.SampleDesc.Count = 1;
texture_description.BindFlags = D3D11_BIND_RENDER_TARGET;
texture_description.Usage = D3D11_USAGE_DEFAULT;
texture_description.CPUAccessFlags = 0;
texture_description.ArraySize = 1;
texture_description.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
texture_description.Height = width;
texture_description.Width = height;
texture_description.MiscFlags = D3D11_RESOURCE_MISC_SHARED;
d3d_device->CreateTexture2D(&texture_description, nullptr,
d3d_texture.GetAddressOf());
}
return d3d_texture;
}
} // namespace
TEST(FlutterWindowsTextureRegistrarTest, CreateDestroy) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
auto gl = std::make_shared<egl::MockProcTable>();
FlutterWindowsTextureRegistrar registrar(engine.get(), gl);
EXPECT_TRUE(true);
}
TEST(FlutterWindowsTextureRegistrarTest, RegisterUnregisterTexture) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
auto gl = std::make_shared<egl::MockProcTable>();
FlutterWindowsTextureRegistrar registrar(engine.get(), gl);
FlutterDesktopTextureInfo texture_info = {};
texture_info.type = kFlutterDesktopPixelBufferTexture;
texture_info.pixel_buffer_config.callback =
[](size_t width, size_t height,
void* user_data) -> const FlutterDesktopPixelBuffer* {
return nullptr;
};
int64_t registered_texture_id = 0;
bool register_called = false;
modifier.embedder_api().RegisterExternalTexture = MOCK_ENGINE_PROC(
RegisterExternalTexture, ([®ister_called, ®istered_texture_id](
auto engine, auto texture_id) {
register_called = true;
registered_texture_id = texture_id;
return kSuccess;
}));
bool unregister_called = false;
modifier.embedder_api().UnregisterExternalTexture = MOCK_ENGINE_PROC(
UnregisterExternalTexture, ([&unregister_called, ®istered_texture_id](
auto engine, auto texture_id) {
unregister_called = true;
EXPECT_EQ(registered_texture_id, texture_id);
return kSuccess;
}));
bool mark_frame_available_called = false;
modifier.embedder_api().MarkExternalTextureFrameAvailable =
MOCK_ENGINE_PROC(MarkExternalTextureFrameAvailable,
([&mark_frame_available_called, ®istered_texture_id](
auto engine, auto texture_id) {
mark_frame_available_called = true;
EXPECT_EQ(registered_texture_id, texture_id);
return kSuccess;
}));
modifier.embedder_api().PostRenderThreadTask =
MOCK_ENGINE_PROC(PostRenderThreadTask,
[](auto engine, auto callback, void* callback_data) {
callback(callback_data);
return kSuccess;
});
auto texture_id = registrar.RegisterTexture(&texture_info);
EXPECT_TRUE(register_called);
EXPECT_NE(texture_id, -1);
EXPECT_EQ(texture_id, registered_texture_id);
EXPECT_TRUE(registrar.MarkTextureFrameAvailable(texture_id));
EXPECT_TRUE(mark_frame_available_called);
fml::AutoResetWaitableEvent latch;
registrar.UnregisterTexture(texture_id, [&]() { latch.Signal(); });
latch.Wait();
ASSERT_TRUE(unregister_called);
}
TEST(FlutterWindowsTextureRegistrarTest, RegisterUnknownTextureType) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
auto gl = std::make_shared<egl::MockProcTable>();
FlutterWindowsTextureRegistrar registrar(engine.get(), gl);
FlutterDesktopTextureInfo texture_info = {};
texture_info.type = static_cast<FlutterDesktopTextureType>(1234);
auto texture_id = registrar.RegisterTexture(&texture_info);
EXPECT_EQ(texture_id, -1);
}
TEST(FlutterWindowsTextureRegistrarTest, PopulatePixelBufferTexture) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
auto gl = std::make_shared<egl::MockProcTable>();
FlutterWindowsTextureRegistrar registrar(engine.get(), gl);
bool release_callback_called = false;
size_t width = 100;
size_t height = 100;
std::unique_ptr<uint8_t[]> pixels =
std::make_unique<uint8_t[]>(width * height * 4);
FlutterDesktopPixelBuffer pixel_buffer = {};
pixel_buffer.width = width;
pixel_buffer.height = height;
pixel_buffer.buffer = pixels.get();
pixel_buffer.release_context = &release_callback_called;
pixel_buffer.release_callback = [](void* release_context) {
bool* called = reinterpret_cast<bool*>(release_context);
*called = true;
};
FlutterDesktopTextureInfo texture_info = {};
texture_info.type = kFlutterDesktopPixelBufferTexture;
texture_info.pixel_buffer_config.user_data = &pixel_buffer;
texture_info.pixel_buffer_config.callback =
[](size_t width, size_t height,
void* user_data) -> const FlutterDesktopPixelBuffer* {
return reinterpret_cast<const FlutterDesktopPixelBuffer*>(user_data);
};
FlutterOpenGLTexture flutter_texture = {};
auto texture_id = registrar.RegisterTexture(&texture_info);
EXPECT_NE(texture_id, -1);
EXPECT_CALL(*gl.get(), GenTextures(1, _))
.Times(1)
.WillOnce([](GLsizei n, GLuint* textures) { textures[0] = 1; });
EXPECT_CALL(*gl.get(), BindTexture).Times(1);
EXPECT_CALL(*gl.get(), TexParameteri).Times(AtLeast(1));
EXPECT_CALL(*gl.get(), TexImage2D).Times(1);
EXPECT_CALL(*gl.get(), DeleteTextures(1, _)).Times(1);
auto result =
registrar.PopulateTexture(texture_id, 640, 480, &flutter_texture);
EXPECT_TRUE(result);
EXPECT_EQ(flutter_texture.width, width);
EXPECT_EQ(flutter_texture.height, height);
EXPECT_EQ(flutter_texture.target, GL_TEXTURE_2D);
EXPECT_TRUE(release_callback_called);
}
TEST(FlutterWindowsTextureRegistrarTest, PopulateD3dTextureWithHandle) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
auto gl = std::make_shared<egl::MockProcTable>();
FlutterWindowsTextureRegistrar registrar(engine.get(), gl);
UINT width = 100;
UINT height = 100;
auto d3d_texture = CreateD3dTexture(engine.get(), width, height);
EXPECT_TRUE(d3d_texture);
ComPtr<IDXGIResource> shared_resource;
EXPECT_TRUE(SUCCEEDED(d3d_texture.As(&shared_resource)));
HANDLE shared_handle;
EXPECT_TRUE(SUCCEEDED(shared_resource->GetSharedHandle(&shared_handle)));
bool release_callback_called = false;
FlutterDesktopGpuSurfaceDescriptor surface_descriptor = {};
surface_descriptor.struct_size = sizeof(FlutterDesktopGpuSurfaceDescriptor);
surface_descriptor.handle = shared_handle;
surface_descriptor.width = surface_descriptor.visible_width = width;
surface_descriptor.height = surface_descriptor.visible_height = height;
surface_descriptor.release_context = &release_callback_called;
surface_descriptor.release_callback = [](void* release_context) {
bool* called = reinterpret_cast<bool*>(release_context);
*called = true;
};
FlutterDesktopTextureInfo texture_info = {};
texture_info.type = kFlutterDesktopGpuSurfaceTexture;
texture_info.gpu_surface_config.struct_size =
sizeof(FlutterDesktopGpuSurfaceTextureConfig);
texture_info.gpu_surface_config.type =
kFlutterDesktopGpuSurfaceTypeDxgiSharedHandle;
texture_info.gpu_surface_config.user_data = &surface_descriptor;
texture_info.gpu_surface_config.callback =
[](size_t width, size_t height,
void* user_data) -> const FlutterDesktopGpuSurfaceDescriptor* {
return reinterpret_cast<const FlutterDesktopGpuSurfaceDescriptor*>(
user_data);
};
FlutterOpenGLTexture flutter_texture = {};
auto texture_id = registrar.RegisterTexture(&texture_info);
EXPECT_NE(texture_id, -1);
EXPECT_CALL(*gl.get(), GenTextures(1, _))
.Times(1)
.WillOnce([](GLsizei n, GLuint* textures) { textures[0] = 1; });
EXPECT_CALL(*gl.get(), BindTexture).Times(1);
EXPECT_CALL(*gl.get(), TexParameteri).Times(AtLeast(1));
EXPECT_CALL(*gl.get(), DeleteTextures(1, _)).Times(1);
auto result =
registrar.PopulateTexture(texture_id, 640, 480, &flutter_texture);
EXPECT_TRUE(result);
EXPECT_EQ(flutter_texture.width, width);
EXPECT_EQ(flutter_texture.height, height);
EXPECT_EQ(flutter_texture.target, GL_TEXTURE_2D);
EXPECT_TRUE(release_callback_called);
}
TEST(FlutterWindowsTextureRegistrarTest, PopulateD3dTexture) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
auto gl = std::make_shared<egl::MockProcTable>();
FlutterWindowsTextureRegistrar registrar(engine.get(), gl);
UINT width = 100;
UINT height = 100;
auto d3d_texture = CreateD3dTexture(engine.get(), width, height);
EXPECT_TRUE(d3d_texture);
bool release_callback_called = false;
FlutterDesktopGpuSurfaceDescriptor surface_descriptor = {};
surface_descriptor.struct_size = sizeof(FlutterDesktopGpuSurfaceDescriptor);
surface_descriptor.handle = d3d_texture.Get();
surface_descriptor.width = surface_descriptor.visible_width = width;
surface_descriptor.height = surface_descriptor.visible_height = height;
surface_descriptor.release_context = &release_callback_called;
surface_descriptor.release_callback = [](void* release_context) {
bool* called = reinterpret_cast<bool*>(release_context);
*called = true;
};
FlutterDesktopTextureInfo texture_info = {};
texture_info.type = kFlutterDesktopGpuSurfaceTexture;
texture_info.gpu_surface_config.struct_size =
sizeof(FlutterDesktopGpuSurfaceTextureConfig);
texture_info.gpu_surface_config.type =
kFlutterDesktopGpuSurfaceTypeD3d11Texture2D;
texture_info.gpu_surface_config.user_data = &surface_descriptor;
texture_info.gpu_surface_config.callback =
[](size_t width, size_t height,
void* user_data) -> const FlutterDesktopGpuSurfaceDescriptor* {
return reinterpret_cast<const FlutterDesktopGpuSurfaceDescriptor*>(
user_data);
};
FlutterOpenGLTexture flutter_texture = {};
auto texture_id = registrar.RegisterTexture(&texture_info);
EXPECT_NE(texture_id, -1);
EXPECT_CALL(*gl.get(), GenTextures(1, _))
.Times(1)
.WillOnce([](GLsizei n, GLuint* textures) { textures[0] = 1; });
EXPECT_CALL(*gl.get(), BindTexture).Times(1);
EXPECT_CALL(*gl.get(), TexParameteri).Times(AtLeast(1));
EXPECT_CALL(*gl.get(), DeleteTextures(1, _)).Times(1);
auto result =
registrar.PopulateTexture(texture_id, 640, 480, &flutter_texture);
EXPECT_TRUE(result);
EXPECT_EQ(flutter_texture.width, width);
EXPECT_EQ(flutter_texture.height, height);
EXPECT_EQ(flutter_texture.target, GL_TEXTURE_2D);
EXPECT_TRUE(release_callback_called);
}
TEST(FlutterWindowsTextureRegistrarTest, PopulateInvalidTexture) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
auto gl = std::make_shared<egl::MockProcTable>();
FlutterWindowsTextureRegistrar registrar(engine.get(), gl);
auto result = registrar.PopulateTexture(1, 640, 480, nullptr);
EXPECT_FALSE(result);
}
TEST(FlutterWindowsTextureRegistrarTest,
UnregisterTextureWithEngineDownInvokesCallback) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
auto gl = std::make_shared<egl::MockProcTable>();
FlutterWindowsTextureRegistrar registrar(engine.get(), gl);
fml::AutoResetWaitableEvent latch;
registrar.UnregisterTexture(1234, [&]() { latch.Signal(); });
latch.Wait();
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/flutter_windows_texture_registrar_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_windows_texture_registrar_unittests.cc",
"repo_id": "engine",
"token_count": 4987
} | 413 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <string>
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/windows/keyboard_manager.h"
#include "flutter/shell/platform/windows/keyboard_utils.h"
namespace flutter {
namespace {
// The maximum number of pending events to keep before
// emitting a warning on the console about unhandled events.
constexpr int kMaxPendingEvents = 1000;
// Returns true if this key is an AltRight key down event.
//
// This is used to resolve an issue where an AltGr press causes CtrlLeft to hang
// when pressed, as reported in https://github.com/flutter/flutter/issues/78005.
//
// When AltGr is pressed (in a supporting layout such as Spanish), Win32 first
// fires a fake CtrlLeft down event, then an AltRight down event.
// This is significant because this fake CtrlLeft down event will not be paired
// with a up event, which is fine until Flutter redispatches the CtrlDown
// event, which Win32 then interprets as a real event, leaving both Win32 and
// the Flutter framework thinking that CtrlLeft is still pressed.
//
// To resolve this, Flutter recognizes this fake CtrlLeft down event using the
// following AltRight down event. Flutter then forges a CtrlLeft key up event
// immediately after the corresponding AltRight key up event.
//
// One catch is that it is impossible to distinguish the fake CtrlLeft down
// from a normal CtrlLeft down (followed by a AltRight down), since they
// contain the exactly same information, including the GetKeyState result.
// Fortunately, this will require the two events to occur *really* close, which
// would be rare, and a misrecognition would only cause a minor consequence
// where the CtrlLeft is released early; the later, real, CtrlLeft up event will
// be ignored.
bool IsKeyDownAltRight(int action, int virtual_key, bool extended) {
return virtual_key == VK_RMENU && extended &&
(action == WM_KEYDOWN || action == WM_SYSKEYDOWN);
}
// Returns true if this key is a key up event of AltRight.
//
// This is used to assist a corner case described in |IsKeyDownAltRight|.
bool IsKeyUpAltRight(int action, int virtual_key, bool extended) {
return virtual_key == VK_RMENU && extended &&
(action == WM_KEYUP || action == WM_SYSKEYUP);
}
// Returns true if this key is a key down event of CtrlLeft.
//
// This is used to assist a corner case described in |IsKeyDownAltRight|.
bool IsKeyDownCtrlLeft(int action, int virtual_key) {
return virtual_key == VK_LCONTROL &&
(action == WM_KEYDOWN || action == WM_SYSKEYDOWN);
}
// Returns if a character sent by Win32 is a dead key.
bool IsDeadKey(uint32_t ch) {
return (ch & kDeadKeyCharMask) != 0;
}
char32_t CodePointFromSurrogatePair(wchar_t high, wchar_t low) {
return 0x10000 + ((static_cast<char32_t>(high) & 0x000003FF) << 10) +
(low & 0x3FF);
}
uint16_t ResolveKeyCode(uint16_t original, bool extended, uint8_t scancode) {
switch (original) {
case VK_SHIFT:
case VK_LSHIFT:
return MapVirtualKey(scancode, MAPVK_VSC_TO_VK_EX);
case VK_MENU:
case VK_LMENU:
return extended ? VK_RMENU : VK_LMENU;
case VK_CONTROL:
case VK_LCONTROL:
return extended ? VK_RCONTROL : VK_LCONTROL;
default:
return original;
}
}
bool IsPrintable(uint32_t c) {
constexpr char32_t kMinPrintable = ' ';
constexpr char32_t kDelete = 0x7F;
return c >= kMinPrintable && c != kDelete;
}
bool IsSysAction(UINT action) {
return action == WM_SYSKEYDOWN || action == WM_SYSKEYUP ||
action == WM_SYSCHAR || action == WM_SYSDEADCHAR;
}
} // namespace
KeyboardManager::KeyboardManager(WindowDelegate* delegate)
: window_delegate_(delegate),
last_key_is_ctrl_left_down(false),
should_synthesize_ctrl_left_up(false),
processing_event_(false) {}
void KeyboardManager::RedispatchEvent(std::unique_ptr<PendingEvent> event) {
for (const Win32Message& message : event->session) {
// Never redispatch sys keys, because their original messages have been
// passed to the system default processor.
if (IsSysAction(message.action)) {
continue;
}
pending_redispatches_.push_back(message);
UINT result = window_delegate_->Win32DispatchMessage(
message.action, message.wparam, message.lparam);
if (result != 0) {
FML_LOG(ERROR) << "Unable to synthesize event for keyboard event.";
}
}
if (pending_redispatches_.size() > kMaxPendingEvents) {
FML_LOG(ERROR)
<< "There are " << pending_redispatches_.size()
<< " keyboard events that have not yet received a response from the "
<< "framework. Are responses being sent?";
}
}
bool KeyboardManager::RemoveRedispatchedMessage(UINT const action,
WPARAM const wparam,
LPARAM const lparam) {
for (auto iter = pending_redispatches_.begin();
iter != pending_redispatches_.end(); ++iter) {
if (action == iter->action && wparam == iter->wparam) {
pending_redispatches_.erase(iter);
return true;
}
}
return false;
}
bool KeyboardManager::HandleMessage(UINT const action,
WPARAM const wparam,
LPARAM const lparam) {
if (RemoveRedispatchedMessage(action, wparam, lparam)) {
return false;
}
switch (action) {
case WM_DEADCHAR:
case WM_SYSDEADCHAR:
case WM_CHAR:
case WM_SYSCHAR: {
const Win32Message message =
Win32Message{.action = action, .wparam = wparam, .lparam = lparam};
current_session_.push_back(message);
char32_t code_point;
if (message.IsHighSurrogate()) {
// A high surrogate is always followed by a low surrogate. Process the
// session later and consider this message as handled.
return true;
} else if (message.IsLowSurrogate()) {
const Win32Message* last_message =
current_session_.size() <= 1
? nullptr
: ¤t_session_[current_session_.size() - 2];
if (last_message == nullptr || !last_message->IsHighSurrogate()) {
return false;
}
// A low surrogate always follows a high surrogate, marking the end of
// a char session. Process the session after the if clause.
code_point =
CodePointFromSurrogatePair(last_message->wparam, message.wparam);
} else {
// A non-surrogate character always appears alone. Process the session
// after the if clause.
code_point = static_cast<wchar_t>(message.wparam);
}
// If this char message is preceded by a key down message, then dispatch
// the key down message as a key down event first, and only dispatch the
// OnText if the key down event is not handled.
if (current_session_.front().IsGeneralKeyDown()) {
const Win32Message first_message = current_session_.front();
const uint8_t scancode = (lparam >> 16) & 0xff;
const uint16_t key_code = first_message.wparam;
const bool extended = ((lparam >> 24) & 0x01) == 0x01;
const bool was_down = lparam & 0x40000000;
// Certain key combinations yield control characters as WM_CHAR's
// lParam. For example, 0x01 for Ctrl-A. Filter these characters. See
// https://docs.microsoft.com/en-us/windows/win32/learnwin32/accelerator-tables
char32_t character;
if (action == WM_DEADCHAR || action == WM_SYSDEADCHAR) {
// Mask the resulting char with kDeadKeyCharMask anyway, because in
// rare cases the bit is *not* set (US INTL Shift-6 circumflex, see
// https://github.com/flutter/flutter/issues/92654 .)
character =
window_delegate_->Win32MapVkToChar(key_code) | kDeadKeyCharMask;
} else {
character = IsPrintable(code_point) ? code_point : 0;
}
auto event = std::make_unique<PendingEvent>(PendingEvent{
.key = key_code,
.scancode = scancode,
.action = static_cast<UINT>(action == WM_SYSCHAR ? WM_SYSKEYDOWN
: WM_KEYDOWN),
.character = character,
.extended = extended,
.was_down = was_down,
.session = std::move(current_session_),
});
pending_events_.push_back(std::move(event));
ProcessNextEvent();
// SYS messages must not be consumed by `HandleMessage` so that they are
// forwarded to the system.
return !IsSysAction(action);
}
// If the charcter session is not preceded by a key down message,
// mark PendingEvent::action as WM_CHAR, informing |PerformProcessEvent|
// to dispatch the text content immediately.
//
// Only WM_CHAR should be treated as characters. WM_SYS*CHAR are not part
// of text input, and WM_DEADCHAR will be incorporated into a later
// WM_CHAR with the full character.
if (action == WM_CHAR) {
auto event = std::make_unique<PendingEvent>(PendingEvent{
.action = WM_CHAR,
.character = code_point,
.session = std::move(current_session_),
});
pending_events_.push_back(std::move(event));
ProcessNextEvent();
}
return true;
}
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP: {
if (wparam == VK_PACKET) {
return false;
}
const uint8_t scancode = (lparam >> 16) & 0xff;
const bool extended = ((lparam >> 24) & 0x01) == 0x01;
// If the key is a modifier, get its side.
const uint16_t key_code = ResolveKeyCode(wparam, extended, scancode);
const bool was_down = lparam & 0x40000000;
// Detect a pattern of key events in order to forge a CtrlLeft up event.
// See |IsKeyDownAltRight| for explanation.
if (IsKeyDownAltRight(action, key_code, extended)) {
if (last_key_is_ctrl_left_down) {
should_synthesize_ctrl_left_up = true;
}
}
if (IsKeyDownCtrlLeft(action, key_code)) {
last_key_is_ctrl_left_down = true;
ctrl_left_scancode = scancode;
should_synthesize_ctrl_left_up = false;
} else {
last_key_is_ctrl_left_down = false;
}
if (IsKeyUpAltRight(action, key_code, extended)) {
if (should_synthesize_ctrl_left_up) {
should_synthesize_ctrl_left_up = false;
const LPARAM lParam =
(1 /* repeat_count */ << 0) | (ctrl_left_scancode << 16) |
(0 /* extended */ << 24) | (1 /* prev_state */ << 30) |
(1 /* transition */ << 31);
window_delegate_->Win32DispatchMessage(WM_KEYUP, VK_CONTROL, lParam);
}
}
current_session_.clear();
current_session_.push_back(
Win32Message{.action = action, .wparam = wparam, .lparam = lparam});
const bool is_keydown_message =
(action == WM_KEYDOWN || action == WM_SYSKEYDOWN);
// Check if this key produces a character by peeking if this key down
// message has a following char message. Certain key messages are not
// followed by char messages even though `MapVirtualKey` returns a valid
// character (such as Ctrl + Digit, see
// https://github.com/flutter/flutter/issues/85587 ).
unsigned int character = window_delegate_->Win32MapVkToChar(wparam);
UINT next_key_action = PeekNextMessageType(WM_KEYFIRST, WM_KEYLAST);
bool has_char_action =
(next_key_action == WM_DEADCHAR ||
next_key_action == WM_SYSDEADCHAR || next_key_action == WM_CHAR ||
next_key_action == WM_SYSCHAR);
if (character > 0 && is_keydown_message && has_char_action) {
// This key down message has a following char message. Process this
// session in the char message, because the character for the key call
// should be decided by the char events. Consider this message as
// handled.
return true;
}
// This key down message is not followed by a char message. Conclude this
// session.
auto event = std::make_unique<PendingEvent>(PendingEvent{
.key = key_code,
.scancode = scancode,
.action = action,
.character = 0,
.extended = extended,
.was_down = was_down,
.session = std::move(current_session_),
});
pending_events_.push_back(std::move(event));
ProcessNextEvent();
// SYS messages must not be consumed by `HandleMessage` so that they are
// forwarded to the system.
return !IsSysAction(action);
}
default:
FML_LOG(FATAL) << "No event handler for keyboard event with action "
<< action;
}
return false;
}
void KeyboardManager::ProcessNextEvent() {
if (processing_event_ || pending_events_.empty()) {
return;
}
processing_event_ = true;
auto pending_event = std::move(pending_events_.front());
pending_events_.pop_front();
PerformProcessEvent(std::move(pending_event), [this] {
FML_DCHECK(processing_event_);
processing_event_ = false;
ProcessNextEvent();
});
}
void KeyboardManager::PerformProcessEvent(std::unique_ptr<PendingEvent> event,
std::function<void()> callback) {
// PendingEvent::action being WM_CHAR means this is a char message without
// a preceding key message, and should be dispatched immediately.
if (event->action == WM_CHAR) {
DispatchText(*event);
callback();
return;
}
// A unique_ptr can't be sent into a lambda without C++23's
// move_only_function. Until then, `event` is sent as a raw pointer, hoping
// WindowDelegate::OnKey to correctly call it once and only once.
PendingEvent* event_p = event.release();
window_delegate_->OnKey(
event_p->key, event_p->scancode, event_p->action, event_p->character,
event_p->extended, event_p->was_down,
[this, event_p, callback = std::move(callback)](bool handled) {
HandleOnKeyResult(std::unique_ptr<PendingEvent>(event_p), handled);
callback();
});
}
void KeyboardManager::HandleOnKeyResult(std::unique_ptr<PendingEvent> event,
bool framework_handled) {
const UINT last_action = event->session.back().action;
// SYS messages must not be redispached, and their text content is not
// dispatched either.
bool handled = framework_handled || IsSysAction(last_action);
if (handled) {
return;
}
// Only WM_CHAR should be treated as characters. WM_SYS*CHAR are not part of
// text input, and WM_DEADCHAR will be incorporated into a later WM_CHAR with
// the full character.
if (last_action == WM_CHAR) {
DispatchText(*event);
}
RedispatchEvent(std::move(event));
}
void KeyboardManager::DispatchText(const PendingEvent& event) {
// Check if the character is printable based on the last wparam, which works
// even if the last wparam is a low surrogate, because the only unprintable
// keys defined by `IsPrintable` are certain characters at lower ASCII range.
// These ASCII control characters are sent as WM_CHAR events for all control
// key shortcuts.
FML_DCHECK(!event.session.empty());
bool is_printable = IsPrintable(event.session.back().wparam);
bool valid = event.character != 0 && is_printable;
if (valid) {
auto text = EncodeUtf16(event.character);
window_delegate_->OnText(text);
}
}
UINT KeyboardManager::PeekNextMessageType(UINT wMsgFilterMin,
UINT wMsgFilterMax) {
MSG next_message;
BOOL has_msg = window_delegate_->Win32PeekMessage(
&next_message, wMsgFilterMin, wMsgFilterMax, PM_NOREMOVE);
if (!has_msg) {
return 0;
}
return next_message.message;
}
} // namespace flutter
| engine/shell/platform/windows/keyboard_manager.cc/0 | {
"file_path": "engine/shell/platform/windows/keyboard_manager.cc",
"repo_id": "engine",
"token_count": 6201
} | 414 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/sequential_id_generator.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
TEST(SequentialIdGeneratorTest, RemoveMultipleNumbers) {
const uint32_t kMinId = 4;
const uint32_t kMaxId = 128;
SequentialIdGenerator generator(kMinId, kMaxId);
EXPECT_EQ(4U, generator.GetGeneratedId(45));
EXPECT_EQ(5U, generator.GetGeneratedId(55));
EXPECT_EQ(6U, generator.GetGeneratedId(15));
generator.ReleaseNumber(45);
EXPECT_FALSE(generator.HasGeneratedIdFor(45));
generator.ReleaseNumber(15);
EXPECT_FALSE(generator.HasGeneratedIdFor(15));
EXPECT_EQ(5U, generator.GetGeneratedId(55));
EXPECT_EQ(4U, generator.GetGeneratedId(12));
generator.ReleaseNumber(12);
generator.ReleaseNumber(55);
EXPECT_EQ(4U, generator.GetGeneratedId(0));
}
TEST(SequentialIdGeneratorTest, MaybeRemoveNumbers) {
const uint32_t kMinId = 0;
const uint32_t kMaxId = 128;
SequentialIdGenerator generator(kMinId, kMaxId);
EXPECT_EQ(0U, generator.GetGeneratedId(42));
generator.ReleaseNumber(42);
EXPECT_FALSE(generator.HasGeneratedIdFor(42));
generator.ReleaseNumber(42);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/sequential_id_generator_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/sequential_id_generator_unittests.cc",
"repo_id": "engine",
"token_count": 479
} | 415 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_ENGINE_MODIFIER_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_ENGINE_MODIFIER_H_
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
#include <chrono>
#include "flutter/fml/macros.h"
namespace flutter {
// A test utility class providing the ability to access and alter various
// private fields in an Engine instance.
//
// This simply provides a way to access the normally-private embedder proc
// table, so the lifetime of any changes made to the proc table is that of the
// engine object, not this helper.
class EngineModifier {
public:
explicit EngineModifier(FlutterWindowsEngine* engine) : engine_(engine) {}
// Returns the engine's embedder API proc table, allowing for modification.
//
// Modifications are to the engine, and will last for the lifetime of the
// engine unless overwritten again.
FlutterEngineProcTable& embedder_api() { return engine_->embedder_api_; }
// Override the EGL manager used by the engine.
//
// Modifications are to the engine, and will last for the lifetime of the
// engine unless overwritten again.
void SetEGLManager(std::unique_ptr<egl::Manager> egl_manager) {
engine_->egl_manager_ = std::move(egl_manager);
}
// Override the engine's implicit view. This is the "default" view
// that Flutter apps render to.
void SetImplicitView(FlutterWindowsView* view) {
engine_->views_[kImplicitViewId] = view;
}
/// Reset the start_time field that is used to align vsync events.
void SetStartTime(uint64_t start_time_nanos) {
engine_->start_time_ = std::chrono::nanoseconds(start_time_nanos);
}
/// Override the frame interval to the provided nanosecond interval.
///
/// This will prevent the windows engine from delegating to dwm to
/// discover the true frame interval, which can vary across machines.
void SetFrameInterval(uint64_t frame_interval_nanos) {
engine_->frame_interval_override_ =
std::optional<std::chrono::nanoseconds>(frame_interval_nanos);
}
// Explicitly releases the egl::Manager being used by the
// FlutterWindowsEngine instance. This should be used if SetEGLManager is
// used to explicitly set to a non-null value (but not a valid object) to test
// a successful ANGLE initialization.
//
// Modifications are to the engine, and will last for the lifetime of the
// engine unless overwritten again.
void ReleaseEGLManager() { engine_->egl_manager_.release(); }
// Run the FlutterWindowsEngine's handler that runs right before an engine
// restart. This resets the keyboard's state if it exists.
void Restart() { engine_->OnPreEngineRestart(); }
// Initialize they keyboard and text input subsystems or reset them them if
// they are already initialized.
void InitializeKeyboard() { engine_->InitializeKeyboard(); }
void SetLifecycleManager(std::unique_ptr<WindowsLifecycleManager>&& handler) {
engine_->lifecycle_manager_ = std::move(handler);
}
void SetPlatformViewPlugin(std::unique_ptr<PlatformViewPlugin>&& manager) {
engine_->platform_view_plugin_ = std::move(manager);
}
private:
FlutterWindowsEngine* engine_;
FML_DISALLOW_COPY_AND_ASSIGN(EngineModifier);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_ENGINE_MODIFIER_H_
| engine/shell/platform/windows/testing/engine_modifier.h/0 | {
"file_path": "engine/shell/platform/windows/testing/engine_modifier.h",
"repo_id": "engine",
"token_count": 1052
} | 416 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "flutter/shell/platform/windows/testing/test_keyboard.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
TEST(TestKeyboard, CloneString) {
const char* str1 = "123";
char* cloned_str1 = clone_string(str1);
EXPECT_STREQ(str1, cloned_str1);
EXPECT_NE(str1, cloned_str1);
delete[] cloned_str1;
EXPECT_EQ(clone_string(nullptr), nullptr);
};
TEST(TestKeyboard, CreateKeyEventLparam) {
EXPECT_EQ(CreateKeyEventLparam(0x1, true, true), 0xC1010001);
EXPECT_EQ(CreateKeyEventLparam(0x05, false, false, 0, 1, 0), 0x20050000);
};
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/testing/test_keyboard_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/testing/test_keyboard_unittests.cc",
"repo_id": "engine",
"token_count": 295
} | 417 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_BINDING_HANDLER_DELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_BINDING_HANDLER_DELEGATE_H_
#include <functional>
#include "flutter/shell/platform/common/geometry.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/windows/windows_lifecycle_manager.h"
#include "flutter/third_party/accessibility/ax/platform/ax_fragment_root_delegate_win.h"
#include "flutter/third_party/accessibility/gfx/native_widget_types.h"
namespace flutter {
class WindowBindingHandlerDelegate {
public:
using KeyEventCallback = std::function<void(bool)>;
// Notifies delegate that backing window size has changed.
//
// Called by |FlutterWindow| on the platform thread.
//
// Returns true if the delegate completed the window resize synchronously.
// The return value is exposed for unit testing.
virtual bool OnWindowSizeChanged(size_t width, size_t height) = 0;
// Notifies delegate that backing window needs to be repainted.
// Typically called by currently configured WindowBindingHandler.
virtual void OnWindowRepaint() = 0;
// Notifies delegate that backing window mouse has moved.
// Typically called by currently configured WindowBindingHandler.
virtual void OnPointerMove(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id,
int modifiers_state) = 0;
// Notifies delegate that backing window mouse pointer button has been
// pressed. Typically called by currently configured WindowBindingHandler.
virtual void OnPointerDown(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id,
FlutterPointerMouseButtons button) = 0;
// Notifies delegate that backing window mouse pointer button has been
// released. Typically called by currently configured WindowBindingHandler.
virtual void OnPointerUp(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id,
FlutterPointerMouseButtons button) = 0;
// Notifies delegate that backing window mouse pointer has left the window.
// Typically called by currently configured WindowBindingHandler.
virtual void OnPointerLeave(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id) = 0;
// Notifies delegate that a pan/zoom gesture has started.
// Typically called by DirectManipulationEventHandler.
virtual void OnPointerPanZoomStart(int32_t device_id) = 0;
// Notifies delegate that a pan/zoom gesture has updated.
// Typically called by DirectManipulationEventHandler.
virtual void OnPointerPanZoomUpdate(int32_t device_id,
double pan_x,
double pan_y,
double scale,
double rotation) = 0;
// Notifies delegate that a pan/zoom gesture has ended.
// Typically called by DirectManipulationEventHandler.
virtual void OnPointerPanZoomEnd(int32_t device_id) = 0;
// Notifies delegate that backing window has received text.
// Typically called by currently configured WindowBindingHandler.
virtual void OnText(const std::u16string&) = 0;
// Notifies delegate that backing window size has received key press. Should
// return true if the event was handled and should not be propagated.
// Typically called by currently configured WindowBindingHandler.
virtual void OnKey(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
KeyEventCallback callback) = 0;
// Notifies the delegate that IME composing mode has begun.
//
// Triggered when the user begins editing composing text using a multi-step
// input method such as in CJK text input.
virtual void OnComposeBegin() = 0;
// Notifies the delegate that IME composing region have been committed.
//
// Triggered when the user triggers a commit of the current composing text
// while using a multi-step input method such as in CJK text input. Composing
// continues with the next keypress.
virtual void OnComposeCommit() = 0;
// Notifies the delegate that IME composing mode has ended.
//
// Triggered when the composing ends, for example when the user presses
// ESC or when the user triggers a commit of the composing text while using a
// multi-step input method such as in CJK text input.
virtual void OnComposeEnd() = 0;
// Notifies the delegate that IME composing region contents have changed.
//
// Triggered when the user edits the composing text while using a multi-step
// input method such as in CJK text input.
virtual void OnComposeChange(const std::u16string& text, int cursor_pos) = 0;
// Notifies delegate that backing window size has recevied scroll.
// Typically called by currently configured WindowBindingHandler.
virtual void OnScroll(double x,
double y,
double delta_x,
double delta_y,
int scroll_offset_multiplier,
FlutterPointerDeviceKind device_kind,
int32_t device_id) = 0;
// Notifies delegate that scroll inertia should be cancelled.
// Typically called by DirectManipulationEventHandler
virtual void OnScrollInertiaCancel(int32_t device_id) = 0;
// Notifies delegate that the Flutter semantics tree should be enabled or
// disabled.
virtual void OnUpdateSemanticsEnabled(bool enabled) = 0;
// Returns the root view accessibility node, or nullptr if none.
virtual gfx::NativeViewAccessible GetNativeViewAccessible() = 0;
// Update the status of the high contrast feature.
virtual void OnHighContrastChanged() = 0;
// Obtain a pointer to the fragment root delegate.
// This is required by UIA in order to obtain the fragment root that
// contains a fragment obtained by, for example, a hit test. Unlike
// MSAA, UIA elements do not explicitly store or enumerate their
// children and parents, so a method such as this is required.
virtual ui::AXFragmentRootDelegateWin* GetAxFragmentRootDelegate() = 0;
// Called when a window receives an event that may alter application lifecycle
// state.
virtual void OnWindowStateEvent(HWND hwnd, WindowStateEvent event) = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_BINDING_HANDLER_DELEGATE_H_
| engine/shell/platform/windows/window_binding_handler_delegate.h/0 | {
"file_path": "engine/shell/platform/windows/window_binding_handler_delegate.h",
"repo_id": "engine",
"token_count": 2553
} | 418 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/impeller/tools/impeller.gni")
import("//flutter/shell/gpu/gpu.gni")
if (is_fuchsia) {
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
}
shell_gpu_configuration("tester_gpu_configuration") {
enable_software = true
enable_gl = true
enable_vulkan = true
enable_metal = false
}
executable("testing") {
output_name = "flutter_tester"
public_configs = [
"//flutter:config",
"//flutter:export_dynamic_test_symbols",
]
sources = [ "tester_main.cc" ]
libs = []
if (is_win) {
libs += [
"psapi.lib",
"user32.lib",
"FontSub.lib",
"shlwapi.lib",
]
}
deps = [
"$dart_src/runtime:libdart_jit",
"$dart_src/runtime/bin:dart_io_api",
"//flutter/assets",
"//flutter/common",
"//flutter/flow",
"//flutter/fml",
"//flutter/lib/snapshot",
"//flutter/shell/common",
"//flutter/shell/gpu:gpu_surface_software",
"//flutter/skia",
"//flutter/third_party/abseil-cpp/absl/base:no_destructor",
"//flutter/third_party/tonic",
]
if (impeller_supports_rendering) {
deps += [
":tester_gpu_configuration",
"//flutter/impeller",
"//flutter/third_party/swiftshader/src/Vulkan:swiftshader_libvulkan_static",
]
}
metadata = {
entitlement_file_path = [ "flutter_tester" ]
}
}
| engine/shell/testing/BUILD.gn/0 | {
"file_path": "engine/shell/testing/BUILD.gn",
"repo_id": "engine",
"token_count": 649
} | 419 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
_skia_root = "//flutter/third_party/skia"
import("$_skia_root/modules/skcms/skcms.gni")
# Use for CPU-specific skcms transform code that needs particular compiler flags.
# (This is patterned after `opts` in Skia's BUILD.gn.)
template("arch") {
if (invoker.enabled) {
source_set(target_name) {
visibility = [ ":*" ]
check_includes = false
forward_variables_from(invoker, "*")
}
} else {
# If not enabled, a phony empty target that swallows all otherwise unused variables.
source_set(target_name) {
visibility = [ ":*" ]
check_includes = false
forward_variables_from(invoker,
"*",
[
"sources",
"cflags",
"defines",
])
}
}
}
arch("skcms_TransformHsw") {
enabled = current_cpu == "x64" && target_os != "android"
sources = skcms_TransformHsw
if (is_win) {
if (is_clang) {
cflags = [
"/clang:-mavx2",
"/clang:-mf16c",
"/clang:-ffp-contract=off",
]
} else {
cflags = [ "/arch:AVX2" ]
}
} else {
cflags = [
"-mavx2",
"-mf16c",
"-std=c11",
]
}
}
arch("skcms_TransformSkx") {
enabled = current_cpu == "x64" && target_os != "android"
sources = skcms_TransformSkx
if (is_win) {
if (is_clang) {
cflags = [
"/clang:-mavx512f",
"/clang:-mavx512dq",
"/clang:-mavx512cd",
"/clang:-mavx512bw",
"/clang:-mavx512vl",
"/clang:-ffp-contract=off",
]
} else {
cflags = [ "/arch:AVX512" ]
}
} else {
cflags = [
"-mavx512f",
"-mavx512dq",
"-mavx512cd",
"-mavx512bw",
"-mavx512vl",
"-std=c11",
]
}
}
static_library("skcms") {
cflags = []
if (!is_win || is_clang) {
cflags += [ "-std=c11" ]
}
if (target_cpu != "x64" || target_os == "android") {
defines = [
"SKCMS_DISABLE_HSW",
"SKCMS_DISABLE_SKX",
]
}
public = skcms_public_headers
sources = skcms_public + skcms_TransformBaseline
deps = [
":skcms_TransformHsw",
":skcms_TransformSkx",
]
}
| engine/skia/modules/skcms/BUILD.gn/0 | {
"file_path": "engine/skia/modules/skcms/BUILD.gn",
"repo_id": "engine",
"token_count": 1210
} | 420 |
#!/usr/bin/env python3
#
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Generates and zip the ios flutter framework including the architecture
# dependent snapshot.
import argparse
import os
import platform
import shutil
import subprocess
import sys
from create_xcframework import create_xcframework # pylint: disable=import-error
ARCH_SUBPATH = 'mac-arm64' if platform.processor() == 'arm' else 'mac-x64'
DSYMUTIL = os.path.join(
os.path.dirname(__file__), '..', '..', '..', 'buildtools', ARCH_SUBPATH, 'clang', 'bin',
'dsymutil'
)
buildroot_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..'))
def main():
parser = argparse.ArgumentParser(
description=(
'Creates Flutter.framework, Flutter.xcframework and '
'copies architecture-dependent gen_snapshot binaries to output dir'
)
)
parser.add_argument('--dst', type=str, required=True)
parser.add_argument('--clang-dir', type=str, default='clang_x64')
parser.add_argument('--x64-out-dir', type=str)
parser.add_argument('--arm64-out-dir', type=str, required=True)
parser.add_argument('--simulator-x64-out-dir', type=str, required=True)
parser.add_argument('--simulator-arm64-out-dir', type=str, required=False)
parser.add_argument('--strip', action='store_true', default=False)
parser.add_argument('--dsym', action='store_true', default=False)
args = parser.parse_args()
dst = (args.dst if os.path.isabs(args.dst) else os.path.join(buildroot_dir, args.dst))
arm64_out_dir = (
args.arm64_out_dir
if os.path.isabs(args.arm64_out_dir) else os.path.join(buildroot_dir, args.arm64_out_dir)
)
x64_out_dir = None
if args.x64_out_dir:
x64_out_dir = (
args.x64_out_dir
if os.path.isabs(args.x64_out_dir) else os.path.join(buildroot_dir, args.x64_out_dir)
)
simulator_x64_out_dir = None
if args.simulator_x64_out_dir:
simulator_x64_out_dir = (
args.simulator_x64_out_dir if os.path.isabs(args.simulator_x64_out_dir) else
os.path.join(buildroot_dir, args.simulator_x64_out_dir)
)
framework = os.path.join(dst, 'Flutter.framework')
simulator_framework = os.path.join(dst, 'sim', 'Flutter.framework')
arm64_framework = os.path.join(arm64_out_dir, 'Flutter.framework')
simulator_x64_framework = os.path.join(simulator_x64_out_dir, 'Flutter.framework')
simulator_arm64_out_dir = None
if args.simulator_arm64_out_dir:
simulator_arm64_out_dir = (
args.simulator_arm64_out_dir if os.path.isabs(args.simulator_arm64_out_dir) else
os.path.join(buildroot_dir, args.simulator_arm64_out_dir)
)
if args.simulator_arm64_out_dir is not None:
simulator_arm64_framework = os.path.join(simulator_arm64_out_dir, 'Flutter.framework')
if not os.path.isdir(arm64_framework):
print('Cannot find iOS arm64 Framework at %s' % arm64_framework)
return 1
if not os.path.isdir(simulator_x64_framework):
print('Cannot find iOS x64 simulator Framework at %s' % simulator_framework)
return 1
if not os.path.isfile(DSYMUTIL):
print('Cannot find dsymutil at %s' % DSYMUTIL)
return 1
create_framework(
args, dst, framework, arm64_framework, simulator_framework, simulator_x64_framework,
simulator_arm64_framework
)
extension_safe_dst = os.path.join(dst, 'extension_safe')
create_extension_safe_framework(
args, extension_safe_dst, '%s_extension_safe' % arm64_out_dir,
'%s_extension_safe' % simulator_x64_out_dir, '%s_extension_safe' % simulator_arm64_out_dir
)
generate_gen_snapshot(args, dst, x64_out_dir, arm64_out_dir)
zip_archive(dst)
return 0
def create_extension_safe_framework( # pylint: disable=too-many-arguments
args, dst, arm64_out_dir, simulator_x64_out_dir, simulator_arm64_out_dir
):
framework = os.path.join(dst, 'Flutter.framework')
simulator_framework = os.path.join(dst, 'sim', 'Flutter.framework')
arm64_framework = os.path.join(arm64_out_dir, 'Flutter.framework')
simulator_x64_framework = os.path.join(simulator_x64_out_dir, 'Flutter.framework')
simulator_arm64_framework = os.path.join(simulator_arm64_out_dir, 'Flutter.framework')
if not os.path.isdir(arm64_framework):
print('Cannot find extension safe iOS arm64 Framework at %s' % arm64_framework)
return 1
if not os.path.isdir(simulator_x64_framework):
print('Cannot find extension safe iOS x64 simulator Framework at %s' % simulator_x64_framework)
return 1
create_framework(
args, dst, framework, arm64_framework, simulator_framework, simulator_x64_framework,
simulator_arm64_framework
)
return 0
def create_framework( # pylint: disable=too-many-arguments
args, dst, framework, arm64_framework, simulator_framework,
simulator_x64_framework, simulator_arm64_framework
):
arm64_dylib = os.path.join(arm64_framework, 'Flutter')
simulator_x64_dylib = os.path.join(simulator_x64_framework, 'Flutter')
simulator_arm64_dylib = os.path.join(simulator_arm64_framework, 'Flutter')
if not os.path.isfile(arm64_dylib):
print('Cannot find iOS arm64 dylib at %s' % arm64_dylib)
return 1
if not os.path.isfile(simulator_x64_dylib):
print('Cannot find iOS simulator dylib at %s' % simulator_x64_dylib)
return 1
shutil.rmtree(framework, True)
shutil.copytree(arm64_framework, framework)
framework_binary = os.path.join(framework, 'Flutter')
process_framework(args, dst, framework, framework_binary)
if args.simulator_arm64_out_dir is not None:
shutil.rmtree(simulator_framework, True)
shutil.copytree(simulator_arm64_framework, simulator_framework)
simulator_framework_binary = os.path.join(simulator_framework, 'Flutter')
# Create the arm64/x64 simulator fat framework.
subprocess.check_call([
'lipo', simulator_x64_dylib, simulator_arm64_dylib, '-create', '-output',
simulator_framework_binary
])
process_framework(args, dst, simulator_framework, simulator_framework_binary)
else:
simulator_framework = simulator_x64_framework
# Create XCFramework from the arm-only fat framework and the arm64/x64
# simulator frameworks, or just the x64 simulator framework if only that one
# exists.
xcframeworks = [simulator_framework, framework]
create_xcframework(location=dst, name='Flutter', frameworks=xcframeworks)
# Add the x64 simulator into the fat framework
subprocess.check_call([
'lipo', arm64_dylib, simulator_x64_dylib, '-create', '-output', framework_binary
])
process_framework(args, dst, framework, framework_binary)
return 0
def embed_codesign_configuration(config_path, contents):
with open(config_path, 'w') as file:
file.write('\n'.join(contents) + '\n')
def zip_archive(dst):
ios_file_with_entitlements = ['gen_snapshot_arm64']
ios_file_without_entitlements = [
'Flutter.xcframework/ios-arm64/Flutter.framework/Flutter',
'Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter',
'extension_safe/Flutter.xcframework/ios-arm64/Flutter.framework/Flutter',
'extension_safe/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter'
]
embed_codesign_configuration(os.path.join(dst, 'entitlements.txt'), ios_file_with_entitlements)
embed_codesign_configuration(
os.path.join(dst, 'without_entitlements.txt'), ios_file_without_entitlements
)
subprocess.check_call([
'zip',
'-r',
'artifacts.zip',
'gen_snapshot_arm64',
'Flutter.xcframework',
'entitlements.txt',
'without_entitlements.txt',
'extension_safe/Flutter.xcframework',
],
cwd=dst)
if os.path.exists(os.path.join(dst, 'Flutter.dSYM')):
subprocess.check_call(['zip', '-r', 'Flutter.dSYM.zip', 'Flutter.dSYM'], cwd=dst)
if os.path.exists(os.path.join(dst, 'extension_safe', 'Flutter.dSYM')):
subprocess.check_call(['zip', '-r', 'extension_safe_Flutter.dSYM.zip', 'Flutter.dSYM'], cwd=dst)
def process_framework(args, dst, framework, framework_binary):
if args.dsym:
dsym_out = os.path.splitext(framework)[0] + '.dSYM'
subprocess.check_call([DSYMUTIL, '-o', dsym_out, framework_binary])
if args.strip:
# copy unstripped
unstripped_out = os.path.join(dst, 'Flutter.unstripped')
shutil.copyfile(framework_binary, unstripped_out)
subprocess.check_call(['strip', '-x', '-S', framework_binary])
def generate_gen_snapshot(args, dst, x64_out_dir, arm64_out_dir):
if x64_out_dir:
_generate_gen_snapshot(x64_out_dir, os.path.join(dst, 'gen_snapshot_x64'))
if arm64_out_dir:
_generate_gen_snapshot(
os.path.join(arm64_out_dir, args.clang_dir), os.path.join(dst, 'gen_snapshot_arm64')
)
def _generate_gen_snapshot(directory, destination):
gen_snapshot_dir = os.path.join(directory, 'gen_snapshot')
if not os.path.isfile(gen_snapshot_dir):
print('Cannot find gen_snapshot at %s' % gen_snapshot_dir)
sys.exit(1)
subprocess.check_call(['xcrun', 'bitcode_strip', '-r', gen_snapshot_dir, '-o', destination])
if __name__ == '__main__':
sys.exit(main())
| engine/sky/tools/create_full_ios_framework.py/0 | {
"file_path": "engine/sky/tools/create_full_ios_framework.py",
"repo_id": "engine",
"token_count": 3585
} | 421 |
Native Activity
===============
Executables packaged as native activities in an Android APK. These activities
contain no Java code.
To create an APK of your existing `exectuable` target, replace `exectuable` with
`native_activity_apk` from the `native_activity.gni` template and give it an
`apk_name`.
## Example
```
native_activity_apk("apk_unittests") {
apk_name = "toolkit_unittests"
testonly = true
sources = [ "toolkit_android_unittests.cc" ]
deps = [
":unittests_lib",
"//flutter/testing/android/native_activity:gtest_activity",
]
}
```
One of the translation units in must contain an implementation of
`flutter::NativeActivityMain`. The `gtest_activity` target contains an
implementation of an activity that run GoogleTests. That can be used off the
shelf.
| engine/testing/android/native_activity/README.md/0 | {
"file_path": "engine/testing/android/native_activity/README.md",
"repo_id": "engine",
"token_count": 250
} | 422 |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="io.flutter.app.FlutterApplication"
android:label="Background Image Tester"
android:supportsRtl="true">
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="com.google.intent.action.TEST_LOOP" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/javascript" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
| engine/testing/android_background_image/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "engine/testing/android_background_image/android/app/src/main/AndroidManifest.xml",
"repo_id": "engine",
"token_count": 543
} | 423 |
#!/usr/bin/env python3
#
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import csv
import json
import sys
import matplotlib.pyplot as plt # pylint: disable=import-error
from matplotlib.backends.backend_pdf import PdfPages as pdfp # pylint: disable=import-error
class BenchmarkResult: # pylint: disable=too-many-instance-attributes
def __init__(self, name, backend, time_unit, draw_call_count):
self.name = name
self.series = {}
self.series_labels = {}
self.backend = backend
self.large_y_values = False
self.y_limit = 200
self.time_unit = time_unit
self.draw_call_count = draw_call_count
self.optional_values = {}
def __repr__(self):
return 'Name: % s\nBackend: % s\nSeries: % s\nSeriesLabels: % s\n' % (
self.name, self.backend, self.series, self.series_labels
)
def add_data_point(self, family, xval, yval):
if family not in self.series:
self.series[family] = {'x': [], 'y': []}
self.series[family]['x'].append(xval)
self.series[family]['y'].append(yval)
if yval > self.y_limit:
self.large_y_values = True
def add_optional_value(self, name, xval, yval):
if name not in self.optional_values:
self.optional_values[name] = {}
self.optional_values[name][xval] = yval
def set_family_label(self, family, label):
# I'm not keying the main series dict off the family label
# just in case we get data where the two aren't a 1:1 mapping
if family in self.series_labels:
assert self.series_labels[family] == label
return
self.series_labels[family] = label
def plot(self):
figures = []
figures.append(plt.figure(dpi=1200, frameon=False, figsize=(11, 8.5)))
for family in self.series:
plt.plot(self.series[family]['x'], self.series[family]['y'], label=self.series_labels[family])
plt.xlabel('Benchmark Seed')
plt.ylabel('Time (' + self.time_unit + ')')
title = ''
# Crop the Y axis so that we can see what's going on at the lower end
if self.large_y_values:
plt.ylim((0, self.y_limit))
title = self.name + ' ' + self.backend + ' (Cropped)'
else:
title = self.name + ' ' + self.backend
if self.draw_call_count != -1:
title += '\nDraw Call Count: ' + str(int(self.draw_call_count))
plt.title(title)
plt.grid(which='both', axis='both')
plt.legend(fontsize='xx-small')
plt.plot()
if self.large_y_values:
# Plot again but with the full Y axis visible
figures.append(plt.figure(dpi=1200, frameon=False, figsize=(11, 8.5)))
for family in self.series:
plt.plot(
self.series[family]['x'], self.series[family]['y'], label=self.series_labels[family]
)
plt.xlabel('Benchmark Seed')
plt.ylabel('Time (' + self.time_unit + ')')
title = self.name + ' ' + self.backend + ' (Complete)'
if self.draw_call_count != -1:
title += '\nDraw Call Count: ' + str(int(self.draw_call_count))
plt.title(title)
plt.grid(which='both', axis='both')
plt.legend(fontsize='xx-small')
plt.plot()
return figures
def write_csv(self, writer):
# For now assume that all our series have the same x values
# this is true for now, but may differ in the future with benchmark changes
x_values = []
y_values = []
for family in self.series:
x_values = ['x'] + self.series[family]['x']
y_values.append([self.series_labels[family]] + self.series[family]['y'])
for name in self.optional_values:
column = [name]
for key in self.optional_values[name]:
column.append(self.optional_values[name][key])
y_values.append(column)
writer.writerow([self.name, self.draw_call_count])
for line, _ in enumerate(x_values):
row = [x_values[line]]
for series, _ in enumerate(y_values):
row.append(y_values[series][line])
writer.writerow(row)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'filename', action='store', help='Path to the JSON output from Google Benchmark'
)
parser.add_argument(
'-o',
'--output-pdf',
dest='output_pdf',
action='store',
default='output.pdf',
help='Filename to output the PDF of graphs to.'
)
parser.add_argument(
'-c',
'--output-csv',
dest='output_csv',
action='store',
default='output.csv',
help='Filename to output the CSV data to.'
)
args = parser.parse_args()
json_data = parse_json(args.filename)
return process_benchmark_data(json_data, args.output_pdf, args.output_csv)
def error(message):
print(message)
sys.exit(1)
def extrac_attributes_label(benchmark_result):
# Possible attribute keys are:
# AntiAliasing
# HairlineStroke
# StrokedStyle
# FilledStyle
attributes = ['AntiAliasing', 'HairlineStroke', 'StrokedStyle', 'FilledStyle']
label = ''
for attr in attributes:
try:
if benchmark_result[attr] != 0:
label += attr + ', '
except KeyError:
pass
return label[:-2]
def process_benchmark_data(benchmark_json, output_pdf, output_csv):
benchmark_results_data = {}
for benchmark_result in benchmark_json:
# Skip aggregate results
if 'aggregate_name' in benchmark_result:
continue
benchmark_variant = benchmark_result['name'].split('/')
# The final split is always `real_time` and can be discarded
benchmark_variant.remove('real_time')
splits = len(benchmark_variant)
# First split is always the benchmark function name
benchmark_name = benchmark_variant[0]
# The last split is always the seeded value into the benchmark
benchmark_seeded_value = benchmark_variant[splits - 1]
# The second last split is always the backend
benchmark_backend = benchmark_variant[splits - 2]
# Time taken (wall clock time) for benchmark to run
benchmark_real_time = benchmark_result['real_time']
benchmark_unit = benchmark_result['time_unit']
benchmark_family_index = benchmark_result['family_index']
benchmark_family_label = ''
if splits > 3:
for i in range(1, splits - 2):
benchmark_family_label += benchmark_variant[i] + ', '
benchmark_family_attributes = extrac_attributes_label(benchmark_result)
if benchmark_family_attributes == '':
benchmark_family_label = benchmark_family_label[:-2]
else:
benchmark_family_label = benchmark_family_label + benchmark_family_attributes
if 'DrawCallCount' in benchmark_result:
benchmark_draw_call_count = benchmark_result['DrawCallCount']
else:
benchmark_draw_call_count = -1
optional_keys = ['DrawCallCount_Varies', 'VerbCount', 'PointCount', 'VertexCount', 'GlyphCount']
if benchmark_name not in benchmark_results_data:
benchmark_results_data[benchmark_name] = BenchmarkResult(
benchmark_name, benchmark_backend, benchmark_unit, benchmark_draw_call_count
)
for key in optional_keys:
if key in benchmark_result:
benchmark_results_data[benchmark_name].add_optional_value(
key, benchmark_seeded_value, benchmark_result[key]
)
benchmark_results_data[benchmark_name].add_data_point(
benchmark_family_index, benchmark_seeded_value, benchmark_real_time
)
benchmark_results_data[benchmark_name].set_family_label(
benchmark_family_index, benchmark_family_label
)
pdf = pdfp(output_pdf)
csv_file = open(output_csv, 'w')
csv_writer = csv.writer(csv_file)
for benchmark in benchmark_results_data:
figures = benchmark_results_data[benchmark].plot()
for fig in figures:
pdf.savefig(fig)
benchmark_results_data[benchmark].write_csv(csv_writer)
pdf.close()
def parse_json(filename):
try:
json_file = open(filename, 'r')
except: # pylint: disable=bare-except
error('Unable to load file.')
try:
json_data = json.load(json_file)
except JSONDecodeError: # pylint: disable=undefined-variable
error('Invalid JSON. Unable to parse.')
return json_data['benchmarks']
if __name__ == '__main__':
sys.exit(main())
| engine/testing/benchmark/displaylist_benchmark_parser.py/0 | {
"file_path": "engine/testing/benchmark/displaylist_benchmark_parser.py",
"repo_id": "engine",
"token_count": 3142
} | 424 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:litetest/litetest.dart';
/// Verifies Dart semantics governed by flags set by Flutter tooling.
void main() {
String greeting = 'hello';
Future<void> changeGreeting() async {
greeting += ' 1';
await Future<void>.value();
greeting += ' 2';
}
test('execution of async method starts synchronously', () async {
expect(greeting, 'hello');
final Future<void> future = changeGreeting();
expect(greeting, 'hello 1');
await future;
expect(greeting, 'hello 1 2');
});
}
| engine/testing/dart/dart_test.dart/0 | {
"file_path": "engine/testing/dart/dart_test.dart",
"repo_id": "engine",
"token_count": 229
} | 425 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('toImage succeeds', () async {
final Image image = await _createImage();
expect(image.runtimeType.toString(), equals('Image'));
image.dispose();
});
}
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_test.dart/0 | {
"file_path": "engine/testing/dart/image_test.dart",
"repo_id": "engine",
"token_count": 242
} | 426 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data' show Float64List;
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('path getBounds', () {
const Rect r = Rect.fromLTRB(1.0, 3.0, 5.0, 7.0);
final Path p = Path()..addRect(r);
expect(p.getBounds(), equals(r));
p.lineTo(20.0, 15.0);
expect(p.getBounds(), equals(const Rect.fromLTRB(1.0, 3.0, 20.0, 15.0)));
});
test('path combine rect', () {
final Rect c1 = Rect.fromCircle(center: const Offset(10.0, 10.0), radius: 10.0);
final Rect c2 = Rect.fromCircle(center: const Offset(5.0, 5.0), radius: 10.0);
final Rect c1UnionC2 = c1.expandToInclude(c2);
final Rect c1IntersectC2 = c1.intersect(c2);
final Path pathCircle1 = Path()..addRect(c1);
final Path pathCircle2 = Path()..addRect(c2);
final Path difference = Path.combine(PathOperation.difference, pathCircle1, pathCircle2);
expect(difference.getBounds(), equals(c1));
final Path reverseDifference = Path.combine(PathOperation.reverseDifference, pathCircle1, pathCircle2);
expect(reverseDifference.getBounds(), equals(c2));
final Path union = Path.combine(PathOperation.union, pathCircle1, pathCircle2);
expect(union.getBounds(), equals(c1UnionC2));
final Path intersect = Path.combine(PathOperation.intersect, pathCircle1, pathCircle2);
expect(intersect.getBounds(), equals(c1IntersectC2));
// the bounds on this will be the same as union - but would draw a missing inside piece.
final Path xor = Path.combine(PathOperation.xor, pathCircle1, pathCircle2);
expect(xor.getBounds(), equals(c1UnionC2));
});
test('path combine oval', () {
final Rect c1 = Rect.fromCircle(center: const Offset(10.0, 10.0), radius: 10.0);
final Rect c2 = Rect.fromCircle(center: const Offset(5.0, 5.0), radius: 10.0);
final Rect c1UnionC2 = c1.expandToInclude(c2);
final Rect c1IntersectC2 = c1.intersect(c2);
final Path pathCircle1 = Path()..addOval(c1);
final Path pathCircle2 = Path()..addOval(c2);
final Path difference = Path.combine(PathOperation.difference, pathCircle1, pathCircle2);
expect(difference.getBounds().top, closeTo(0.88, 0.01));
final Path reverseDifference = Path.combine(PathOperation.reverseDifference, pathCircle1, pathCircle2);
expect(reverseDifference.getBounds().right, closeTo(14.11, 0.01));
final Path union = Path.combine(PathOperation.union, pathCircle1, pathCircle2);
expect(union.getBounds(), equals(c1UnionC2));
final Path intersect = Path.combine(PathOperation.intersect, pathCircle1, pathCircle2);
expect(intersect.getBounds(), equals(c1IntersectC2));
// the bounds on this will be the same as union - but would draw a missing inside piece.
final Path xor = Path.combine(PathOperation.xor, pathCircle1, pathCircle2);
expect(xor.getBounds(), equals(c1UnionC2));
});
test('path clone', () {
final Path p1 = Path()..lineTo(20.0, 20.0);
final Path p2 = Path.from(p1);
expect(p1.getBounds(), equals(p2.getBounds()));
p1.lineTo(10.0, 30.0);
expect(p1.getBounds().bottom, equals(p2.getBounds().bottom + 10));
});
test('shift tests', () {
const Rect bounds = Rect.fromLTRB(0.0, 0.0, 10.0, 10.0);
final Path p = Path()..addRect(bounds);
expect(p.getBounds(), equals(bounds));
final Path shifted = p.shift(const Offset(10, 10));
expect(shifted.getBounds(), equals(const Rect.fromLTRB(10, 10, 20, 20)));
});
test('transformation tests', () {
const Rect bounds = Rect.fromLTRB(0.0, 0.0, 10.0, 10.0);
final Path p = Path()..addRect(bounds);
final Float64List scaleMatrix = Float64List.fromList(<double>[
2.5, 0.0, 0.0, 0.0, // first col
0.0, 0.5, 0.0, 0.0, // second col
0.0, 0.0, 1.0, 0.0, // third col
0.0, 0.0, 0.0, 1.0, // fourth col
]);
expect(p.getBounds(), equals(bounds));
final Path pTransformed = p.transform(scaleMatrix);
expect(pTransformed.getBounds(),
equals(const Rect.fromLTRB(0.0, 0.0, 10 * 2.5, 10 * 0.5)));
final Path p2 = Path()..lineTo(10.0, 10.0);
p.addPath(p2, const Offset(10.0, 10.0));
expect(p.getBounds(), equals(const Rect.fromLTRB(0.0, 0.0, 20.0, 20.0)));
p.addPath(p2, const Offset(20.0, 20.0), matrix4: scaleMatrix);
expect(p.getBounds(),
equals(const Rect.fromLTRB(0.0, 0.0, 20 + (10 * 2.5), 20 + (10 * .5))));
p.extendWithPath(p2, Offset.zero);
expect(p.getBounds(), equals(const Rect.fromLTRB(0.0, 0.0, 45.0, 25.0)));
p.extendWithPath(p2, const Offset(45.0, 25.0), matrix4: scaleMatrix);
expect(p.getBounds(), equals(const Rect.fromLTRB(0.0, 0.0, 70.0, 30.0)));
});
test('path metrics tests', () {
final Path simpleHorizontalLine = Path()..lineTo(10.0, 0.0);
// basic tests on horizontal line
final PathMetrics simpleHorizontalMetrics = simpleHorizontalLine.computeMetrics();
expect(() => simpleHorizontalMetrics.iterator.current, throwsRangeError);
expect(simpleHorizontalMetrics.iterator.moveNext(), isTrue);
expect(simpleHorizontalMetrics.iterator.current, isNotNull);
expect(simpleHorizontalMetrics.iterator.current.length, equals(10.0));
expect(simpleHorizontalMetrics.iterator.current.isClosed, isFalse);
final Path simpleExtract = simpleHorizontalMetrics.iterator.current.extractPath(1.0, 9.0);
expect(simpleExtract.getBounds(), equals(const Rect.fromLTRB(1.0, 0.0, 9.0, 0.0)));
final Tangent posTan = simpleHorizontalMetrics.iterator.current.getTangentForOffset(1.0)!;
expect(posTan.position, equals(const Offset(1.0, 0.0)));
expect(posTan.angle, equals(0.0));
expect(simpleHorizontalMetrics.iterator.moveNext(), isFalse);
expect(() => simpleHorizontalMetrics.iterator.current, throwsRangeError);
// test with forceClosed
final PathMetrics simpleMetricsClosed = simpleHorizontalLine.computeMetrics(forceClosed: true);
expect(() => simpleHorizontalMetrics.iterator.current, throwsRangeError);
expect(simpleMetricsClosed.iterator.moveNext(), isTrue);
expect(simpleMetricsClosed.iterator.current, isNotNull);
expect(simpleMetricsClosed.iterator.current.length, equals(20.0)); // because we forced close
expect(simpleMetricsClosed.iterator.current.isClosed, isTrue);
final Path simpleExtract2 = simpleMetricsClosed.iterator.current.extractPath(1.0, 9.0);
expect(simpleExtract2.getBounds(), equals(const Rect.fromLTRB(1.0, 0.0, 9.0, 0.0)));
expect(simpleMetricsClosed.iterator.moveNext(), isFalse);
// test getTangentForOffset with vertical line
final Path simpleVerticalLine = Path()..lineTo(0.0, 10.0);
final PathMetrics simpleMetricsVertical = simpleVerticalLine.computeMetrics()..iterator.moveNext();
final Tangent posTanVertical = simpleMetricsVertical.iterator.current.getTangentForOffset(5.0)!;
expect(posTanVertical.position, equals(const Offset(0.0, 5.0)));
expect(posTanVertical.angle, closeTo(-1.5708, .0001)); // 90 degrees
// test getTangentForOffset with diagonal line
final Path simpleDiagonalLine = Path()..lineTo(10.0, 10.0);
final PathMetrics simpleMetricsDiagonal = simpleDiagonalLine.computeMetrics()..iterator.moveNext();
final double midPoint = simpleMetricsDiagonal.iterator.current.length / 2;
final Tangent posTanDiagonal = simpleMetricsDiagonal.iterator.current.getTangentForOffset(midPoint)!;
expect(posTanDiagonal.position, equals(const Offset(5.0, 5.0)));
expect(posTanDiagonal.angle, closeTo(-0.7853981633974483, .00001)); // ~45 degrees
// test a multi-contour path
final Path multiContour = Path()
..lineTo(0.0, 10.0)
..moveTo(10.0, 10.0)
..lineTo(10.0, 15.0);
final PathMetrics multiContourMetric = multiContour.computeMetrics();
expect(() => multiContourMetric.iterator.current, throwsRangeError);
expect(multiContourMetric.iterator.moveNext(), isTrue);
expect(multiContourMetric.iterator.current, isNotNull);
expect(multiContourMetric.iterator.current.length, equals(10.0));
expect(multiContourMetric.iterator.moveNext(), isTrue);
expect(multiContourMetric.iterator.current, isNotNull);
expect(multiContourMetric.iterator.current.length, equals(5.0));
expect(multiContourMetric.iterator.moveNext(), isFalse);
expect(() => multiContourMetric.iterator.current, throwsRangeError);
});
test('PathMetrics can remember lengths and isClosed', () {
final Path path = Path()..lineTo(0, 10)
..close()
..moveTo(0, 15)
..lineTo(10, 15);
final List<PathMetric> metrics = path.computeMetrics().toList();
expect(metrics.length, 2);
expect(metrics[0].length, 20);
expect(metrics[0].isClosed, true);
expect(metrics[0].getTangentForOffset(4.0)!.vector, const Offset(0.0, 1.0));
expect(metrics[0].extractPath(4.0, 10.0).computeMetrics().first.length, 6.0);
expect(metrics[1].length, 10);
expect(metrics[1].isClosed, false);
expect(metrics[1].getTangentForOffset(4.0)!.vector, const Offset(1.0, 0.0));
expect(metrics[1].extractPath(4.0, 6.0).computeMetrics().first.length, 2.0);
});
test('PathMetrics on a mutated path', () {
final Path path = Path()..lineTo(0, 10);
final PathMetrics metrics = path.computeMetrics();
final PathMetric firstMetric = metrics.first;
// We've consumed the iterator.
expect(metrics, isEmpty);
expect(firstMetric.length, 10);
expect(firstMetric.isClosed, false);
expect(firstMetric.getTangentForOffset(4.0)!.vector, const Offset(0.0, 1.0));
expect(firstMetric.extractPath(4.0, 10.0).computeMetrics().first.length, 6.0);
path..lineTo(10, 10)..lineTo(10, 0)..close();
// mutating the path shouldn't have added anything to the iterator.
expect(metrics, isEmpty);
expect(firstMetric.length, 10);
expect(firstMetric.isClosed, false);
expect(firstMetric.getTangentForOffset(4.0)!.vector, const Offset(0.0, 1.0));
expect(firstMetric.extractPath(4.0, 10.0).computeMetrics().first.length, 6.0);
// getting a new iterator should update us.
final PathMetrics newMetrics = path.computeMetrics();
final PathMetric newFirstMetric = newMetrics.first;
expect(newMetrics, isEmpty);
expect(newFirstMetric.length, 40);
expect(newFirstMetric.isClosed, true);
expect(newFirstMetric.getTangentForOffset(4.0)!.vector, const Offset(0.0, 1.0));
expect(newFirstMetric.extractPath(4.0, 10.0).computeMetrics().first.length, 6.0);
});
test('PathMetrics on a mutated path', () {
final Path path = Path()
..lineTo(0, 30)
..lineTo(40, 30)
..moveTo(100, 0)
..lineTo(100, 30)
..lineTo(140, 30)
..close();
final PathMetrics metrics = path.computeMetrics();
expect(metrics.toString(),
'(PathMetric(length: 70.0, isClosed: false, contourIndex: 0), '
'PathMetric(length: 120.0, isClosed: true, contourIndex: 1))',
);
});
}
| engine/testing/dart/path_test.dart/0 | {
"file_path": "engine/testing/dart/path_test.dart",
"repo_id": "engine",
"token_count": 4303
} | 427 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('window.sendPlatformMessage preserves callback zone', () {
runZoned(() {
final Zone innerZone = Zone.current;
PlatformDispatcher.instance.sendPlatformMessage('test', ByteData.view(Uint8List(0).buffer), expectAsync1((ByteData? data) {
final Zone runZone = Zone.current;
expect(runZone, isNotNull);
expect(runZone, same(innerZone));
}));
});
});
test('FrameTiming.toString has the correct format', () {
final FrameTiming timing = FrameTiming(
vsyncStart: 500,
buildStart: 1000,
buildFinish: 8000,
rasterStart: 9000,
rasterFinish: 19500,
rasterFinishWallTime: 19501,
frameNumber: 23,
);
expect(timing.toString(),
'FrameTiming(buildDuration: 7.0ms, '
'rasterDuration: 10.5ms, '
'vsyncOverhead: 0.5ms, '
'totalSpan: 19.0ms, '
'layerCacheCount: 0, '
'layerCacheBytes: 0, '
'pictureCacheCount: 0, '
'pictureCacheBytes: 0, '
'frameNumber: 23)');
});
test('FrameTiming.toString with cache statistics has the correct format', () {
final FrameTiming timing = FrameTiming(
vsyncStart: 500,
buildStart: 1000,
buildFinish: 8000,
rasterStart: 9000,
rasterFinish: 19500,
rasterFinishWallTime: 19501,
layerCacheCount: 5,
layerCacheBytes: 200000,
pictureCacheCount: 3,
pictureCacheBytes: 300000,
frameNumber: 29,
);
expect(timing.toString(),
'FrameTiming(buildDuration: 7.0ms, '
'rasterDuration: 10.5ms, '
'vsyncOverhead: 0.5ms, '
'totalSpan: 19.0ms, '
'layerCacheCount: 5, '
'layerCacheBytes: 200000, '
'pictureCacheCount: 3, '
'pictureCacheBytes: 300000, '
'frameNumber: 29)');
});
test('computePlatformResolvedLocale basic', () {
final List<Locale> supportedLocales = <Locale>[
const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),
const Locale.fromSubtags(languageCode: 'fr', countryCode: 'FR'),
const Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
const Locale.fromSubtags(languageCode: 'en'),
];
// The default implementation returns null due to lack of a real platform.
final Locale? result = PlatformDispatcher.instance.computePlatformResolvedLocale(supportedLocales);
expect(result, null);
});
test('Display is configured for the implicitView', () {
final FlutterView implicitView = PlatformDispatcher.instance.implicitView!;
final Display display = implicitView.display;
expect(display.id, 0);
expect(display.devicePixelRatio, implicitView.devicePixelRatio);
expect(display.refreshRate, 60);
expect(display.size, implicitView.physicalSize);
});
test('FlutterView.toString contains the viewId', () {
final FlutterView flutterView = PlatformDispatcher.instance.implicitView!;
expect(flutterView.viewId, 0);
expect(flutterView.toString(), 'FlutterView(id: 0)');
});
test('scaleFontSize is the identity function by default when textScaleFactor = 1', () {
expect(PlatformDispatcher.instance.scaleFontSize(0), 0.0);
expect(PlatformDispatcher.instance.scaleFontSize(1), 1.0);
expect(PlatformDispatcher.instance.scaleFontSize(2), 2.0);
expect(PlatformDispatcher.instance.scaleFontSize(3), 3.0);
expect(PlatformDispatcher.instance.scaleFontSize(3.4), 3.4);
});
}
| engine/testing/dart/window_test.dart/0 | {
"file_path": "engine/testing/dart/window_test.dart",
"repo_id": "engine",
"token_count": 1492
} | 428 |
# This configuration file specifies several test suites with their package and
# test command for femu_test.py.
- test_command: test run fuchsia-pkg://fuchsia.com/dart_runner_tests#meta/dart_runner_tests.cm
package: dart_runner_tests-0.far
- test_command: test run fuchsia-pkg://fuchsia.com/flutter_runner_tests#meta/flutter_runner_tests.cm
package: flutter_runner_tests-0.far
- test_command: test run fuchsia-pkg://fuchsia.com/flutter_runner_tzdata_tests#meta/flutter_runner_tzdata_tests.cm
package: flutter_runner_tzdata_tests-0.far
- test_command: test run fuchsia-pkg://fuchsia.com/flutter_runner_tzdata_missing_tests#meta/flutter_runner_tzdata_missing_tests.cm
package: flutter_runner_tzdata_missing_tests-0.far
- test_command: test run fuchsia-pkg://fuchsia.com/fml_tests#meta/fml_tests.cm
package: fml_tests-0.far
- test_command: test run fuchsia-pkg://fuchsia.com/display_list_tests#meta/display_list_tests.cm
package: display_list_tests-0.far
- test_command: test run fuchsia-pkg://fuchsia.com/display_list_render_tests#meta/display_list_render_tests.cm
package: display_list_render_tests-0.far
disabled: on arm64 because of the slowness
variant: x64
- test_command: test run fuchsia-pkg://fuchsia.com/flow_tests#meta/flow_tests.cm
package: flow_tests-0.far
- test_command: test run fuchsia-pkg://fuchsia.com/runtime_tests#meta/runtime_tests.cm
package: runtime_tests-0.far
disabled: on debug_arm64 because of the slowness
variant: debug_x64
- test_command: test run fuchsia-pkg://fuchsia.com/shell_tests#meta/shell_tests.cm
package: shell_tests-0.far
variant: debug_x64
- test_command: test run fuchsia-pkg://fuchsia.com/testing_tests#meta/testing_tests.cm
package: testing_tests-0.far
- test_command: test run fuchsia-pkg://fuchsia.com/txt_tests#meta/txt_tests.cm -- --gtest_filter=-ParagraphTest.*
package: txt_tests-0.far
variant: debug
- test_command: test run fuchsia-pkg://fuchsia.com/ui_tests#meta/ui_tests.cm
package: ui_tests-0.far
disabled: on debug_arm64 because of the slowness
variant: debug_x64
- test_command: test run fuchsia-pkg://fuchsia.com/embedder_tests#meta/embedder_tests.cm
package: embedder_tests-0.far
variant: debug_x64
- test_command: test run fuchsia-pkg://fuchsia.com/dart_utils_tests#meta/dart_utils_tests.cm
package: dart_utils_tests-0.far
- test_command: test run fuchsia-pkg://fuchsia.com/dart-jit-runner-integration-test#meta/dart-jit-runner-integration-test.cm
packages:
- oot_dart_jit_runner-0.far
- dart-jit-runner-integration-test-0.far
- gen/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/dart_jit_echo_server/dart_jit_echo_server.far
emulator_arch:
- 'x64'
- 'arm64'
variant: debug
- test_command: test run fuchsia-pkg://fuchsia.com/dart-aot-runner-integration-test#meta/dart-aot-runner-integration-test.cm
run_with_dart_aot: 'true'
packages:
- oot_dart_aot_runner-0.far
- dart-aot-runner-integration-test-0.far
- gen/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/dart_aot_echo_server/dart_aot_echo_server.far
emulator_arch:
- 'x64'
- 'arm64'
variant: profile
- test_command: test run fuchsia-pkg://fuchsia.com/flutter-embedder-test#meta/flutter-embedder-test.cm
packages:
- flutter-embedder-test-0.far
- oot_flutter_jit_runner-0.far
- gen/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/child-view/child-view.far
- gen/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/parent-view/parent-view.far
variant: debug_x64
- test_command: test run fuchsia-pkg://fuchsia.com/touch-input-test#meta/touch-input-test.cm
packages:
- touch-input-test-0.far
- oot_flutter_jit_runner-0.far
- gen/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/touch-input-view/touch-input-view.far
- gen/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/embedding-flutter-view/embedding-flutter-view.far
variant: debug_x64
- test_command: test run fuchsia-pkg://fuchsia.com/mouse-input-test#meta/mouse-input-test.cm
packages:
- mouse-input-test-0.far
- oot_flutter_jit_runner-0.far
- gen/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/mouse-input-view/mouse-input-view.far
- test_command: test run fuchsia-pkg://fuchsia.com/text-input-test#meta/text-input-test.cm
packages:
- text-input-test-0.far
- oot_flutter_jit_runner-0.far
- gen/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/text-input-view/text-input-view.far
variant: debug_x64
| engine/testing/fuchsia/test_suites.yaml/0 | {
"file_path": "engine/testing/fuchsia/test_suites.yaml",
"repo_id": "engine",
"token_count": 1817
} | 429 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io' show stdout;
import 'dart:isolate';
import 'package:async_helper/async_minitest.dart' as m;
import 'package:expect/expect.dart' as e;
/// The state that each [Test] may be in.
enum TestState {
/// Initial state of a [Test] after it has been allocated.
allocated,
/// State of a [Test] when it is on the queue of a [TestSuite].
queued,
/// State of a [Test] when it has been started.
started,
/// State of a [Test] when it has succeeded.
succeeded,
/// State of a [Test] when it has failed.
failed,
}
/// A test that a [TestSuite] can enqueue to run.
class Test {
/// Creates a [Test] with the given name, body, logger, and lifecycle.
Test(
this.name,
this.body, {
StringSink? logger,
TestLifecycle? lifecycle,
}) :
_logger = logger ?? stdout,
_lifecycle = lifecycle ?? _DefaultTestLifecycle(name);
/// The name of the test.
final String name;
/// The body of the test.
final dynamic Function() body;
/// The logger that records information about the test.
final StringSink _logger;
/// The state that the test is in.
TestState state = TestState.allocated;
final TestLifecycle _lifecycle;
/// Runs the test.
///
/// Also signals the test's progress to the [TestLifecycle] object
/// that was provided when the [Test] was constructed, which will eventually
/// call the provided [onDone] callback.
void run({
void Function()? onDone,
}) {
m.test(name, () async {
await Future<void>(() async {
state = TestState.started;
_logger.writeln('Test "$name": Started');
try {
await body();
state = TestState.succeeded;
_logger.writeln('Test "$name": Passed');
} on e.ExpectException catch (e, st) {
state = TestState.failed;
_logger.writeln('Test "$name": Failed\n$e\n$st');
} finally {
_lifecycle.onDone(cleanup: onDone);
}
});
});
_lifecycle.onStart();
}
}
/// Callbacks for the lifecycle of a test.
abstract class TestLifecycle {
/// Called after a test has started.
void onStart();
/// Called when a test is finished.
///
/// The callback should ensure that the [cleanup] function should run
/// eventually if provided.
void onDone({void Function()? cleanup});
}
class _DefaultTestLifecycle implements TestLifecycle {
_DefaultTestLifecycle(String name) : _port = ReceivePort(name);
final ReceivePort _port;
void Function()? _cleanup;
@override
void onStart() {
_port.listen((dynamic msg) {
_port.close();
if (_cleanup != null) {
_cleanup!();
}
});
}
@override
void onDone({void Function()? cleanup}) {
_port.sendPort.send(null);
_cleanup = cleanup;
}
}
| engine/testing/litetest/lib/src/test.dart/0 | {
"file_path": "engine/testing/litetest/lib/src/test.dart",
"repo_id": "engine",
"token_count": 1067
} | 430 |
# Scenario App
[](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3A%22e%3A+scenario-app%22)
This package simulates a Flutter app that uses the engine (`dart:ui`) only,
in conjunction with Android and iOS-specific embedding code that simulates the
use of the engine in a real app (such as plugins and platform views).
The [`bin/run_android_tests.dart`](bin/run_android_tests.dart) and
[`run_ios_tests.sh`](run_ios_tests.sh) are then used to run the tests on a
connected device or emulator.
See also:
- [File an issue][file_issue] with the `e: scenario-app` label.
- [`bin/`](bin/), the entry point for running Android integration tests.
- [`lib/`](lib/), the Dart code and instrumentation for the scenario app.
- [`ios/`](ios/), the iOS-side native code and tests.
- [`android/`](android/), the Android-side native code and tests.
[file_issue]: https://github.com/flutter/flutter/issues/new?labels=e:%20scenario-app,engine,team-engine
## Running a smoke test on Firebase TestLab
To run the smoke test on Firebase TestLab test, build `android_profile_arm64`,
and run [`./ci/firebase_testlab.py`](../../ci/firebase_testlab.py), or pass
`--variant` to run a different configuration.
```sh
# From the root of the engine repository
$ ./ci/firebase_testlab.py --variant android_debug_arm64
```
> [!NOTE]
> These instructions were not verified at the time of writing/refactoring.
## Adding a New Scenario
Create a new subclass of [Scenario](lib/src/scenario.dart) and add it to the map
in [scenarios.dart](lib/src/scenarios.dart). For an example, see
[animated_color_square.dart](lib/src/animated_color_square.dart), which draws a
continuously animating colored square that bounces off the sides of the
viewport.
Then set the scenario from the Android or iOS app by calling `set_scenario` on
platform channel `driver`.
| engine/testing/scenario_app/README.md/0 | {
"file_path": "engine/testing/scenario_app/README.md",
"repo_id": "engine",
"token_count": 644
} | 431 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.scenariosui;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import dev.flutter.scenarios.PlatformViewsActivity;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class PlatformViewWithSurfaceViewBadContextUiTest {
Intent intent;
@Rule @NonNull
public ActivityTestRule<PlatformViewsActivity> activityRule =
new ActivityTestRule<>(
PlatformViewsActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false);
private static String goldName(String suffix) {
return "PlatformViewWithSurfaceViewBadContextUiTest_" + suffix;
}
@Before
public void setUp() {
intent = new Intent(Intent.ACTION_MAIN);
// Render a texture.
intent.putExtra("use_android_view", false);
intent.putExtra("view_type", PlatformViewsActivity.SURFACE_VIEW_BAD_CONTEXT_PV);
}
@Test
public void testPlatformView() throws Exception {
intent.putExtra("scenario_name", "platform_view");
ScreenshotUtil.capture(activityRule.launchActivity(intent), goldName("testPlatformView"));
}
}
| engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewBadContextUiTest.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewBadContextUiTest.java",
"repo_id": "engine",
"token_count": 468
} | 432 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.scenarios;
import static io.flutter.Build.API_LEVELS;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.Log;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.common.StringCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
import java.nio.ByteBuffer;
@TargetApi(API_LEVELS.API_23)
public final class SurfacePlatformViewFactory extends PlatformViewFactory {
private boolean preserveContext;
SurfacePlatformViewFactory(boolean preserveContext) {
super(
new MessageCodec<Object>() {
@Nullable
@Override
public ByteBuffer encodeMessage(@Nullable Object o) {
if (o instanceof String) {
return StringCodec.INSTANCE.encodeMessage((String) o);
}
return null;
}
@Nullable
@Override
public Object decodeMessage(@Nullable ByteBuffer byteBuffer) {
return StringCodec.INSTANCE.decodeMessage(byteBuffer);
}
});
this.preserveContext = preserveContext;
}
@SuppressWarnings("unchecked")
@Override
@NonNull
public PlatformView create(@NonNull Context context, int id, @Nullable Object args) {
if (preserveContext) {
return new SurfacePlatformView(context);
} else {
final Context differentContext = new ContextWrapper(context);
return new SurfacePlatformView(differentContext);
}
}
private static class SurfacePlatformView implements PlatformView {
static String TAG = "SurfacePlatformView";
final SurfaceView surfaceView;
@SuppressWarnings("unchecked")
SurfacePlatformView(@NonNull final Context context) {
surfaceView = new SurfaceView(context);
surfaceView
.getHolder()
.addCallback(
new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.i(TAG, "surfaceCreated");
final Surface surface = holder.getSurface();
final Canvas canvas = surface.lockHardwareCanvas();
canvas.drawColor(Color.WHITE);
final Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, 20, paint);
surface.unlockCanvasAndPost(canvas);
}
@Override
public void surfaceChanged(
SurfaceHolder holder, int format, int width, int height) {
Log.i(TAG, "surfaceChanged");
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i(TAG, "surfaceDestroyed");
}
});
}
@Override
@NonNull
public View getView() {
return surfaceView;
}
@Override
public void dispose() {}
}
}
| engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/SurfacePlatformViewFactory.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/SurfacePlatformViewFactory.java",
"repo_id": "engine",
"token_count": 1440
} | 433 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Some notes about filtering `adb logcat` output, especially as a result of
/// running `adb shell` to instrument the app and test scripts, as it's
/// non-trivial and error-prone.
///
/// 1. It's probably worth keeping `ActivityManager` lines unconditionally.
/// They are the most important ones, and they are not too verbose (for
/// example, they don't typically contain stack traces).
///
/// 2. `ActivityManager` starts with the application name and process ID:
///
/// ```txt
/// [stdout] 02-15 10:20:36.914 1735 1752 I ActivityManager: Start proc 6840:dev.flutter.scenarios/u0a98 for added application dev.flutter.scenarios
/// ```
///
/// The "application" comes from the file `android/app/build.gradle` under
/// `android > defaultConfig > applicationId`.
///
/// 3. Once we have the process ID, we can filter the logcat output further:
///
/// ```txt
/// [stdout] 02-15 10:20:37.430 6840 6840 E GeneratedPluginsRegister: Tried to automatically register plugins with FlutterEngine (io.flutter.embedding.engine.FlutterEngine@144d737) but could not find or invoke the GeneratedPluginRegistrant.
/// ```
///
/// A sample output of `adb logcat` command lives in `./sample_adb_logcat.txt`.
///
/// See also: <https://developer.android.com/tools/logcat>.
library;
import 'package:meta/meta.dart';
import 'logs.dart';
/// Represents a line of `adb logcat` output parsed into a structured form.
///
/// For example the line:
/// ```txt
/// 02-22 13:54:39.839 549 3683 I ActivityManager: Force stopping dev.flutter.scenarios appid=10226 user=0: start instr
/// ```
///
/// ## Implementation notes
///
/// The reason this is an extension type and not a class is partially to use the
/// language feature, and partially because extension types work really well
/// with lazy parsing.
extension type const AdbLogLine._(Match _match) {
// RegEx that parses into the following groups:
// 1. The time of the log message, such as `02-22 13:54:39.839`.
// 2. The process ID.
// 3. The thread ID.
// 4. The character representing the severity of the log message, such as `I`.
// 5. The tag, such as `ActivityManager`.
// 6. The actual log message.
//
// This regex is simple versus being more precise. Feel free to improve it.
static final RegExp _pattern = RegExp(r'(\d+-\d+\s[\d|:]+\.\d+)\s+(\d+)\s+(\d+)\s(\w)\s(\S+)\s*:\s*(.*)');
/// Parses the given [adbLogCatLine] into a structured form.
///
/// Returns `null` if the line does not match the expected format.
static AdbLogLine? tryParse(String adbLogCatLine) {
final Match? match = _pattern.firstMatch(adbLogCatLine);
return match == null ? null : AdbLogLine._(match);
}
/// Tries to parse the process that was started, if the log line is about it.
String? tryParseProcess() {
if (name == activityManagerTag && message.startsWith('Start proc')) {
// ActivityManager: Start proc 4475:dev.flutter.scenarios/u0a190 for added application ...
final RegExpMatch? match = RegExp('Start proc (\\d+):$flutterProcessName').firstMatch(message);
return match?.group(1);
}
return null;
}
@visibleForTesting
static const String activityManagerTag = 'ActivityManager';
@visibleForTesting
static const String flutterProcessName = 'dev.flutter.scenarios';
@visibleForTesting
static const Set<String> knownNoiseTags = <String>{
'CCodec',
'CCodecBufferChannel',
'CCodecConfig',
'Codec2Client',
'ColorUtils',
'DMABUFHEAPS',
'Gralloc4',
'MediaCodec',
'MonitoringInstr',
'ResourceExtractor',
'UsageTrackerFacilitator',
'hw-BpHwBinder',
'ziparchive',
};
@visibleForTesting
static const Set<String> knownUsefulTags = <String>{
activityManagerTag
};
@visibleForTesting
static const Set<String> knownUsefulErrorTags = <String>{
'androidemu',
'THREAD_STATE',
};
/// Returns `true` if the log line is verbose.
bool isVerbose({String? filterProcessId}) => !_isRelevant(filterProcessId: filterProcessId);
bool _isRelevant({String? filterProcessId}) {
// Fatal errors are always useful.
if (severity == 'F') {
return true;
}
// Verbose and debug logs are rarely useful.
if (severity == 'V' || severity == 'D') {
return false;
}
if (knownNoiseTags.contains(name)) {
return false;
}
if (knownUsefulTags.contains(name)) {
return true;
}
if (severity == 'E' && knownUsefulErrorTags.contains(name)) {
return true;
}
// If a process ID is specified, exclude logs _not_ from that process.
if (filterProcessId == null) {
// YOLO, let's keep it anyway.
return name.toLowerCase().contains('flutter') ||
message.toLowerCase().contains('flutter');
}
return process == filterProcessId;
}
/// Logs the line to the console.
void printFormatted() {
final String formatted = '$time [$severity] $name: $message';
if (severity == 'W' || severity == 'E' || severity == 'F') {
logWarning(formatted);
} else if (name == 'TestRunner') {
logImportant(formatted);
} else {
log(formatted);
}
}
/// The full line of `adb logcat` output.
String get line => _match.group(0)!;
/// The time of the log message, such as `02-22 13:54:39.839`.
String get time => _match.group(1)!;
/// The process ID.
String get process => _match.group(2)!;
/// The thread ID.
String get thread => _match.group(3)!;
/// The character representing the severity of the log message, such as `I`.
String get severity => _match.group(4)!;
/// The tag, such as `ActivityManager`.
String get name => _match.group(5)!;
/// The actual log message.
String get message => _match.group(6)!;
String toDebugString() {
return 'AdbLogLine(time: $time, process: $process, thread: $thread, severity: $severity, name: $name, message: $message)';
}
}
| engine/testing/scenario_app/bin/utils/adb_logcat_filtering.dart/0 | {
"file_path": "engine/testing/scenario_app/bin/utils/adb_logcat_filtering.dart",
"repo_id": "engine",
"token_count": 2049
} | 434 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_SCREENBEFOREFLUTTER_H_
#define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_SCREENBEFOREFLUTTER_H_
#import <Flutter/Flutter.h>
@interface ScreenBeforeFlutter : UIViewController
- (id)initWithEngineRunCompletion:(dispatch_block_t)engineRunCompletion;
- (FlutterViewController*)showFlutter:(dispatch_block_t)showCompletion;
@property(nonatomic, readonly) FlutterEngine* engine;
@end
#endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_SCREENBEFOREFLUTTER_H_
| engine/testing/scenario_app/ios/Scenarios/Scenarios/ScreenBeforeFlutter.h/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/ScreenBeforeFlutter.h",
"repo_id": "engine",
"token_count": 268
} | 435 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Flutter/Flutter.h>
#import <XCTest/XCTest.h>
#import "GoldenTestManager.h"
FLUTTER_ASSERT_ARC
@interface BogusFontTextTest : XCTestCase
@end
@implementation BogusFontTextTest
- (void)testFontRenderingWhenSuppliedWithBogusFont {
self.continueAfterFailure = NO;
XCUIApplication* application = [[XCUIApplication alloc] init];
application.launchArguments = @[ @"--bogus-font-text" ];
[application launch];
XCUIElement* addTextField = application.textFields[@"ready"];
XCTAssertTrue([addTextField waitForExistenceWithTimeout:30]);
GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--bogus-font-text"];
[manager checkGoldenForTest:self rmesThreshold:kDefaultRmseThreshold];
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/BogusFontTextTest.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/BogusFontTextTest.m",
"repo_id": "engine",
"token_count": 296
} | 436 |
// Copyright 2020 The Flutter 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 "StatusBarTest.h"
@implementation StatusBarTest
- (void)setUp {
[super setUp];
self.continueAfterFailure = NO;
self.application = [[XCUIApplication alloc] init];
self.application.launchArguments = @[ @"--tap-status-bar" ];
[self.application launch];
}
- (void)testTapStatusBar {
if (@available(iOS 13, *)) {
XCUIApplication* systemApp =
[[XCUIApplication alloc] initWithBundleIdentifier:@"com.apple.springboard"];
XCUIElement* statusBar = [systemApp.statusBars firstMatch];
if (statusBar.isHittable) {
[statusBar tap];
} else {
XCUICoordinate* coordinates = [statusBar coordinateWithNormalizedOffset:CGVectorMake(0, 0)];
[coordinates tap];
}
} else {
[[self.application.statusBars firstMatch] tap];
}
XCUIElement* addTextField =
self.application
.textFields[@"0,PointerChange.add,device=0,buttons=0,signalKind=PointerSignalKind.none"];
BOOL exists = [addTextField waitForExistenceWithTimeout:1];
XCTAssertTrue(exists, @"");
XCUIElement* downTextField =
self.application
.textFields[@"1,PointerChange.down,device=0,buttons=0,signalKind=PointerSignalKind.none"];
exists = [downTextField waitForExistenceWithTimeout:1];
XCTAssertTrue(exists, @"");
XCUIElement* upTextField =
self.application
.textFields[@"2,PointerChange.up,device=0,buttons=0,signalKind=PointerSignalKind.none"];
exists = [upTextField waitForExistenceWithTimeout:1];
XCTAssertTrue(exists, @"");
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/StatusBarTest.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/StatusBarTest.m",
"repo_id": "engine",
"token_count": 634
} | 437 |
// Copyright 2013 The Flutter 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:math' as math;
import 'dart:ui';
import 'scenario.dart';
/// A square that animates it color and bounces off the sides of the
/// device.
///
/// This scenario drives animation as quickly as possible, requesting new frames
/// that are constantly changing.
class AnimatedColorSquareScenario extends Scenario {
/// Creates the AnimatedColorSquare scenario.
AnimatedColorSquareScenario(super.view);
static const double _squareSize = 200;
/// Used to animate the red value in the color of the square.
final _NumberSwinger<int> _r = _NumberSwinger<int>(0, 255);
late _NumberSwinger<double> _top = _NumberSwinger<double>(
0,
view.physicalSize.height - _squareSize,
);
late _NumberSwinger<double> _left = _NumberSwinger<double>(
0,
view.physicalSize.width - _squareSize,
);
@override
void onBeginFrame(Duration duration) {
final SceneBuilder builder = SceneBuilder();
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawRect(
const Rect.fromLTWH(0, 0, _squareSize, _squareSize),
Paint()..color = Color.fromARGB(255, _r.swing(), 50, 50),
);
final Picture picture = recorder.endRecording();
builder.pushOffset(_left.swing(), _top.swing());
builder.addPicture(
Offset.zero,
picture,
willChangeHint: true,
);
final Scene scene = builder.build();
view.render(scene);
scene.dispose();
}
@override
void onDrawFrame() {
view.platformDispatcher.scheduleFrame();
}
@override
void onMetricsChanged() {
_top = _NumberSwinger<double>(
0,
view.physicalSize.height - _squareSize,
math.min(_top.current, view.physicalSize.height - _squareSize),
);
_left = _NumberSwinger<double>(
0,
view.physicalSize.width - _squareSize,
math.min(_left.current, view.physicalSize.width - _squareSize),
);
}
}
class _NumberSwinger<T extends num> {
_NumberSwinger(this._begin, this._end, [T? current])
: _up = _begin < _end {
_current = current ?? _begin;
}
final T _begin;
final T _end;
/// The current value of the swinger.
T get current => _current;
late T _current;
bool _up;
T swing() {
if (_current >= _end) {
_up = false;
} else if (_current <= _begin) {
_up = true;
}
_current = (_up ? _current + 1 : _current - 1) as T;
return _current;
}
}
| engine/testing/scenario_app/lib/src/animated_color_square.dart/0 | {
"file_path": "engine/testing/scenario_app/lib/src/animated_color_square.dart",
"repo_id": "engine",
"token_count": 918
} | 438 |
#!/bin/bash
set -e
# Needed because if it is set, cd may print the path it changed to.
unset CDPATH
# 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 [[ -L "$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)"
if uname -m | grep "arm64"; then
FLUTTER_ENGINE="ios_debug_sim_unopt_arm64"
else
FLUTTER_ENGINE="ios_debug_sim_unopt"
fi
if [[ $# -eq 1 ]]; then
FLUTTER_ENGINE="$1"
fi
# Make sure simulators rotate automatically for "PlatformViewRotation" test.
# Can also be set via Simulator app Device > Rotate Device Automatically
defaults write com.apple.iphonesimulator RotateWindowWhenSignaledByGuest -int 1
SCENARIO_PATH=$SRC_DIR/out/$FLUTTER_ENGINE/scenario_app/Scenarios
pushd .
cd $SCENARIO_PATH
RESULT_BUNDLE_FOLDER=$(mktemp -d ios_scenario_xcresult_XXX)
RESULT_BUNDLE_PATH="${SCENARIO_PATH}/${RESULT_BUNDLE_FOLDER}"
# Zip and upload xcresult to luci.
# First parameter ($1) is the zip output name.
zip_and_upload_xcresult_to_luci () {
# We don't want the zip to contain the abusolute path,
# so use relative path (./$RESULT_BUNDLE_FOLDER) instead.
zip -q -r $1 "./$RESULT_BUNDLE_FOLDER"
mv -f $1 $FLUTTER_TEST_OUTPUTS_DIR
exit 1
}
readonly DEVICE_NAME="iPhone SE (3rd generation)"
readonly DEVICE=com.apple.CoreSimulator.SimDeviceType.iPhone-SE-3rd-generation
readonly OS_RUNTIME=com.apple.CoreSimulator.SimRuntime.iOS-17-0
readonly OS="17.0"
# Delete any existing devices named "iPhone SE (3rd generation)". Having more
# than one may cause issues when builds target the device.
echo "Deleting any existing devices names $DEVICE_NAME..."
RESULT=0
while [[ $RESULT == 0 ]]; do
xcrun simctl delete "$DEVICE_NAME" || RESULT=1
if [ $RESULT == 0 ]; then
echo "Deleted $DEVICE_NAME"
fi
done
echo ""
echo "Creating $DEVICE_NAME $DEVICE $OS_RUNTIME ..."
xcrun simctl create "$DEVICE_NAME" "$DEVICE" "$OS_RUNTIME"
echo ""
echo "Running simulator tests with Skia"
echo ""
if set -o pipefail && xcodebuild -sdk iphonesimulator \
-scheme Scenarios \
-resultBundlePath "$RESULT_BUNDLE_PATH/ios_scenario.xcresult" \
-destination "platform=iOS Simulator,OS=$OS,name=$DEVICE_NAME" \
clean test \
FLUTTER_ENGINE="$FLUTTER_ENGINE"; then
echo "test success."
else
echo "test failed."
zip_and_upload_xcresult_to_luci "ios_scenario_xcresult.zip"
fi
rm -rf $RESULT_BUNDLE_PATH
echo "Running simulator tests with Impeller"
echo ""
# Skip testFontRenderingWhenSuppliedWithBogusFont: https://github.com/flutter/flutter/issues/113250
# Skip golden tests that use software rendering: https://github.com/flutter/flutter/issues/131888
if set -o pipefail && xcodebuild -sdk iphonesimulator \
-scheme Scenarios \
-resultBundlePath "$RESULT_BUNDLE_PATH/ios_scenario.xcresult" \
-destination "platform=iOS Simulator,OS=$OS,name=$DEVICE_NAME" \
clean test \
FLUTTER_ENGINE="$FLUTTER_ENGINE" \
-skip-testing ScenariosUITests/MultiplePlatformViewsBackgroundForegroundTest/testPlatformView \
-skip-testing ScenariosUITests/MultiplePlatformViewsTest/testPlatformView \
-skip-testing ScenariosUITests/NonFullScreenFlutterViewPlatformViewUITests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationClipPathTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationClipPathWithTransformTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationClipRectAfterMovedTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationClipRectTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationClipRectWithTransformTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationClipRRectTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationClipRRectWithTransformTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationLargeClipRRectTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationLargeClipRRectWithTransformTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationOpacityTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewMutationTransformTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewRotation/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewUITests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewWithNegativeOtherBackDropFilterTests/testPlatformView \
-skip-testing ScenariosUITests/PlatformViewWithOtherBackdropFilterTests/testPlatformView \
-skip-testing ScenariosUITests/RenderingSelectionTest/testSoftwareRendering \
-skip-testing ScenariosUITests/TwoPlatformViewClipPathTests/testPlatformView \
-skip-testing ScenariosUITests/TwoPlatformViewClipRectTests/testPlatformView \
-skip-testing ScenariosUITests/TwoPlatformViewClipRRectTests/testPlatformView \
-skip-testing ScenariosUITests/TwoPlatformViewsWithOtherBackDropFilterTests/testPlatformView \
-skip-testing ScenariosUITests/UnobstructedPlatformViewTests/testMultiplePlatformViewsWithOverlays \
# Plist with FLTEnableImpeller=YES, all projects in the workspace requires this file.
# For example, FlutterAppExtensionTestHost has a dummy file under the below directory.
INFOPLIST_FILE="Scenarios/Info_Impeller.plist"; then
echo "test success."
else
echo "test failed."
zip_and_upload_xcresult_to_luci "ios_scenario_impeller_xcresult.zip"
fi
rm -rf $RESULT_BUNDLE_PATH
popd
| engine/testing/scenario_app/run_ios_tests.sh/0 | {
"file_path": "engine/testing/scenario_app/run_ios_tests.sh",
"repo_id": "engine",
"token_count": 2059
} | 439 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/testing/test_metal_surface.h"
#include "flutter/fml/logging.h"
#include "flutter/testing/test_metal_surface_impl.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace flutter {
bool TestMetalSurface::PlatformSupportsMetal() {
return true;
}
std::unique_ptr<TestMetalSurface> TestMetalSurface::Create(
const TestMetalContext& test_metal_context,
SkISize surface_size) {
return std::make_unique<TestMetalSurfaceImpl>(test_metal_context,
surface_size);
}
std::unique_ptr<TestMetalSurface> TestMetalSurface::Create(
const TestMetalContext& test_metal_context,
int64_t texture_id,
SkISize surface_size) {
return std::make_unique<TestMetalSurfaceImpl>(test_metal_context, texture_id,
surface_size);
}
TestMetalSurface::TestMetalSurface() = default;
TestMetalSurface::~TestMetalSurface() = default;
bool TestMetalSurface::IsValid() const {
return impl_ ? impl_->IsValid() : false;
}
sk_sp<GrDirectContext> TestMetalSurface::GetGrContext() const {
return impl_ ? impl_->GetGrContext() : nullptr;
}
sk_sp<SkSurface> TestMetalSurface::GetSurface() const {
return impl_ ? impl_->GetSurface() : nullptr;
}
sk_sp<SkImage> TestMetalSurface::GetRasterSurfaceSnapshot() {
return impl_ ? impl_->GetRasterSurfaceSnapshot() : nullptr;
}
TestMetalContext::TextureInfo TestMetalSurface::GetTextureInfo() {
return impl_ ? impl_->GetTextureInfo() : TestMetalContext::TextureInfo();
}
} // namespace flutter
| engine/testing/test_metal_surface.cc/0 | {
"file_path": "engine/testing/test_metal_surface.cc",
"repo_id": "engine",
"token_count": 639
} | 440 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#include "flutter/testing/thread_test.h"
namespace flutter {
namespace testing {
namespace {
fml::RefPtr<fml::TaskRunner> GetDefaultTaskRunner() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
return fml::MessageLoop::GetCurrent().GetTaskRunner();
}
} // namespace
ThreadTest::ThreadTest() : current_task_runner_(GetDefaultTaskRunner()) {}
fml::RefPtr<fml::TaskRunner> ThreadTest::GetCurrentTaskRunner() {
return current_task_runner_;
}
fml::RefPtr<fml::TaskRunner> ThreadTest::CreateNewThread(
const std::string& name) {
auto thread = std::make_unique<fml::Thread>(name);
auto runner = thread->GetTaskRunner();
extra_threads_.emplace_back(std::move(thread));
return runner;
}
} // namespace testing
} // namespace flutter
| engine/testing/thread_test.cc/0 | {
"file_path": "engine/testing/thread_test.cc",
"repo_id": "engine",
"token_count": 297
} | 441 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax_action_handler_base.h"
#include "ax_tree_id_registry.h"
#include "base/logging.h"
namespace ui {
bool AXActionHandlerBase::RequiresPerformActionPointInPixels() const {
return false;
}
AXActionHandlerBase::AXActionHandlerBase()
: AXActionHandlerBase(ui::AXTreeIDUnknown()) {}
AXActionHandlerBase::AXActionHandlerBase(const AXTreeID& ax_tree_id)
: tree_id_(ax_tree_id) {}
AXActionHandlerBase::~AXActionHandlerBase() {
AXTreeIDRegistry::GetInstance().RemoveAXTreeID(tree_id_);
}
void AXActionHandlerBase::SetAXTreeID(AXTreeID new_ax_tree_id) {
BASE_DCHECK(new_ax_tree_id != ui::AXTreeIDUnknown());
AXTreeIDRegistry::GetInstance().RemoveAXTreeID(tree_id_);
tree_id_ = new_ax_tree_id;
AXTreeIDRegistry::GetInstance().SetAXTreeID(tree_id_, this);
}
} // namespace ui
| engine/third_party/accessibility/ax/ax_action_handler_base.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_action_handler_base.cc",
"repo_id": "engine",
"token_count": 350
} | 442 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_EVENT_INTENT_H_
#define UI_ACCESSIBILITY_AX_EVENT_INTENT_H_
#include <string>
#include "ax_base_export.h"
#include "ax_enums.h"
namespace ui {
// Describes what caused an accessibility event to be raised. For example, a
// character could have been typed, a word replaced, or a line deleted. Or, the
// selection could have been extended to the beginning of the previous word, or
// it could have been moved to the end of the next line.
struct AX_BASE_EXPORT AXEventIntent final {
AXEventIntent();
AXEventIntent(ax::mojom::Command command,
ax::mojom::TextBoundary text_boundary,
ax::mojom::MoveDirection move_direction);
virtual ~AXEventIntent();
AXEventIntent(const AXEventIntent& intent);
AXEventIntent& operator=(const AXEventIntent& intent);
friend AX_BASE_EXPORT bool operator==(const AXEventIntent& a,
const AXEventIntent& b);
friend AX_BASE_EXPORT bool operator!=(const AXEventIntent& a,
const AXEventIntent& b);
ax::mojom::Command command = ax::mojom::Command::kType;
// TODO(nektar): Split TextBoundary into TextUnit and TextBoundary.
ax::mojom::TextBoundary text_boundary = ax::mojom::TextBoundary::kCharacter;
ax::mojom::MoveDirection move_direction = ax::mojom::MoveDirection::kForward;
// Returns a string representation of this data, for debugging.
std::string ToString() const;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_EVENT_INTENT_H_
| engine/third_party/accessibility/ax/ax_event_intent.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_event_intent.h",
"repo_id": "engine",
"token_count": 627
} | 443 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_POSITION_H_
#define UI_ACCESSIBILITY_AX_POSITION_H_
#include <cmath>
#include <cstdint>
#include <functional>
#include <memory>
#include <ostream>
#include <stack>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "ax_enum_util.h"
#include "ax_enums.h"
#include "ax_node.h"
#include "ax_node_text_styles.h"
#include "ax_role_properties.h"
#include "ax_tree_id.h"
#include "base/container_utils.h"
#include "base/logging.h"
#include "base/string_utils.h"
namespace ui {
// Defines the type of position in the accessibility tree.
// A tree position is used when referring to a specific child of a node in the
// accessibility tree.
// A text position is used when referring to a specific character of text inside
// a particular node.
// A null position is used to signify that the provided data is invalid or that
// a boundary has been reached.
enum class AXPositionKind { NULL_POSITION, TREE_POSITION, TEXT_POSITION };
// Defines how creating the next or previous position should behave whenever we
// are at or are crossing a boundary, such as at the start of an anchor, a word
// or a line.
enum class AXBoundaryBehavior {
CrossBoundary,
StopAtAnchorBoundary,
StopIfAlreadyAtBoundary,
StopAtLastAnchorBoundary
};
// Describes in further detail what type of boundary a current position is on.
// For complex boundaries such as format boundaries, it can be useful to know
// why a particular boundary was chosen.
enum class AXBoundaryType {
// Not at a unit boundary.
kNone,
// At a unit boundary (e.g. a format boundary).
kUnitBoundary,
// At the start of a document.
kDocumentStart,
// At the end of a document.
kDocumentEnd
};
// When converting to an unignored position, determines how to adjust the new
// position in order to make it valid, either moving backward or forward in
// the accessibility tree.
enum class AXPositionAdjustmentBehavior { kMoveBackward, kMoveForward };
// Specifies how AXPosition::ExpandToEnclosingTextBoundary behaves.
//
// As an example, imagine we have the text "hello world" and a position before
// the space character. We want to expand to the surrounding word boundary.
// Since we are right at the end of the first word, we could either expand to
// the left first, find the start of the first word and then use that to find
// the corresponding word end, resulting in the word "Hello". Another
// possibility is to expand to the right first, find the end of the next word
// and use that as our starting point to find the previous word start, resulting
// in the word "world".
enum class AXRangeExpandBehavior {
// Expands to the left boundary first and then uses that position as the
// starting point to find the boundary to the right.
kLeftFirst,
// Expands to the right boundary first and then uses that position as the
// starting point to find the boundary to the left.
kRightFirst
};
// Some platforms require empty objects to be represented by a replacement
// character in order for text navigation to work correctly. This enum controls
// whether a replacement character will be exposed for such objects.
//
// When an embedded object is replaced by a real character, the expectations
// are the same with this character as with other ordinary characters.
// For example, with UIA on Windows, we need to be able to navigate inside and
// outside of this character as if it was an ordinary character, using the
// AXPlatformNodeTextRangeProvider methods. Since an embedded object character
// is the only character in a node, we also treat this character as a word.
enum class AXEmbeddedObjectBehavior {
kExposeCharacter,
kSuppressCharacter,
};
// Controls whether embedded objects are represented by a replacement
// character. This is initialized to a per-platform default but can be
// overridden for testing.
AX_EXPORT extern AXEmbeddedObjectBehavior g_ax_embedded_object_behavior;
class AX_EXPORT ScopedAXEmbeddedObjectBehaviorSetter {
public:
explicit ScopedAXEmbeddedObjectBehaviorSetter(
AXEmbeddedObjectBehavior behavior);
~ScopedAXEmbeddedObjectBehaviorSetter();
private:
AXEmbeddedObjectBehavior prev_behavior_;
};
// Forward declarations.
template <class AXPositionType, class AXNodeType>
class AXPosition;
template <class AXPositionType>
class AXRange;
template <class AXPositionType, class AXNodeType>
bool operator==(const AXPosition<AXPositionType, AXNodeType>& first,
const AXPosition<AXPositionType, AXNodeType>& second);
template <class AXPositionType, class AXNodeType>
bool operator!=(const AXPosition<AXPositionType, AXNodeType>& first,
const AXPosition<AXPositionType, AXNodeType>& second);
// A position in the accessibility tree.
//
// This class could either represent a tree position or a text position.
// Tree positions point to either a child of a specific node or at the end of a
// node (i.e. an "after children" position).
// Text positions point to either a character offset in the text inside a
// particular node including text from all its children, or to the end of the
// node's text, (i.e. an "after text" position).
// On tree positions that have a leaf node as their anchor, we also need to
// distinguish between "before text" and "after text" positions. To do this, if
// the child index is 0 and the anchor is a leaf node, then it's an "after text"
// position. If the child index is |BEFORE_TEXT| and the anchor is a leaf node,
// then this is a "before text" position.
// It doesn't make sense to have a "before text" position on a text position,
// because it is identical to setting its offset to the first character.
//
// To avoid re-computing either the text offset or the child index when
// converting between the two types of positions, both values are saved after
// the first conversion.
//
// This class template uses static polymorphism in order to allow sub-classes to
// be created from the base class without the base class knowing the type of the
// sub-class in advance.
// The template argument |AXPositionType| should always be set to the type of
// any class that inherits from this template, making this a
// "curiously recursive template".
//
// This class can be copied using the |Clone| method. It is designed to be
// immutable.
template <class AXPositionType, class AXNodeType>
class AXPosition {
public:
using AXPositionInstance =
std::unique_ptr<AXPosition<AXPositionType, AXNodeType>>;
using AXRangeType = AXRange<AXPosition<AXPositionType, AXNodeType>>;
typedef bool BoundaryConditionPredicate(const AXPositionInstance&);
typedef std::vector<int32_t> BoundaryTextOffsetsFunc(
const AXPositionInstance&);
static const int BEFORE_TEXT = -1;
static const int INVALID_INDEX = -2;
static const int INVALID_OFFSET = -1;
// Replacement character used to represent an empty object. See
// AXEmbeddedObjectBehavior for more information.
//
// Duplicate of AXPlatformNodeBase::kEmbeddedCharacter because we don't want
// to include platform specific code in here.
static constexpr char16_t kEmbeddedCharacter = L'\xfffc';
static AXPositionInstance CreateNullPosition() {
AXPositionInstance new_position(new AXPositionType());
new_position->Initialize(
AXPositionKind::NULL_POSITION, AXTreeIDUnknown(), AXNode::kInvalidAXID,
INVALID_INDEX, INVALID_OFFSET, ax::mojom::TextAffinity::kDownstream);
return new_position;
}
static AXPositionInstance CreateTreePosition(AXTreeID tree_id,
AXNode::AXID anchor_id,
int child_index) {
AXPositionInstance new_position(new AXPositionType());
new_position->Initialize(AXPositionKind::TREE_POSITION, tree_id, anchor_id,
child_index, INVALID_OFFSET,
ax::mojom::TextAffinity::kDownstream);
return new_position;
}
static AXPositionInstance CreateTextPosition(
AXTreeID tree_id,
AXNode::AXID anchor_id,
int text_offset,
ax::mojom::TextAffinity affinity) {
AXPositionInstance new_position(new AXPositionType());
new_position->Initialize(AXPositionKind::TEXT_POSITION, tree_id, anchor_id,
INVALID_INDEX, text_offset, affinity);
return new_position;
}
virtual ~AXPosition() = default;
// Implemented based on the copy and swap idiom.
AXPosition& operator=(const AXPosition& other) {
AXPositionInstance clone = other.Clone();
swap(*clone);
return *this;
}
virtual AXPositionInstance Clone() const = 0;
// A serialization of a position as POD. Not for sharing on disk or sharing
// across thread or process boundaries, just for passing a position to an
// API that works with positions as opaque objects.
struct SerializedPosition {
AXPositionKind kind;
AXNode::AXID anchor_id;
int child_index;
int text_offset;
ax::mojom::TextAffinity affinity;
char tree_id[33];
};
static_assert(std::is_trivially_copyable<SerializedPosition>::value,
"SerializedPosition must be POD");
SerializedPosition Serialize() {
SerializedPosition result;
result.kind = kind_;
// A tree ID can be serialized as a 32-byte string.
std::string tree_id_string = tree_id_.ToString();
BASE_DCHECK(tree_id_string.size() <= 32U);
strncpy(result.tree_id, tree_id_string.c_str(), 32);
result.tree_id[32] = 0;
result.anchor_id = anchor_id_;
result.child_index = child_index_;
result.text_offset = text_offset_;
result.affinity = affinity_;
return result;
}
static AXPositionInstance Unserialize(
const SerializedPosition& serialization) {
AXPositionInstance new_position(new AXPositionType());
new_position->Initialize(serialization.kind,
ui::AXTreeID::FromString(serialization.tree_id),
serialization.anchor_id, serialization.child_index,
serialization.text_offset, serialization.affinity);
return new_position;
}
std::string ToString() const {
std::string str;
switch (kind_) {
case AXPositionKind::NULL_POSITION:
return "NullPosition";
case AXPositionKind::TREE_POSITION: {
std::string str_child_index;
if (child_index_ == BEFORE_TEXT) {
str_child_index = "before_text";
} else if (child_index_ == INVALID_INDEX) {
str_child_index = "invalid";
} else {
str_child_index = base::NumberToString(child_index_);
}
str = "TreePosition tree_id=" + tree_id_.ToString() +
" anchor_id=" + base::NumberToString(anchor_id_) +
" child_index=" + str_child_index;
break;
}
case AXPositionKind::TEXT_POSITION: {
std::string str_text_offset;
if (text_offset_ == INVALID_OFFSET) {
str_text_offset = "invalid";
} else {
str_text_offset = base::NumberToString(text_offset_);
}
str = "TextPosition anchor_id=" + base::NumberToString(anchor_id_) +
" text_offset=" + str_text_offset + " affinity=" +
ui::ToString(static_cast<ax::mojom::TextAffinity>(affinity_));
break;
}
}
if (!IsTextPosition() || text_offset_ > MaxTextOffset())
return str;
std::u16string text = GetText();
BASE_DCHECK(text_offset_ >= 0);
int max_text_offset = MaxTextOffset();
BASE_DCHECK(text_offset_ <= max_text_offset);
std::u16string annotated_text;
if (text_offset_ == max_text_offset) {
annotated_text = text + u"<>";
} else {
annotated_text = text.substr(0, text_offset_) + u"<" +
text[text_offset_] + u">" +
text.substr(text_offset_ + 1);
}
return str + " annotated_text=" + base::UTF16ToUTF8(annotated_text);
}
AXTreeID tree_id() const { return tree_id_; }
AXNode::AXID anchor_id() const { return anchor_id_; }
AXNodeType* GetAnchor() const {
if (tree_id_ == AXTreeIDUnknown() || anchor_id_ == AXNode::kInvalidAXID)
return nullptr;
return GetNodeInTree(tree_id_, anchor_id_);
}
AXPositionKind kind() const { return kind_; }
int child_index() const { return child_index_; }
int text_offset() const { return text_offset_; }
ax::mojom::TextAffinity affinity() const { return affinity_; }
bool IsIgnored() const {
if (IsNullPosition())
return false;
BASE_DCHECK(GetAnchor());
// If this position is anchored to an ignored node, then consider this
// position to be ignored.
if (GetAnchor()->IsIgnored()) {
return true;
}
switch (kind_) {
case AXPositionKind::NULL_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TREE_POSITION: {
// If this is a "before text" or an "after text" tree position, it's
// pointing to the anchor itself, which we've determined to be
// unignored.
BASE_DCHECK(!IsLeaf() || child_index_ == BEFORE_TEXT ||
child_index_ == 0)
<< "\"Before text\" and \"after text\" tree positions are only "
"valid on leaf nodes.";
if (child_index_ == BEFORE_TEXT || IsLeaf())
return false;
// If this position is an "after children" position, consider the
// position to be ignored if the last child is ignored. This is because
// the last child will not be visible in the unignored tree. If the
// position is not adjusted, the resulting position would erroneously
// point before the second child in the unignored subtree rooted at the
// last child.
//
// 1 kRootWebArea
// ++2 kGenericContainer ignored
// ++++3 kStaticText "Line 1."
// ++++4 kStaticText "Line 2."
//
// Tree position anchor=kGenericContainer, child_index=1.
//
// Alternatively, if there is a node at the position pointed to by
// "child_index_", i.e. this position is neither a leaf position nor an
// "after children" position, consider this tree position to be ignored
// if the child node is ignored.
int adjusted_child_index = child_index_ != AnchorChildCount()
? child_index_
: child_index_ - 1;
AXPositionInstance child_position =
CreateChildPositionAt(adjusted_child_index);
BASE_DCHECK(child_position && !child_position->IsNullPosition());
return child_position->GetAnchor()->IsIgnored();
}
case AXPositionKind::TEXT_POSITION:
// If the corresponding leaf position is ignored, the current text
// offset will point to ignored text. Therefore, consider this position
// to be ignored.
if (!IsLeaf()) {
return AsLeafTreePosition()->IsIgnored();
}
return false;
}
}
bool IsNullPosition() const {
return kind_ == AXPositionKind::NULL_POSITION || !GetAnchor();
}
bool IsTreePosition() const {
return GetAnchor() && kind_ == AXPositionKind::TREE_POSITION;
}
bool IsLeafTreePosition() const { return IsTreePosition() && IsLeaf(); }
bool IsTextPosition() const {
return GetAnchor() && kind_ == AXPositionKind::TEXT_POSITION;
}
bool IsLeafTextPosition() const { return IsTextPosition() && IsLeaf(); }
bool IsLeaf() const {
if (IsNullPosition())
return false;
return !AnchorChildCount() || IsEmptyObjectReplacedByCharacter();
}
// Returns true if this is a valid position, e.g. the child_index_ or
// text_offset_ is within a valid range.
bool IsValid() const {
switch (kind_) {
case AXPositionKind::NULL_POSITION:
return tree_id_ == AXTreeIDUnknown() &&
anchor_id_ == AXNode::kInvalidAXID &&
child_index_ == INVALID_INDEX &&
text_offset_ == INVALID_OFFSET &&
affinity_ == ax::mojom::TextAffinity::kDownstream;
case AXPositionKind::TREE_POSITION:
return GetAnchor() &&
(child_index_ == BEFORE_TEXT ||
(child_index_ >= 0 && child_index_ <= AnchorChildCount())) &&
!IsInDescendantOfEmptyObject();
case AXPositionKind::TEXT_POSITION:
if (!GetAnchor() || IsInDescendantOfEmptyObject()) {
return false;
}
// For performance reasons we skip any validation of the text offset
// that involves retrieving the anchor's text, if the offset is set to
// 0, because 0 is frequently used and always valid regardless of the
// actual text.
return text_offset_ == 0 ||
(text_offset_ > 0 && text_offset_ <= MaxTextOffset());
}
}
// TODO(nektar): Update logic of AtStartOfAnchor() for text_offset_ == 0 and
// fix related bug.
bool AtStartOfAnchor() const {
if (!GetAnchor())
return false;
switch (kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
if (text_offset_ > 0)
return false;
if (!IsLeaf() || text_offset_ == 0)
return child_index_ == 0;
return child_index_ == BEFORE_TEXT;
case AXPositionKind::TEXT_POSITION:
return text_offset_ == 0;
}
}
bool AtEndOfAnchor() const {
if (!GetAnchor())
return false;
switch (kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
return child_index_ == AnchorChildCount();
case AXPositionKind::TEXT_POSITION:
return text_offset_ == MaxTextOffset();
}
}
bool AtStartOfWord() const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (text_position->kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TEXT_POSITION: {
const std::vector<int32_t> word_starts =
text_position->GetWordStartOffsets();
return base::Contains(word_starts,
int32_t{text_position->text_offset_});
}
}
}
bool AtEndOfWord() const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (text_position->kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TEXT_POSITION: {
const std::vector<int32_t> word_ends =
text_position->GetWordEndOffsets();
return base::Contains(word_ends, int32_t{text_position->text_offset_});
}
}
}
bool AtStartOfLine() const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (text_position->kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TEXT_POSITION:
// We treat a position after some white space that is not connected to
// any node after it via "next on line ID", to be equivalent to a
// position before the next line, and therefore as being at start of
// line.
//
// We assume that white space, including but not limited to hard line
// breaks, might be used to separate lines. For example, an inline text
// box with just a single space character inside it can be used to
// represent a soft line break. If an inline text box containing white
// space separates two lines, it should always be connected to the first
// line via "kPreviousOnLineId". This is guaranteed by the renderer. If
// there are multiple line breaks separating the two lines, then only
// the first line break is connected to the first line via
// "kPreviousOnLineId".
//
// Sometimes there might be an inline text box with a single space in it
// at the end of a text field. We should not mark positions that are at
// the end of text fields, or in general at the end of their anchor, as
// being at the start of line, except when that anchor is an inline text
// box that is in the middle of a text span. Note that in most but not
// all cases, the parent of an inline text box is a static text object,
// whose end signifies the end of the text span. One exception is line
// breaks.
if (text_position->AtEndOfAnchor() &&
!text_position->AtEndOfTextSpan() &&
text_position->IsInWhiteSpace() &&
GetNextOnLineID(text_position->anchor_id_) ==
AXNode::kInvalidAXID) {
return true;
}
return GetPreviousOnLineID(text_position->anchor_id_) ==
AXNode::kInvalidAXID &&
text_position->AtStartOfAnchor();
}
}
bool AtEndOfLine() const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (text_position->kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TEXT_POSITION:
// Text positions on objects with no text should not be considered at
// end of line because the empty position may share a text offset with
// a non-empty text position in which case the end of line iterators
// must move to the line end of the non-empty content. Specified next
// line IDs are ignored.
if (!text_position->MaxTextOffset())
return false;
// If affinity has been used to specify whether the caret is at the end
// of a line or at the start of the next one, this should have been
// reflected in the leaf text position we got via "AsLeafTextPosition".
// If affinity had been set to upstream, the leaf text position should
// be pointing to the end of the inline text box that ends the first
// line. If it had been set to downstream, the leaf text position should
// be pointing to the start of the inline text box that starts the
// second line.
//
// In other cases, we assume that white space, including but not limited
// to hard line breaks, might be used to separate lines. For example, an
// inline text box with just a single space character inside it can be
// used to represent a soft line break. If an inline text box containing
// white space separates two lines, it should always be connected to the
// first line via "kPreviousOnLineId". This is guaranteed by the
// renderer. If there are multiple line breaks separating the two lines,
// then only the first line break is connected to the first line via
// "kPreviousOnLineId".
//
// We don't treat a position that is at the start of white space that is
// on a line by itself as being at the end of the line. This is in order
// to enable screen readers to recognize and announce blank lines
// correctly. However, we do treat positions at the start of white space
// that end a line of text as being at the end of that line. We also
// treat positions at the end of white space that is on a line by
// itself, i.e. on a blank line, as being at the end of that line.
//
// Sometimes there might be an inline text box with a single space in it
// at the end of a text field. We should mark positions that are at the
// end of text fields, or in general at the end of an anchor with no
// "kNextOnLineId", as being at end of line, except when that anchor is
// an inline text box that is in the middle of a text span. Note that
// in most but not all cases, the parent of an inline text box is a
// static text object, whose end signifies the end of the text span. One
// exception is line breaks.
if (GetNextOnLineID(text_position->anchor_id_) ==
AXNode::kInvalidAXID) {
return (!text_position->AtEndOfTextSpan() &&
text_position->IsInWhiteSpace() &&
GetPreviousOnLineID(text_position->anchor_id_) !=
AXNode::kInvalidAXID)
? text_position->AtStartOfAnchor()
: text_position->AtEndOfAnchor();
}
// The current anchor might be followed by a soft line break.
return text_position->AtEndOfAnchor() &&
text_position->CreateNextLeafTextPosition()->AtEndOfLine();
}
}
// |AtStartOfParagraph| is asymmetric from |AtEndOfParagraph| because of
// trailing whitespace collapse rules.
// The start of a paragraph should be a leaf text position (or equivalent),
// either at the start of the document, or at the start of the next leaf text
// position from the one representing the end of the previous paragraph.
// A position |AsLeafTextPosition| is the start of a paragraph if all of the
// following are true :
// 1. The current leaf text position must be an unignored position at
// the start of an anchor.
// 2. The current position is not whitespace only, unless it is also
// the first leaf text position within the document.
// 3. Either (a) the current leaf text position is the first leaf text
// position in the document, or (b) there are no line breaking
// objects between it and the previous non-whitespace leaf text
// position.
bool AtStartOfParagraph() const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (text_position->kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TEXT_POSITION: {
// 1. The current leaf text position must be an unignored position at
// the start of an anchor.
if (text_position->IsIgnored() || !text_position->AtStartOfAnchor())
return false;
// 2. The current position is not whitespace only, unless it is also
// the first leaf text position within the document.
if (text_position->IsInWhiteSpace()) {
return text_position->CreatePreviousLeafTextPosition()
->IsNullPosition();
}
// 3. Either (a) the current leaf text position is the first leaf text
// position in the document, or (b) there are no line breaking
// objects between it and the previous non-whitespace leaf text
// position.
//
// Search for the previous text position within the current paragraph,
// using the paragraph boundary abort predicate.
// If a valid position was found, then this position cannot be
// the start of a paragraph.
// This will return a null position when an anchor movement would
// cross a paragraph boundary, or the start of document was reached.
bool crossed_line_breaking_object_token = false;
auto abort_move_predicate =
[&crossed_line_breaking_object_token](
const AXPosition& move_from, const AXPosition& move_to,
const AXMoveType type, const AXMoveDirection direction) {
return AbortMoveAtParagraphBoundary(
crossed_line_breaking_object_token, move_from, move_to, type,
direction);
};
AXPositionInstance previous_text_position = text_position->Clone();
do {
previous_text_position =
previous_text_position->CreatePreviousTextAnchorPosition(
abort_move_predicate);
// If the previous position is whitespace, then continue searching
// until a non-whitespace leaf text position is found within the
// current paragraph because whitespace is supposed to be collapsed.
// There's a chance that |CreatePreviousTextAnchorPosition| will
// return whitespace that should be appended to a previous paragraph
// rather than separating two pieces of the current paragraph.
} while (previous_text_position->IsInWhiteSpace() ||
previous_text_position->IsIgnored());
return previous_text_position->IsNullPosition();
}
}
}
// |AtEndOfParagraph| is asymmetric from |AtStartOfParagraph| because of
// trailing whitespace collapse rules.
// The end of a paragraph should be a leaf text position (or equivalent),
// either at the end of the document, or at the end of the previous leaf text
// position from the one representing the start of the next paragraph.
// A position |AsLeafTextPosition| is the end of a paragraph if all of the
// following are true :
// 1. The current leaf text position must be an unignored position at
// the end of an anchor.
// 2. Either (a) the current leaf text position is the last leaf text
// position in the document, or (b) there are no line breaking
// objects between it and the next leaf text position except when
// the next leaf text position is whitespace only since whitespace
// must be collapsed.
// 3. If there is a next leaf text position then it must not be
// whitespace only.
// 4. If there is a next leaf text position and it is not whitespace
// only, it must also be the start of a paragraph for the current
// position to be the end of a paragraph.
bool AtEndOfParagraph() const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (text_position->kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TEXT_POSITION: {
// 1. The current leaf text position must be an unignored position at
// the end of an anchor.
if (text_position->IsIgnored() || !text_position->AtEndOfAnchor())
return false;
// 2. Either (a) the current leaf text position is the last leaf text
// position in the document, or (b) there are no line breaking
// objects between it and the next leaf text position except when
// the next leaf text position is whitespace only since whitespace
// must be collapsed.
//
// Search for the next text position within the current paragraph,
// using the paragraph boundary abort predicate.
// If a null position was found, then this position must be the end of
// a paragraph.
// |CreateNextTextAnchorPosition| + |AbortMoveAtParagraphBoundary|
// will return a null position when an anchor movement would
// cross a paragraph boundary and there is no doubt that it is the end
// of a paragraph, or the end of document was reached.
// There are some fringe cases related to whitespace collapse that
// cannot be handled easily with only |AbortMoveAtParagraphBoundary|.
bool crossed_line_breaking_object_token = false;
auto abort_move_predicate =
[&crossed_line_breaking_object_token](
const AXPosition& move_from, const AXPosition& move_to,
const AXMoveType type, const AXMoveDirection direction) {
return AbortMoveAtParagraphBoundary(
crossed_line_breaking_object_token, move_from, move_to, type,
direction);
};
AXPositionInstance next_text_position = text_position->Clone();
do {
next_text_position = next_text_position->CreateNextTextAnchorPosition(
abort_move_predicate);
} while (next_text_position->IsIgnored());
if (next_text_position->IsNullPosition())
return true;
// 3. If there is a next leaf text position then it must not be
// whitespace only.
if (next_text_position->IsInWhiteSpace())
return false;
// 4. If there is a next leaf text position and it is not whitespace
// only, it must also be the start of a paragraph for the current
// position to be the end of a paragraph.
//
// Consider the following example :
// ++{1} kStaticText "First Paragraph"
// ++++{2} kInlineTextBox "First Paragraph"
// ++{3} kStaticText "\n Second Paragraph"
// ++++{4} kInlineTextBox "\n" kIsLineBreakingObject
// ++++{5} kInlineTextBox " "
// ++++{6} kInlineTextBox "Second Paragraph"
// A position at the end of {5} is the end of a paragraph, because
// the first paragraph must collapse trailing whitespace and contain
// leaf text anchors {2, 4, 5}. The second paragraph is only {6}.
return next_text_position->CreatePositionAtStartOfAnchor()
->AtStartOfParagraph();
}
}
}
bool AtStartOfPage() const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (text_position->kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TEXT_POSITION: {
if (!text_position->AtStartOfAnchor())
return false;
// Search for the previous text position within the current page,
// using the page boundary abort predicate.
// If a valid position was found, then this position cannot be
// the start of a page.
// This will return a null position when an anchor movement would
// cross a page boundary, or the start of document was reached.
AXPositionInstance previous_text_position =
text_position->CreatePreviousTextAnchorPosition(
AbortMoveAtPageBoundary);
return previous_text_position->IsNullPosition();
}
}
}
bool AtEndOfPage() const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (text_position->kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TEXT_POSITION: {
if (!text_position->AtEndOfAnchor())
return false;
// Search for the next text position within the current page,
// using the page boundary abort predicate.
// If a valid position was found, then this position cannot be
// the end of a page.
// This will return a null position when an anchor movement would
// cross a page boundary, or the end of document was reached.
AXPositionInstance next_text_position =
text_position->CreateNextTextAnchorPosition(
AbortMoveAtPageBoundary);
return next_text_position->IsNullPosition();
}
}
}
bool AtStartOfAXTree() const {
if (IsNullPosition())
return false;
if (AtStartOfAnchor()) {
AXPositionInstance previous_anchor = CreatePreviousAnchorPosition();
// Consider the start of the document as the start of an AXTree.
if (previous_anchor->IsNullPosition())
return true;
else
return previous_anchor->tree_id() != tree_id();
}
return false;
}
bool AtEndOfAXTree() const {
if (IsNullPosition())
return false;
if (AtEndOfAnchor()) {
AXPositionInstance next_anchor = CreateNextAnchorPosition();
// Consider the end of the document as the end of an AXTree.
if (next_anchor->IsNullPosition())
return true;
else
return next_anchor->tree_id() != tree_id();
}
return false;
}
AXBoundaryType GetFormatStartBoundaryType() const {
// Since formats are stored on text anchors, the start of a format boundary
// must be at the start of an anchor.
if (IsNullPosition() || !AtStartOfAnchor())
return AXBoundaryType::kNone;
// Treat the first iterable node as a format boundary.
if (CreatePreviousLeafTreePosition()->IsNullPosition())
return AXBoundaryType::kDocumentStart;
// Ignored positions cannot be format boundaries.
if (IsIgnored())
return AXBoundaryType::kNone;
// Iterate over anchors until a format boundary is found. This will return a
// null position upon crossing a boundary. Make sure the previous position
// is not on an ignored node.
AXPositionInstance previous_position = Clone();
do {
previous_position = previous_position->CreatePreviousLeafTreePosition(
AbortMoveAtFormatBoundary);
} while (previous_position->IsIgnored());
if (previous_position->IsNullPosition())
return AXBoundaryType::kUnitBoundary;
return AXBoundaryType::kNone;
}
bool AtStartOfFormat() const {
return GetFormatStartBoundaryType() != AXBoundaryType::kNone;
}
AXBoundaryType GetFormatEndBoundaryType() const {
// Since formats are stored on text anchors, the end of a format break must
// be at the end of an anchor.
if (IsNullPosition() || !AtEndOfAnchor())
return AXBoundaryType::kNone;
// Treat the last iterable node as a format boundary
if (CreateNextLeafTreePosition()->IsNullPosition())
return AXBoundaryType::kDocumentEnd;
// Ignored positions cannot be format boundaries.
if (IsIgnored())
return AXBoundaryType::kNone;
// Iterate over anchors until a format boundary is found. This will return a
// null position upon crossing a boundary. Make sure the next position is
// not on an ignored node.
AXPositionInstance next_position = Clone();
do {
next_position =
next_position->CreateNextLeafTreePosition(AbortMoveAtFormatBoundary);
} while (next_position->IsIgnored());
if (next_position->IsNullPosition())
return AXBoundaryType::kUnitBoundary;
return AXBoundaryType::kNone;
}
bool AtEndOfFormat() const {
return GetFormatEndBoundaryType() != AXBoundaryType::kNone;
}
bool AtStartOfInlineBlock() const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (text_position->kind_) {
case AXPositionKind::NULL_POSITION:
return false;
case AXPositionKind::TREE_POSITION:
BASE_UNREACHABLE();
return false;
case AXPositionKind::TEXT_POSITION: {
if (text_position->AtStartOfAnchor()) {
AXPositionInstance previous_position =
text_position->CreatePreviousLeafTreePosition();
// Check that this position is not the start of the first anchor.
if (!previous_position->IsNullPosition()) {
previous_position = text_position->CreatePreviousLeafTreePosition(
&AbortMoveAtStartOfInlineBlock);
// If we get a null position here it means we have crossed an inline
// block's start, thus this position is located at such start.
if (previous_position->IsNullPosition())
return true;
}
}
if (text_position->AtEndOfAnchor()) {
AXPositionInstance next_position =
text_position->CreateNextLeafTreePosition();
// Check that this position is not the end of the last anchor.
if (!next_position->IsNullPosition()) {
next_position = text_position->CreateNextLeafTreePosition(
&AbortMoveAtStartOfInlineBlock);
// If we get a null position here it means we have crossed an inline
// block's start, thus this position is located at such start.
if (next_position->IsNullPosition())
return true;
}
}
return false;
}
}
}
bool AtStartOfDocument() const {
if (IsNullPosition())
return false;
return IsDocument(GetAnchorRole()) && AtStartOfAnchor();
}
bool AtEndOfDocument() const {
if (IsNullPosition())
return false;
return AtLastNodeInTree() && AtEndOfAnchor();
}
bool AtLastNodeInTree() const {
if (IsNullPosition())
return false;
// Avoid a potentionally expensive MaxTextOffset call by only using tree
// positions. The only thing that matters is whether our anchor_id_ is at
// the last anchor of the document, so we're free to ignore text_offset_.
AXPositionInstance tree_position =
CreateTreePosition(tree_id_, anchor_id_, 0);
return tree_position->CreateNextAnchorPosition()->IsNullPosition();
}
// This method finds the lowest common AXNodeType of |this| and |second|.
AXNodeType* LowestCommonAnchor(const AXPosition& second) const {
if (IsNullPosition() || second.IsNullPosition())
return nullptr;
if (GetAnchor() == second.GetAnchor())
return GetAnchor();
std::stack<AXNodeType*> our_ancestors = GetAncestorAnchors();
std::stack<AXNodeType*> other_ancestors = second.GetAncestorAnchors();
AXNodeType* common_anchor = nullptr;
while (!our_ancestors.empty() && !other_ancestors.empty() &&
our_ancestors.top() == other_ancestors.top()) {
common_anchor = our_ancestors.top();
our_ancestors.pop();
other_ancestors.pop();
}
return common_anchor;
}
// This method returns a position instead of a node because this allows us to
// return the corresponding text offset or child index in the ancestor that
// relates to the current position.
// Also, this method uses position instead of tree logic to traverse the tree,
// because positions can handle moving across multiple trees, while trees
// cannot.
AXPositionInstance LowestCommonAncestor(const AXPosition& second) const {
return CreateAncestorPosition(LowestCommonAnchor(second));
}
// See "CreateParentPosition" for an explanation of the use of
// |move_direction|.
AXPositionInstance CreateAncestorPosition(
const AXNodeType* ancestor_anchor,
ax::mojom::MoveDirection move_direction =
ax::mojom::MoveDirection::kForward) const {
if (!ancestor_anchor) {
return CreateNullPosition();
}
AXPositionInstance ancestor_position = Clone();
while (!ancestor_position->IsNullPosition() &&
ancestor_position->GetAnchor() != ancestor_anchor) {
ancestor_position =
ancestor_position->CreateParentPosition(move_direction);
}
return ancestor_position;
}
// If the position is not valid, we return a new valid position that is
// closest to the original position if possible, or a null position otherwise.
AXPositionInstance AsValidPosition() const {
AXPositionInstance position = Clone();
switch (position->kind_) {
case AXPositionKind::NULL_POSITION:
// We avoid cloning to ensure that all fields will be valid.
return CreateNullPosition();
case AXPositionKind::TREE_POSITION: {
if (!position->GetAnchor())
return CreateNullPosition();
if (AXNodeType* empty_object_node = GetEmptyObjectAncestorNode()) {
// In this class and on certain platforms, we define the empty object
// as one that doesn't expose its underlying content. Its content is
// replaced by the empty object character (string of length 1). A
// position on a descendant of an empty object is invalid. To make it
// valid we move the position from the descendant to the empty object
// node itself.
return CreateTreePosition(
position->tree_id(), GetAnchorID(empty_object_node),
position->child_index() == BEFORE_TEXT ? BEFORE_TEXT : 0);
}
if (position->child_index_ == BEFORE_TEXT)
return position;
if (position->child_index_ < 0)
position->child_index_ = 0;
else if (position->child_index_ > position->AnchorChildCount())
position->child_index_ = position->AnchorChildCount();
break;
}
case AXPositionKind::TEXT_POSITION: {
if (!position->GetAnchor())
return CreateNullPosition();
if (AXNodeType* empty_object_node = GetEmptyObjectAncestorNode()) {
// This is needed because an empty object as defined in this class and
// on certain platforms can have descendants that should not be
// exposed. See comment above in similar implementation for
// AXPositionKind::TREE_POSITION.
//
// We set the |text_offset_| to either 0 or 1 here because the
// MaxTextOffset of an empty object is 1 (the empty object character,
// a string of length 1). If the invalid position was already at the
// start of the node, we set it to 0.
return CreateTextPosition(position->tree_id(),
GetAnchorID(empty_object_node),
position->text_offset() > 0 ? 1 : 0,
ax::mojom::TextAffinity::kDownstream);
}
if (position->text_offset_ <= 0) {
// 0 is always a valid offset, so skip calling MaxTextOffset in that
// case.
position->text_offset_ = 0;
position->affinity_ = ax::mojom::TextAffinity::kDownstream;
} else {
int max_text_offset = position->MaxTextOffset();
if (position->text_offset_ > max_text_offset) {
position->text_offset_ = max_text_offset;
position->affinity_ = ax::mojom::TextAffinity::kDownstream;
}
}
break;
}
}
BASE_DCHECK(position->IsValid());
return position;
}
AXPositionInstance AsTreePosition() const {
if (IsNullPosition() || IsTreePosition())
return Clone();
AXPositionInstance copy = Clone();
BASE_DCHECK(copy);
BASE_DCHECK(copy->text_offset_ >= 0);
if (copy->IsLeaf()) {
const int max_text_offset = copy->MaxTextOffset();
copy->child_index_ =
(max_text_offset != 0 && copy->text_offset_ != max_text_offset)
? BEFORE_TEXT
: 0;
copy->kind_ = AXPositionKind::TREE_POSITION;
return copy;
}
// We stop at the last child that we can reach with the current text offset
// and ignore any remaining children. This is for defensive programming
// purposes, in case "MaxTextOffset" doesn't match the total length of all
// our children. This may happen if, for example, there is a bug in the
// internal accessibility tree we get from the renderer. In contrast, the
// current offset could not be greater than the length of all our children
// because the position would have been invalid.
int current_offset = 0;
int child_index = 0;
for (; child_index < copy->AnchorChildCount(); ++child_index) {
AXPositionInstance child = copy->CreateChildPositionAt(child_index);
BASE_DCHECK(child);
int child_length = child->MaxTextOffsetInParent();
// If the text offset falls on the boundary between two adjacent children,
// we look at the affinity to decide whether to place the tree position on
// the first child vs. the second child. Upstream affinity would always
// choose the first child, whilst downstream affinity the second. This
// also has implications when converting the resulting tree position back
// to a text position. In that case, maintaining an upstream affinity
// would place the text position at the end of the first child, whilst
// maintaining a downstream affinity will place the text position at the
// beginning of the second child.
//
// This is vital for text positions on soft line breaks, as well as text
// positions before and after character, to work properly.
//
// See also `CreateLeafTextPositionBeforeCharacter` and
// `CreateLeafTextPositionAfterCharacter`.
if (copy->text_offset_ >= current_offset &&
(copy->text_offset_ < (current_offset + child_length) ||
(copy->affinity_ == ax::mojom::TextAffinity::kUpstream &&
copy->text_offset_ == (current_offset + child_length)))) {
break;
}
current_offset += child_length;
}
copy->child_index_ = child_index;
copy->kind_ = AXPositionKind::TREE_POSITION;
return copy;
}
// This is an optimization over "AsLeafTextPosition", in cases when computing
// the corresponding text offset on the leaf node is not needed. If this
// method is called on a text position, it will conservatively fall back to
// the non-optimized "AsLeafTextPosition", if the current text offset is
// greater than 0, or the affinity is upstream, since converting to a tree
// position at any point before reaching the leaf node could potentially lose
// information.
AXPositionInstance AsLeafTreePosition() const {
if (IsNullPosition() || IsLeaf())
return AsTreePosition();
// If our text offset is greater than 0, or if our affinity is set to
// upstream, we need to ensure that text offset and affinity will be taken
// into consideration during our descend to the leaves. Switching to a tree
// position early in this case will potentially lose information, so we
// descend using a text position instead.
//
// We purposely don't check whether this position is a text position, to
// allow for the possibility that this position has recently been converted
// from a text to a tree position and text offset or affinity information
// has been left intact.
if (text_offset_ > 0 || affinity_ == ax::mojom::TextAffinity::kUpstream)
return AsLeafTextPosition()->AsTreePosition();
AXPositionInstance tree_position = AsTreePosition();
do {
if (tree_position->child_index_ == tree_position->AnchorChildCount()) {
tree_position =
tree_position
->CreateChildPositionAt(tree_position->child_index_ - 1)
->CreatePositionAtEndOfAnchor();
} else {
tree_position =
tree_position->CreateChildPositionAt(tree_position->child_index_);
}
BASE_DCHECK(tree_position && !tree_position->IsNullPosition());
} while (!tree_position->IsLeaf());
BASE_DCHECK(tree_position && tree_position->IsLeafTreePosition());
return tree_position;
}
AXPositionInstance AsTextPosition() const {
if (IsNullPosition() || IsTextPosition())
return Clone();
AXPositionInstance copy = Clone();
BASE_DCHECK(copy);
// Check if it is a "before text" position.
if (copy->child_index_ == BEFORE_TEXT) {
// "Before text" positions can only appear on leaf nodes.
BASE_DCHECK(copy->IsLeaf());
// If the current text offset is valid, we don't touch it to potentially
// allow converting from a text position to a tree position and back
// without losing information.
//
// We test for INVALID_OFFSET first, due to the possible performance
// implications of calling MaxTextOffset().
BASE_DCHECK(copy->text_offset_ >= INVALID_OFFSET);
if (copy->text_offset_ == INVALID_OFFSET ||
(copy->text_offset_ > 0 &&
copy->text_offset_ >= copy->MaxTextOffset())) {
copy->text_offset_ = 0;
}
} else if (copy->child_index_ == copy->AnchorChildCount()) {
copy->text_offset_ = copy->MaxTextOffset();
} else {
BASE_DCHECK(copy->child_index_ >= 0);
BASE_DCHECK(copy->child_index_ < copy->AnchorChildCount());
int new_offset = 0;
for (int i = 0; i <= child_index_; ++i) {
AXPositionInstance child = copy->CreateChildPositionAt(i);
BASE_DCHECK(child);
// If the current text offset is valid, we don't touch it to
// potentially allow converting from a text position to a tree
// position and back without losing information. Otherwise, if the
// text_offset is invalid, equals to 0 or is smaller than
// |new_offset|, we reset it to the beginning of the current child
// node.
if (i == child_index_ && copy->text_offset_ <= new_offset) {
copy->text_offset_ = new_offset;
break;
}
int child_length = child->MaxTextOffsetInParent();
// Same comment as above: we don't touch the text offset if it's
// already valid.
if (i == child_index_ &&
(copy->text_offset_ > (new_offset + child_length) ||
// When the text offset is equal to the text's length but this is
// not an "after text" position.
(!copy->AtEndOfAnchor() &&
copy->text_offset_ == (new_offset + child_length)))) {
copy->text_offset_ = new_offset;
break;
}
new_offset += child_length;
}
}
// Affinity should always be left as downstream. The only case when the
// resulting text position is at the end of the line is when we get an
// "after text" leaf position, but even in this case downstream is
// appropriate because there is no ambiguity whetehr the position is at the
// end of the current line vs. the start of the next line. It would always
// be the former.
copy->kind_ = AXPositionKind::TEXT_POSITION;
return copy;
}
AXPositionInstance AsLeafTextPosition() const {
if (IsNullPosition() || IsLeaf()) {
return AsTextPosition();
}
// Adjust the text offset.
// No need to check for "before text" positions here because they are only
// present on leaf anchor nodes.
AXPositionInstance text_position = AsTextPosition();
int adjusted_offset = text_position->text_offset_;
do {
AXPositionInstance child_position =
text_position->CreateChildPositionAt(0);
BASE_DCHECK(child_position);
// If the text offset corresponds to multiple child positions because some
// of the children have empty text, the condition "adjusted_offset > 0"
// below ensures that the first child will be chosen.
for (int i = 1;
i < text_position->AnchorChildCount() && adjusted_offset > 0; ++i) {
const int max_text_offset_in_parent =
child_position->MaxTextOffsetInParent();
if (adjusted_offset < max_text_offset_in_parent) {
break;
}
if (affinity_ == ax::mojom::TextAffinity::kUpstream &&
adjusted_offset == max_text_offset_in_parent) {
// Maintain upstream affinity so that we'll be able to choose the
// correct leaf anchor if the text offset is right on the boundary
// between two leaves.
child_position->affinity_ = ax::mojom::TextAffinity::kUpstream;
break;
}
child_position = std::move(text_position->CreateChildPositionAt(i));
adjusted_offset -= max_text_offset_in_parent;
}
text_position = std::move(child_position);
} while (!text_position->IsLeaf());
BASE_DCHECK(text_position);
BASE_DCHECK(text_position->IsLeafTextPosition());
text_position->text_offset_ = adjusted_offset;
// A leaf Text position is always downstream since there is no ambiguity as
// to whether it refers to the end of the current or the start of the next
// line.
text_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
return text_position;
}
// We deploy three strategies in order to find the best match for an ignored
// position in the accessibility tree:
//
// 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.
// 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.
// 3. As a last resort, we move either to the next or previous unignored
// position in the accessibility tree, based on the "adjustment_behavior".
AXPositionInstance AsUnignoredPosition(
AXPositionAdjustmentBehavior adjustment_behavior) const {
if (IsNullPosition() || !IsIgnored())
return Clone();
AXPositionInstance leaf_tree_position = AsLeafTreePosition();
// If this is a text position, first try moving up to a parent equivalent
// position and check if the resulting position is still ignored. This
// won't result in the loss of any information. We can't do that in the
// case of tree positions, because we would be better off to move to the
// next or previous position within the same anchor, as this would lose
// less information than moving to a parent equivalent position.
//
// Text positions are considered ignored if either the current anchor is
// ignored, or if the equivalent leaf tree position is ignored.
// If this position is a leaf text position, or the equivalent leaf tree
// position is ignored, then it's not possible to create an ancestor text
// position that is unignored.
if (IsTextPosition() && !IsLeafTextPosition() &&
!leaf_tree_position->IsIgnored()) {
AXPositionInstance unignored_position = CreateParentPosition();
while (!unignored_position->IsNullPosition()) {
// Since the equivalent leaf tree position is unignored, search for the
// first unignored ancestor anchor and return that text position.
if (!unignored_position->GetAnchor()->IsIgnored()) {
BASE_DCHECK(!unignored_position->IsIgnored());
return unignored_position;
}
unignored_position = unignored_position->CreateParentPosition();
}
}
// There is a possibility that the position became unignored by moving to a
// leaf equivalent position. Otherwise, we have no choice but to move to the
// next or previous position and lose some information in the process.
while (leaf_tree_position->IsIgnored()) {
switch (adjustment_behavior) {
case AXPositionAdjustmentBehavior::kMoveForward:
leaf_tree_position = leaf_tree_position->CreateNextLeafTreePosition();
break;
case AXPositionAdjustmentBehavior::kMoveBackward:
leaf_tree_position =
leaf_tree_position->CreatePreviousLeafTreePosition();
// in case the unignored leaf node contains some text, ensure that the
// resulting position is an "after text" position, as such a position
// would be the closest to the ignored one, given the fact that we are
// moving backwards through the tree.
leaf_tree_position =
leaf_tree_position->CreatePositionAtEndOfAnchor();
break;
}
}
if (IsTextPosition())
return leaf_tree_position->AsTextPosition();
return leaf_tree_position;
}
// Searches backward and forward from this position until it finds the given
// text boundary, and creates an AXRange that spans from the former to the
// latter. The resulting AXRange is always a forward range: its anchor always
// comes before its focus in document order. The resulting AXRange is bounded
// by the anchor of this position, i.e. the AXBoundaryBehavior is set to
// StopAtAnchorBoundary. The exception is ax::mojom::TextBoundary::kWebPage,
// where this behavior won't make sense. This behavior is based on current
// platform needs and might be relaxed if necessary in the future.
//
// Please note that |expand_behavior| should have no effect for
// ax::mojom::TextBoundary::kObject and ax::mojom::TextBoundary::kWebPage
// because the range should be the same regardless if we first move left or
// right.
AXRangeType ExpandToEnclosingTextBoundary(
ax::mojom::TextBoundary boundary,
AXRangeExpandBehavior expand_behavior) const {
AXBoundaryBehavior boundary_behavior =
AXBoundaryBehavior::StopAtAnchorBoundary;
if (boundary == ax::mojom::TextBoundary::kWebPage)
boundary_behavior = AXBoundaryBehavior::CrossBoundary;
switch (expand_behavior) {
case AXRangeExpandBehavior::kLeftFirst: {
AXPositionInstance left_position = CreatePositionAtTextBoundary(
boundary, ax::mojom::MoveDirection::kBackward, boundary_behavior);
AXPositionInstance right_position =
left_position->CreatePositionAtTextBoundary(
boundary, ax::mojom::MoveDirection::kForward,
boundary_behavior);
return AXRangeType(std::move(left_position), std::move(right_position));
}
case AXRangeExpandBehavior::kRightFirst: {
AXPositionInstance right_position = CreatePositionAtTextBoundary(
boundary, ax::mojom::MoveDirection::kForward, boundary_behavior);
AXPositionInstance left_position =
right_position->CreatePositionAtTextBoundary(
boundary, ax::mojom::MoveDirection::kBackward,
boundary_behavior);
return AXRangeType(std::move(left_position), std::move(right_position));
}
}
}
// Starting from this position, moves in the given direction until it finds
// the given text boundary, and creates a new position at that location.
//
// When a boundary has the "StartOrEnd" suffix, it means that this method will
// find the start boundary when moving in the backward direction, and the end
// boundary when moving in the forward direction.
AXPositionInstance CreatePositionAtTextBoundary(
ax::mojom::TextBoundary boundary,
ax::mojom::MoveDirection direction,
AXBoundaryBehavior boundary_behavior) const {
AXPositionInstance resulting_position = CreateNullPosition();
switch (boundary) {
case ax::mojom::TextBoundary::kCharacter:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousCharacterPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextCharacterPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kFormat:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousFormatStartPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextFormatEndPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kLineEnd:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousLineEndPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextLineEndPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kLineStart:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousLineStartPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextLineStartPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kLineStartOrEnd:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousLineStartPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextLineEndPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kObject:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position = CreatePositionAtStartOfAnchor();
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreatePositionAtEndOfAnchor();
break;
}
break;
case ax::mojom::TextBoundary::kPageEnd:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousPageEndPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextPageEndPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kPageStart:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousPageStartPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextPageStartPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kPageStartOrEnd:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousPageStartPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextPageEndPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kParagraphEnd:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousParagraphEndPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position =
CreateNextParagraphEndPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kParagraphStart:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousParagraphStartPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position =
CreateNextParagraphStartPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kParagraphStartOrEnd:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousParagraphStartPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position =
CreateNextParagraphEndPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kSentenceEnd:
BASE_LOG() << "Sentence boundaries are not yet supported.";
BASE_UNREACHABLE();
return CreateNullPosition();
case ax::mojom::TextBoundary::kSentenceStart:
BASE_LOG() << "Sentence boundaries are not yet supported.";
BASE_UNREACHABLE();
return CreateNullPosition();
case ax::mojom::TextBoundary::kSentenceStartOrEnd:
BASE_LOG() << "Sentence boundaries are not yet supported.";
BASE_UNREACHABLE();
return CreateNullPosition();
case ax::mojom::TextBoundary::kWebPage:
if (boundary_behavior != AXBoundaryBehavior::CrossBoundary) {
BASE_LOG() << "We can't reach the start of the document if we "
"are disallowed "
"from crossing boundaries.";
BASE_UNREACHABLE();
}
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position = CreatePositionAtStartOfDocument();
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreatePositionAtEndOfDocument();
break;
}
break;
case ax::mojom::TextBoundary::kWordEnd:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousWordEndPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextWordEndPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kWordStart:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousWordStartPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextWordStartPosition(boundary_behavior);
break;
}
break;
case ax::mojom::TextBoundary::kWordStartOrEnd:
switch (direction) {
case ax::mojom::MoveDirection::kBackward:
resulting_position =
CreatePreviousWordStartPosition(boundary_behavior);
break;
case ax::mojom::MoveDirection::kForward:
resulting_position = CreateNextWordEndPosition(boundary_behavior);
break;
}
break;
}
return resulting_position;
}
AXPositionInstance CreatePositionAtStartOfAnchor() const {
switch (kind_) {
case AXPositionKind::NULL_POSITION:
return CreateNullPosition();
case AXPositionKind::TREE_POSITION:
if (IsLeaf())
return CreateTreePosition(tree_id_, anchor_id_, BEFORE_TEXT);
return CreateTreePosition(tree_id_, anchor_id_, 0 /* child_index */);
case AXPositionKind::TEXT_POSITION:
return CreateTextPosition(tree_id_, anchor_id_, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
}
return CreateNullPosition();
}
AXPositionInstance CreatePositionAtEndOfAnchor() const {
switch (kind_) {
case AXPositionKind::NULL_POSITION:
return CreateNullPosition();
case AXPositionKind::TREE_POSITION:
return CreateTreePosition(
tree_id_, anchor_id_,
IsEmptyObjectReplacedByCharacter() ? 0 : AnchorChildCount());
case AXPositionKind::TEXT_POSITION:
return CreateTextPosition(tree_id_, anchor_id_, MaxTextOffset(),
ax::mojom::TextAffinity::kDownstream);
}
return CreateNullPosition();
}
AXPositionInstance CreatePositionAtStartOfAXTree() const {
if (IsNullPosition() || AtStartOfAXTree())
return Clone();
// First check for positions on nodes which are AXTree boundaries, but where
// the text position on that node is not at the start of the anchor.
if (CreatePositionAtStartOfAnchor()->AtStartOfAXTree())
return CreatePositionAtStartOfAnchor();
// Iterate over tree positions until a boundary is reached.
AXPositionInstance previous_position = AsTreePosition();
do {
previous_position = previous_position->CreatePreviousAnchorPosition();
} while (!previous_position->AtStartOfAXTree());
// This method should not cross tree boundaries.
BASE_DCHECK(previous_position->tree_id() == tree_id());
if (IsTextPosition())
previous_position = previous_position->AsTextPosition();
return previous_position;
}
AXPositionInstance CreatePositionAtEndOfAXTree() const {
if (IsNullPosition() || AtEndOfAXTree())
return Clone();
// First check for positions on nodes which are AXTree boundaries, but where
// the text position on that node is not at the end of the anchor.
if (CreatePositionAtEndOfAnchor()->AtEndOfAXTree())
return CreatePositionAtEndOfAnchor();
// Iterate over tree positions until a boundary is reached.
AXPositionInstance next_position = AsTreePosition();
do {
next_position = next_position->CreateNextAnchorPosition()
->CreatePositionAtEndOfAnchor();
} while (!next_position->AtEndOfAXTree());
// This method should not cross tree boundaries.
BASE_DCHECK(next_position->tree_id() == tree_id());
if (IsTextPosition())
next_position = next_position->AsTextPosition();
return next_position->CreatePositionAtEndOfAnchor();
}
// "document" is defined here as a single, top-level, navigatable unit from
// a user's perspective. This means that all iframes are part of a single
// "document" that contains the top-level navigatable page. So this method
// will break out of an iframe and return a position at the start of the
// top-level document.
//
// Note that this definition is different than HTML's definition of
// "document", where each iframe has its own document object. For a similar
// method that stops at iframe boundaries, see
// CreatePositionAtStartOfAXTree().
AXPositionInstance CreatePositionAtStartOfDocument() const {
AXPositionInstance position =
AsTreePosition()->CreateDocumentAncestorPosition();
if (!position->IsNullPosition()) {
position = position->CreatePositionAtStartOfAnchor();
if (IsTextPosition())
position = position->AsTextPosition();
}
return position;
}
// "document" is defined here as a single, top-level, navigatable unit from
// a user's perspective. This means that all iframes are part of a single
// "document" that contains the top-level navigatable page. So this method
// will break out of an iframe and return a position at the end of the
// top-level document.
//
// Note that this definition is different than HTML's definition of
// "document", where each iframe has its own document object. For a similar
// method that stops at iframe boundaries, see CreatePositionAtEndOfAXTree().
AXPositionInstance CreatePositionAtEndOfDocument() const {
AXPositionInstance position =
AsTreePosition()->CreateDocumentAncestorPosition();
if (!position->IsNullPosition()) {
while (!position->IsLeaf()) {
position =
position->CreateChildPositionAt(position->AnchorChildCount() - 1);
}
position = position->CreatePositionAtEndOfAnchor();
if (IsTextPosition())
position = position->AsTextPosition();
}
return position;
}
AXPositionInstance CreateChildPositionAt(int child_index) const {
if (IsNullPosition() || IsLeaf())
return CreateNullPosition();
if (child_index < 0 || child_index >= AnchorChildCount())
return CreateNullPosition();
AXTreeID tree_id = AXTreeIDUnknown();
AXNode::AXID child_id = AXNode::kInvalidAXID;
AnchorChild(child_index, &tree_id, &child_id);
BASE_DCHECK(tree_id != AXTreeIDUnknown());
BASE_DCHECK(child_id != AXNode::kInvalidAXID);
switch (kind_) {
case AXPositionKind::NULL_POSITION:
BASE_UNREACHABLE();
return CreateNullPosition();
case AXPositionKind::TREE_POSITION: {
AXPositionInstance child_position =
CreateTreePosition(tree_id, child_id, 0 /* child_index */);
// If the child's anchor is a leaf node, make this a "before text"
// position.
if (child_position->IsLeaf())
child_position->child_index_ = BEFORE_TEXT;
return child_position;
}
case AXPositionKind::TEXT_POSITION:
return CreateTextPosition(tree_id, child_id, 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
}
return CreateNullPosition();
}
// Creates a parent equivalent position.
//
// "move_direction" is used only in the case of a text position, when in
// the process of searching for a text boundary, and on platforms where child
// nodes are represented by embedded object characters. On such platforms, the
// "IsEmbeddedObjectInParent" method returns true. We need to decide whether
// to create a parent equivalent position that is before or after the child
// node, since moving to a parent position would always cause us to lose some
// information. We can't simply re-use the text offset of the child position
// because by definition the parent node doesn't include all the text of the
// child node, but only a single embedded object character.
//
// staticText name='Line one' IA2-hypertext='<embedded_object>'
// ++inlineTextBox name='Line one'
//
// If we are given a text position pointing to somewhere inside the
// inlineTextBox, and we move to the parent equivalent position, we need to
// decide whether the parent position would be set to point to before the
// embedded object character or after it. Both are valid, depending on the
// direction on motion, e.g. if we are trying to find the start of the line
// vs. the end of the line.
AXPositionInstance CreateParentPosition(
ax::mojom::MoveDirection move_direction =
ax::mojom::MoveDirection::kForward) const {
if (IsNullPosition())
return CreateNullPosition();
AXTreeID tree_id = AXTreeIDUnknown();
AXNode::AXID parent_id = AXNode::kInvalidAXID;
AnchorParent(&tree_id, &parent_id);
if (tree_id == AXTreeIDUnknown() || parent_id == AXNode::kInvalidAXID)
return CreateNullPosition();
switch (kind_) {
case AXPositionKind::NULL_POSITION:
BASE_UNREACHABLE();
return CreateNullPosition();
case AXPositionKind::TREE_POSITION:
return CreateTreePosition(tree_id, parent_id, AnchorIndexInParent());
case AXPositionKind::TEXT_POSITION: {
// On some platforms, such as Android, Mac and Chrome OS, the inner text
// of a node is made up by concatenating the text of child nodes. On
// other platforms, such as Windows IA2 and Linux ATK, child nodes are
// represented by a single embedded object character.
//
// If our parent's inner text is a concatenation of all its children's
// text, we need to maintain the affinity and compute the corresponding
// text offset. Otherwise, we have no choice but to return a position
// that is either before or after this child, losing some information in
// the process. Regardless to whether our parent contains all our text,
// we always recompute the affinity when the position is after the
// child.
//
// Recomputing the affinity in the latter situation is important because
// even though a text position might unambiguously be at the end of a
// line, its parent position might be the same as the parent position of
// a position that represents the start of the next line. For example:
//
// staticText name='Line oneLine two'
// ++inlineTextBox name='Line one'
// ++inlineTextBox name='Line two'
//
// If the original position is at the end of the inline text box for
// "Line one", then the resulting parent equivalent position would be
// the same as the one that would have been computed if the original
// position were at the start of the inline text box for "Line two".
const int max_text_offset = MaxTextOffset();
int max_text_offset_in_parent =
IsEmbeddedObjectInParent() ? 1 : max_text_offset;
int parent_offset = AnchorTextOffsetInParent();
ax::mojom::TextAffinity parent_affinity = affinity_;
if (max_text_offset == max_text_offset_in_parent) {
// Our parent contains all our text. No information would be lost when
// moving to a parent equivalent position.
parent_offset += text_offset_;
} else if (text_offset_ > 0) {
// If "text_offset_" == 0, then the child position is clearly before
// any embedded object character. No information would be lost when
// moving to a parent equivalent position, including affinity
// information. Otherwise, we should decide whether to set the parent
// position to be before or after the child, based on the direction of
// motion, and also reset the affinity.
switch (move_direction) {
case ax::mojom::MoveDirection::kBackward:
// Keep the offset to be right before the embedded object
// character.
break;
case ax::mojom::MoveDirection::kForward:
// Set the offset to be after the embedded object character.
parent_offset += max_text_offset_in_parent;
break;
}
// The original affinity doesn't apply any more. In most cases, it
// should be downstream, unless there is an ambiguity as to whether
// the parent position is between the end of one line and the start of
// the next. We perform this check below.
parent_affinity = ax::mojom::TextAffinity::kDownstream;
}
// This dummy position serves to retrieve the max text offset of the
// anchor-node in which we want to create the parent position.
AXPositionInstance dummy_position =
CreateTextPosition(tree_id, parent_id, 0, parent_affinity);
max_text_offset_in_parent = dummy_position->MaxTextOffset();
if (parent_offset > max_text_offset_in_parent) {
parent_offset = max_text_offset_in_parent;
}
AXPositionInstance parent_position = CreateTextPosition(
tree_id, parent_id, parent_offset, parent_affinity);
// If the current position is pointing at the end of its anchor, we need
// to check if the parent position has introduced ambiguity as to
// whether it refers to the end of a line or the start of the next.
// Ambiguity is only present when the parent position points to a text
// offset that is neither at the start nor at the end of its anchor. We
// check for ambiguity by creating the parent position and testing if it
// is erroneously at the start of the next line. Given that the current
// position, by the nature of being at the end of its anchor, could only
// be at end of line, the fact that the parent position is also
// determined to be at start of line demonstrates the presence of
// ambiguity which is resolved by setting its affinity to upstream.
//
// We could not have
// checked if the child was at the end of the line, because our
// "AtEndOfLine" predicate takes into account trailing line breaks,
// which would create false positives.
if (text_offset_ == max_text_offset &&
!parent_position->AtEndOfAnchor() &&
parent_position->AtStartOfLine()) {
parent_position->affinity_ = ax::mojom::TextAffinity::kUpstream;
}
return parent_position;
}
}
return CreateNullPosition();
}
// Creates a tree position using the next text-only node as its anchor.
// Assumes that text-only nodes are leaf nodes.
AXPositionInstance CreateNextLeafTreePosition() const {
return CreateNextLeafTreePosition(&DefaultAbortMovePredicate);
}
// Creates a tree position using the previous text-only node as its anchor.
// Assumes that text-only nodes are leaf nodes.
AXPositionInstance CreatePreviousLeafTreePosition() const {
return CreatePreviousLeafTreePosition(&DefaultAbortMovePredicate);
}
// Creates the next text position anchored at a leaf node of the AXTree.
//
// If a pointer |crossed_line_breaking_object| is provided, it'll be set to
// |true| if any line breaking object boundary was crossed by moving from this
// leaf text position to the next (if it exists), |false| otherwise.
AXPositionInstance CreateNextLeafTextPosition(
bool* crossed_line_breaking_object = nullptr) const {
if (crossed_line_breaking_object)
*crossed_line_breaking_object = false;
// If this is an ancestor text position, resolve to its leaf text position.
if (IsTextPosition() && !IsLeaf())
return AsLeafTextPosition();
std::function<AbortMovePredicate> abort_move_predicate;
if (crossed_line_breaking_object) {
abort_move_predicate = [crossed_line_breaking_object](
const AXPosition& move_from,
const AXPosition& move_to,
const AXMoveType type,
const AXMoveDirection direction) {
return UpdateCrossedLineBreakingObjectToken(
*crossed_line_breaking_object, move_from, move_to, type, direction);
};
} else {
abort_move_predicate =
[](const AXPosition& move_from, const AXPosition& move_to,
const AXMoveType type, const AXMoveDirection direction) {
return AXPosition::DefaultAbortMovePredicate(move_from, move_to,
type, direction);
};
}
return CreateNextLeafTreePosition(abort_move_predicate)->AsTextPosition();
}
// Creates a text position using the previous text-only node as its anchor.
// Assumes that text-only nodes are leaf nodes.
AXPositionInstance CreatePreviousLeafTextPosition() const {
return CreatePreviousTextAnchorPosition(DefaultAbortMovePredicate);
}
// Returns a text position located right before the next character (from this
// position) in the tree's text representation, following these conditions:
//
// - If this position is at the end of its anchor, normalize it to the start
// of the next text anchor, regardless of the position's affinity.
// Both text positions are equal when compared, but we consider the start of
// an anchor to be a position BEFORE its first character and the end of the
// previous to be AFTER its last character.
//
// - Skip any empty text anchors; they're "invisible" to the text
// representation and the next character could be ahead.
//
// - Return a null position if there is no next character forward.
//
// If possible, return a position anchored at the current position's anchor;
// this is necessary because we don't want to return any position that might
// be located in the shadow DOM or in a position anchored at a node that is
// not visible to a specific platform's APIs.
//
// Also, |text_offset| is adjusted to point to a valid character offset, i.e.
// it cannot be pointing to a low surrogate pair or to the middle of a
// grapheme cluster.
AXPositionInstance AsLeafTextPositionBeforeCharacter() const {
if (IsNullPosition())
return Clone();
AXPositionInstance text_position = AsTextPosition();
// In case the input affinity is upstream, reset it to downstream.
//
// This is to ensure that when we find the equivalent leaf text position, it
// will be at the start of anchor if the original position is anchored to a
// node higher up in the tree and pointing to a text offset that falls on
// the boundary between two leaf nodes. In other words, the returned
// position will always be "before character".
text_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
text_position = text_position->AsLeafTextPosition();
BASE_DCHECK(!text_position->IsNullPosition())
<< "Adjusting to a leaf position should never turn a non-null position "
"into a null one.";
if (!text_position->IsIgnored() && !text_position->AtEndOfAnchor()) {
BASE_DCHECK(text_position->text_offset_ >= 0);
return text_position;
}
text_position = text_position->CreateNextLeafTextPosition();
while (!text_position->IsNullPosition() &&
(text_position->IsIgnored() || !text_position->MaxTextOffset())) {
text_position = text_position->CreateNextLeafTextPosition();
}
return text_position;
}
// Returns a text position located right after the previous character (from
// this position) in the tree's text representation.
//
// See `AsLeafTextPositionBeforeCharacter`, as this is its "reversed" version.
AXPositionInstance AsLeafTextPositionAfterCharacter() const {
if (IsNullPosition())
return Clone();
AXPositionInstance text_position = AsTextPosition();
// Temporarily set the affinity to upstream.
//
// This is to ensure that when we find the equivalent leaf text position, it
// will be at the end of anchor if the original position is anchored to a
// node higher up in the tree and pointing to a text offset that falls on
// the boundary between two leaf nodes. In other words, the returned
// position will always be "after character".
text_position->affinity_ = ax::mojom::TextAffinity::kUpstream;
text_position = text_position->AsLeafTextPosition();
BASE_DCHECK(!text_position->IsNullPosition())
<< "Adjusting to a leaf position should never turn a non-null position "
"into a null one.";
if (!text_position->IsIgnored() && !text_position->AtStartOfAnchor()) {
// The following situation should not be possible but there are existing
// crashes in the field.
//
// TODO(nektar): Remove this workaround as soon as the source of the bug
// is identified.
BASE_DCHECK(text_position->text_offset_ >= 0);
// TODO(chunhtai): handles grapheme.
// Reset the affinity to downstream, because an upstream affinity doesn't
// make sense on a leaf anchor.
text_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
return text_position;
}
text_position = text_position->CreatePreviousLeafTextPosition();
while (!text_position->IsNullPosition() &&
(text_position->IsIgnored() || !text_position->MaxTextOffset())) {
text_position = text_position->CreatePreviousLeafTextPosition();
}
return text_position->CreatePositionAtEndOfAnchor();
}
// Creates a position pointing to before the next character, which is defined
// as the start of the next grapheme cluster. Also, ensures that the created
// position will not point to a low surrogate pair.
//
// A grapheme cluster is what an end-user would consider a character and it
// could include a letter with additional diacritics. It could be more than
// one Unicode code unit in length.
//
// See also http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
AXPositionInstance CreateNextCharacterPosition(
AXBoundaryBehavior boundary_behavior) const {
if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary &&
AtEndOfAnchor()) {
return Clone();
}
// There is no next character position.
AXPositionInstance text_position = AsLeafTextPositionBeforeCharacter();
if (text_position->IsNullPosition()) {
if (boundary_behavior == AXBoundaryBehavior::StopIfAlreadyAtBoundary ||
boundary_behavior == AXBoundaryBehavior::StopAtLastAnchorBoundary) {
text_position = Clone();
}
return text_position;
}
if (boundary_behavior == AXBoundaryBehavior::StopIfAlreadyAtBoundary &&
*text_position == *this) {
return Clone();
}
BASE_DCHECK(text_position->text_offset_ < text_position->MaxTextOffset());
// TODO(chunhtai): Need to consider grapheme cluster.
++text_position->text_offset_;
BASE_DCHECK(text_position->text_offset_ > 0);
BASE_DCHECK(text_position->text_offset_ <= text_position->MaxTextOffset());
// If the character boundary is in the same subtree, return a position
// rooted at this position's anchor. This is necessary because we don't want
// to return a position that might be in the shadow DOM when this position
// is not.
const AXNodeType* common_anchor = text_position->LowestCommonAnchor(*this);
if (GetAnchor() == common_anchor) {
text_position = text_position->CreateAncestorPosition(
common_anchor, ax::mojom::MoveDirection::kForward);
} else if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary) {
// If the next character position crosses the current anchor boundary
// with StopAtAnchorBoundary, snap to the end of the current anchor.
return CreatePositionAtEndOfAnchor();
}
// Even if the resulting position is right on a soft line break, affinity is
// defaulted to downstream so that this method will always produce the same
// result regardless of the direction of motion or the input affinity.
text_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
if (IsTreePosition())
return text_position->AsTreePosition();
return text_position;
}
// Creates a position pointing to before the previous character, which is
// defined as the start of the previous grapheme cluster. Also, ensures that
// the created position will not point to a low surrogate pair.
//
// See the comment above `CreateNextCharacterPosition` for the definition of a
// grapheme cluster.
AXPositionInstance CreatePreviousCharacterPosition(
AXBoundaryBehavior boundary_behavior) const {
if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary &&
AtStartOfAnchor()) {
return Clone();
}
// There is no previous character position.
AXPositionInstance text_position = AsLeafTextPositionAfterCharacter();
if (text_position->IsNullPosition()) {
if (boundary_behavior == AXBoundaryBehavior::StopIfAlreadyAtBoundary ||
boundary_behavior == AXBoundaryBehavior::StopAtLastAnchorBoundary) {
text_position = Clone();
}
return text_position;
}
if (boundary_behavior == AXBoundaryBehavior::StopIfAlreadyAtBoundary &&
*text_position == *this) {
return Clone();
}
BASE_DCHECK(text_position->text_offset_ > 0);
// TODO(chunhtai): Need to consider grapheme cluster.
--text_position->text_offset_;
BASE_DCHECK(text_position->text_offset_ >= 0);
BASE_DCHECK(text_position->text_offset_ < text_position->MaxTextOffset());
// The character boundary should be in the same subtree. Return a position
// rooted at this position's anchor. This is necessary because we don't want
// to return a position that might be in the shadow DOM when this position
// is not.
const AXNodeType* common_anchor = text_position->LowestCommonAnchor(*this);
if (GetAnchor() == common_anchor) {
text_position = text_position->CreateAncestorPosition(
common_anchor, ax::mojom::MoveDirection::kBackward);
} else if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary) {
// If the previous character position crosses the current anchor boundary
// with StopAtAnchorBoundary, snap to the start of the current anchor.
return CreatePositionAtStartOfAnchor();
}
// Even if the resulting position is right on a soft line break, affinity is
// defaulted to downstream so that this method will always produce the same
// result regardless of the direction of motion or the input affinity.
text_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
if (IsTreePosition())
return text_position->AsTreePosition();
return text_position;
}
AXPositionInstance CreateNextWordStartPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryStartPosition(
boundary_behavior, ax::mojom::MoveDirection::kForward,
&AtStartOfWordPredicate, &AtEndOfWordPredicate,
&GetWordStartOffsetsFunc);
}
AXPositionInstance CreatePreviousWordStartPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryStartPosition(
boundary_behavior, ax::mojom::MoveDirection::kBackward,
&AtStartOfWordPredicate, &AtEndOfWordPredicate,
&GetWordStartOffsetsFunc);
}
// Word end positions are one past the last character of the word.
AXPositionInstance CreateNextWordEndPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryEndPosition(
boundary_behavior, ax::mojom::MoveDirection::kForward,
&AtStartOfWordPredicate, &AtEndOfWordPredicate, &GetWordEndOffsetsFunc);
}
// Word end positions are one past the last character of the word.
AXPositionInstance CreatePreviousWordEndPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryEndPosition(
boundary_behavior, ax::mojom::MoveDirection::kBackward,
&AtStartOfWordPredicate, &AtEndOfWordPredicate, &GetWordEndOffsetsFunc);
}
AXPositionInstance CreateNextLineStartPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryStartPosition(
boundary_behavior, ax::mojom::MoveDirection::kForward,
&AtStartOfLinePredicate, &AtEndOfLinePredicate);
}
AXPositionInstance CreatePreviousLineStartPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryStartPosition(
boundary_behavior, ax::mojom::MoveDirection::kBackward,
&AtStartOfLinePredicate, &AtEndOfLinePredicate);
}
// Line end positions are one past the last character of the line, excluding
// any white space or newline characters that separate the lines.
AXPositionInstance CreateNextLineEndPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryEndPosition(
boundary_behavior, ax::mojom::MoveDirection::kForward,
&AtStartOfLinePredicate, &AtEndOfLinePredicate);
}
// Line end positions are one past the last character of the line, excluding
// any white space or newline characters separating the lines.
AXPositionInstance CreatePreviousLineEndPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryEndPosition(
boundary_behavior, ax::mojom::MoveDirection::kBackward,
&AtStartOfLinePredicate, &AtEndOfLinePredicate);
}
AXPositionInstance CreatePreviousFormatStartPosition(
AXBoundaryBehavior boundary_behavior) const {
if (IsNullPosition())
return Clone();
AXBoundaryType boundary_type = GetFormatStartBoundaryType();
if (boundary_type != AXBoundaryType::kNone) {
if (boundary_behavior == AXBoundaryBehavior::StopIfAlreadyAtBoundary ||
(boundary_behavior == AXBoundaryBehavior::StopAtLastAnchorBoundary &&
boundary_type == AXBoundaryType::kDocumentStart)) {
AXPositionInstance clone = Clone();
// In order to make equality checks simpler, affinity should be reset so
// that we would get consistent output from this function regardless of
// input affinity.
clone->affinity_ = ax::mojom::TextAffinity::kDownstream;
return clone;
} else if (boundary_behavior == AXBoundaryBehavior::CrossBoundary &&
boundary_type == AXBoundaryType::kDocumentStart) {
// If we're at a format boundary and there are no more text positions
// to traverse, return a null position for cross-boundary moves.
return CreateNullPosition();
}
}
AXPositionInstance tree_position =
AsTreePosition()->CreatePositionAtStartOfAnchor();
AXPositionInstance previous_tree_position =
tree_position->CreatePreviousLeafTreePosition();
// If moving to the start of the current anchor hasn't changed our position
// from the original position, we need to test the previous leaf tree
// position.
if (AtStartOfAnchor() &&
boundary_behavior != AXBoundaryBehavior::StopIfAlreadyAtBoundary) {
tree_position = std::move(previous_tree_position);
previous_tree_position = tree_position->CreatePreviousLeafTreePosition();
}
// The first position in the document is also a format start boundary, so we
// should not return NullPosition unless we started from that location.
while (boundary_type != AXBoundaryType::kDocumentStart &&
!previous_tree_position->IsNullPosition() &&
!tree_position->AtStartOfFormat()) {
tree_position = std::move(previous_tree_position);
previous_tree_position = tree_position->CreatePreviousLeafTreePosition();
}
// If the format boundary is in the same subtree, return a position rooted
// at the current position.
// This is necessary because we don't want to return any position that might
// be in the shadow DOM if the original position was not.
const AXNodeType* common_anchor = tree_position->LowestCommonAnchor(*this);
if (GetAnchor() == common_anchor) {
tree_position = tree_position->CreateAncestorPosition(
common_anchor, ax::mojom::MoveDirection::kBackward);
} else if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary) {
return CreatePositionAtStartOfAnchor();
}
if (IsTextPosition())
return tree_position->AsTextPosition();
return tree_position;
}
AXPositionInstance CreateNextFormatEndPosition(
AXBoundaryBehavior boundary_behavior) const {
if (IsNullPosition())
return Clone();
AXBoundaryType boundary_type = GetFormatEndBoundaryType();
if (boundary_type != AXBoundaryType::kNone) {
if (boundary_behavior == AXBoundaryBehavior::StopIfAlreadyAtBoundary ||
(boundary_behavior == AXBoundaryBehavior::StopAtLastAnchorBoundary &&
boundary_type == AXBoundaryType::kDocumentEnd)) {
AXPositionInstance clone = Clone();
// In order to make equality checks simpler, affinity should be reset so
// that we would get consistent output from this function regardless of
// input affinity.
clone->affinity_ = ax::mojom::TextAffinity::kDownstream;
return clone;
} else if (boundary_behavior == AXBoundaryBehavior::CrossBoundary &&
boundary_type == AXBoundaryType::kDocumentEnd) {
// If we're at a format boundary and there are no more text positions
// to traverse, return a null position for cross-boundary moves.
return CreateNullPosition();
}
}
AXPositionInstance tree_position =
AsTreePosition()->CreatePositionAtEndOfAnchor();
AXPositionInstance next_tree_position =
tree_position->CreateNextLeafTreePosition()
->CreatePositionAtEndOfAnchor();
// If moving to the end of the current anchor hasn't changed our original
// position, we need to test the next leaf tree position.
if (AtEndOfAnchor() &&
boundary_behavior != AXBoundaryBehavior::StopIfAlreadyAtBoundary) {
tree_position = std::move(next_tree_position);
next_tree_position = tree_position->CreateNextLeafTreePosition()
->CreatePositionAtEndOfAnchor();
}
// The last position in the document is also a format end boundary, so we
// should not return NullPosition unless we started from that location.
while (boundary_type != AXBoundaryType::kDocumentEnd &&
!next_tree_position->IsNullPosition() &&
!tree_position->AtEndOfFormat()) {
tree_position = std::move(next_tree_position);
next_tree_position = tree_position->CreateNextLeafTreePosition()
->CreatePositionAtEndOfAnchor();
}
// If the format boundary is in the same subtree, return a position
// rooted at the current position.
// This is necessary because we don't want to return any position that might
// be in the shadow DOM if the original position was not.
const AXNodeType* common_anchor = tree_position->LowestCommonAnchor(*this);
if (GetAnchor() == common_anchor) {
tree_position = tree_position->CreateAncestorPosition(
common_anchor, ax::mojom::MoveDirection::kForward);
} else if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary) {
return CreatePositionAtEndOfAnchor();
}
if (IsTextPosition())
return tree_position->AsTextPosition();
return tree_position;
}
AXPositionInstance CreateNextParagraphStartPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryStartPosition(
boundary_behavior, ax::mojom::MoveDirection::kForward,
&AtStartOfParagraphPredicate, &AtEndOfParagraphPredicate);
}
AXPositionInstance CreatePreviousParagraphStartPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryStartPosition(
boundary_behavior, ax::mojom::MoveDirection::kBackward,
&AtStartOfParagraphPredicate, &AtEndOfParagraphPredicate);
}
AXPositionInstance CreateNextParagraphEndPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryEndPosition(
boundary_behavior, ax::mojom::MoveDirection::kForward,
&AtStartOfParagraphPredicate, &AtEndOfParagraphPredicate);
}
AXPositionInstance CreatePreviousParagraphEndPosition(
AXBoundaryBehavior boundary_behavior) const {
AXPositionInstance previous_position = CreateBoundaryEndPosition(
boundary_behavior, ax::mojom::MoveDirection::kBackward,
&AtStartOfParagraphPredicate, &AtEndOfParagraphPredicate);
if (boundary_behavior == AXBoundaryBehavior::CrossBoundary ||
boundary_behavior == AXBoundaryBehavior::StopAtLastAnchorBoundary) {
// This is asymmetric with CreateNextParagraphEndPosition due to
// asymmetries in text anchor movement. Consider:
//
// ++1 rootWebArea
// ++++2 staticText name="FIRST"
// ++++3 genericContainer isLineBreakingObject=true
// ++++++4 genericContainer isLineBreakingObject=true
// ++++++5 staticText name="SECOND"
//
// Node 2 offset 5 FIRST<> is a paragraph end since node 3 is a line-
// breaking object that's not collapsible (since it's not a leaf). When
// looking for the next text anchor position from there, we advance to
// sibling node 3, then since that node has descendants, we convert to a
// tree position to find the leaf node that maps to "node 3 offset 0".
// Since node 4 has no text, we skip it and land on node 5. We end up at
// node 5 offset 6 SECOND<> as our next paragraph end.
//
// The set of paragraph ends should be consistent when moving in the
// reverse direction. But starting from node 5 offset 6, the previous text
// anchor position is previous sibling node 4. We'll consider that a
// paragraph end since it's a leaf line-breaking object and stop.
//
// Essentially, we have two consecutive line-breaking objects, each of
// which stops movement in the "outward" direction, for different reasons.
//
// We handle this by looking back one more step after finding a candidate
// for previous paragraph end, then testing a forward step from the look-
// back position. That will land us on the candidate position if it's a
// valid paragraph boundary.
//
while (!previous_position->IsNullPosition()) {
AXPositionInstance look_back_position =
previous_position->AsLeafTextPosition()
->CreatePreviousLeafTextPosition()
->CreatePositionAtEndOfAnchor();
if (look_back_position->IsNullPosition()) {
// Nowhere to look back to, so our candidate must be a valid paragraph
// boundary.
break;
}
AXPositionInstance forward_step_position =
look_back_position->CreateNextLeafTextPosition()
->CreatePositionAtEndOfAnchor();
if (*forward_step_position == *previous_position)
break;
previous_position = previous_position->CreateBoundaryEndPosition(
boundary_behavior, ax::mojom::MoveDirection::kBackward,
&AtStartOfParagraphPredicate, &AtEndOfParagraphPredicate);
}
}
return previous_position;
}
AXPositionInstance CreateNextPageStartPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryStartPosition(
boundary_behavior, ax::mojom::MoveDirection::kForward,
&AtStartOfPagePredicate, &AtEndOfPagePredicate);
}
AXPositionInstance CreatePreviousPageStartPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryStartPosition(
boundary_behavior, ax::mojom::MoveDirection::kBackward,
&AtStartOfPagePredicate, &AtEndOfPagePredicate);
}
AXPositionInstance CreateNextPageEndPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryEndPosition(
boundary_behavior, ax::mojom::MoveDirection::kForward,
&AtStartOfPagePredicate, &AtEndOfPagePredicate);
}
AXPositionInstance CreatePreviousPageEndPosition(
AXBoundaryBehavior boundary_behavior) const {
return CreateBoundaryEndPosition(
boundary_behavior, ax::mojom::MoveDirection::kBackward,
&AtStartOfPagePredicate, &AtEndOfPagePredicate);
}
AXPositionInstance CreateBoundaryStartPosition(
AXBoundaryBehavior boundary_behavior,
ax::mojom::MoveDirection move_direction,
BoundaryConditionPredicate at_start_condition,
BoundaryConditionPredicate at_end_condition,
BoundaryTextOffsetsFunc get_start_offsets = {}) const {
AXPositionInstance text_position = AsLeafTextPosition();
if (text_position->IsNullPosition())
return text_position;
if (boundary_behavior != AXBoundaryBehavior::StopIfAlreadyAtBoundary) {
text_position =
text_position->CreateAdjacentLeafTextPosition(move_direction);
if (text_position->IsNullPosition()) {
// There is no adjacent position to move to; in such case, CrossBoundary
// behavior shall return a null position, while any other behavior shall
// fallback to return the initial position.
if (boundary_behavior == AXBoundaryBehavior::CrossBoundary)
return text_position;
return Clone();
}
}
if (!at_start_condition(text_position)) {
text_position = text_position->CreatePositionAtNextOffsetBoundary(
move_direction, get_start_offsets);
while (!at_start_condition(text_position)) {
AXPositionInstance next_position;
if (move_direction == ax::mojom::MoveDirection::kForward) {
next_position = text_position->CreateNextLeafTextPosition();
} else {
if (text_position->AtStartOfAnchor()) {
next_position = text_position->CreatePreviousLeafTextPosition();
} else {
text_position = text_position->CreatePositionAtStartOfAnchor();
BASE_DCHECK(!text_position->IsNullPosition());
continue;
}
}
if (next_position->IsNullPosition()) {
if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary) {
switch (move_direction) {
case ax::mojom::MoveDirection::kForward:
return CreatePositionAtEndOfAnchor()->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
case ax::mojom::MoveDirection::kBackward:
return CreatePositionAtStartOfAnchor()->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
}
}
if (boundary_behavior ==
AXBoundaryBehavior::StopAtLastAnchorBoundary) {
// We can't simply return the following position; break and after
// this loop we'll try to do some adjustments to text_position.
switch (move_direction) {
case ax::mojom::MoveDirection::kForward:
text_position = text_position->CreatePositionAtEndOfAnchor();
break;
case ax::mojom::MoveDirection::kBackward:
text_position = text_position->CreatePositionAtStartOfAnchor();
break;
}
break;
}
return next_position->AsUnignoredPosition(
AdjustmentBehaviorFromBoundaryDirection(move_direction));
}
// Continue searching for the next boundary start in the specified
// direction until the next logical text position is reached.
text_position = next_position->CreatePositionAtFirstOffsetBoundary(
move_direction, get_start_offsets);
}
}
// If the boundary is in the same subtree, return a position rooted at this
// position's anchor. This is necessary because we don't want to return a
// position that might be in the shadow DOM when this position is not.
const AXNodeType* common_anchor = text_position->LowestCommonAnchor(*this);
if (GetAnchor() == common_anchor) {
text_position =
text_position->CreateAncestorPosition(common_anchor, move_direction);
} else if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary) {
switch (move_direction) {
case ax::mojom::MoveDirection::kForward:
return CreatePositionAtEndOfAnchor()->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
case ax::mojom::MoveDirection::kBackward:
return CreatePositionAtStartOfAnchor()->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
}
}
// Affinity is only upstream at the end of a line, and so a start boundary
// will never have an upstream affinity.
text_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
if (IsTreePosition())
text_position = text_position->AsTreePosition();
AXPositionInstance unignored_position = text_position->AsUnignoredPosition(
AdjustmentBehaviorFromBoundaryDirection(move_direction));
// If there are no unignored positions in |move_direction| then
// |text_position| is anchored in ignored content at the start or end
// of the document.
// For StopAtLastAnchorBoundary, try to adjust in the opposite direction
// to return a position within the document just before crossing into
// the ignored content. This will be the last unignored anchor boundary.
if (unignored_position->IsNullPosition() &&
boundary_behavior == AXBoundaryBehavior::StopAtLastAnchorBoundary) {
unignored_position =
text_position->AsUnignoredPosition(OppositeAdjustmentBehavior(
AdjustmentBehaviorFromBoundaryDirection(move_direction)));
}
return unignored_position;
}
AXPositionInstance CreateBoundaryEndPosition(
AXBoundaryBehavior boundary_behavior,
ax::mojom::MoveDirection move_direction,
BoundaryConditionPredicate at_start_condition,
BoundaryConditionPredicate at_end_condition,
BoundaryTextOffsetsFunc get_end_offsets = {}) const {
AXPositionInstance text_position = AsLeafTextPosition();
if (text_position->IsNullPosition())
return text_position;
if (boundary_behavior != AXBoundaryBehavior::StopIfAlreadyAtBoundary) {
text_position =
text_position->CreateAdjacentLeafTextPosition(move_direction);
if (text_position->IsNullPosition()) {
// There is no adjacent position to move to; in such case, CrossBoundary
// behavior shall return a null position, while any other behavior shall
// fallback to return the initial position.
if (boundary_behavior == AXBoundaryBehavior::CrossBoundary)
return text_position;
return Clone();
}
}
if (!at_end_condition(text_position)) {
text_position = text_position->CreatePositionAtNextOffsetBoundary(
move_direction, get_end_offsets);
while (!at_end_condition(text_position)) {
AXPositionInstance next_position;
if (move_direction == ax::mojom::MoveDirection::kForward) {
if (text_position->AtEndOfAnchor()) {
next_position = text_position->CreateNextLeafTextPosition();
} else {
text_position = text_position->CreatePositionAtEndOfAnchor();
BASE_DCHECK(!text_position->IsNullPosition());
continue;
}
} else {
next_position = text_position->CreatePreviousLeafTextPosition()
->CreatePositionAtEndOfAnchor();
}
if (next_position->IsNullPosition()) {
if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary) {
switch (move_direction) {
case ax::mojom::MoveDirection::kForward:
return CreatePositionAtEndOfAnchor()->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
case ax::mojom::MoveDirection::kBackward:
return CreatePositionAtStartOfAnchor()->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
}
}
if (boundary_behavior ==
AXBoundaryBehavior::StopAtLastAnchorBoundary) {
// We can't simply return the following position; break and after
// this loop we'll try to do some adjustments to text_position.
switch (move_direction) {
case ax::mojom::MoveDirection::kForward:
text_position = text_position->CreatePositionAtEndOfAnchor();
break;
case ax::mojom::MoveDirection::kBackward:
text_position = text_position->CreatePositionAtStartOfAnchor();
break;
}
break;
}
return next_position->AsUnignoredPosition(
AdjustmentBehaviorFromBoundaryDirection(move_direction));
}
// Continue searching for the next boundary end in the specified
// direction until the next logical text position is reached.
text_position = next_position->CreatePositionAtFirstOffsetBoundary(
move_direction, get_end_offsets);
}
}
// If the boundary is in the same subtree, return a position rooted at this
// position's anchor. This is necessary because we don't want to return a
// position that might be in the shadow DOM when this position is not.
const AXNodeType* common_anchor = text_position->LowestCommonAnchor(*this);
if (GetAnchor() == common_anchor) {
text_position =
text_position->CreateAncestorPosition(common_anchor, move_direction);
} else if (boundary_behavior == AXBoundaryBehavior::StopAtAnchorBoundary) {
switch (move_direction) {
case ax::mojom::MoveDirection::kForward:
return CreatePositionAtEndOfAnchor()->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
case ax::mojom::MoveDirection::kBackward:
return CreatePositionAtStartOfAnchor()->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
}
}
// If there is no ambiguity as to whether the position is at the end of
// the current boundary or the start of the next boundary, an upstream
// affinity should be reset to downstream in order to get consistent output
// from this method, regardless of input affinity.
//
// Note that there could be no ambiguity if the boundary is either at the
// start or the end of the current anchor, so we should always reset to
// downstream affinity in those cases.
if (text_position->affinity_ == ax::mojom::TextAffinity::kUpstream) {
AXPositionInstance downstream_position = text_position->Clone();
downstream_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
if (downstream_position->AtStartOfAnchor() ||
downstream_position->AtEndOfAnchor() ||
!at_start_condition(downstream_position)) {
text_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
}
}
if (IsTreePosition())
text_position = text_position->AsTreePosition();
AXPositionInstance unignored_position = text_position->AsUnignoredPosition(
AdjustmentBehaviorFromBoundaryDirection(move_direction));
// If there are no unignored positions in |move_direction| then
// |text_position| is anchored in ignored content at the start or end
// of the document.
// For StopAtLastAnchorBoundary, try to adjust in the opposite direction
// to return a position within the document just before crossing into
// the ignored content. This will be the last unignored anchor boundary.
if (unignored_position->IsNullPosition() &&
boundary_behavior == AXBoundaryBehavior::StopAtLastAnchorBoundary) {
unignored_position =
text_position->AsUnignoredPosition(OppositeAdjustmentBehavior(
AdjustmentBehaviorFromBoundaryDirection(move_direction)));
}
return unignored_position;
}
// TODO(nektar): Add sentence navigation methods.
// Uses depth-first pre-order traversal.
AXPositionInstance CreateNextAnchorPosition() const {
return CreateNextAnchorPosition(&DefaultAbortMovePredicate);
}
// Uses depth-first pre-order traversal.
AXPositionInstance CreatePreviousAnchorPosition() const {
return CreatePreviousAnchorPosition(&DefaultAbortMovePredicate);
}
// Returns an optional integer indicating the logical order of this position
// compared to another position or returns an empty optional if the positions
// are not comparable. Any text position at the same character location is
// logically equivalent although they may be on different anchors or have
// different text offsets. Positions are not comparable when one position is
// null and the other is not or if the positions do not have any common
// ancestor.
// 0: if this position is logically equivalent to the other position
// <0: if this position is logically less than the other position
// >0: if this position is logically greater than the other position
std::optional<int> CompareTo(const AXPosition& other) const {
if (this->IsNullPosition() && other.IsNullPosition())
return std::optional<int>(0);
if (this->IsNullPosition() || other.IsNullPosition())
return std::optional<int>(std::nullopt);
// If both positions share an anchor and are of the same type, we can do a
// straight compare of text offsets or child indices.
if (GetAnchor() == other.GetAnchor()) {
if (IsTextPosition() && other.IsTextPosition())
return text_offset() - other.text_offset();
if (IsTreePosition() && other.IsTreePosition())
return child_index() - other.child_index();
}
// Ancestor positions are expensive to compute. If possible, we will avoid
// doing so by computing the ancestor chain of the two positions' anchors.
// If the lowest common ancestor is neither position's anchor, we can use
// the order of the first uncommon ancestors as a proxy for the order of the
// positions.
//
// In order to do that, we need to normalize text positions at the end of an
// anchor to equivalent positions at the start of the next anchor. Ignored
// positions are a special case in that they need to be shifted to the
// nearest unignored position in order to be normalized. That shifting can
// change the comparison result, so if we have an ignored position, we must
// use the slow path.
if (IsIgnored() || other.IsIgnored())
return SlowCompareTo(other);
// Normalize any text positions at the end of an anchor to equivalent
// positions at the start of the next anchor.
AXPositionInstance normalized_this_position = Clone();
if (normalized_this_position->IsTextPosition()) {
normalized_this_position =
normalized_this_position->AsLeafTextPositionBeforeCharacter();
}
AXPositionInstance normalized_other_position = other.Clone();
if (normalized_other_position->IsTextPosition()) {
normalized_other_position =
normalized_other_position->AsLeafTextPositionBeforeCharacter();
}
if (normalized_this_position->IsNullPosition()) {
if (normalized_other_position->IsNullPosition()) {
// Both positions normalized to a position past the end of the document.
BASE_DCHECK(SlowCompareTo(other).value() == 0);
return 0;
}
// |this| normalized to a position past the end of the document.
BASE_DCHECK(SlowCompareTo(other).value() > 0);
return 1;
} else if (normalized_other_position->IsNullPosition()) {
// |other| normalized to a position past the end of the document.
BASE_DCHECK(SlowCompareTo(other).value() < 0);
return -1;
}
// Compute the ancestor stacks of both positions and walk them ourselves
// rather than calling LowestCommonAnchor(). That way, we can discover the
// first uncommon ancestors.
const AXNodeType* common_anchor = nullptr;
std::stack<AXNodeType*> our_ancestors =
normalized_this_position->GetAncestorAnchors();
std::stack<AXNodeType*> other_ancestors =
normalized_other_position->GetAncestorAnchors();
while (!our_ancestors.empty() && !other_ancestors.empty() &&
our_ancestors.top() == other_ancestors.top()) {
common_anchor = our_ancestors.top();
our_ancestors.pop();
other_ancestors.pop();
}
if (!common_anchor)
return std::optional<int>(std::nullopt);
// If each position has an uncommon ancestor node, we can compare those
// instead of needing to compute ancestor positions.
if (!our_ancestors.empty() && !other_ancestors.empty()) {
AXPositionInstance this_uncommon_tree_position = CreateTreePosition(
GetTreeID(our_ancestors.top()), GetAnchorID(our_ancestors.top()),
0 /*child_index*/);
int this_uncommon_ancestor_index =
this_uncommon_tree_position->AnchorIndexInParent();
AXPositionInstance other_uncommon_tree_position = CreateTreePosition(
GetTreeID(other_ancestors.top()), GetAnchorID(other_ancestors.top()),
0 /*child_index*/);
int other_uncommon_ancestor_index =
other_uncommon_tree_position->AnchorIndexInParent();
BASE_DCHECK(this_uncommon_ancestor_index !=
other_uncommon_ancestor_index);
int result = this_uncommon_ancestor_index - other_uncommon_ancestor_index;
// On platforms that support embedded objects, if a text position is
// within an embedded object and if it is not at the start of that object,
// the resulting ancestor position should be adjusted to point after the
// embedded object. Otherwise, assistive software will not be able to get
// out of the embedded object if its text is not editable when navigating
// by character.
//
// For example, look at the following accessibility tree and the two
// example text positions together with their equivalent ancestor
// positions.
// ++1 kRootWebArea
// ++++2 kTextField "Before<embedded_object>after"
// ++++++3 kStaticText "Before"
// ++++++++4 kInlineTextBox "Before"
// ++++++5 kImage "Test image"
// ++++++6 kStaticText "after"
// ++++++++7 kInlineTextBox "after"
//
// Note that the alt text of an image cannot be navigated with cursor
// left/right, even when the rest of the contents are in a
// contenteditable.
//
// Ancestor position should not be adjusted:
// TextPosition anchor_id=kImage text_offset=0 affinity=downstream
// annotated_text=<T>est image AncestorTextPosition anchor_id=kTextField
// text_offset=6 affinity=downstream
// annotated_text=Before<embedded_object>after
//
// Ancestor position should be adjusted:
// TextPosition anchor_id=kImage text_offset=1 affinity=downstream
// annotated_text=T<e>st image AncestorTextPosition anchor_id=kTextField
// text_offset=7 affinity=downstream
// annotated_text=Beforeembedded_object<a>fter
//
// Note that since the adjustment to the distance between the ancestor
// positions could at most be by one, we skip doing this check if the
// ancestor positions have a distance of more than one since it can never
// change the outcome of the comparison. Note too that if both ancestor
// positions need to be adjusted, the adjustments will cancel out.
if (abs(result) == 1) {
if (!normalized_this_position->AtStartOfAnchor() &&
this_uncommon_tree_position->IsEmbeddedObjectInParent()) {
result += 1;
}
if (!normalized_other_position->AtStartOfAnchor() &&
other_uncommon_tree_position->IsEmbeddedObjectInParent()) {
result -= 1;
}
}
#ifndef NDEBUG
// Validate the optimization.
int slow_result = SlowCompareTo(other).value();
BASE_DCHECK((result == 0 && slow_result == 0) ||
(result < 0 && slow_result < 0) ||
(result > 0 && slow_result > 0));
#endif
return result;
}
return SlowCompareTo(other);
}
std::optional<int> SlowCompareTo(const AXPosition& other) const {
// It is potentially costly to compute the parent position of a text
// position, whilst computing the parent position of a tree position is
// really inexpensive. In order to find the lowest common ancestor,
// especially if that ancestor is all the way up to the root of the tree,
// this will need to be done repeatedly. We avoid the performance hit by
// converting both positions to tree positions and only falling back to text
// positions if both are text positions and the lowest common ancestor is
// not one of their anchors. Essentially, the question we need to answer is:
// "When are two non equivalent positions going to have the same lowest
// common ancestor position when converted to tree positions?" The answer is
// when they are both text positions and they either have the same anchor,
// or one is the ancestor of the other.
const AXNodeType* common_anchor = this->LowestCommonAnchor(other);
if (!common_anchor)
return std::optional<int>(std::nullopt);
// Attempt to avoid recomputing the lowest common ancestor because we may
// already have its anchor in which case just find the text offset.
if (this->IsTextPosition() && other.IsTextPosition()) {
// This text position's anchor is the common ancestor of the other text
// position's anchor.
if (this->GetAnchor() == common_anchor) {
AXPositionInstance other_text_position =
other.CreateAncestorPosition(common_anchor);
return std::optional<int>(this->text_offset_ -
other_text_position->text_offset_);
}
// The other text position's anchor is the common ancestor of this text
// position's anchor.
if (other.GetAnchor() == common_anchor) {
AXPositionInstance this_text_position =
this->CreateAncestorPosition(common_anchor);
return std::optional<int>(this_text_position->text_offset_ -
other.text_offset_);
}
// All optimizations failed. Fall back to comparing text positions with
// the common text position ancestor.
AXPositionInstance this_text_position_ancestor =
this->CreateAncestorPosition(common_anchor);
AXPositionInstance other_text_position_ancestor =
other.CreateAncestorPosition(common_anchor);
BASE_DCHECK(this_text_position_ancestor->IsTextPosition());
BASE_DCHECK(other_text_position_ancestor->IsTextPosition());
BASE_DCHECK(common_anchor == this_text_position_ancestor->GetAnchor());
BASE_DCHECK(common_anchor == other_text_position_ancestor->GetAnchor());
// TODO - This does not take into account |affinity_|, so we may return
// a false positive when comparing at the end of a line.
// For example :
// ++1 kRootWebArea
// ++++2 kTextField "Line 1\nLine 2"
// ++++++3 kStaticText "Line 1"
// ++++++++4 kInlineTextBox "Line 1"
// ++++++5 kLineBreak "\n"
// ++++++6 kStaticText "Line 2"
// ++++++++7 kInlineTextBox "Line 2"
//
// TextPosition anchor_id=5 text_offset=1
// affinity=downstream annotated_text=\n<>
//
// TextPosition anchor_id=7 text_offset=0
// affinity=downstream annotated_text=<L>ine 2
//
// |LowestCommonAncestor| for both will be :
// TextPosition anchor_id=2 text_offset=7
// ... except anchor_id=5 creates a kUpstream position, while
// anchor_id=7 creates a kDownstream position.
return std::optional<int>(this_text_position_ancestor->text_offset_ -
other_text_position_ancestor->text_offset_);
}
// All optimizations failed. Fall back to comparing child index with
// the common tree position ancestor.
AXPositionInstance this_tree_position_ancestor =
this->AsTreePosition()->CreateAncestorPosition(common_anchor);
AXPositionInstance other_tree_position_ancestor =
other.AsTreePosition()->CreateAncestorPosition(common_anchor);
BASE_DCHECK(this_tree_position_ancestor->IsTreePosition());
BASE_DCHECK(other_tree_position_ancestor->IsTreePosition());
BASE_DCHECK(common_anchor == this_tree_position_ancestor->GetAnchor());
BASE_DCHECK(common_anchor == other_tree_position_ancestor->GetAnchor());
return std::optional<int>(this_tree_position_ancestor->child_index() -
other_tree_position_ancestor->child_index());
}
// A valid position can become invalid if the underlying tree structure
// changes. This is expected behavior, but it is sometimes necessary to
// maintain valid positions. This method modifies an invalid position that is
// beyond MaxTextOffset to snap to MaxTextOffset.
void SnapToMaxTextOffsetIfBeyond() {
int max_text_offset = MaxTextOffset();
if (text_offset_ > max_text_offset)
text_offset_ = max_text_offset;
}
// Returns true if this position is on an empty object node that needs to
// be represented by an empty object replacement character. It does when the
// node is a collapsed menu list popup button or has no unignored child and is
// not a text object. This feature is only enabled on some platforms.
bool IsEmptyObjectReplacedByCharacter() const {
if (g_ax_embedded_object_behavior ==
AXEmbeddedObjectBehavior::kSuppressCharacter ||
IsNullPosition()) {
return false;
}
// A collapsed popup button that contains a menu list popup (i.e, the exact
// subtree representation we get from a collapsed <select> element on
// Windows) should not expose its children even though they are not ignored.
if (GetAnchor()->IsCollapsedMenuListPopUpButton())
return true;
// All other elements that have unignored descendants should not be treated
// as empty objects.
if (AnchorUnignoredChildCount())
return false;
// All unignored leaf nodes in the AXTree except document and text
// nodes should be replaced by the embedded object character. Also, nodes
// that only have ignored children (e.g., a button that contains only an
// empty div) need to be treated as leaf nodes.
//
// Calling AXPosition::IsIgnored here is not possible as it would create an
// infinite loop. However, GetAnchor()->IsIgnored() is sufficient here
// because we know that the anchor at this position doesn't have an
// unignored child, making this a leaf tree or text position.
return !GetAnchor()->IsIgnored() && !IsDocument(GetAnchorRole()) &&
!IsInTextObject() && !IsIframe(GetAnchorRole());
}
bool IsInDescendantOfEmptyObject() const {
if (g_ax_embedded_object_behavior ==
AXEmbeddedObjectBehavior::kSuppressCharacter ||
IsNullPosition()) {
return false;
}
// Empty objects are only possible on a collapsed popup button parent of a
// menu list popup or a node that only has ignored descendants. If it has no
// empty object ancestor, it can't be inside of an empty object.
return GetEmptyObjectAncestorNode();
}
AXNodeType* GetEmptyObjectAncestorNode() const {
if (g_ax_embedded_object_behavior ==
AXEmbeddedObjectBehavior::kSuppressCharacter ||
!GetAnchor()) {
return nullptr;
}
if (!GetAnchor()->IsIgnored()) {
// The only case where a descendant of an empty object can be unignored is
// when we are inside of a collapsed popup button parent of a menu list
// popup.
if (AXNodeType* popup_button =
GetAnchor()->GetCollapsedMenuListPopUpButtonAncestor()) {
return popup_button;
}
return nullptr;
}
// The first unignored ancestor is necessarily the empty object if this node
// is the descendant of an empty object.
AXNodeType* ancestor_node = GetLowestUnignoredAncestor();
if (!ancestor_node)
return nullptr;
AXPositionInstance position = CreateTextPosition(
tree_id_, GetAnchorID(ancestor_node), 0 /* text_offset */,
ax::mojom::TextAffinity::kDownstream);
if (position && position->IsEmptyObjectReplacedByCharacter())
return ancestor_node;
return nullptr;
}
void swap(AXPosition& other) {
std::swap(kind_, other.kind_);
std::swap(tree_id_, other.tree_id_);
std::swap(anchor_id_, other.anchor_id_);
std::swap(child_index_, other.child_index_);
std::swap(text_offset_, other.text_offset_);
std::swap(affinity_, other.affinity_);
}
// Abstract methods.
// Returns the text that is present inside the anchor node, including any text
// found in descendant text nodes, based on the platform's text
// representation. Some platforms use an embedded object replacement character
// that replaces the text coming from each child node.
virtual std::u16string GetText() const = 0;
// Determines if the anchor containing this position is a <br> or a text
// object whose parent's anchor is an enclosing <br>.
virtual bool IsInLineBreak() const = 0;
// Determines if the anchor containing this position is a text object.
virtual bool IsInTextObject() const = 0;
// Determines if the text representation of this position's anchor contains
// only whitespace characters; <br> objects span a single '\n' character, so
// positions inside line breaks are also considered "in whitespace".
virtual bool IsInWhiteSpace() const = 0;
// Returns the length of the text that is present inside the anchor node,
// including any text found in descendant text nodes. This is based on the
// platform's text representation. Some platforms use an embedded object
// character that replaces the text coming from each child node.
//
// Similar to "text_offset_", the length of the text is in UTF16 code units,
// not in grapheme clusters.
virtual int MaxTextOffset() const {
if (IsNullPosition())
return INVALID_OFFSET;
return static_cast<int>(GetText().length());
}
protected:
AXPosition()
: kind_(AXPositionKind::NULL_POSITION),
tree_id_(AXTreeIDUnknown()),
anchor_id_(AXNode::kInvalidAXID),
child_index_(INVALID_INDEX),
text_offset_(INVALID_OFFSET),
affinity_(ax::mojom::TextAffinity::kDownstream) {}
// We explicitly don't copy any cached members.
AXPosition(const AXPosition& other)
: kind_(other.kind_),
tree_id_(other.tree_id_),
anchor_id_(other.anchor_id_),
child_index_(other.child_index_),
text_offset_(other.text_offset_),
affinity_(other.affinity_) {}
// Returns the character offset inside our anchor's parent at which our text
// starts.
int AnchorTextOffsetInParent() const {
if (IsNullPosition())
return INVALID_OFFSET;
// Calculate how much text there is to the left of this anchor.
AXPositionInstance tree_position = AsTreePosition();
BASE_DCHECK(tree_position);
AXPositionInstance parent_position = tree_position->CreateParentPosition();
BASE_DCHECK(parent_position);
if (parent_position->IsNullPosition())
return 0;
int offset_in_parent = 0;
for (int i = 0; i < parent_position->child_index(); ++i) {
AXPositionInstance child = parent_position->CreateChildPositionAt(i);
BASE_DCHECK(child);
offset_in_parent += child->MaxTextOffsetInParent();
}
return offset_in_parent;
}
void Initialize(AXPositionKind kind,
AXTreeID tree_id,
int32_t anchor_id,
int child_index,
int text_offset,
ax::mojom::TextAffinity affinity) {
kind_ = kind;
tree_id_ = tree_id;
anchor_id_ = anchor_id;
child_index_ = child_index;
text_offset_ = text_offset;
affinity_ = affinity;
if (!IsValid()) {
// Reset to the null position.
kind_ = AXPositionKind::NULL_POSITION;
tree_id_ = AXTreeIDUnknown();
anchor_id_ = AXNode::kInvalidAXID;
child_index_ = INVALID_INDEX;
text_offset_ = INVALID_OFFSET;
affinity_ = ax::mojom::TextAffinity::kDownstream;
}
}
// Abstract methods.
virtual void AnchorChild(int child_index,
AXTreeID* tree_id,
int32_t* child_id) const = 0;
virtual int AnchorChildCount() const = 0;
// When a child is ignored, it looks for unignored nodes of that child's
// children until there are no more descendants.
//
// E.g.
// ++TextField
// ++++GenericContainer ignored
// ++++++StaticText "Hello"
// When we call the following method on TextField, it would return 1.
virtual int AnchorUnignoredChildCount() const = 0;
virtual int AnchorIndexInParent() const = 0;
virtual int AnchorSiblingCount() const = 0;
virtual std::stack<AXNodeType*> GetAncestorAnchors() const = 0;
virtual AXNodeType* GetLowestUnignoredAncestor() const = 0;
virtual void AnchorParent(AXTreeID* tree_id, int32_t* parent_id) const = 0;
virtual AXNodeType* GetNodeInTree(AXTreeID tree_id,
int32_t node_id) const = 0;
virtual int32_t GetAnchorID(AXNodeType* node) const = 0;
virtual AXTreeID GetTreeID(AXNodeType* node) const = 0;
// Returns the length of text that this anchor node takes up in its parent.
// On some platforms, embedded objects are represented in their parent with a
// single embedded object character.
int MaxTextOffsetInParent() const {
return IsEmbeddedObjectInParent() ? 1 : MaxTextOffset();
}
// Returns whether or not this anchor is represented in their parent with a
// single embedded object character.
virtual bool IsEmbeddedObjectInParent() const = 0;
// Determines if the anchor containing this position produces a hard line
// break in the text representation, e.g. a block level element or a <br>.
virtual bool IsInLineBreakingObject() const = 0;
virtual ax::mojom::Role GetAnchorRole() const = 0;
virtual ax::mojom::Role GetRole(AXNodeType* node) const = 0;
virtual AXNodeTextStyles GetTextStyles() const = 0;
virtual std::vector<int32_t> GetWordStartOffsets() const = 0;
virtual std::vector<int32_t> GetWordEndOffsets() const = 0;
virtual int32_t GetNextOnLineID(int32_t node_id) const = 0;
virtual int32_t GetPreviousOnLineID(int32_t node_id) const = 0;
private:
// Defines the relationship between positions during traversal.
// For example, moving from a descendant to an ancestor, is a kAncestor move.
enum class AXMoveType {
kAncestor,
kDescendant,
kSibling,
};
// Defines the direction of position movement, either next / previous in tree.
enum class AXMoveDirection {
kNextInTree,
kPreviousInTree,
};
// Type of predicate function called during anchor navigation.
// When the predicate returns |true|, the navigation stops and returns a
// null position object.
typedef bool AbortMovePredicate(const AXPosition& move_from,
const AXPosition& move_to,
const AXMoveType type,
const AXMoveDirection direction);
// A text span is defined by a series of inline text boxes that make up a
// single static text object.
bool AtEndOfTextSpan() const {
if (GetAnchorRole() != ax::mojom::Role::kInlineTextBox || !AtEndOfAnchor())
return false;
// We are at the end of text span if |this| position has
// role::kInlineTextBox, the parent of |this| has role::kStaticText, and the
// anchor node of |this| is the last child of parent's children.
const bool is_last_child =
AnchorIndexInParent() == (AnchorSiblingCount() - 1);
return is_last_child && GetRole(GetLowestUnignoredAncestor()) ==
ax::mojom::Role::kStaticText;
}
// Uses depth-first pre-order traversal.
AXPositionInstance CreateNextAnchorPosition(
std::function<AbortMovePredicate> abort_predicate) const {
if (IsNullPosition())
return Clone();
AXPositionInstance current_position = AsTreePosition();
BASE_DCHECK(!current_position->IsNullPosition());
if (!IsLeaf()) {
const int child_index = current_position->child_index_;
if (child_index < current_position->AnchorChildCount()) {
AXPositionInstance child_position =
current_position->CreateChildPositionAt(child_index);
if (abort_predicate(*current_position, *child_position,
AXMoveType::kDescendant,
AXMoveDirection::kNextInTree)) {
return CreateNullPosition();
}
return child_position;
}
}
AXPositionInstance parent_position =
current_position->CreateParentPosition();
// Get the next sibling if it exists, otherwise move up the AXTree to the
// lowest next sibling of this position's ancestors.
while (!parent_position->IsNullPosition()) {
const int index_in_parent = current_position->AnchorIndexInParent();
if (index_in_parent + 1 < parent_position->AnchorChildCount()) {
AXPositionInstance next_sibling =
parent_position->CreateChildPositionAt(index_in_parent + 1);
BASE_DCHECK(!next_sibling->IsNullPosition());
if (abort_predicate(*current_position, *next_sibling,
AXMoveType::kSibling,
AXMoveDirection::kNextInTree)) {
return CreateNullPosition();
}
return next_sibling;
}
if (abort_predicate(*current_position, *parent_position,
AXMoveType::kAncestor,
AXMoveDirection::kNextInTree)) {
return CreateNullPosition();
}
current_position = std::move(parent_position);
parent_position = current_position->CreateParentPosition();
}
return CreateNullPosition();
}
// Uses depth-first pre-order traversal.
AXPositionInstance CreatePreviousAnchorPosition(
std::function<AbortMovePredicate> abort_predicate) const {
if (IsNullPosition())
return Clone();
AXPositionInstance current_position = AsTreePosition();
BASE_DCHECK(!current_position->IsNullPosition());
AXPositionInstance parent_position =
current_position->CreateParentPosition();
if (parent_position->IsNullPosition())
return parent_position;
// If there is no previous sibling, move up to the parent.
const int index_in_parent = current_position->AnchorIndexInParent();
if (index_in_parent <= 0) {
if (abort_predicate(*current_position, *parent_position,
AXMoveType::kAncestor,
AXMoveDirection::kPreviousInTree)) {
return CreateNullPosition();
}
return parent_position;
}
// Get the previous sibling's deepest last child.
AXPositionInstance rightmost_leaf =
parent_position->CreateChildPositionAt(index_in_parent - 1);
BASE_DCHECK(!rightmost_leaf->IsNullPosition());
if (abort_predicate(*current_position, *rightmost_leaf,
AXMoveType::kSibling,
AXMoveDirection::kPreviousInTree)) {
return CreateNullPosition();
}
while (!rightmost_leaf->IsLeaf()) {
parent_position = std::move(rightmost_leaf);
rightmost_leaf = parent_position->CreateChildPositionAt(
parent_position->AnchorChildCount() - 1);
BASE_DCHECK(!rightmost_leaf->IsNullPosition());
if (abort_predicate(*parent_position, *rightmost_leaf,
AXMoveType::kDescendant,
AXMoveDirection::kPreviousInTree)) {
return CreateNullPosition();
}
}
return rightmost_leaf;
}
// Creates a position using the next text-only node as its anchor.
// Assumes that text-only nodes are leaf nodes.
AXPositionInstance CreateNextTextAnchorPosition(
std::function<AbortMovePredicate> abort_predicate) const {
// If this is an ancestor text position, resolve to its leaf text position.
if (IsTextPosition() && !IsLeaf())
return AsLeafTextPosition();
AXPositionInstance next_leaf = CreateNextAnchorPosition(abort_predicate);
while (!next_leaf->IsNullPosition() && !next_leaf->IsLeaf())
next_leaf = next_leaf->CreateNextAnchorPosition(abort_predicate);
BASE_DCHECK(next_leaf);
return next_leaf->AsLeafTextPosition();
}
// Creates a position using the previous text-only node as its anchor.
// Assumes that text-only nodes are leaf nodes.
AXPositionInstance CreatePreviousTextAnchorPosition(
std::function<AbortMovePredicate> abort_predicate) const {
// If this is an ancestor text position, resolve to its leaf text position.
if (IsTextPosition() && !IsLeaf())
return AsLeafTextPosition();
AXPositionInstance previous_leaf =
CreatePreviousAnchorPosition(abort_predicate);
while (!previous_leaf->IsNullPosition() && !previous_leaf->IsLeaf()) {
previous_leaf =
previous_leaf->CreatePreviousAnchorPosition(abort_predicate);
}
BASE_DCHECK(previous_leaf);
return previous_leaf->AsLeafTextPosition();
}
// Creates a tree position using the next text-only node as its anchor.
// Assumes that text-only nodes are leaf nodes.
AXPositionInstance CreateNextLeafTreePosition(
std::function<AbortMovePredicate> abort_predicate) const {
AXPositionInstance next_leaf =
AsTreePosition()->CreateNextAnchorPosition(abort_predicate);
while (!next_leaf->IsNullPosition() && !next_leaf->IsLeaf())
next_leaf = next_leaf->CreateNextAnchorPosition(abort_predicate);
BASE_DCHECK(next_leaf);
return next_leaf;
}
// Creates a tree position using the previous text-only node as its anchor.
// Assumes that text-only nodes are leaf nodes.
AXPositionInstance CreatePreviousLeafTreePosition(
std::function<AbortMovePredicate> abort_predicate) const {
AXPositionInstance previous_leaf =
AsTreePosition()->CreatePreviousAnchorPosition(abort_predicate);
while (!previous_leaf->IsNullPosition() && !previous_leaf->IsLeaf()) {
previous_leaf =
previous_leaf->CreatePreviousAnchorPosition(abort_predicate);
}
BASE_DCHECK(previous_leaf);
return previous_leaf;
}
//
// Static helpers for lambda usage.
//
static bool AtStartOfPagePredicate(const AXPositionInstance& position) {
// If a page boundary is ignored, then it should not be exposed to assistive
// software.
return !position->IsIgnored() && position->AtStartOfPage();
}
static bool AtEndOfPagePredicate(const AXPositionInstance& position) {
// If a page boundary is ignored, then it should not be exposed to assistive
// software.
return !position->IsIgnored() && position->AtEndOfPage();
}
static bool AtStartOfParagraphPredicate(const AXPositionInstance& position) {
// The "AtStartOfParagraph" method already excludes ignored nodes.
return position->AtStartOfParagraph();
}
static bool AtEndOfParagraphPredicate(const AXPositionInstance& position) {
// The "AtEndOfParagraph" method already excludes ignored nodes.
return position->AtEndOfParagraph();
}
static bool AtStartOfLinePredicate(const AXPositionInstance& position) {
// Sometimes, nodes that are used to signify line boundaries are ignored.
return position->AtStartOfLine();
}
static bool AtEndOfLinePredicate(const AXPositionInstance& position) {
// Sometimes, nodes that are used to signify line boundaries are ignored.
return position->AtEndOfLine();
}
static bool AtStartOfWordPredicate(const AXPositionInstance& position) {
// Word boundaries should be at specific text offsets that are "visible" to
// assistive software, hence not ignored. Ignored nodes are often used for
// additional layout information, such as line and paragraph boundaries.
// Their text is not currently processed.
return !position->IsIgnored() && position->AtStartOfWord();
}
static bool AtEndOfWordPredicate(const AXPositionInstance& position) {
// Word boundaries should be at specific text offsets that are "visible" to
// assistive software, hence not ignored. Ignored nodes are often used for
// additional layout information, such as line and paragraph boundaries.
// Their text is not currently processed.
return !position->IsIgnored() && position->AtEndOfWord();
}
static bool DefaultAbortMovePredicate(const AXPosition& move_from,
const AXPosition& move_to,
const AXMoveType move_type,
const AXMoveDirection direction) {
// Default behavior is to never abort.
return false;
}
// AbortMovePredicate function used to detect format boundaries.
static bool AbortMoveAtFormatBoundary(const AXPosition& move_from,
const AXPosition& move_to,
const AXMoveType move_type,
const AXMoveDirection direction) {
if (move_from.IsNullPosition() || move_to.IsNullPosition() ||
move_from.IsEmptyObjectReplacedByCharacter() ||
move_to.IsEmptyObjectReplacedByCharacter()) {
return true;
}
// Treat moving into or out of nodes with certain roles as a format break.
ax::mojom::Role from_role = move_from.GetAnchorRole();
ax::mojom::Role to_role = move_to.GetAnchorRole();
if (from_role != to_role) {
if (IsFormatBoundary(from_role) || IsFormatBoundary(to_role))
return true;
}
// Stop moving when text styles differ.
return move_from.AsLeafTreePosition()->GetTextStyles() !=
move_to.AsLeafTreePosition()->GetTextStyles();
}
static bool MoveCrossesLineBreakingObject(const AXPosition& move_from,
const AXPosition& move_to,
const AXMoveType move_type,
const AXMoveDirection direction) {
const bool move_from_break = move_from.IsInLineBreakingObject();
const bool move_to_break = move_to.IsInLineBreakingObject();
switch (move_type) {
case AXMoveType::kAncestor:
// For Ancestor moves, only abort when exiting a block descendant.
// We don't care if the ancestor is a block or not, since the
// descendant is contained by it.
return move_from_break;
case AXMoveType::kDescendant:
// For Descendant moves, only abort when entering a block descendant.
// We don't care if the ancestor is a block or not, since the
// descendant is contained by it.
return move_to_break;
case AXMoveType::kSibling:
// For Sibling moves, abort if at least one of the siblings are a block,
// because that would mean exiting and/or entering a block.
return move_from_break || move_to_break;
}
BASE_UNREACHABLE();
return false;
}
// AbortMovePredicate function used to detect paragraph boundaries.
// We don't want to abort immediately after crossing a line breaking object
// boundary if the anchor we're moving to is not a leaf, this is necessary to
// avoid aborting if the next leaf position is whitespace-only; update
// |crossed_line_breaking_object_token| and wait until a leaf anchor is
// reached in order to correctly determine paragraph boundaries.
static bool AbortMoveAtParagraphBoundary(
bool& crossed_line_breaking_object_token,
const AXPosition& move_from,
const AXPosition& move_to,
const AXMoveType move_type,
const AXMoveDirection direction) {
if (move_from.IsNullPosition() || move_to.IsNullPosition() ||
move_from.IsEmptyObjectReplacedByCharacter() ||
move_to.IsEmptyObjectReplacedByCharacter()) {
return true;
}
if (!crossed_line_breaking_object_token) {
crossed_line_breaking_object_token = MoveCrossesLineBreakingObject(
move_from, move_to, move_type, direction);
}
if (crossed_line_breaking_object_token && move_to.IsLeaf()) {
// If there's a sequence of whitespace-only anchors, collapse so only the
// last whitespace-only anchor is considered a paragraph boundary.
return direction != AXMoveDirection::kNextInTree ||
!move_to.IsInWhiteSpace();
}
return false;
}
// This AbortMovePredicate never aborts, but detects whether a sequence of
// consecutive moves cross any line breaking object boundary.
static bool UpdateCrossedLineBreakingObjectToken(
bool& crossed_line_breaking_object_token,
const AXPosition& move_from,
const AXPosition& move_to,
const AXMoveType move_type,
const AXMoveDirection direction) {
if (!crossed_line_breaking_object_token) {
crossed_line_breaking_object_token = MoveCrossesLineBreakingObject(
move_from, move_to, move_type, direction);
}
return false;
}
// AbortMovePredicate function used to detect page boundaries.
static bool AbortMoveAtPageBoundary(const AXPosition& move_from,
const AXPosition& move_to,
const AXMoveType move_type,
const AXMoveDirection direction) {
if (move_from.IsNullPosition() || move_to.IsNullPosition())
return true;
const bool move_from_break = move_from.GetAnchor()->GetBoolAttribute(
ax::mojom::BoolAttribute::kIsPageBreakingObject);
const bool move_to_break = move_to.GetAnchor()->GetBoolAttribute(
ax::mojom::BoolAttribute::kIsPageBreakingObject);
switch (move_type) {
case AXMoveType::kAncestor:
// For Ancestor moves, only abort when exiting a page break.
// We don't care if the ancestor is a page break or not, since the
// descendant is contained by it.
return move_from_break;
case AXMoveType::kDescendant:
// For Descendant moves, only abort when entering a page break
// descendant. We don't care if the ancestor is a page break or not,
// since the descendant is contained by it.
return move_to_break;
case AXMoveType::kSibling:
// For Sibling moves, abort if at both of the siblings are a page
// break, because that would mean exiting and/or entering a page break.
return move_from_break && move_to_break;
}
BASE_UNREACHABLE();
return false;
}
static bool AbortMoveAtStartOfInlineBlock(const AXPosition& move_from,
const AXPosition& move_to,
const AXMoveType move_type,
const AXMoveDirection direction) {
if (move_from.IsNullPosition() || move_to.IsNullPosition())
return true;
// These will only be available if AXMode has kHTML set.
const bool move_from_is_inline_block =
move_from.GetAnchor()->GetStringAttribute(
ax::mojom::StringAttribute::kDisplay) == "inline-block";
const bool move_to_is_inline_block =
move_to.GetAnchor()->GetStringAttribute(
ax::mojom::StringAttribute::kDisplay) == "inline-block";
switch (direction) {
case AXMoveDirection::kNextInTree:
// When moving forward, break if we enter an inline block.
return move_to_is_inline_block &&
(move_type == AXMoveType::kDescendant ||
move_type == AXMoveType::kSibling);
case AXMoveDirection::kPreviousInTree:
// When moving backward, break if we exit an inline block.
return move_from_is_inline_block &&
(move_type == AXMoveType::kAncestor ||
move_type == AXMoveType::kSibling);
}
BASE_UNREACHABLE();
return false;
}
static AXPositionAdjustmentBehavior AdjustmentBehaviorFromBoundaryDirection(
ax::mojom::MoveDirection move_direction) {
switch (move_direction) {
case ax::mojom::MoveDirection::kForward:
return AXPositionAdjustmentBehavior::kMoveForward;
case ax::mojom::MoveDirection::kBackward:
return AXPositionAdjustmentBehavior::kMoveBackward;
}
}
static AXPositionAdjustmentBehavior OppositeAdjustmentBehavior(
AXPositionAdjustmentBehavior adjustment_behavior) {
switch (adjustment_behavior) {
case AXPositionAdjustmentBehavior::kMoveForward:
return AXPositionAdjustmentBehavior::kMoveBackward;
case AXPositionAdjustmentBehavior::kMoveBackward:
return AXPositionAdjustmentBehavior::kMoveForward;
}
}
static std::vector<int32_t> GetWordStartOffsetsFunc(
const AXPositionInstance& position) {
return position->GetWordStartOffsets();
}
static std::vector<int32_t> GetWordEndOffsetsFunc(
const AXPositionInstance& position) {
return position->GetWordEndOffsets();
}
AXPositionInstance CreateDocumentAncestorPosition() const {
AXPositionInstance iterator = Clone();
while (!iterator->IsNullPosition()) {
if (IsDocument(iterator->GetAnchorRole()) &&
iterator->CreateParentPosition()->IsNullPosition()) {
break;
}
iterator = iterator->CreateParentPosition();
}
return iterator;
}
// Creates a text position that is in the same anchor as the current
// position, but starting from the current text offset, adjusts to the next
// or the previous boundary offset depending on the boundary direction. If
// there is no next / previous offset, the current text offset is unchanged.
AXPositionInstance CreatePositionAtNextOffsetBoundary(
ax::mojom::MoveDirection move_direction,
BoundaryTextOffsetsFunc get_offsets) const {
if (IsNullPosition() || !get_offsets)
return Clone();
AXPositionInstance text_position = AsTextPosition();
const std::vector<int32_t> boundary_offsets = get_offsets(text_position);
if (boundary_offsets.empty())
return text_position;
switch (move_direction) {
case ax::mojom::MoveDirection::kForward: {
const auto offsets_iterator =
std::upper_bound(boundary_offsets.begin(), boundary_offsets.end(),
int32_t{text_position->text_offset_});
// If there is no next offset, the current offset should be unchanged.
if (offsets_iterator < boundary_offsets.end()) {
text_position->text_offset_ = static_cast<int>(*offsets_iterator);
text_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
}
break;
}
case ax::mojom::MoveDirection::kBackward: {
auto offsets_iterator =
std::lower_bound(boundary_offsets.begin(), boundary_offsets.end(),
int32_t{text_position->text_offset_});
// If there is no previous offset, the current offset should be
// unchanged.
if (offsets_iterator > boundary_offsets.begin()) {
// Since we already checked if "boundary_offsets" are non-empty, we
// can safely move the iterator one position back, even if it's
// currently at the vector's end.
--offsets_iterator;
text_position->text_offset_ = static_cast<int>(*offsets_iterator);
text_position->affinity_ = ax::mojom::TextAffinity::kDownstream;
}
break;
}
}
return text_position;
}
// Creates a text position that is in the same anchor as the current
// position, but adjusts its text offset to be either at the first or last
// offset boundary, based on the boundary direction. When moving forward,
// the text position is adjusted to point to the first offset boundary, or
// to the end of its anchor if there are no offset boundaries. When moving
// backward, it is adjusted to point to the last offset boundary, or to the
// start of its anchor if there are no offset boundaries.
AXPositionInstance CreatePositionAtFirstOffsetBoundary(
ax::mojom::MoveDirection move_direction,
BoundaryTextOffsetsFunc get_offsets) const {
if (IsNullPosition() || !get_offsets)
return Clone();
AXPositionInstance text_position = AsTextPosition();
const std::vector<int32_t> boundary_offsets = get_offsets(text_position);
switch (move_direction) {
case ax::mojom::MoveDirection::kForward:
if (boundary_offsets.empty()) {
return text_position->CreatePositionAtEndOfAnchor();
} else {
text_position->text_offset_ = static_cast<int>(boundary_offsets[0]);
return text_position;
}
break;
case ax::mojom::MoveDirection::kBackward:
if (boundary_offsets.empty()) {
return text_position->CreatePositionAtStartOfAnchor();
} else {
text_position->text_offset_ =
static_cast<int>(boundary_offsets[boundary_offsets.size() - 1]);
return text_position;
}
break;
}
}
// Returns the next leaf text position in the specified direction ensuring
// that *AsLeafTextPosition() != *CreateAdjacentLeafTextPosition() is true;
// returns a null position if no adjacent position exists.
//
// This method is the first step for CreateBoundary[Start|End]Position to
// guarantee that the resulting position when using a boundary behavior other
// than StopIfAlreadyAtBoundary is not equivalent to the initial position.
//
// Note that using CompareTo with text positions does not take into account
// position affinity or tree pre-order, two text positions are considered
// equivalent if their offsets in the text representation of the entire AXTree
// are the same. As such, using Create[Next|Previous]LeafTextPosition is not
// enough to create adjacent positions, e.g. the end of an anchor and the
// start of the next one are equivalent; furthermore, there could be nodes
// with no text representation between them, all of them being equivalent too.
//
// IMPORTANT: This method basically moves the given position one character
// forward/backward, but it could end up at the middle of a grapheme cluster,
// so it shouldn't be used to move by ax::mojom::TextBoundary::kCharacter (for
// such purpose use Create[Next|Previous]CharacterPosition instead).
AXPositionInstance CreateAdjacentLeafTextPosition(
ax::mojom::MoveDirection move_direction) const {
AXPositionInstance text_position = AsLeafTextPosition();
switch (move_direction) {
case ax::mojom::MoveDirection::kForward:
// If we are at a text offset less than MaxTextOffset, we will simply
// increase the offset by one; otherwise, create a position at the start
// of the next leaf node with non-empty text and increase its offset.
//
// Note that a position located at offset 0 of an empty text node is
// considered both, at the start and at the end of its anchor, so the
// following loop skips over empty text leaf nodes, which is expected
// since those positions are equivalent to both, the previous non-empty
// leaf node's end and the next non-empty leaf node's start.
while (text_position->AtEndOfAnchor()) {
text_position = text_position->CreateNextLeafTextPosition();
}
if (!text_position->IsNullPosition())
++text_position->text_offset_;
break;
case ax::mojom::MoveDirection::kBackward:
// If we are at a text offset greater than 0, we will simply decrease
// the offset by one; otherwise, create a position at the end of the
// previous leaf node with non-empty text and decrease its offset.
//
// Same as the comment above, using AtStartOfAnchor is enough to skip
// empty text nodes that are equivalent to the initial position.
while (text_position->AtStartOfAnchor()) {
text_position = text_position->CreatePreviousLeafTextPosition()
->CreatePositionAtEndOfAnchor();
}
if (!text_position->IsNullPosition())
--text_position->text_offset_;
break;
}
BASE_DCHECK(text_position->IsValid());
return text_position;
}
AXPositionKind kind_;
AXTreeID tree_id_;
AXNode::AXID anchor_id_;
// For text positions, |child_index_| is initially set to |-1| and only
// computed on demand. The same with tree positions and |text_offset_|.
int child_index_;
// "text_offset_" represents the number of UTF16 code units before this
// position. It doesn't count grapheme clusters.
int text_offset_;
// Affinity is used to distinguish between two text positions that point to
// the same text offset, but which happens to fall on a soft line break. A
// soft line break doesn't insert any white space in the accessibility tree,
// so without affinity there would be no way to determine whether a text
// position is before or after the soft line break. An upstream affinity
// means that the position is before the soft line break, whilst a
// downstream affinity means that the position is after the soft line break.
//
// Please note that affinity could only be set to upstream for positions
// that are anchored to non-leaf nodes. When on a leaf node, there could
// never be an ambiguity as to which line a position points to because Blink
// creates separate inline text boxes for each line of text. Therefore, a
// leaf text position before the soft line break would be pointing to the
// end of its anchor node, whilst a leaf text position after the soft line
// break would be pointing to the start of the next node.
ax::mojom::TextAffinity affinity_;
};
template <class AXPositionType, class AXNodeType>
const int AXPosition<AXPositionType, AXNodeType>::BEFORE_TEXT;
template <class AXPositionType, class AXNodeType>
const int AXPosition<AXPositionType, AXNodeType>::INVALID_INDEX;
template <class AXPositionType, class AXNodeType>
const int AXPosition<AXPositionType, AXNodeType>::INVALID_OFFSET;
template <class AXPositionType, class AXNodeType>
bool operator==(const AXPosition<AXPositionType, AXNodeType>& first,
const AXPosition<AXPositionType, AXNodeType>& second) {
const std::optional<int> compare_to_optional = first.CompareTo(second);
return compare_to_optional.has_value() && compare_to_optional.value() == 0;
}
template <class AXPositionType, class AXNodeType>
bool operator!=(const AXPosition<AXPositionType, AXNodeType>& first,
const AXPosition<AXPositionType, AXNodeType>& second) {
const std::optional<int> compare_to_optional = first.CompareTo(second);
return compare_to_optional.has_value() && compare_to_optional.value() != 0;
}
template <class AXPositionType, class AXNodeType>
bool operator<(const AXPosition<AXPositionType, AXNodeType>& first,
const AXPosition<AXPositionType, AXNodeType>& second) {
const std::optional<int> compare_to_optional = first.CompareTo(second);
return compare_to_optional.has_value() && compare_to_optional.value() < 0;
}
template <class AXPositionType, class AXNodeType>
bool operator<=(const AXPosition<AXPositionType, AXNodeType>& first,
const AXPosition<AXPositionType, AXNodeType>& second) {
const std::optional<int> compare_to_optional = first.CompareTo(second);
return compare_to_optional.has_value() && compare_to_optional.value() <= 0;
}
template <class AXPositionType, class AXNodeType>
bool operator>(const AXPosition<AXPositionType, AXNodeType>& first,
const AXPosition<AXPositionType, AXNodeType>& second) {
const std::optional<int> compare_to_optional = first.CompareTo(second);
return compare_to_optional.has_value() && compare_to_optional.value() > 0;
}
template <class AXPositionType, class AXNodeType>
bool operator>=(const AXPosition<AXPositionType, AXNodeType>& first,
const AXPosition<AXPositionType, AXNodeType>& second) {
const std::optional<int> compare_to_optional = first.CompareTo(second);
return compare_to_optional.has_value() && compare_to_optional.value() >= 0;
}
template <class AXPositionType, class AXNodeType>
void swap(AXPosition<AXPositionType, AXNodeType>& first,
AXPosition<AXPositionType, AXNodeType>& second) {
first.swap(second);
}
template <class AXPositionType, class AXNodeType>
std::ostream& operator<<(
std::ostream& stream,
const AXPosition<AXPositionType, AXNodeType>& position) {
return stream << position.ToString();
}
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_POSITION_H_
| engine/third_party/accessibility/ax/ax_position.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_position.h",
"repo_id": "engine",
"token_count": 62521
} | 444 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_TREE_ID_H_
#define UI_ACCESSIBILITY_AX_TREE_ID_H_
#include <string>
#include "ax_base_export.h"
#include "ax_enums.h"
#include "base/no_destructor.h"
#include "base/simple_token.h"
namespace ui {
// A unique ID representing an accessibility tree.
class AX_BASE_EXPORT AXTreeID {
public:
// Create an Unknown AXTreeID.
AXTreeID();
// Copy constructor.
AXTreeID(const AXTreeID& other);
// Create a new unique AXTreeID.
static AXTreeID CreateNewAXTreeID();
// Unserialize an AXTreeID from a string. This is used so that tree IDs
// can be stored compactly as a string attribute in an AXNodeData, and
// so that AXTreeIDs can be passed to JavaScript bindings in the
// automation API.
static AXTreeID FromString(const std::string& string);
// Convenience method to unserialize an AXTreeID from an SimpleToken.
static AXTreeID FromToken(const base::SimpleToken& token);
AXTreeID& operator=(const AXTreeID& other);
std::string ToString() const;
ax::mojom::AXTreeIDType type() const { return type_; }
const std::optional<base::SimpleToken>& token() const { return token_; }
bool operator==(const AXTreeID& rhs) const;
bool operator!=(const AXTreeID& rhs) const;
bool operator<(const AXTreeID& rhs) const;
bool operator<=(const AXTreeID& rhs) const;
bool operator>(const AXTreeID& rhs) const;
bool operator>=(const AXTreeID& rhs) const;
private:
explicit AXTreeID(ax::mojom::AXTreeIDType type);
explicit AXTreeID(const std::string& string);
friend class base::NoDestructor<AXTreeID>;
friend void swap(AXTreeID& first, AXTreeID& second);
ax::mojom::AXTreeIDType type_;
std::optional<base::SimpleToken> token_ = std::nullopt;
};
// For use in std::unordered_map.
struct AX_BASE_EXPORT AXTreeIDHash {
size_t operator()(const ui::AXTreeID& tree_id) const;
};
AX_BASE_EXPORT std::ostream& operator<<(std::ostream& stream,
const AXTreeID& value);
// The value to use when an AXTreeID is unknown.
AX_BASE_EXPORT extern const AXTreeID& AXTreeIDUnknown();
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_TREE_ID_H_
| engine/third_party/accessibility/ax/ax_tree_id.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_tree_id.h",
"repo_id": "engine",
"token_count": 836
} | 445 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax_platform_node_base.h"
#include <algorithm>
#include <iomanip>
#include <limits>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "ax/ax_action_data.h"
#include "ax/ax_enums.h"
#include "ax/ax_node_data.h"
#include "ax/ax_role_properties.h"
#include "ax/ax_tree_data.h"
#include "ax_platform_node_delegate.h"
#include "base/color_utils.h"
#include "base/string_utils.h"
#include "compute_attributes.h"
#include "gfx/geometry/rect_conversions.h"
namespace ui {
namespace {
// Check for descendant comment, using limited depth first search.
bool FindDescendantRoleWithMaxDepth(AXPlatformNodeBase* node,
ax::mojom::Role descendant_role,
int max_depth,
int max_children_to_check) {
if (node->GetData().role == descendant_role)
return true;
if (max_depth <= 1)
return false;
int num_children_to_check =
std::min(node->GetChildCount(), max_children_to_check);
for (int index = 0; index < num_children_to_check; index++) {
auto* child = static_cast<AXPlatformNodeBase*>(
AXPlatformNode::FromNativeViewAccessible(node->ChildAtIndex(index)));
if (child &&
FindDescendantRoleWithMaxDepth(child, descendant_role, max_depth - 1,
max_children_to_check)) {
return true;
}
}
return false;
}
} // namespace
const char16_t AXPlatformNodeBase::kEmbeddedCharacter = L'\xfffc';
// Map from each AXPlatformNode's unique id to its instance.
using UniqueIdMap = std::unordered_map<int32_t, AXPlatformNode*>;
UniqueIdMap g_unique_id_map;
// static
AXPlatformNode* AXPlatformNodeBase::GetFromUniqueId(int32_t unique_id) {
auto iter = g_unique_id_map.find(unique_id);
if (iter != g_unique_id_map.end())
return iter->second;
return nullptr;
}
// static
size_t AXPlatformNodeBase::GetInstanceCountForTesting() {
return g_unique_id_map.size();
}
AXPlatformNodeBase::AXPlatformNodeBase() = default;
AXPlatformNodeBase::~AXPlatformNodeBase() = default;
void AXPlatformNodeBase::Init(AXPlatformNodeDelegate* delegate) {
delegate_ = delegate;
// This must be called after assigning our delegate.
g_unique_id_map[GetUniqueId()] = this;
}
const AXNodeData& AXPlatformNodeBase::GetData() const {
static const base::NoDestructor<AXNodeData> empty_data;
if (delegate_)
return delegate_->GetData();
return *empty_data;
}
gfx::NativeViewAccessible AXPlatformNodeBase::GetFocus() {
if (delegate_)
return delegate_->GetFocus();
return nullptr;
}
gfx::NativeViewAccessible AXPlatformNodeBase::GetParent() const {
if (delegate_)
return delegate_->GetParent();
return nullptr;
}
int AXPlatformNodeBase::GetChildCount() const {
if (delegate_)
return delegate_->GetChildCount();
return 0;
}
gfx::NativeViewAccessible AXPlatformNodeBase::ChildAtIndex(int index) const {
if (delegate_)
return delegate_->ChildAtIndex(index);
return nullptr;
}
std::string AXPlatformNodeBase::GetName() const {
if (delegate_)
return delegate_->GetName();
return std::string();
}
std::u16string AXPlatformNodeBase::GetNameAsString16() const {
std::string name = GetName();
if (name.empty())
return std::u16string();
return base::UTF8ToUTF16(name);
}
std::optional<int> AXPlatformNodeBase::GetIndexInParent() {
AXPlatformNodeBase* parent = FromNativeViewAccessible(GetParent());
if (!parent)
return std::nullopt;
int child_count = parent->GetChildCount();
if (child_count == 0) {
// |child_count| could be 0 if the parent is IsLeaf.
BASE_DCHECK(parent->IsLeaf());
return std::nullopt;
}
// Ask the delegate for the index in parent, and return it if it's plausible.
//
// Delegates are allowed to not implement this (ViewsAXPlatformNodeDelegate
// returns -1). Also, delegates may not know the correct answer if this
// node is the root of a tree that's embedded in another tree, in which
// case the delegate should return -1 and we'll compute it.
int index = delegate_ ? delegate_->GetIndexInParent() : -1;
if (index >= 0 && index < child_count)
return index;
// Otherwise, search the parent's children.
gfx::NativeViewAccessible current = GetNativeViewAccessible();
for (int i = 0; i < child_count; i++) {
if (parent->ChildAtIndex(i) == current)
return i;
}
// If the parent has a modal dialog, it doesn't count other children.
if (parent->delegate_ && parent->delegate_->HasModalDialog())
return std::nullopt;
BASE_LOG()
<< "Unable to find the child in the list of its parent's children.";
BASE_UNREACHABLE();
return std::nullopt;
}
std::stack<gfx::NativeViewAccessible> AXPlatformNodeBase::GetAncestors() {
std::stack<gfx::NativeViewAccessible> ancestors;
gfx::NativeViewAccessible current_node = GetNativeViewAccessible();
while (current_node) {
ancestors.push(current_node);
current_node = FromNativeViewAccessible(current_node)->GetParent();
}
return ancestors;
}
std::optional<int> AXPlatformNodeBase::CompareTo(AXPlatformNodeBase& other) {
// We define two node's relative positions in the following way:
// 1. this->CompareTo(other) == 0:
// - |this| and |other| are the same node.
// 2. this->CompareTo(other) < 0:
// - |this| is an ancestor of |other|.
// - |this|'s first uncommon ancestor comes before |other|'s first uncommon
// ancestor. The first uncommon ancestor is defined as the immediate child
// of the lowest common anestor of the two nodes. The first uncommon
// ancestor of |this| and |other| share the same parent (i.e. lowest common
// ancestor), so we can just compare the first uncommon ancestors' child
// indices to determine their relative positions.
// 3. this->CompareTo(other) == nullopt:
// - |this| and |other| are not comparable. E.g. they do not have a common
// ancestor.
//
// Another way to look at the nodes' relative positions/logical orders is that
// they are equivalent to pre-order traversal of the tree. If we pre-order
// traverse from the root, the node that we visited earlier is always going to
// be before (logically less) the node we visit later.
if (this == &other)
return std::optional<int>(0);
// Compute the ancestor stacks of both positions and traverse them from the
// top most ancestor down, so we can discover the first uncommon ancestors.
// The first uncommon ancestor is the immediate child of the lowest common
// ancestor.
gfx::NativeViewAccessible common_ancestor = nullptr;
std::stack<gfx::NativeViewAccessible> our_ancestors = GetAncestors();
std::stack<gfx::NativeViewAccessible> other_ancestors = other.GetAncestors();
// Start at the root and traverse down. Keep going until the |this|'s ancestor
// chain and |other|'s ancestor chain disagree. The last node before they
// disagree is the lowest common ancestor.
while (!our_ancestors.empty() && !other_ancestors.empty() &&
our_ancestors.top() == other_ancestors.top()) {
common_ancestor = our_ancestors.top();
our_ancestors.pop();
other_ancestors.pop();
}
// Nodes do not have a common ancestor, they are not comparable.
if (!common_ancestor)
return std::nullopt;
// Compute the logical order when the common ancestor is |this| or |other|.
auto* common_ancestor_platform_node =
FromNativeViewAccessible(common_ancestor);
if (common_ancestor_platform_node == this)
return std::optional<int>(-1);
if (common_ancestor_platform_node == &other)
return std::optional<int>(1);
// Compute the logical order of |this| and |other| by using their first
// uncommon ancestors.
if (!our_ancestors.empty() && !other_ancestors.empty()) {
std::optional<int> this_index_in_parent =
FromNativeViewAccessible(our_ancestors.top())->GetIndexInParent();
std::optional<int> other_index_in_parent =
FromNativeViewAccessible(other_ancestors.top())->GetIndexInParent();
if (!this_index_in_parent || !other_index_in_parent)
return std::nullopt;
int this_uncommon_ancestor_index = this_index_in_parent.value();
int other_uncommon_ancestor_index = other_index_in_parent.value();
if (this_uncommon_ancestor_index == other_uncommon_ancestor_index) {
BASE_LOG()
<< "Deepest uncommon ancestors should truly be uncommon, i.e. not "
"the same.";
BASE_UNREACHABLE();
}
return std::optional<int>(this_uncommon_ancestor_index -
other_uncommon_ancestor_index);
}
return std::nullopt;
}
// AXPlatformNode overrides.
void AXPlatformNodeBase::Destroy() {
g_unique_id_map.erase(GetUniqueId());
AXPlatformNode::Destroy();
delegate_ = nullptr;
Dispose();
}
void AXPlatformNodeBase::Dispose() {
delete this;
}
gfx::NativeViewAccessible AXPlatformNodeBase::GetNativeViewAccessible() {
return nullptr;
}
void AXPlatformNodeBase::NotifyAccessibilityEvent(ax::mojom::Event event_type) {
}
#if defined(OS_APPLE)
void AXPlatformNodeBase::AnnounceText(const std::u16string& text) {}
#endif
AXPlatformNodeDelegate* AXPlatformNodeBase::GetDelegate() const {
return delegate_;
}
bool AXPlatformNodeBase::IsDescendantOf(AXPlatformNode* ancestor) const {
if (!ancestor)
return false;
if (this == ancestor)
return true;
AXPlatformNodeBase* parent = FromNativeViewAccessible(GetParent());
if (!parent)
return false;
return parent->IsDescendantOf(ancestor);
}
AXPlatformNodeBase::AXPlatformNodeChildIterator
AXPlatformNodeBase::AXPlatformNodeChildrenBegin() const {
return AXPlatformNodeChildIterator(this, GetFirstChild());
}
AXPlatformNodeBase::AXPlatformNodeChildIterator
AXPlatformNodeBase::AXPlatformNodeChildrenEnd() const {
return AXPlatformNodeChildIterator(this, nullptr);
}
// Helpers.
AXPlatformNodeBase* AXPlatformNodeBase::GetPreviousSibling() const {
if (!delegate_)
return nullptr;
return FromNativeViewAccessible(delegate_->GetPreviousSibling());
}
AXPlatformNodeBase* AXPlatformNodeBase::GetNextSibling() const {
if (!delegate_)
return nullptr;
return FromNativeViewAccessible(delegate_->GetNextSibling());
}
AXPlatformNodeBase* AXPlatformNodeBase::GetFirstChild() const {
if (!delegate_)
return nullptr;
return FromNativeViewAccessible(delegate_->GetFirstChild());
}
AXPlatformNodeBase* AXPlatformNodeBase::GetLastChild() const {
if (!delegate_)
return nullptr;
return FromNativeViewAccessible(delegate_->GetLastChild());
}
bool AXPlatformNodeBase::IsDescendant(AXPlatformNodeBase* node) {
if (!delegate_)
return false;
if (!node)
return false;
if (node == this)
return true;
gfx::NativeViewAccessible native_parent = node->GetParent();
if (!native_parent)
return false;
AXPlatformNodeBase* parent = FromNativeViewAccessible(native_parent);
return IsDescendant(parent);
}
bool AXPlatformNodeBase::HasBoolAttribute(
ax::mojom::BoolAttribute attribute) const {
if (!delegate_)
return false;
return GetData().HasBoolAttribute(attribute);
}
bool AXPlatformNodeBase::GetBoolAttribute(
ax::mojom::BoolAttribute attribute) const {
if (!delegate_)
return false;
return GetData().GetBoolAttribute(attribute);
}
bool AXPlatformNodeBase::GetBoolAttribute(ax::mojom::BoolAttribute attribute,
bool* value) const {
if (!delegate_)
return false;
return GetData().GetBoolAttribute(attribute, value);
}
bool AXPlatformNodeBase::HasFloatAttribute(
ax::mojom::FloatAttribute attribute) const {
if (!delegate_)
return false;
return GetData().HasFloatAttribute(attribute);
}
float AXPlatformNodeBase::GetFloatAttribute(
ax::mojom::FloatAttribute attribute) const {
if (!delegate_)
return false;
return GetData().GetFloatAttribute(attribute);
}
bool AXPlatformNodeBase::GetFloatAttribute(ax::mojom::FloatAttribute attribute,
float* value) const {
if (!delegate_)
return false;
return GetData().GetFloatAttribute(attribute, value);
}
bool AXPlatformNodeBase::HasIntAttribute(
ax::mojom::IntAttribute attribute) const {
if (!delegate_)
return false;
return GetData().HasIntAttribute(attribute);
}
int AXPlatformNodeBase::GetIntAttribute(
ax::mojom::IntAttribute attribute) const {
if (!delegate_)
return 0;
return GetData().GetIntAttribute(attribute);
}
bool AXPlatformNodeBase::GetIntAttribute(ax::mojom::IntAttribute attribute,
int* value) const {
if (!delegate_)
return false;
return GetData().GetIntAttribute(attribute, value);
}
bool AXPlatformNodeBase::HasStringAttribute(
ax::mojom::StringAttribute attribute) const {
if (!delegate_)
return false;
return GetData().HasStringAttribute(attribute);
}
const std::string& AXPlatformNodeBase::GetStringAttribute(
ax::mojom::StringAttribute attribute) const {
if (!delegate_)
return base::EmptyString();
return GetData().GetStringAttribute(attribute);
}
bool AXPlatformNodeBase::GetStringAttribute(
ax::mojom::StringAttribute attribute,
std::string* value) const {
if (!delegate_)
return false;
return GetData().GetStringAttribute(attribute, value);
}
std::u16string AXPlatformNodeBase::GetString16Attribute(
ax::mojom::StringAttribute attribute) const {
if (!delegate_)
return std::u16string();
return GetData().GetString16Attribute(attribute);
}
bool AXPlatformNodeBase::GetString16Attribute(
ax::mojom::StringAttribute attribute,
std::u16string* value) const {
if (!delegate_)
return false;
return GetData().GetString16Attribute(attribute, value);
}
bool AXPlatformNodeBase::HasInheritedStringAttribute(
ax::mojom::StringAttribute attribute) const {
const AXPlatformNodeBase* current_node = this;
do {
if (!current_node->delegate_) {
return false;
}
if (current_node->GetData().HasStringAttribute(attribute)) {
return true;
}
current_node = FromNativeViewAccessible(current_node->GetParent());
} while (current_node);
return false;
}
const std::string& AXPlatformNodeBase::GetInheritedStringAttribute(
ax::mojom::StringAttribute attribute) const {
const AXPlatformNodeBase* current_node = this;
do {
if (!current_node->delegate_)
return base::EmptyString();
if (current_node->GetData().HasStringAttribute(attribute)) {
return current_node->GetData().GetStringAttribute(attribute);
}
current_node = FromNativeViewAccessible(current_node->GetParent());
} while (current_node);
return base::EmptyString();
}
std::u16string AXPlatformNodeBase::GetInheritedString16Attribute(
ax::mojom::StringAttribute attribute) const {
return base::UTF8ToUTF16(GetInheritedStringAttribute(attribute));
}
bool AXPlatformNodeBase::GetInheritedStringAttribute(
ax::mojom::StringAttribute attribute,
std::string* value) const {
const AXPlatformNodeBase* current_node = this;
do {
if (!current_node->delegate_) {
return false;
}
if (current_node->GetData().GetStringAttribute(attribute, value)) {
return true;
}
current_node = FromNativeViewAccessible(current_node->GetParent());
} while (current_node);
return false;
}
bool AXPlatformNodeBase::GetInheritedString16Attribute(
ax::mojom::StringAttribute attribute,
std::u16string* value) const {
std::string value_utf8;
if (!GetInheritedStringAttribute(attribute, &value_utf8))
return false;
*value = base::UTF8ToUTF16(value_utf8);
return true;
}
bool AXPlatformNodeBase::HasIntListAttribute(
ax::mojom::IntListAttribute attribute) const {
if (!delegate_)
return false;
return GetData().HasIntListAttribute(attribute);
}
const std::vector<int32_t>& AXPlatformNodeBase::GetIntListAttribute(
ax::mojom::IntListAttribute attribute) const {
static const base::NoDestructor<std::vector<int32_t>> empty_data;
if (!delegate_)
return *empty_data;
return GetData().GetIntListAttribute(attribute);
}
bool AXPlatformNodeBase::GetIntListAttribute(
ax::mojom::IntListAttribute attribute,
std::vector<int32_t>* value) const {
if (!delegate_)
return false;
return GetData().GetIntListAttribute(attribute, value);
}
// static
AXPlatformNodeBase* AXPlatformNodeBase::FromNativeViewAccessible(
gfx::NativeViewAccessible accessible) {
return static_cast<AXPlatformNodeBase*>(
AXPlatformNode::FromNativeViewAccessible(accessible));
}
bool AXPlatformNodeBase::SetHypertextSelection(int start_offset,
int end_offset) {
if (!delegate_)
return false;
return delegate_->SetHypertextSelection(start_offset, end_offset);
}
bool AXPlatformNodeBase::IsDocument() const {
return ui::IsDocument(GetData().role);
}
bool AXPlatformNodeBase::IsSelectionItemSupported() const {
switch (GetData().role) {
// An ARIA 1.1+ role of "cell", or a role of "row" inside
// an ARIA 1.1 role of "table", should not be selectable.
// ARIA "table" is not interactable, ARIA "grid" is.
case ax::mojom::Role::kCell:
case ax::mojom::Role::kColumnHeader:
case ax::mojom::Role::kRow:
case ax::mojom::Role::kRowHeader: {
// An ARIA grid subwidget is only selectable if explicitly marked as
// selected (or not) with the aria-selected property.
if (!HasBoolAttribute(ax::mojom::BoolAttribute::kSelected))
return false;
AXPlatformNodeBase* table = GetTable();
if (!table)
return false;
return table->GetData().role == ax::mojom::Role::kGrid ||
table->GetData().role == ax::mojom::Role::kTreeGrid;
}
// https://www.w3.org/TR/core-aam-1.1/#mapping_state-property_table
// SelectionItem.IsSelected is exposed when aria-checked is True or False,
// for 'radio' and 'menuitemradio' roles.
case ax::mojom::Role::kRadioButton:
case ax::mojom::Role::kMenuItemRadio: {
if (GetData().GetCheckedState() == ax::mojom::CheckedState::kTrue ||
GetData().GetCheckedState() == ax::mojom::CheckedState::kFalse)
return true;
return false;
}
// https://www.w3.org/TR/wai-aria-1.1/#aria-selected
// SelectionItem.IsSelected is exposed when aria-select is True or False.
case ax::mojom::Role::kListBoxOption:
case ax::mojom::Role::kListItem:
case ax::mojom::Role::kMenuListOption:
case ax::mojom::Role::kTab:
case ax::mojom::Role::kTreeItem:
return HasBoolAttribute(ax::mojom::BoolAttribute::kSelected);
default:
return false;
}
}
bool AXPlatformNodeBase::IsTextField() const {
return GetData().IsTextField();
}
bool AXPlatformNodeBase::IsPlainTextField() const {
return GetData().IsPlainTextField();
}
bool AXPlatformNodeBase::IsRichTextField() const {
return GetData().IsRichTextField();
}
bool AXPlatformNodeBase::IsText() const {
return delegate_ && delegate_->IsText();
}
std::u16string AXPlatformNodeBase::GetHypertext() const {
if (!delegate_)
return std::u16string();
// Hypertext of platform leaves, which internally are composite objects, are
// represented with the inner text of the internal composite object. These
// don't exist on non-web content.
if (IsChildOfLeaf())
return GetInnerText();
if (hypertext_.needs_update)
UpdateComputedHypertext();
return hypertext_.hypertext;
}
std::u16string AXPlatformNodeBase::GetInnerText() const {
if (!delegate_)
return std::u16string();
return delegate_->GetInnerText();
}
std::u16string AXPlatformNodeBase::GetRangeValueText() const {
float fval;
std::u16string value =
GetString16Attribute(ax::mojom::StringAttribute::kValue);
if (value.empty() &&
GetFloatAttribute(ax::mojom::FloatAttribute::kValueForRange, &fval)) {
value = base::NumberToString16(fval);
}
return value;
}
std::u16string
AXPlatformNodeBase::GetRoleDescriptionFromImageAnnotationStatusOrFromAttribute()
const {
if (GetData().role == ax::mojom::Role::kImage &&
(GetData().GetImageAnnotationStatus() ==
ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation ||
GetData().GetImageAnnotationStatus() ==
ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation)) {
return GetDelegate()->GetLocalizedRoleDescriptionForUnlabeledImage();
}
return GetString16Attribute(ax::mojom::StringAttribute::kRoleDescription);
}
std::u16string AXPlatformNodeBase::GetRoleDescription() const {
std::u16string role_description =
GetRoleDescriptionFromImageAnnotationStatusOrFromAttribute();
if (!role_description.empty()) {
return role_description;
}
return GetDelegate()->GetLocalizedStringForRoleDescription();
}
AXPlatformNodeBase* AXPlatformNodeBase::GetSelectionContainer() const {
if (!delegate_)
return nullptr;
AXPlatformNodeBase* container = const_cast<AXPlatformNodeBase*>(this);
while (container &&
!IsContainerWithSelectableChildren(container->GetData().role)) {
gfx::NativeViewAccessible parent_accessible = container->GetParent();
AXPlatformNodeBase* parent = FromNativeViewAccessible(parent_accessible);
container = parent;
}
return container;
}
AXPlatformNodeBase* AXPlatformNodeBase::GetTable() const {
if (!delegate_)
return nullptr;
AXPlatformNodeBase* table = const_cast<AXPlatformNodeBase*>(this);
while (table && !IsTableLike(table->GetData().role)) {
gfx::NativeViewAccessible parent_accessible = table->GetParent();
AXPlatformNodeBase* parent = FromNativeViewAccessible(parent_accessible);
table = parent;
}
return table;
}
AXPlatformNodeBase* AXPlatformNodeBase::GetTableCaption() const {
if (!delegate_)
return nullptr;
AXPlatformNodeBase* table = GetTable();
if (!table)
return nullptr;
BASE_DCHECK(table->delegate_);
return static_cast<AXPlatformNodeBase*>(table->delegate_->GetTableCaption());
}
AXPlatformNodeBase* AXPlatformNodeBase::GetTableCell(int index) const {
if (!delegate_)
return nullptr;
if (!IsTableLike(GetData().role) && !IsCellOrTableHeader(GetData().role))
return nullptr;
AXPlatformNodeBase* table = GetTable();
if (!table)
return nullptr;
BASE_DCHECK(table->delegate_);
std::optional<int32_t> cell_id = table->delegate_->CellIndexToId(index);
if (!cell_id)
return nullptr;
return static_cast<AXPlatformNodeBase*>(
table->delegate_->GetFromNodeID(*cell_id));
}
AXPlatformNodeBase* AXPlatformNodeBase::GetTableCell(int row,
int column) const {
if (!IsTableLike(GetData().role) && !IsCellOrTableHeader(GetData().role))
return nullptr;
AXPlatformNodeBase* table = GetTable();
if (!table || !GetTableRowCount() || !GetTableColumnCount())
return nullptr;
if (row < 0 || row >= *GetTableRowCount() || column < 0 ||
column >= *GetTableColumnCount()) {
return nullptr;
}
BASE_DCHECK(table->delegate_);
std::optional<int32_t> cell_id = table->delegate_->GetCellId(row, column);
if (!cell_id)
return nullptr;
return static_cast<AXPlatformNodeBase*>(
table->delegate_->GetFromNodeID(*cell_id));
}
std::optional<int> AXPlatformNodeBase::GetTableCellIndex() const {
if (!delegate_)
return std::nullopt;
return delegate_->GetTableCellIndex();
}
std::optional<int> AXPlatformNodeBase::GetTableColumn() const {
if (!delegate_)
return std::nullopt;
return delegate_->GetTableCellColIndex();
}
std::optional<int> AXPlatformNodeBase::GetTableColumnCount() const {
if (!delegate_)
return std::nullopt;
AXPlatformNodeBase* table = GetTable();
if (!table)
return std::nullopt;
BASE_DCHECK(table->delegate_);
return table->delegate_->GetTableColCount();
}
std::optional<int> AXPlatformNodeBase::GetTableAriaColumnCount() const {
if (!delegate_)
return std::nullopt;
AXPlatformNodeBase* table = GetTable();
if (!table)
return std::nullopt;
BASE_DCHECK(table->delegate_);
return table->delegate_->GetTableAriaColCount();
}
std::optional<int> AXPlatformNodeBase::GetTableColumnSpan() const {
if (!delegate_)
return std::nullopt;
return delegate_->GetTableCellColSpan();
}
std::optional<int> AXPlatformNodeBase::GetTableRow() const {
if (!delegate_)
return std::nullopt;
if (delegate_->IsTableRow())
return delegate_->GetTableRowRowIndex();
if (delegate_->IsTableCellOrHeader())
return delegate_->GetTableCellRowIndex();
return std::nullopt;
}
std::optional<int> AXPlatformNodeBase::GetTableRowCount() const {
if (!delegate_)
return std::nullopt;
AXPlatformNodeBase* table = GetTable();
if (!table)
return std::nullopt;
BASE_DCHECK(table->delegate_);
return table->delegate_->GetTableRowCount();
}
std::optional<int> AXPlatformNodeBase::GetTableAriaRowCount() const {
if (!delegate_)
return std::nullopt;
AXPlatformNodeBase* table = GetTable();
if (!table)
return std::nullopt;
BASE_DCHECK(table->delegate_);
return table->delegate_->GetTableAriaRowCount();
}
std::optional<int> AXPlatformNodeBase::GetTableRowSpan() const {
if (!delegate_)
return std::nullopt;
return delegate_->GetTableCellRowSpan();
}
std::optional<float> AXPlatformNodeBase::GetFontSizeInPoints() const {
float font_size;
// Attribute has no default value.
if (GetFloatAttribute(ax::mojom::FloatAttribute::kFontSize, &font_size)) {
// The IA2 Spec requires the value to be in pt, not in pixels.
// There are 72 points per inch.
// We assume that there are 96 pixels per inch on a standard display.
// TODO(nektar): Figure out the current value of pixels per inch.
float points = font_size * 72.0 / 96.0;
// Round to the nearest 0.5 points.
points = std::round(points * 2.0) / 2.0;
return points;
}
return std::nullopt;
}
bool AXPlatformNodeBase::HasCaret(
const AXTree::Selection* unignored_selection) {
if (IsInvisibleOrIgnored())
return false;
if (IsPlainTextField() &&
HasIntAttribute(ax::mojom::IntAttribute::kTextSelStart) &&
HasIntAttribute(ax::mojom::IntAttribute::kTextSelEnd)) {
return true;
}
// The caret is always at the focus of the selection.
int32_t focus_id;
if (unignored_selection)
focus_id = unignored_selection->focus_object_id;
else
focus_id = delegate_->GetUnignoredSelection().focus_object_id;
AXPlatformNodeBase* focus_object =
static_cast<AXPlatformNodeBase*>(delegate_->GetFromNodeID(focus_id));
if (!focus_object)
return false;
return focus_object->IsDescendantOf(this);
}
bool AXPlatformNodeBase::IsLeaf() const {
return delegate_ && delegate_->IsLeaf();
}
bool AXPlatformNodeBase::IsChildOfLeaf() const {
return delegate_ && delegate_->IsChildOfLeaf();
}
bool AXPlatformNodeBase::IsInvisibleOrIgnored() const {
return GetData().IsInvisibleOrIgnored();
}
bool AXPlatformNodeBase::IsScrollable() const {
return (HasIntAttribute(ax::mojom::IntAttribute::kScrollXMin) &&
HasIntAttribute(ax::mojom::IntAttribute::kScrollXMax) &&
HasIntAttribute(ax::mojom::IntAttribute::kScrollX)) ||
(HasIntAttribute(ax::mojom::IntAttribute::kScrollYMin) &&
HasIntAttribute(ax::mojom::IntAttribute::kScrollYMax) &&
HasIntAttribute(ax::mojom::IntAttribute::kScrollY));
}
bool AXPlatformNodeBase::IsHorizontallyScrollable() const {
BASE_DCHECK(GetIntAttribute(ax::mojom::IntAttribute::kScrollXMin) >= 0);
BASE_DCHECK(GetIntAttribute(ax::mojom::IntAttribute::kScrollXMax) >= 0);
return IsScrollable() &&
GetIntAttribute(ax::mojom::IntAttribute::kScrollXMin) <
GetIntAttribute(ax::mojom::IntAttribute::kScrollXMax);
}
bool AXPlatformNodeBase::IsVerticallyScrollable() const {
BASE_DCHECK(GetIntAttribute(ax::mojom::IntAttribute::kScrollYMin) >= 0);
BASE_DCHECK(GetIntAttribute(ax::mojom::IntAttribute::kScrollYMax) >= 0);
return IsScrollable() &&
GetIntAttribute(ax::mojom::IntAttribute::kScrollYMin) <
GetIntAttribute(ax::mojom::IntAttribute::kScrollYMax);
}
std::u16string AXPlatformNodeBase::GetValue() const {
// Expose slider value.
if (GetData().IsRangeValueSupported())
return GetRangeValueText();
// On Windows, the value of a document should be its URL.
if (ui::IsDocument(GetData().role))
return base::UTF8ToUTF16(delegate_->GetTreeData().url);
std::u16string value =
GetString16Attribute(ax::mojom::StringAttribute::kValue);
// Some screen readers like Jaws and VoiceOver require a
// value to be set in text fields with rich content, even though the same
// information is available on the children.
if (value.empty() && IsRichTextField())
return GetInnerText();
return value;
}
void AXPlatformNodeBase::ComputeAttributes(PlatformAttributeList* attributes) {
BASE_DCHECK(delegate_);
// Expose some HTML and ARIA attributes in the IAccessible2 attributes string
// "display", "tag", and "xml-roles" have somewhat unusual names for
// historical reasons. Aside from that virtually every ARIA attribute
// is exposed in a really straightforward way, i.e. "aria-foo" is exposed
// as "foo".
AddAttributeToList(ax::mojom::StringAttribute::kDisplay, "display",
attributes);
AddAttributeToList(ax::mojom::StringAttribute::kHtmlTag, "tag", attributes);
AddAttributeToList(ax::mojom::StringAttribute::kRole, "xml-roles",
attributes);
AddAttributeToList(ax::mojom::StringAttribute::kPlaceholder, "placeholder",
attributes);
AddAttributeToList(ax::mojom::StringAttribute::kAutoComplete, "autocomplete",
attributes);
if (!HasStringAttribute(ax::mojom::StringAttribute::kAutoComplete) &&
GetData().HasState(ax::mojom::State::kAutofillAvailable)) {
AddAttributeToList("autocomplete", "list", attributes);
}
std::u16string role_description =
GetRoleDescriptionFromImageAnnotationStatusOrFromAttribute();
if (!role_description.empty() ||
HasStringAttribute(ax::mojom::StringAttribute::kRoleDescription)) {
AddAttributeToList("roledescription", base::UTF16ToUTF8(role_description),
attributes);
}
AddAttributeToList(ax::mojom::StringAttribute::kKeyShortcuts, "keyshortcuts",
attributes);
AddAttributeToList(ax::mojom::IntAttribute::kHierarchicalLevel, "level",
attributes);
AddAttributeToList(ax::mojom::IntAttribute::kSetSize, "setsize", attributes);
AddAttributeToList(ax::mojom::IntAttribute::kPosInSet, "posinset",
attributes);
if (IsPlatformCheckable())
AddAttributeToList("checkable", "true", attributes);
if (IsInvisibleOrIgnored()) // Note: NVDA prefers this over INVISIBLE state.
AddAttributeToList("hidden", "true", attributes);
// Expose live region attributes.
AddAttributeToList(ax::mojom::StringAttribute::kLiveStatus, "live",
attributes);
AddAttributeToList(ax::mojom::StringAttribute::kLiveRelevant, "relevant",
attributes);
AddAttributeToList(ax::mojom::BoolAttribute::kLiveAtomic, "atomic",
attributes);
// Busy is usually associated with live regions but can occur anywhere:
AddAttributeToList(ax::mojom::BoolAttribute::kBusy, "busy", attributes);
// Expose container live region attributes.
AddAttributeToList(ax::mojom::StringAttribute::kContainerLiveStatus,
"container-live", attributes);
AddAttributeToList(ax::mojom::StringAttribute::kContainerLiveRelevant,
"container-relevant", attributes);
AddAttributeToList(ax::mojom::BoolAttribute::kContainerLiveAtomic,
"container-atomic", attributes);
AddAttributeToList(ax::mojom::BoolAttribute::kContainerLiveBusy,
"container-busy", attributes);
// Expose the non-standard explicit-name IA2 attribute.
int name_from;
if (GetIntAttribute(ax::mojom::IntAttribute::kNameFrom, &name_from) &&
name_from != static_cast<int32_t>(ax::mojom::NameFrom::kContents)) {
AddAttributeToList("explicit-name", "true", attributes);
}
// Expose the aria-haspopup attribute.
int32_t has_popup;
if (GetIntAttribute(ax::mojom::IntAttribute::kHasPopup, &has_popup)) {
switch (static_cast<ax::mojom::HasPopup>(has_popup)) {
case ax::mojom::HasPopup::kFalse:
break;
case ax::mojom::HasPopup::kTrue:
AddAttributeToList("haspopup", "true", attributes);
break;
case ax::mojom::HasPopup::kMenu:
AddAttributeToList("haspopup", "menu", attributes);
break;
case ax::mojom::HasPopup::kListbox:
AddAttributeToList("haspopup", "listbox", attributes);
break;
case ax::mojom::HasPopup::kTree:
AddAttributeToList("haspopup", "tree", attributes);
break;
case ax::mojom::HasPopup::kGrid:
AddAttributeToList("haspopup", "grid", attributes);
break;
case ax::mojom::HasPopup::kDialog:
AddAttributeToList("haspopup", "dialog", attributes);
break;
}
} else if (GetData().HasState(ax::mojom::State::kAutofillAvailable)) {
AddAttributeToList("haspopup", "menu", attributes);
}
// Expose the aria-current attribute.
int32_t aria_current_state;
if (GetIntAttribute(ax::mojom::IntAttribute::kAriaCurrentState,
&aria_current_state)) {
switch (static_cast<ax::mojom::AriaCurrentState>(aria_current_state)) {
case ax::mojom::AriaCurrentState::kNone:
break;
case ax::mojom::AriaCurrentState::kFalse:
AddAttributeToList("current", "false", attributes);
break;
case ax::mojom::AriaCurrentState::kTrue:
AddAttributeToList("current", "true", attributes);
break;
case ax::mojom::AriaCurrentState::kPage:
AddAttributeToList("current", "page", attributes);
break;
case ax::mojom::AriaCurrentState::kStep:
AddAttributeToList("current", "step", attributes);
break;
case ax::mojom::AriaCurrentState::kLocation:
AddAttributeToList("current", "location", attributes);
break;
case ax::mojom::AriaCurrentState::kUnclippedLocation:
AddAttributeToList("current", "unclippedLocation", attributes);
break;
case ax::mojom::AriaCurrentState::kDate:
AddAttributeToList("current", "date", attributes);
break;
case ax::mojom::AriaCurrentState::kTime:
AddAttributeToList("current", "time", attributes);
break;
}
}
// Expose table cell index.
if (IsCellOrTableHeader(GetData().role)) {
std::optional<int> index = delegate_->GetTableCellIndex();
if (index) {
std::string str_index(base::NumberToString(*index));
AddAttributeToList("table-cell-index", str_index, attributes);
}
}
if (GetData().role == ax::mojom::Role::kLayoutTable)
AddAttributeToList("layout-guess", "true", attributes);
// Expose aria-colcount and aria-rowcount in a table, grid or treegrid if they
// are different from its physical dimensions.
if (IsTableLike(GetData().role) &&
(delegate_->GetTableAriaRowCount() != delegate_->GetTableRowCount() ||
delegate_->GetTableAriaColCount() != delegate_->GetTableColCount())) {
AddAttributeToList(ax::mojom::IntAttribute::kAriaColumnCount, "colcount",
attributes);
AddAttributeToList(ax::mojom::IntAttribute::kAriaRowCount, "rowcount",
attributes);
}
if (IsCellOrTableHeader(GetData().role) || IsTableRow(GetData().role)) {
// Expose aria-colindex and aria-rowindex in a cell or row only if they are
// different from the table's physical coordinates.
if (delegate_->GetTableCellAriaRowIndex() !=
delegate_->GetTableCellRowIndex() ||
delegate_->GetTableCellAriaColIndex() !=
delegate_->GetTableCellColIndex()) {
if (!IsTableRow(GetData().role)) {
AddAttributeToList(ax::mojom::IntAttribute::kAriaCellColumnIndex,
"colindex", attributes);
}
AddAttributeToList(ax::mojom::IntAttribute::kAriaCellRowIndex, "rowindex",
attributes);
}
// Experimental: expose aria-rowtext / aria-coltext. Not standardized
// yet, but obscure enough that it's safe to expose.
// http://crbug.com/791634
for (size_t i = 0; i < GetData().html_attributes.size(); ++i) {
const std::string& attr = GetData().html_attributes[i].first;
const std::string& value = GetData().html_attributes[i].second;
if (attr == "aria-coltext") {
AddAttributeToList("coltext", value, attributes);
}
if (attr == "aria-rowtext") {
AddAttributeToList("rowtext", value, attributes);
}
}
}
// Expose row or column header sort direction.
int32_t sort_direction;
if (IsTableHeader(GetData().role) &&
GetIntAttribute(ax::mojom::IntAttribute::kSortDirection,
&sort_direction)) {
switch (static_cast<ax::mojom::SortDirection>(sort_direction)) {
case ax::mojom::SortDirection::kNone:
break;
case ax::mojom::SortDirection::kUnsorted:
AddAttributeToList("sort", "none", attributes);
break;
case ax::mojom::SortDirection::kAscending:
AddAttributeToList("sort", "ascending", attributes);
break;
case ax::mojom::SortDirection::kDescending:
AddAttributeToList("sort", "descending", attributes);
break;
case ax::mojom::SortDirection::kOther:
AddAttributeToList("sort", "other", attributes);
break;
}
}
if (IsCellOrTableHeader(GetData().role)) {
// Expose colspan attribute.
std::string colspan;
if (GetData().GetHtmlAttribute("aria-colspan", &colspan)) {
AddAttributeToList("colspan", colspan, attributes);
}
// Expose rowspan attribute.
std::string rowspan;
if (GetData().GetHtmlAttribute("aria-rowspan", &rowspan)) {
AddAttributeToList("rowspan", rowspan, attributes);
}
}
// Expose slider value.
if (GetData().IsRangeValueSupported() ||
GetData().role == ax::mojom::Role::kComboBoxMenuButton) {
std::string value = base::UTF16ToUTF8(GetRangeValueText());
if (!value.empty())
AddAttributeToList("valuetext", value, attributes);
}
// Expose dropeffect attribute.
// aria-dropeffect is deprecated in WAI-ARIA 1.1.
if (GetData().HasIntAttribute(ax::mojom::IntAttribute::kDropeffect)) {
std::string dropeffect = GetData().DropeffectBitfieldToString();
AddAttributeToList("dropeffect", dropeffect, attributes);
}
// Expose grabbed attribute.
// aria-grabbed is deprecated in WAI-ARIA 1.1.
AddAttributeToList(ax::mojom::BoolAttribute::kGrabbed, "grabbed", attributes);
// Expose class attribute.
std::string class_attr;
if (GetData().GetStringAttribute(ax::mojom::StringAttribute::kClassName,
&class_attr)) {
AddAttributeToList("class", class_attr, attributes);
}
// Expose datetime attribute.
std::string datetime;
if (GetData().role == ax::mojom::Role::kTime &&
GetData().GetHtmlAttribute("datetime", &datetime)) {
AddAttributeToList("datetime", datetime, attributes);
}
// Expose id attribute.
std::string id;
if (GetData().GetHtmlAttribute("id", &id)) {
AddAttributeToList("id", id, attributes);
}
// Expose src attribute.
std::string src;
if (GetData().role == ax::mojom::Role::kImage &&
GetData().GetHtmlAttribute("src", &src)) {
AddAttributeToList("src", src, attributes);
}
if (GetData().HasIntAttribute(ax::mojom::IntAttribute::kTextAlign)) {
auto text_align = static_cast<ax::mojom::TextAlign>(
GetData().GetIntAttribute(ax::mojom::IntAttribute::kTextAlign));
switch (text_align) {
case ax::mojom::TextAlign::kNone:
break;
case ax::mojom::TextAlign::kLeft:
AddAttributeToList("text-align", "left", attributes);
break;
case ax::mojom::TextAlign::kRight:
AddAttributeToList("text-align", "right", attributes);
break;
case ax::mojom::TextAlign::kCenter:
AddAttributeToList("text-align", "center", attributes);
break;
case ax::mojom::TextAlign::kJustify:
AddAttributeToList("text-align", "justify", attributes);
break;
}
}
float text_indent;
if (GetFloatAttribute(ax::mojom::FloatAttribute::kTextIndent, &text_indent) !=
0.0f) {
// Round value to two decimal places.
std::stringstream value;
value << std::fixed << std::setprecision(2) << text_indent << "mm";
AddAttributeToList("text-indent", value.str(), attributes);
}
// Text fields need to report the attribute "text-model:a1" to instruct
// screen readers to use IAccessible2 APIs to handle text editing in this
// object (as opposed to treating it like a native Windows text box).
// The text-model:a1 attribute is documented here:
// http://www.linuxfoundation.org/collaborate/workgroups/accessibility/ia2/ia2_implementation_guide
if (IsTextField())
AddAttributeToList("text-model", "a1", attributes);
std::string details_roles = ComputeDetailsRoles();
if (!details_roles.empty())
AddAttributeToList("details-roles", details_roles, attributes);
}
void AXPlatformNodeBase::AddAttributeToList(
const ax::mojom::StringAttribute attribute,
const char* name,
PlatformAttributeList* attributes) {
BASE_DCHECK(attributes);
std::string value;
if (GetStringAttribute(attribute, &value)) {
AddAttributeToList(name, value, attributes);
}
}
void AXPlatformNodeBase::AddAttributeToList(
const ax::mojom::BoolAttribute attribute,
const char* name,
PlatformAttributeList* attributes) {
BASE_DCHECK(attributes);
bool value;
if (GetBoolAttribute(attribute, &value)) {
AddAttributeToList(name, value ? "true" : "false", attributes);
}
}
void AXPlatformNodeBase::AddAttributeToList(
const ax::mojom::IntAttribute attribute,
const char* name,
PlatformAttributeList* attributes) {
BASE_DCHECK(attributes);
auto maybe_value = ComputeAttribute(delegate_, attribute);
if (maybe_value.has_value()) {
std::string str_value = base::NumberToString(maybe_value.value());
AddAttributeToList(name, str_value, attributes);
}
}
void AXPlatformNodeBase::AddAttributeToList(const char* name,
const std::string& value,
PlatformAttributeList* attributes) {
AddAttributeToList(name, value.c_str(), attributes);
}
AXHypertext::AXHypertext() = default;
AXHypertext::~AXHypertext() = default;
AXHypertext::AXHypertext(const AXHypertext& other) = default;
AXHypertext& AXHypertext::operator=(const AXHypertext& other) = default;
void AXPlatformNodeBase::UpdateComputedHypertext() const {
if (!delegate_)
return;
hypertext_ = AXHypertext();
if (IsLeaf()) {
hypertext_.hypertext = GetInnerText();
hypertext_.needs_update = false;
return;
}
// Construct the hypertext for this node, which contains the concatenation
// of all of the static text and widespace of this node's children and an
// embedded object character for all the other children. Build up a map from
// the character index of each embedded object character to the id of the
// child object it points to.
std::u16string hypertext;
for (AXPlatformNodeChildIterator child_iter = AXPlatformNodeChildrenBegin();
child_iter != AXPlatformNodeChildrenEnd(); ++child_iter) {
// Similar to Firefox, we don't expose text-only objects in IA2 and ATK
// hypertext with the embedded object character. We copy all of their text
// instead.
if (child_iter->IsText()) {
hypertext_.hypertext += child_iter->GetNameAsString16();
} else {
int32_t char_offset = static_cast<int32_t>(hypertext_.hypertext.size());
int32_t child_unique_id = child_iter->GetUniqueId();
int32_t index = static_cast<int32_t>(hypertext_.hyperlinks.size());
hypertext_.hyperlink_offset_to_index[char_offset] = index;
hypertext_.hyperlinks.push_back(child_unique_id);
hypertext_.hypertext += kEmbeddedCharacter;
}
}
hypertext_.needs_update = false;
}
void AXPlatformNodeBase::AddAttributeToList(const char* name,
const char* value,
PlatformAttributeList* attributes) {
}
std::optional<int> AXPlatformNodeBase::GetPosInSet() const {
if (!delegate_)
return std::nullopt;
return delegate_->GetPosInSet();
}
std::optional<int> AXPlatformNodeBase::GetSetSize() const {
if (!delegate_)
return std::nullopt;
return delegate_->GetSetSize();
}
bool AXPlatformNodeBase::ScrollToNode(ScrollType scroll_type) {
// ax::mojom::Action::kScrollToMakeVisible wants a target rect in *local*
// coords.
gfx::Rect r = gfx::ToEnclosingRect(GetData().relative_bounds.bounds);
r -= r.OffsetFromOrigin();
switch (scroll_type) {
case ScrollType::TopLeft:
r = gfx::Rect(r.x(), r.y(), 0, 0);
break;
case ScrollType::BottomRight:
r = gfx::Rect(r.right(), r.bottom(), 0, 0);
break;
case ScrollType::TopEdge:
r = gfx::Rect(r.x(), r.y(), r.width(), 0);
break;
case ScrollType::BottomEdge:
r = gfx::Rect(r.x(), r.bottom(), r.width(), 0);
break;
case ScrollType::LeftEdge:
r = gfx::Rect(r.x(), r.y(), 0, r.height());
break;
case ScrollType::RightEdge:
r = gfx::Rect(r.right(), r.y(), 0, r.height());
break;
case ScrollType::Anywhere:
break;
}
ui::AXActionData action_data;
action_data.target_node_id = GetData().id;
action_data.action = ax::mojom::Action::kScrollToMakeVisible;
action_data.horizontal_scroll_alignment =
ax::mojom::ScrollAlignment::kScrollAlignmentCenter;
action_data.vertical_scroll_alignment =
ax::mojom::ScrollAlignment::kScrollAlignmentCenter;
action_data.scroll_behavior =
ax::mojom::ScrollBehavior::kDoNotScrollIfVisible;
action_data.target_rect = r;
GetDelegate()->AccessibilityPerformAction(action_data);
return true;
}
// static
void AXPlatformNodeBase::SanitizeStringAttribute(const std::string& input,
std::string* output) {
BASE_DCHECK(output);
// According to the IA2 spec and AT-SPI2, these characters need to be escaped
// with a backslash: backslash, colon, comma, equals and semicolon. Note
// that backslash must be replaced first.
base::ReplaceChars(input, "\\", "\\\\", output);
base::ReplaceChars(*output, ":", "\\:", output);
base::ReplaceChars(*output, ",", "\\,", output);
base::ReplaceChars(*output, "=", "\\=", output);
base::ReplaceChars(*output, ";", "\\;", output);
}
AXPlatformNodeBase* AXPlatformNodeBase::GetHyperlinkFromHypertextOffset(
int offset) {
std::map<int32_t, int32_t>::iterator iterator =
hypertext_.hyperlink_offset_to_index.find(offset);
if (iterator == hypertext_.hyperlink_offset_to_index.end())
return nullptr;
int32_t index = iterator->second;
BASE_DCHECK(index >= 0);
BASE_DCHECK(index < static_cast<int32_t>(hypertext_.hyperlinks.size()));
int32_t id = hypertext_.hyperlinks[index];
auto* hyperlink =
static_cast<AXPlatformNodeBase*>(AXPlatformNodeBase::GetFromUniqueId(id));
if (!hyperlink)
return nullptr;
return hyperlink;
}
int32_t AXPlatformNodeBase::GetHyperlinkIndexFromChild(
AXPlatformNodeBase* child) {
if (hypertext_.hyperlinks.empty())
return -1;
auto iterator = std::find(hypertext_.hyperlinks.begin(),
hypertext_.hyperlinks.end(), child->GetUniqueId());
if (iterator == hypertext_.hyperlinks.end())
return -1;
return static_cast<int32_t>(iterator - hypertext_.hyperlinks.begin());
}
int32_t AXPlatformNodeBase::GetHypertextOffsetFromHyperlinkIndex(
int32_t hyperlink_index) {
for (auto& offset_index : hypertext_.hyperlink_offset_to_index) {
if (offset_index.second == hyperlink_index)
return offset_index.first;
}
return -1;
}
int32_t AXPlatformNodeBase::GetHypertextOffsetFromChild(
AXPlatformNodeBase* child) {
// TODO(dougt) BASE_DCHECK(child.owner()->PlatformGetParent() == owner());
if (IsLeaf())
return -1;
// Handle the case when we are dealing with a text-only child.
// Text-only children should not be present at tree roots and so no
// cross-tree traversal is necessary.
if (child->IsText()) {
int32_t hypertext_offset = 0;
for (auto child_iter = AXPlatformNodeChildrenBegin();
child_iter != AXPlatformNodeChildrenEnd() && child_iter.get() != child;
++child_iter) {
if (child_iter->IsText()) {
hypertext_offset +=
static_cast<int32_t>(child_iter->GetHypertext().size());
} else {
++hypertext_offset;
}
}
return hypertext_offset;
}
int32_t hyperlink_index = GetHyperlinkIndexFromChild(child);
if (hyperlink_index < 0)
return -1;
return GetHypertextOffsetFromHyperlinkIndex(hyperlink_index);
}
int32_t AXPlatformNodeBase::GetHypertextOffsetFromDescendant(
AXPlatformNodeBase* descendant) {
auto* parent_object = static_cast<AXPlatformNodeBase*>(
FromNativeViewAccessible(descendant->GetDelegate()->GetParent()));
while (parent_object && parent_object != this) {
descendant = parent_object;
parent_object = static_cast<AXPlatformNodeBase*>(
FromNativeViewAccessible(descendant->GetParent()));
}
if (!parent_object)
return -1;
return parent_object->GetHypertextOffsetFromChild(descendant);
}
int AXPlatformNodeBase::GetHypertextOffsetFromEndpoint(
AXPlatformNodeBase* endpoint_object,
int endpoint_offset) {
// There are three cases:
// 1. The selection endpoint is inside this object but not one of its
// descendants, or is in an ancestor of this object. endpoint_offset should be
// returned, possibly adjusted from a child offset to a hypertext offset.
// 2. The selection endpoint is a descendant of this object. The offset of the
// character in this object's hypertext corresponding to the subtree in which
// the endpoint is located should be returned.
// 3. The selection endpoint is in a completely different part of the tree.
// Either 0 or hypertext length should be returned depending on the direction
// that one needs to travel to find the endpoint.
//
// TODO(nektar): Replace all this logic with the use of AXNodePosition.
// Case 1. Is the endpoint object equal to this object or an ancestor of this
// object?
//
// IsDescendantOf includes the case when endpoint_object == this.
if (IsDescendantOf(endpoint_object)) {
if (endpoint_object->IsLeaf()) {
BASE_DCHECK(endpoint_object == this);
return endpoint_offset;
} else {
BASE_DCHECK(endpoint_offset >= 0);
BASE_DCHECK(endpoint_offset <=
endpoint_object->GetDelegate()->GetChildCount());
// Adjust the |endpoint_offset| because the selection endpoint is a tree
// position, i.e. it represents a child index and not a text offset.
if (endpoint_offset >= endpoint_object->GetChildCount()) {
return static_cast<int>(endpoint_object->GetHypertext().size());
} else {
auto* child = static_cast<AXPlatformNodeBase*>(FromNativeViewAccessible(
endpoint_object->ChildAtIndex(endpoint_offset)));
BASE_DCHECK(child);
return endpoint_object->GetHypertextOffsetFromChild(child);
}
}
}
AXPlatformNodeBase* common_parent = this;
std::optional<int> index_in_common_parent = GetIndexInParent();
while (common_parent && !endpoint_object->IsDescendantOf(common_parent)) {
index_in_common_parent = common_parent->GetIndexInParent();
common_parent = static_cast<AXPlatformNodeBase*>(
FromNativeViewAccessible(common_parent->GetParent()));
}
if (!common_parent)
return -1;
BASE_DCHECK(!(common_parent->IsText()));
// Case 2. Is the selection endpoint inside a descendant of this object?
//
// We already checked in case 1 if our endpoint object is equal to this
// object. We can safely assume that it is a descendant or in a completely
// different part of the tree.
if (common_parent == this) {
int32_t hypertext_offset =
GetHypertextOffsetFromDescendant(endpoint_object);
auto* parent = static_cast<AXPlatformNodeBase*>(
FromNativeViewAccessible(endpoint_object->GetParent()));
if (parent == this && endpoint_object->IsText()) {
// Due to a historical design decision, the hypertext of the immediate
// parents of text objects includes all their text. We therefore need to
// adjust the hypertext offset in the parent by adding any text offset.
hypertext_offset += endpoint_offset;
}
return hypertext_offset;
}
// Case 3. Is the selection endpoint in a completely different part of the
// tree?
//
// We can safely assume that the endpoint is in another part of the tree or
// at common parent, and that this object is a descendant of common parent.
std::optional<int> endpoint_index_in_common_parent;
for (auto child_iter = common_parent->AXPlatformNodeChildrenBegin();
child_iter != common_parent->AXPlatformNodeChildrenEnd(); ++child_iter) {
if (endpoint_object->IsDescendantOf(child_iter.get())) {
endpoint_index_in_common_parent = child_iter->GetIndexInParent();
break;
}
}
if (endpoint_index_in_common_parent < index_in_common_parent)
return 0;
if (endpoint_index_in_common_parent > index_in_common_parent)
return static_cast<int32_t>(GetHypertext().size());
BASE_UNREACHABLE();
return -1;
}
int AXPlatformNodeBase::GetSelectionAnchor(const AXTree::Selection* selection) {
BASE_DCHECK(selection);
int32_t anchor_id = selection->anchor_object_id;
AXPlatformNodeBase* anchor_object =
static_cast<AXPlatformNodeBase*>(delegate_->GetFromNodeID(anchor_id));
if (!anchor_object)
return -1;
int anchor_offset = static_cast<int>(selection->anchor_offset);
return GetHypertextOffsetFromEndpoint(anchor_object, anchor_offset);
}
int AXPlatformNodeBase::GetSelectionFocus(const AXTree::Selection* selection) {
BASE_DCHECK(selection);
int32_t focus_id = selection->focus_object_id;
AXPlatformNodeBase* focus_object =
static_cast<AXPlatformNodeBase*>(GetDelegate()->GetFromNodeID(focus_id));
if (!focus_object)
return -1;
int focus_offset = static_cast<int>(selection->focus_offset);
return GetHypertextOffsetFromEndpoint(focus_object, focus_offset);
}
void AXPlatformNodeBase::GetSelectionOffsets(int* selection_start,
int* selection_end) {
GetSelectionOffsets(nullptr, selection_start, selection_end);
}
void AXPlatformNodeBase::GetSelectionOffsets(const AXTree::Selection* selection,
int* selection_start,
int* selection_end) {
BASE_DCHECK(selection_start && selection_end);
if (IsPlainTextField() &&
GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart,
selection_start) &&
GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, selection_end)) {
return;
}
// If the unignored selection has not been computed yet, compute it now.
AXTree::Selection unignored_selection;
if (!selection) {
unignored_selection = delegate_->GetUnignoredSelection();
selection = &unignored_selection;
}
BASE_DCHECK(selection);
GetSelectionOffsetsFromTree(selection, selection_start, selection_end);
}
void AXPlatformNodeBase::GetSelectionOffsetsFromTree(
const AXTree::Selection* selection,
int* selection_start,
int* selection_end) {
BASE_DCHECK(selection_start && selection_end);
*selection_start = GetSelectionAnchor(selection);
*selection_end = GetSelectionFocus(selection);
if (*selection_start < 0 || *selection_end < 0)
return;
// There are three cases when a selection would start and end on the same
// character:
// 1. Anchor and focus are both in a subtree that is to the right of this
// object.
// 2. Anchor and focus are both in a subtree that is to the left of this
// object.
// 3. Anchor and focus are in a subtree represented by a single embedded
// object character.
// Only case 3 refers to a valid selection because cases 1 and 2 fall
// outside this object in their entirety.
// Selections that span more than one character are by definition inside
// this object, so checking them is not necessary.
if (*selection_start == *selection_end && !HasCaret(selection)) {
*selection_start = -1;
*selection_end = -1;
return;
}
// The IA2 Spec says that if the largest of the two offsets falls on an
// embedded object character and if there is a selection in that embedded
// object, it should be incremented by one so that it points after the
// embedded object character.
// This is a signal to AT software that the embedded object is also part of
// the selection.
int* largest_offset =
(*selection_start <= *selection_end) ? selection_end : selection_start;
AXPlatformNodeBase* hyperlink =
GetHyperlinkFromHypertextOffset(*largest_offset);
if (!hyperlink)
return;
int hyperlink_selection_start, hyperlink_selection_end;
hyperlink->GetSelectionOffsets(selection, &hyperlink_selection_start,
&hyperlink_selection_end);
if (hyperlink_selection_start >= 0 && hyperlink_selection_end >= 0 &&
hyperlink_selection_start != hyperlink_selection_end) {
++(*largest_offset);
}
}
bool AXPlatformNodeBase::IsSameHypertextCharacter(
const AXHypertext& old_hypertext,
size_t old_char_index,
size_t new_char_index) {
if (old_char_index >= old_hypertext.hypertext.size() ||
new_char_index >= hypertext_.hypertext.size()) {
return false;
}
// For anything other than the "embedded character", we just compare the
// characters directly.
char16_t old_ch = old_hypertext.hypertext[old_char_index];
char16_t new_ch = hypertext_.hypertext[new_char_index];
if (old_ch != new_ch)
return false;
if (new_ch != kEmbeddedCharacter)
return true;
// If it's an embedded character, they're only identical if the child id
// the hyperlink points to is the same.
const std::map<int32_t, int32_t>& old_offset_to_index =
old_hypertext.hyperlink_offset_to_index;
const std::vector<int32_t>& old_hyperlinks = old_hypertext.hyperlinks;
int32_t old_hyperlinkscount = static_cast<int32_t>(old_hyperlinks.size());
auto iter = old_offset_to_index.find(static_cast<int32_t>(old_char_index));
int old_index = (iter != old_offset_to_index.end()) ? iter->second : -1;
int old_child_id = (old_index >= 0 && old_index < old_hyperlinkscount)
? old_hyperlinks[old_index]
: -1;
const std::map<int32_t, int32_t>& new_offset_to_index =
hypertext_.hyperlink_offset_to_index;
const std::vector<int32_t>& new_hyperlinks = hypertext_.hyperlinks;
int32_t new_hyperlinkscount = static_cast<int32_t>(new_hyperlinks.size());
iter = new_offset_to_index.find(static_cast<int32_t>(new_char_index));
int new_index = (iter != new_offset_to_index.end()) ? iter->second : -1;
int new_child_id = (new_index >= 0 && new_index < new_hyperlinkscount)
? new_hyperlinks[new_index]
: -1;
return old_child_id == new_child_id;
}
// Return true if the index represents a text character.
bool AXPlatformNodeBase::IsText(const std::u16string& text,
size_t index,
bool is_indexed_from_end) {
size_t text_len = text.size();
if (index == text_len)
return false;
auto ch = text[is_indexed_from_end ? text_len - index - 1 : index];
return ch != kEmbeddedCharacter;
}
bool AXPlatformNodeBase::IsPlatformCheckable() const {
return delegate_ && GetData().HasCheckedState();
}
AXPlatformNodeBase* AXPlatformNodeBase::NearestLeafToPoint(
gfx::Point point) const {
// First, scope the search to the node that contains point.
AXPlatformNodeBase* nearest_node =
static_cast<AXPlatformNodeBase*>(AXPlatformNode::FromNativeViewAccessible(
GetDelegate()->HitTestSync(point.x(), point.y())));
if (!nearest_node)
return nullptr;
AXPlatformNodeBase* parent = nearest_node;
// GetFirstChild does not consider if the parent is a leaf.
AXPlatformNodeBase* current_descendant =
parent->GetChildCount() ? parent->GetFirstChild() : nullptr;
AXPlatformNodeBase* nearest_descendant = nullptr;
float shortest_distance;
while (parent && current_descendant) {
// Manhattan Distance is used to provide faster distance estimates.
float current_distance = current_descendant->GetDelegate()
->GetClippedScreenBoundsRect()
.ManhattanDistanceToPoint(point);
if (!nearest_descendant || current_distance < shortest_distance) {
shortest_distance = current_distance;
nearest_descendant = current_descendant;
}
// Traverse
AXPlatformNodeBase* next_sibling = current_descendant->GetNextSibling();
if (next_sibling) {
current_descendant = next_sibling;
} else {
// We have gone through all siblings, update nearest and descend if
// possible.
if (nearest_descendant) {
nearest_node = nearest_descendant;
// If the nearest node is a leaf that does not have a child tree, break.
if (!nearest_node->GetChildCount())
break;
parent = nearest_node;
current_descendant = parent->GetFirstChild();
// Reset nearest_descendant to force the nearest node to be a descendant
// of "parent".
nearest_descendant = nullptr;
}
}
}
return nearest_node;
}
int AXPlatformNodeBase::NearestTextIndexToPoint(gfx::Point point) {
// For text objects, find the text position nearest to the point.The nearest
// index of a non-text object is implicitly 0. Text fields such as textarea
// have an embedded div inside them that holds all the text,
// GetRangeBoundsRect will correctly handle these nodes
int nearest_index = 0;
const AXCoordinateSystem coordinate_system = AXCoordinateSystem::kScreenDIPs;
const AXClippingBehavior clipping_behavior = AXClippingBehavior::kUnclipped;
// Manhattan Distance is used to provide faster distance estimates.
// get the distance from the point to the bounds of each character.
float shortest_distance = GetDelegate()
->GetInnerTextRangeBoundsRect(
0, 1, coordinate_system, clipping_behavior)
.ManhattanDistanceToPoint(point);
for (int i = 1, text_length = GetInnerText().length(); i < text_length; ++i) {
float current_distance =
GetDelegate()
->GetInnerTextRangeBoundsRect(i, i + 1, coordinate_system,
clipping_behavior)
.ManhattanDistanceToPoint(point);
if (current_distance < shortest_distance) {
shortest_distance = current_distance;
nearest_index = i;
}
}
return nearest_index;
}
std::string AXPlatformNodeBase::GetInvalidValue() const {
const AXPlatformNodeBase* target = this;
// The aria-invalid=spelling/grammar need to be exposed as text attributes for
// a range matching the visual underline representing the error.
if (static_cast<ax::mojom::InvalidState>(
target->GetIntAttribute(ax::mojom::IntAttribute::kInvalidState)) ==
ax::mojom::InvalidState::kNone &&
target->IsText() && target->GetParent()) {
// Text nodes need to reflect the invalid state of their parent object,
// otherwise spelling and grammar errors communicated through aria-invalid
// won't be reflected in text attributes.
target = static_cast<AXPlatformNodeBase*>(
FromNativeViewAccessible(target->GetParent()));
}
std::string invalid_value("");
// Note: spelling+grammar errors case is disallowed and not supported. It
// could possibly arise with aria-invalid on the ancestor of a spelling error,
// but this is not currently described in any spec and no real-world use cases
// have been found.
switch (static_cast<ax::mojom::InvalidState>(
target->GetIntAttribute(ax::mojom::IntAttribute::kInvalidState))) {
case ax::mojom::InvalidState::kNone:
case ax::mojom::InvalidState::kFalse:
break;
case ax::mojom::InvalidState::kTrue:
invalid_value = "true";
break;
case ax::mojom::InvalidState::kOther: {
if (!target->GetStringAttribute(
ax::mojom::StringAttribute::kAriaInvalidValue, &invalid_value)) {
// Set the attribute to "true", since we cannot be more specific.
invalid_value = "true";
}
break;
}
}
return invalid_value;
}
ui::TextAttributeList AXPlatformNodeBase::ComputeTextAttributes() const {
ui::TextAttributeList attributes;
// We include list markers for now, but there might be other objects that are
// auto generated.
// TODO(nektar): Compute what objects are auto-generated in Blink.
if (GetData().role == ax::mojom::Role::kListMarker)
attributes.push_back(std::make_pair("auto-generated", "true"));
int color;
if (GetIntAttribute(ax::mojom::IntAttribute::kBackgroundColor, &color)) {
unsigned int alpha = ColorGetA(color);
unsigned int red = ColorGetR(color);
unsigned int green = ColorGetG(color);
unsigned int blue = ColorGetB(color);
// Don't expose default value of pure white.
if (alpha && (red != 255 || green != 255 || blue != 255)) {
std::string color_value = "rgb(" + base::NumberToString(red) + ',' +
base::NumberToString(green) + ',' +
base::NumberToString(blue) + ')';
SanitizeTextAttributeValue(color_value, &color_value);
attributes.push_back(std::make_pair("background-color", color_value));
}
}
if (GetIntAttribute(ax::mojom::IntAttribute::kColor, &color)) {
unsigned int red = ColorGetR(color);
unsigned int green = ColorGetG(color);
unsigned int blue = ColorGetB(color);
// Don't expose default value of black.
if (red || green || blue) {
std::string color_value = "rgb(" + base::NumberToString(red) + ',' +
base::NumberToString(green) + ',' +
base::NumberToString(blue) + ')';
SanitizeTextAttributeValue(color_value, &color_value);
attributes.push_back(std::make_pair("color", color_value));
}
}
// First try to get the inherited font family name from the delegate. If we
// cannot find any name, fall back to looking the hierarchy of this node's
// AXNodeData instead.
std::string font_family(GetDelegate()->GetInheritedFontFamilyName());
if (font_family.empty()) {
font_family =
GetInheritedStringAttribute(ax::mojom::StringAttribute::kFontFamily);
}
// Attribute has no default value.
if (!font_family.empty()) {
SanitizeTextAttributeValue(font_family, &font_family);
attributes.push_back(std::make_pair("font-family", font_family));
}
std::optional<float> font_size_in_points = GetFontSizeInPoints();
// Attribute has no default value.
if (font_size_in_points) {
attributes.push_back(std::make_pair(
"font-size", base::NumberToString(*font_size_in_points) + "pt"));
}
// TODO(nektar): Add Blink support for the following attributes:
// text-line-through-mode, text-line-through-width, text-outline:false,
// text-position:baseline, text-shadow:none, text-underline-mode:continuous.
int32_t text_style = GetIntAttribute(ax::mojom::IntAttribute::kTextStyle);
if (text_style) {
if (GetData().HasTextStyle(ax::mojom::TextStyle::kBold))
attributes.push_back(std::make_pair("font-weight", "bold"));
if (GetData().HasTextStyle(ax::mojom::TextStyle::kItalic))
attributes.push_back(std::make_pair("font-style", "italic"));
if (GetData().HasTextStyle(ax::mojom::TextStyle::kLineThrough)) {
// TODO(nektar): Figure out a more specific value.
attributes.push_back(std::make_pair("text-line-through-style", "solid"));
}
if (GetData().HasTextStyle(ax::mojom::TextStyle::kUnderline)) {
// TODO(nektar): Figure out a more specific value.
attributes.push_back(std::make_pair("text-underline-style", "solid"));
}
}
// Screen readers look at the text attributes to determine if something is
// misspelled, so we need to propagate any spelling attributes from immediate
// parents of text-only objects.
std::string invalid_value = GetInvalidValue();
if (!invalid_value.empty())
attributes.push_back(std::make_pair("invalid", invalid_value));
std::string language = GetDelegate()->GetLanguage();
if (!language.empty()) {
SanitizeTextAttributeValue(language, &language);
attributes.push_back(std::make_pair("language", language));
}
auto text_direction = static_cast<ax::mojom::WritingDirection>(
GetIntAttribute(ax::mojom::IntAttribute::kTextDirection));
switch (text_direction) {
case ax::mojom::WritingDirection::kNone:
break;
case ax::mojom::WritingDirection::kLtr:
attributes.push_back(std::make_pair("writing-mode", "lr"));
break;
case ax::mojom::WritingDirection::kRtl:
attributes.push_back(std::make_pair("writing-mode", "rl"));
break;
case ax::mojom::WritingDirection::kTtb:
attributes.push_back(std::make_pair("writing-mode", "tb"));
break;
case ax::mojom::WritingDirection::kBtt:
// Not listed in the IA2 Spec.
attributes.push_back(std::make_pair("writing-mode", "bt"));
break;
}
auto text_position = static_cast<ax::mojom::TextPosition>(
GetIntAttribute(ax::mojom::IntAttribute::kTextPosition));
switch (text_position) {
case ax::mojom::TextPosition::kNone:
break;
case ax::mojom::TextPosition::kSubscript:
attributes.push_back(std::make_pair("text-position", "sub"));
break;
case ax::mojom::TextPosition::kSuperscript:
attributes.push_back(std::make_pair("text-position", "super"));
break;
}
return attributes;
}
int AXPlatformNodeBase::GetSelectionCount() const {
int max_items = GetMaxSelectableItems();
if (!max_items)
return 0;
return GetSelectedItems(max_items);
}
AXPlatformNodeBase* AXPlatformNodeBase::GetSelectedItem(
int selected_index) const {
BASE_DCHECK(selected_index >= 0);
int max_items = GetMaxSelectableItems();
if (max_items == 0)
return nullptr;
if (selected_index >= max_items)
return nullptr;
std::vector<AXPlatformNodeBase*> selected_children;
int requested_count = selected_index + 1;
int returned_count = GetSelectedItems(requested_count, &selected_children);
if (returned_count <= selected_index)
return nullptr;
BASE_DCHECK(!selected_children.empty());
BASE_DCHECK(selected_index < static_cast<int>(selected_children.size()));
return selected_children[selected_index];
}
int AXPlatformNodeBase::GetSelectedItems(
int max_items,
std::vector<AXPlatformNodeBase*>* out_selected_items) const {
int selected_count = 0;
for (auto child_iter = AXPlatformNodeChildrenBegin();
child_iter != AXPlatformNodeChildrenEnd() && selected_count < max_items;
++child_iter) {
if (!IsItemLike(child_iter->GetData().role)) {
selected_count += child_iter->GetSelectedItems(max_items - selected_count,
out_selected_items);
} else if (child_iter->GetBoolAttribute(
ax::mojom::BoolAttribute::kSelected)) {
selected_count++;
if (out_selected_items)
out_selected_items->emplace_back(child_iter.get());
}
}
return selected_count;
}
void AXPlatformNodeBase::SanitizeTextAttributeValue(const std::string& input,
std::string* output) const {
BASE_DCHECK(output);
}
std::string AXPlatformNodeBase::ComputeDetailsRoles() const {
const std::vector<int32_t>& details_ids =
GetIntListAttribute(ax::mojom::IntListAttribute::kDetailsIds);
if (details_ids.empty())
return std::string();
std::set<std::string> details_roles_set;
for (int id : details_ids) {
AXPlatformNodeBase* detail_object =
static_cast<AXPlatformNodeBase*>(delegate_->GetFromNodeID(id));
if (!detail_object)
continue;
switch (detail_object->GetData().role) {
case ax::mojom::Role::kComment:
details_roles_set.insert("comment");
break;
case ax::mojom::Role::kDefinition:
details_roles_set.insert("definition");
break;
case ax::mojom::Role::kDocEndnote:
details_roles_set.insert("doc-endnote");
break;
case ax::mojom::Role::kDocFootnote:
details_roles_set.insert("doc-footnote");
break;
case ax::mojom::Role::kGroup:
case ax::mojom::Role::kRegion: {
// These should still report comment if there are comments inside them.
constexpr int kMaxChildrenToCheck = 8;
constexpr int kMaxDepthToCheck = 4;
if (FindDescendantRoleWithMaxDepth(
detail_object, ax::mojom::Role::kComment, kMaxDepthToCheck,
kMaxChildrenToCheck)) {
details_roles_set.insert("comment");
break;
}
// FALLTHROUGH;
}
default:
// Use * to indicate some other role.
details_roles_set.insert("*");
break;
}
}
// Create space delimited list of types. The set will not be large, as there
// are not very many possible types.
std::vector<std::string> details_roles_vector(details_roles_set.begin(),
details_roles_set.end());
return base::JoinString(details_roles_vector, " ");
}
int AXPlatformNodeBase::GetMaxSelectableItems() const {
if (!GetData().HasState(ax::mojom::State::kFocusable))
return 0;
if (IsLeaf())
return 0;
if (!IsContainerWithSelectableChildren(GetData().role))
return 0;
int max_items = 1;
if (GetData().HasState(ax::mojom::State::kMultiselectable))
max_items = std::numeric_limits<int>::max();
return max_items;
}
} // namespace ui
| engine/third_party/accessibility/ax/platform/ax_platform_node_base.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_base.cc",
"repo_id": "engine",
"token_count": 27168
} | 446 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTRANGEPROVIDER_WIN_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTRANGEPROVIDER_WIN_H_
#include <atlbase.h>
#include <atlcom.h>
#include <UIAutomationCore.h>
#include "ax/ax_node_position.h"
#include "ax/ax_tree_observer.h"
#include "ax/platform/ax_platform_node_delegate.h"
#include "ax/platform/ax_platform_node_win.h"
namespace ui {
class AX_EXPORT __declspec(uuid("3071e40d-a10d-45ff-a59f-6e8e1138e2c1"))
AXPlatformNodeTextRangeProviderWin
: public CComObjectRootEx<CComMultiThreadModel>,
public ITextRangeProvider {
public:
BEGIN_COM_MAP(AXPlatformNodeTextRangeProviderWin)
COM_INTERFACE_ENTRY(ITextRangeProvider)
COM_INTERFACE_ENTRY(AXPlatformNodeTextRangeProviderWin)
END_COM_MAP()
AXPlatformNodeTextRangeProviderWin();
~AXPlatformNodeTextRangeProviderWin();
static ITextRangeProvider* CreateTextRangeProvider(
AXNodePosition::AXPositionInstance start,
AXNodePosition::AXPositionInstance end);
// Creates an instance of the class for unit tests, where AXPlatformNodes
// cannot be queried automatically from endpoints.
static ITextRangeProvider* CreateTextRangeProviderForTesting(
AXPlatformNodeWin* owner,
AXNodePosition::AXPositionInstance start,
AXNodePosition::AXPositionInstance end);
//
// ITextRangeProvider methods.
//
IFACEMETHODIMP Clone(ITextRangeProvider** clone) override;
IFACEMETHODIMP Compare(ITextRangeProvider* other, BOOL* result) override;
IFACEMETHODIMP
CompareEndpoints(TextPatternRangeEndpoint this_endpoint,
ITextRangeProvider* other,
TextPatternRangeEndpoint other_endpoint,
int* result) override;
IFACEMETHODIMP ExpandToEnclosingUnit(TextUnit unit) override;
IFACEMETHODIMP
FindAttribute(TEXTATTRIBUTEID attribute_id,
VARIANT attribute_val,
BOOL is_backward,
ITextRangeProvider** result) override;
IFACEMETHODIMP
FindText(BSTR string,
BOOL backwards,
BOOL ignore_case,
ITextRangeProvider** result) override;
IFACEMETHODIMP GetAttributeValue(TEXTATTRIBUTEID attribute_id,
VARIANT* value) override;
IFACEMETHODIMP
GetBoundingRectangles(SAFEARRAY** screen_physical_pixel_rectangles) override;
IFACEMETHODIMP
GetEnclosingElement(IRawElementProviderSimple** element) override;
IFACEMETHODIMP GetText(int max_count, BSTR* text) override;
IFACEMETHODIMP Move(TextUnit unit, int count, int* units_moved) override;
IFACEMETHODIMP
MoveEndpointByUnit(TextPatternRangeEndpoint endpoint,
TextUnit unit,
int count,
int* units_moved) override;
IFACEMETHODIMP
MoveEndpointByRange(TextPatternRangeEndpoint this_endpoint,
ITextRangeProvider* other,
TextPatternRangeEndpoint other_endpoint) override;
IFACEMETHODIMP Select() override;
IFACEMETHODIMP AddToSelection() override;
IFACEMETHODIMP RemoveFromSelection() override;
IFACEMETHODIMP ScrollIntoView(BOOL align_to_top) override;
IFACEMETHODIMP GetChildren(SAFEARRAY** children) override;
AXPlatformNodeWin* GetOwner() const;
void SetOwnerForTesting(AXPlatformNodeWin* owner);
private:
using AXPositionInstance = AXNodePosition::AXPositionInstance;
using AXPositionInstanceType = typename AXPositionInstance::element_type;
using AXNodeRange = AXRange<AXPositionInstanceType>;
friend class AXPlatformNodeTextRangeProviderTest;
friend class AXPlatformNodeTextProviderTest;
friend class AXRangePhysicalPixelRectDelegate;
static bool AtStartOfLinePredicate(const AXPositionInstance& position);
static bool AtEndOfLinePredicate(const AXPositionInstance& position);
static AXPositionInstance GetNextTextBoundaryPosition(
const AXPositionInstance& position,
ax::mojom::TextBoundary boundary_type,
AXBoundaryBehavior options,
ax::mojom::MoveDirection boundary_direction);
// Prefer these *Impl methods when functionality is needed internally. We
// should avoid calling external APIs internally as it will cause the
// histograms to become innaccurate.
HRESULT MoveEndpointByUnitImpl(TextPatternRangeEndpoint endpoint,
TextUnit unit,
int count,
int* units_moved);
IFACEMETHODIMP ExpandToEnclosingUnitImpl(TextUnit unit);
std::u16string GetString(int max_count,
size_t* appended_newlines_count = nullptr);
const AXPositionInstance& start() const { return endpoints_.GetStart(); }
const AXPositionInstance& end() const { return endpoints_.GetEnd(); }
AXPlatformNodeDelegate* GetDelegate(
const AXPositionInstanceType* position) const;
AXPlatformNodeDelegate* GetDelegate(const AXTreeID tree_id,
const AXNode::AXID node_id) const;
template <typename AnchorIterator, typename ExpandMatchLambda>
HRESULT FindAttributeRange(const TEXTATTRIBUTEID text_attribute_id,
VARIANT attribute_val,
const AnchorIterator first,
const AnchorIterator last,
ExpandMatchLambda expand_match);
AXPositionInstance MoveEndpointByCharacter(const AXPositionInstance& endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByWord(const AXPositionInstance& endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByLine(const AXPositionInstance& endpoint,
bool is_start_endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByParagraph(const AXPositionInstance& endpoint,
const bool is_start_endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByPage(const AXPositionInstance& endpoint,
const bool is_start_endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByDocument(const AXPositionInstance& endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByUnitHelper(
const AXPositionInstance& endpoint,
const ax::mojom::TextBoundary boundary_type,
const int count,
int* units_moved);
// A text range normalization is necessary to prevent a |start_| endpoint to
// be positioned at the end of an anchor when it can be at the start of the
// next anchor. After normalization, it is guaranteed that:
// * both endpoints passed by parameter are always positioned on unignored
// anchors;
// * both endpoints passed by parameter are never between a grapheme cluster;
// * if the endpoints passed by parameter create a degenerate range, both
// endpoints are on the same anchor.
// Normalization never updates the internal endpoints directly. Instead, it
// normalizes the endpoints passed by parameter.
void NormalizeTextRange(AXPositionInstance& start, AXPositionInstance& end);
static void NormalizeAsUnignoredPosition(AXPositionInstance& position);
static void NormalizeAsUnignoredTextRange(AXPositionInstance& start,
AXPositionInstance& end);
AXPlatformNodeDelegate* GetRootDelegate(const ui::AXTreeID tree_id);
AXNode* GetSelectionCommonAnchor();
void RemoveFocusFromPreviousSelectionIfNeeded(
const AXNodeRange& new_selection);
AXPlatformNodeWin* GetPlatformNodeFromAXNode(const AXNode* node) const;
AXPlatformNodeWin* GetLowestAccessibleCommonPlatformNode() const;
bool HasTextRangeOrSelectionInAtomicTextField(
const AXPositionInstance& start_position,
const AXPositionInstance& end_position) const;
void SetStart(AXPositionInstance start);
void SetEnd(AXPositionInstance end);
static bool TextAttributeIsArrayType(TEXTATTRIBUTEID attribute_id);
static bool TextAttributeIsUiaReservedValue(
const base::win::VariantVector& vector);
static bool ShouldReleaseTextAttributeAsSafearray(
TEXTATTRIBUTEID attribute_id,
const base::win::VariantVector& vector);
Microsoft::WRL::ComPtr<AXPlatformNodeWin> owner_for_test_;
// The TextRangeEndpoints class has the responsibility of keeping the
// endpoints of the range valid or nullify them when it can't find a valid
// alternative.
//
// An endpoint can become invalid when
// A. the node it's on gets deleted,
// B. when an ancestor node gets deleted, deleting the subtree our endpoint
// is on, or
// C. when a descendant node gets deleted, potentially rendering the
// position invalid due to a smaller MaxTextOffset value (for a text
// position) or fewer child nodes (for a tree position).
//
// In all cases, our approach to resolve the endpoints to valid positions
// takes two steps:
// 1. Move the endpoint to an equivalent ancestor position before the node
// gets deleted - we can't move the position once the node it's on is
// deleted since this position would already be considered invalid.
// 2. Call AsValidPosition on that new position once the node is deleted -
// calling this function before the node gets deleted wouldn't do much
// since our position would still be considered valid at this point.
//
// Because AsValidPosition can potentially be expensive, we only want to run
// it when necessary. For this reason, we store the node ID and tree ID that
// causes the first step to happen and only run the second step in
// OnNodeDeleted for the corresponding node deletion. When OnNodeDeleted is
// called, the |start_| and |end_| endpoints have already been moved up to an
// ancestor that is still part of the tree. This is to ensure that we don't
// have to read the node/tree structure of the deleted node in that function -
// which would likely result in a crash.
//
// Both scenarios A and B are fixed by this approach (by the implementation of
// OnSubtreeWillBeDeleted), but we still have work to do to fix scenario C.
// This case, in theory, would only require the second step to ensure that the
// position is always valid but computing whether node is part of the subtree
// of the endpoint we're on would be very expensive. Furthermore, because the
// endpoints are generally on leaf nodes, the scenario is unlikely - we
// haven't heard of issues caused by this scenario yet. Eventually, we might
// be able to scope the fix to specific use cases, like when the range is on
// UIA embedded object (e.g. button, select, etc.)
//
// ***
//
// Why we can't use a ScopedObserver here:
// We tried using a ScopedObserver instead of a simple observer in this case,
// but there appears to be a problem with the lifetime of the referenced
// AXTreeManager in the ScopedObserver. The AXTreeManager can get deleted
// before the TextRangeEndpoints does, so when the destructor of the
// ScopedObserver calls ScopedObserver::RemoveAll on an already deleted
// AXTreeManager, it crashes.
class TextRangeEndpoints : public AXTreeObserver {
public:
TextRangeEndpoints();
~TextRangeEndpoints() override;
const AXPositionInstance& GetStart() const { return start_; }
const AXPositionInstance& GetEnd() const { return end_; }
void SetStart(AXPositionInstance new_start);
void SetEnd(AXPositionInstance new_end);
void AddObserver(const AXTreeID tree_id);
void RemoveObserver(const AXTreeID tree_id);
void OnSubtreeWillBeDeleted(AXTree* tree, AXNode* node) override;
void OnNodeDeleted(AXTree* tree, AXNode::AXID node_id) override;
private:
struct DeletionOfInterest {
AXTreeID tree_id;
AXNode::AXID node_id;
};
void AdjustEndpointForSubtreeDeletion(AXTree* tree,
const AXNode* const node,
bool is_start_endpoint);
AXPositionInstance start_;
AXPositionInstance end_;
std::optional<DeletionOfInterest> validation_necessary_for_start_;
std::optional<DeletionOfInterest> validation_necessary_for_end_;
};
TextRangeEndpoints endpoints_;
};
// Optionally case-insensitive or reverse string search.
//
// Exposed as non-static for use in testing.
bool StringSearch(std::u16string_view search_string,
std::u16string_view find_in,
size_t* find_start,
size_t* find_length,
bool ignore_case,
bool backwards);
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTRANGEPROVIDER_WIN_H_
| engine/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win.h",
"repo_id": "engine",
"token_count": 4989
} | 447 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "test_ax_node_wrapper.h"
#include <map>
#include <utility>
#include "ax/ax_action_data.h"
#include "ax/ax_role_properties.h"
#include "ax/ax_table_info.h"
#include "ax/ax_tree_observer.h"
#include "base/numerics/ranges.h"
#include "base/string_utils.h"
#include "gfx/geometry/rect_conversions.h"
namespace ui {
namespace {
// A global map from AXNodes to TestAXNodeWrappers.
std::map<AXNode::AXID, TestAXNodeWrapper*> g_node_id_to_wrapper_map;
// A global coordinate offset.
gfx::Vector2d g_offset;
// A global scale factor.
float g_scale_factor = 1.0;
// A global map that stores which node is focused on a determined tree.
// - If a tree has no node being focused, there shouldn't be any entry on the
// map associated with such tree, i.e. a pair {tree, nullptr} is invalid.
// - For testing purposes, assume there is a single node being focused in the
// entire tree and if such node is deleted, focus is completely lost.
std::map<AXTree*, AXNode*> g_focused_node_in_tree;
// A global indicating the last node which ShowContextMenu was called from.
AXNode* g_node_from_last_show_context_menu;
// A global indicating the last node which accessibility perform action
// default action was called from.
AXNode* g_node_from_last_default_action;
// A global indicating that AXPlatformNodeDelegate objects are web content.
bool g_is_web_content = false;
// A map of hit test results - a map from source node ID to destination node
// ID.
std::map<AXNode::AXID, AXNode::AXID> g_hit_test_result;
// A simple implementation of AXTreeObserver to catch when AXNodes are
// deleted so we can delete their wrappers.
class TestAXTreeObserver : public AXTreeObserver {
private:
void OnNodeDeleted(AXTree* tree, int32_t node_id) override {
const auto& iter = g_node_id_to_wrapper_map.find(node_id);
if (iter != g_node_id_to_wrapper_map.end()) {
TestAXNodeWrapper* wrapper = iter->second;
const auto& focus_iter = g_focused_node_in_tree.find(tree);
if (focus_iter != g_focused_node_in_tree.end() &&
focus_iter->second->id() == node_id) {
g_focused_node_in_tree.erase(tree);
}
delete wrapper;
g_node_id_to_wrapper_map.erase(node_id);
}
}
};
TestAXTreeObserver g_ax_tree_observer;
} // namespace
// static
TestAXNodeWrapper* TestAXNodeWrapper::GetOrCreate(AXTree* tree, AXNode* node) {
if (!tree || !node)
return nullptr;
if (!tree->HasObserver(&g_ax_tree_observer))
tree->AddObserver(&g_ax_tree_observer);
auto iter = g_node_id_to_wrapper_map.find(node->id());
if (iter != g_node_id_to_wrapper_map.end())
return iter->second;
TestAXNodeWrapper* wrapper = new TestAXNodeWrapper(tree, node);
g_node_id_to_wrapper_map[node->id()] = wrapper;
return wrapper;
}
// static
void TestAXNodeWrapper::SetGlobalCoordinateOffset(const gfx::Vector2d& offset) {
g_offset = offset;
}
// static
const AXNode* TestAXNodeWrapper::GetNodeFromLastShowContextMenu() {
return g_node_from_last_show_context_menu;
}
// static
const AXNode* TestAXNodeWrapper::GetNodeFromLastDefaultAction() {
return g_node_from_last_default_action;
}
// static
void TestAXNodeWrapper::SetNodeFromLastDefaultAction(AXNode* node) {
g_node_from_last_default_action = node;
}
// static
std::unique_ptr<base::AutoReset<float>> TestAXNodeWrapper::SetScaleFactor(
float value) {
return std::make_unique<base::AutoReset<float>>(&g_scale_factor, value);
}
// static
void TestAXNodeWrapper::SetGlobalIsWebContent(bool is_web_content) {
g_is_web_content = is_web_content;
}
// static
void TestAXNodeWrapper::SetHitTestResult(AXNode::AXID src_node_id,
AXNode::AXID dst_node_id) {
g_hit_test_result[src_node_id] = dst_node_id;
}
// static
void TestAXNodeWrapper::ClearHitTestResults() {
g_hit_test_result.clear();
}
TestAXNodeWrapper::~TestAXNodeWrapper() {
platform_node_->Destroy();
}
const AXNodeData& TestAXNodeWrapper::GetData() const {
return node_->data();
}
const AXTreeData& TestAXNodeWrapper::GetTreeData() const {
return tree_->data();
}
const AXTree::Selection TestAXNodeWrapper::GetUnignoredSelection() const {
return tree_->GetUnignoredSelection();
}
AXNodePosition::AXPositionInstance TestAXNodeWrapper::CreateTextPositionAt(
int offset) const {
return ui::AXNodePosition::CreateTextPosition(
GetTreeData().tree_id, node_->id(), offset,
ax::mojom::TextAffinity::kDownstream);
}
gfx::NativeViewAccessible TestAXNodeWrapper::GetNativeViewAccessible() {
return ax_platform_node()->GetNativeViewAccessible();
}
gfx::NativeViewAccessible TestAXNodeWrapper::GetParent() {
TestAXNodeWrapper* parent_wrapper =
GetOrCreate(tree_, node_->GetUnignoredParent());
return parent_wrapper
? parent_wrapper->ax_platform_node()->GetNativeViewAccessible()
: nullptr;
}
int TestAXNodeWrapper::GetChildCount() const {
return InternalChildCount();
}
gfx::NativeViewAccessible TestAXNodeWrapper::ChildAtIndex(int index) {
TestAXNodeWrapper* child_wrapper = InternalGetChild(index);
return child_wrapper
? child_wrapper->ax_platform_node()->GetNativeViewAccessible()
: nullptr;
}
gfx::Rect TestAXNodeWrapper::GetBoundsRect(
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const {
switch (coordinate_system) {
case AXCoordinateSystem::kScreenPhysicalPixels:
// For unit testing purposes, assume a device scale factor of 1 and fall
// through.
case AXCoordinateSystem::kScreenDIPs: {
// We could optionally add clipping here if ever needed.
gfx::RectF bounds = GetLocation();
bounds.Offset(g_offset);
// For test behavior only, for bounds that are offscreen we currently do
// not apply clipping to the bounds but we still return the offscreen
// status.
if (offscreen_result) {
*offscreen_result = DetermineOffscreenResult(bounds);
}
return gfx::ToEnclosingRect(bounds);
}
case AXCoordinateSystem::kRootFrame:
case AXCoordinateSystem::kFrame:
BASE_UNREACHABLE();
return gfx::Rect();
}
}
gfx::Rect TestAXNodeWrapper::GetInnerTextRangeBoundsRect(
const int start_offset,
const int end_offset,
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const {
switch (coordinate_system) {
case AXCoordinateSystem::kScreenPhysicalPixels:
// For unit testing purposes, assume a device scale factor of 1 and fall
// through.
case AXCoordinateSystem::kScreenDIPs: {
gfx::RectF bounds = GetLocation();
// This implementation currently only deals with text node that has role
// kInlineTextBox and kStaticText.
// For test purposes, assume node with kStaticText always has a single
// child with role kInlineTextBox.
if (GetData().role == ax::mojom::Role::kInlineTextBox) {
bounds = GetInlineTextRect(start_offset, end_offset);
} else if (GetData().role == ax::mojom::Role::kStaticText &&
InternalChildCount() > 0) {
TestAXNodeWrapper* child = InternalGetChild(0);
if (child != nullptr &&
child->GetData().role == ax::mojom::Role::kInlineTextBox) {
bounds = child->GetInlineTextRect(start_offset, end_offset);
}
}
bounds.Offset(g_offset);
// For test behavior only, for bounds that are offscreen we currently do
// not apply clipping to the bounds but we still return the offscreen
// status.
if (offscreen_result) {
*offscreen_result = DetermineOffscreenResult(bounds);
}
return gfx::ToEnclosingRect(bounds);
}
case AXCoordinateSystem::kRootFrame:
case AXCoordinateSystem::kFrame:
BASE_UNREACHABLE();
return gfx::Rect();
}
}
gfx::Rect TestAXNodeWrapper::GetHypertextRangeBoundsRect(
const int start_offset,
const int end_offset,
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const {
switch (coordinate_system) {
case AXCoordinateSystem::kScreenPhysicalPixels:
// For unit testing purposes, assume a device scale factor of 1 and fall
// through.
case AXCoordinateSystem::kScreenDIPs: {
// Ignoring start, len, and clipped, as there's no clean way to map these
// via unit tests.
gfx::RectF bounds = GetLocation();
bounds.Offset(g_offset);
return gfx::ToEnclosingRect(bounds);
}
case AXCoordinateSystem::kRootFrame:
case AXCoordinateSystem::kFrame:
BASE_UNREACHABLE();
return gfx::Rect();
}
}
TestAXNodeWrapper* TestAXNodeWrapper::HitTestSyncInternal(int x, int y) {
if (g_hit_test_result.find(node_->id()) != g_hit_test_result.end()) {
int result_id = g_hit_test_result[node_->id()];
AXNode* result_node = tree_->GetFromId(result_id);
return GetOrCreate(tree_, result_node);
}
// Here we find the deepest child whose bounding box contains the given point.
// The assumptions are that there are no overlapping bounding rects and that
// all children have smaller bounding rects than their parents.
if (!GetClippedScreenBoundsRect().Contains(gfx::Rect(x, y, 0, 0)))
return nullptr;
for (int i = 0; i < GetChildCount(); i++) {
TestAXNodeWrapper* child = GetOrCreate(tree_, node_->children()[i]);
if (!child)
return nullptr;
TestAXNodeWrapper* result = child->HitTestSyncInternal(x, y);
if (result) {
return result;
}
}
return this;
}
gfx::NativeViewAccessible TestAXNodeWrapper::HitTestSync(
int screen_physical_pixel_x,
int screen_physical_pixel_y) const {
const TestAXNodeWrapper* wrapper =
const_cast<TestAXNodeWrapper*>(this)->HitTestSyncInternal(
screen_physical_pixel_x / g_scale_factor,
screen_physical_pixel_y / g_scale_factor);
return wrapper ? wrapper->ax_platform_node()->GetNativeViewAccessible()
: nullptr;
}
gfx::NativeViewAccessible TestAXNodeWrapper::GetFocus() {
auto focused = g_focused_node_in_tree.find(tree_);
if (focused != g_focused_node_in_tree.end() &&
focused->second->IsDescendantOf(node_)) {
return GetOrCreate(tree_, focused->second)
->ax_platform_node()
->GetNativeViewAccessible();
}
return nullptr;
}
bool TestAXNodeWrapper::IsMinimized() const {
return minimized_;
}
bool TestAXNodeWrapper::IsWebContent() const {
return g_is_web_content;
}
// Walk the AXTree and ensure that all wrappers are created
void TestAXNodeWrapper::BuildAllWrappers(AXTree* tree, AXNode* node) {
for (auto* child : node->children()) {
TestAXNodeWrapper::GetOrCreate(tree, child);
BuildAllWrappers(tree, child);
}
}
void TestAXNodeWrapper::ResetNativeEventTarget() {
native_event_target_ = gfx::kNullAcceleratedWidget;
}
AXPlatformNode* TestAXNodeWrapper::GetFromNodeID(int32_t id) {
// Force creating all of the wrappers for this tree.
BuildAllWrappers(tree_, node_);
const auto iter = g_node_id_to_wrapper_map.find(id);
if (iter != g_node_id_to_wrapper_map.end())
return iter->second->ax_platform_node();
return nullptr;
}
AXPlatformNode* TestAXNodeWrapper::GetFromTreeIDAndNodeID(
const ui::AXTreeID& ax_tree_id,
int32_t id) {
// TestAXNodeWrapper only supports one accessibility tree.
// Additional work would need to be done to support multiple trees.
BASE_CHECK(GetTreeData().tree_id == ax_tree_id);
return GetFromNodeID(id);
}
int TestAXNodeWrapper::GetIndexInParent() {
return node_ ? static_cast<int>(node_->GetUnignoredIndexInParent()) : -1;
}
void TestAXNodeWrapper::ReplaceIntAttribute(int32_t node_id,
ax::mojom::IntAttribute attribute,
int32_t value) {
if (!tree_)
return;
AXNode* node = tree_->GetFromId(node_id);
if (!node)
return;
AXNodeData new_data = node->data();
std::vector<std::pair<ax::mojom::IntAttribute, int32_t>>& attributes =
new_data.int_attributes;
auto it = std::remove_if(
attributes.begin(), attributes.end(),
[attribute](auto& pair) { return pair.first == attribute; });
attributes.erase(it, attributes.end());
new_data.AddIntAttribute(attribute, value);
node->SetData(new_data);
}
void TestAXNodeWrapper::ReplaceFloatAttribute(
ax::mojom::FloatAttribute attribute,
float value) {
AXNodeData new_data = GetData();
std::vector<std::pair<ax::mojom::FloatAttribute, float>>& attributes =
new_data.float_attributes;
auto it = std::remove_if(
attributes.begin(), attributes.end(),
[attribute](auto& pair) { return pair.first == attribute; });
attributes.erase(it, attributes.end());
new_data.AddFloatAttribute(attribute, value);
node_->SetData(new_data);
}
void TestAXNodeWrapper::ReplaceBoolAttribute(ax::mojom::BoolAttribute attribute,
bool value) {
AXNodeData new_data = GetData();
std::vector<std::pair<ax::mojom::BoolAttribute, bool>>& attributes =
new_data.bool_attributes;
auto it = std::remove_if(
attributes.begin(), attributes.end(),
[attribute](auto& pair) { return pair.first == attribute; });
attributes.erase(it, attributes.end());
new_data.AddBoolAttribute(attribute, value);
node_->SetData(new_data);
}
void TestAXNodeWrapper::ReplaceStringAttribute(
ax::mojom::StringAttribute attribute,
std::string value) {
AXNodeData new_data = GetData();
std::vector<std::pair<ax::mojom::StringAttribute, std::string>>& attributes =
new_data.string_attributes;
auto it = std::remove_if(
attributes.begin(), attributes.end(),
[attribute](auto& pair) { return pair.first == attribute; });
attributes.erase(it, attributes.end());
new_data.AddStringAttribute(attribute, value);
node_->SetData(new_data);
}
void TestAXNodeWrapper::ReplaceTreeDataTextSelection(int32_t anchor_node_id,
int32_t anchor_offset,
int32_t focus_node_id,
int32_t focus_offset) {
if (!tree_)
return;
AXTreeData new_tree_data = GetTreeData();
new_tree_data.sel_anchor_object_id = anchor_node_id;
new_tree_data.sel_anchor_offset = anchor_offset;
new_tree_data.sel_focus_object_id = focus_node_id;
new_tree_data.sel_focus_offset = focus_offset;
tree_->UpdateData(new_tree_data);
}
bool TestAXNodeWrapper::IsTable() const {
return node_->IsTable();
}
std::optional<int> TestAXNodeWrapper::GetTableRowCount() const {
return node_->GetTableRowCount();
}
std::optional<int> TestAXNodeWrapper::GetTableColCount() const {
return node_->GetTableColCount();
}
std::optional<int> TestAXNodeWrapper::GetTableAriaRowCount() const {
return node_->GetTableAriaRowCount();
}
std::optional<int> TestAXNodeWrapper::GetTableAriaColCount() const {
return node_->GetTableAriaColCount();
}
std::optional<int> TestAXNodeWrapper::GetTableCellCount() const {
return node_->GetTableCellCount();
}
std::optional<bool> TestAXNodeWrapper::GetTableHasColumnOrRowHeaderNode()
const {
return node_->GetTableHasColumnOrRowHeaderNode();
}
std::vector<AXNode::AXID> TestAXNodeWrapper::GetColHeaderNodeIds() const {
return node_->GetTableColHeaderNodeIds();
}
std::vector<AXNode::AXID> TestAXNodeWrapper::GetColHeaderNodeIds(
int col_index) const {
return node_->GetTableColHeaderNodeIds(col_index);
}
std::vector<AXNode::AXID> TestAXNodeWrapper::GetRowHeaderNodeIds() const {
return node_->GetTableCellRowHeaderNodeIds();
}
std::vector<AXNode::AXID> TestAXNodeWrapper::GetRowHeaderNodeIds(
int row_index) const {
return node_->GetTableRowHeaderNodeIds(row_index);
}
bool TestAXNodeWrapper::IsTableRow() const {
return node_->IsTableRow();
}
std::optional<int> TestAXNodeWrapper::GetTableRowRowIndex() const {
return node_->GetTableRowRowIndex();
}
bool TestAXNodeWrapper::IsTableCellOrHeader() const {
return node_->IsTableCellOrHeader();
}
std::optional<int> TestAXNodeWrapper::GetTableCellIndex() const {
return node_->GetTableCellIndex();
}
std::optional<int> TestAXNodeWrapper::GetTableCellColIndex() const {
return node_->GetTableCellColIndex();
}
std::optional<int> TestAXNodeWrapper::GetTableCellRowIndex() const {
return node_->GetTableCellRowIndex();
}
std::optional<int> TestAXNodeWrapper::GetTableCellColSpan() const {
return node_->GetTableCellColSpan();
}
std::optional<int> TestAXNodeWrapper::GetTableCellRowSpan() const {
return node_->GetTableCellRowSpan();
}
std::optional<int> TestAXNodeWrapper::GetTableCellAriaColIndex() const {
return node_->GetTableCellAriaColIndex();
}
std::optional<int> TestAXNodeWrapper::GetTableCellAriaRowIndex() const {
return node_->GetTableCellAriaRowIndex();
}
std::optional<int32_t> TestAXNodeWrapper::GetCellId(int row_index,
int col_index) const {
AXNode* cell = node_->GetTableCellFromCoords(row_index, col_index);
if (!cell)
return std::nullopt;
return cell->id();
}
gfx::AcceleratedWidget
TestAXNodeWrapper::GetTargetForNativeAccessibilityEvent() {
return native_event_target_;
}
std::optional<int32_t> TestAXNodeWrapper::CellIndexToId(int cell_index) const {
AXNode* cell = node_->GetTableCellFromIndex(cell_index);
if (!cell)
return std::nullopt;
return cell->id();
}
bool TestAXNodeWrapper::IsCellOrHeaderOfARIATable() const {
return node_->IsCellOrHeaderOfARIATable();
}
bool TestAXNodeWrapper::IsCellOrHeaderOfARIAGrid() const {
return node_->IsCellOrHeaderOfARIAGrid();
}
bool TestAXNodeWrapper::AccessibilityPerformAction(
const ui::AXActionData& data) {
switch (data.action) {
case ax::mojom::Action::kScrollToPoint:
g_offset = gfx::Vector2d(data.target_point.x(), data.target_point.y());
return true;
case ax::mojom::Action::kSetScrollOffset: {
int scroll_x_min =
GetData().GetIntAttribute(ax::mojom::IntAttribute::kScrollXMin);
int scroll_x_max =
GetData().GetIntAttribute(ax::mojom::IntAttribute::kScrollXMax);
int scroll_y_min =
GetData().GetIntAttribute(ax::mojom::IntAttribute::kScrollYMin);
int scroll_y_max =
GetData().GetIntAttribute(ax::mojom::IntAttribute::kScrollYMax);
int scroll_x =
base::ClampToRange(data.target_point.x(), scroll_x_min, scroll_x_max);
int scroll_y =
base::ClampToRange(data.target_point.y(), scroll_y_min, scroll_y_max);
ReplaceIntAttribute(node_->id(), ax::mojom::IntAttribute::kScrollX,
scroll_x);
ReplaceIntAttribute(node_->id(), ax::mojom::IntAttribute::kScrollY,
scroll_y);
return true;
}
case ax::mojom::Action::kScrollToMakeVisible: {
auto offset = node_->data().relative_bounds.bounds.OffsetFromOrigin();
g_offset = gfx::Vector2d(-offset.x(), -offset.y());
return true;
}
case ax::mojom::Action::kDoDefault: {
// If a default action such as a click is performed on an element, it
// could result in a selected state change. In which case, the element's
// selected state no longer comes from focus action, so we should set
// |kSelectedFromFocus| to false.
if (GetData().HasBoolAttribute(
ax::mojom::BoolAttribute::kSelectedFromFocus))
ReplaceBoolAttribute(ax::mojom::BoolAttribute::kSelectedFromFocus,
false);
switch (GetData().role) {
case ax::mojom::Role::kListBoxOption:
case ax::mojom::Role::kCell: {
bool current_value =
GetData().GetBoolAttribute(ax::mojom::BoolAttribute::kSelected);
ReplaceBoolAttribute(ax::mojom::BoolAttribute::kSelected,
!current_value);
break;
}
case ax::mojom::Role::kRadioButton:
case ax::mojom::Role::kMenuItemRadio: {
if (GetData().GetCheckedState() == ax::mojom::CheckedState::kTrue)
ReplaceIntAttribute(
node_->id(), ax::mojom::IntAttribute::kCheckedState,
static_cast<int32_t>(ax::mojom::CheckedState::kFalse));
else if (GetData().GetCheckedState() ==
ax::mojom::CheckedState::kFalse)
ReplaceIntAttribute(
node_->id(), ax::mojom::IntAttribute::kCheckedState,
static_cast<int32_t>(ax::mojom::CheckedState::kTrue));
break;
}
default:
break;
}
SetNodeFromLastDefaultAction(node_);
return true;
}
case ax::mojom::Action::kSetValue:
if (GetData().IsRangeValueSupported()) {
ReplaceFloatAttribute(ax::mojom::FloatAttribute::kValueForRange,
std::stof(data.value));
} else if (GetData().role == ax::mojom::Role::kTextField) {
ReplaceStringAttribute(ax::mojom::StringAttribute::kValue, data.value);
}
return true;
case ax::mojom::Action::kSetSelection: {
ReplaceIntAttribute(data.anchor_node_id,
ax::mojom::IntAttribute::kTextSelStart,
data.anchor_offset);
ReplaceIntAttribute(data.focus_node_id,
ax::mojom::IntAttribute::kTextSelEnd,
data.focus_offset);
ReplaceTreeDataTextSelection(data.anchor_node_id, data.anchor_offset,
data.focus_node_id, data.focus_offset);
return true;
}
case ax::mojom::Action::kFocus: {
g_focused_node_in_tree[tree_] = node_;
// The platform has select follows focus behavior:
// https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_selection_follows_focus
// For test purpose, we support select follows focus for all elements, and
// not just single-selection container elements.
if (SupportsSelected(GetData().role)) {
ReplaceBoolAttribute(ax::mojom::BoolAttribute::kSelected, true);
ReplaceBoolAttribute(ax::mojom::BoolAttribute::kSelectedFromFocus,
true);
}
return true;
}
case ax::mojom::Action::kShowContextMenu:
g_node_from_last_show_context_menu = node_;
return true;
default:
return true;
}
}
std::u16string TestAXNodeWrapper::GetLocalizedRoleDescriptionForUnlabeledImage()
const {
return base::ASCIIToUTF16("Unlabeled image");
}
std::u16string TestAXNodeWrapper::GetLocalizedStringForLandmarkType() const {
const AXNodeData& data = GetData();
switch (data.role) {
case ax::mojom::Role::kBanner:
case ax::mojom::Role::kHeader:
return base::ASCIIToUTF16("banner");
case ax::mojom::Role::kComplementary:
return base::ASCIIToUTF16("complementary");
case ax::mojom::Role::kContentInfo:
case ax::mojom::Role::kFooter:
return base::ASCIIToUTF16("content information");
case ax::mojom::Role::kRegion:
case ax::mojom::Role::kSection:
if (data.HasStringAttribute(ax::mojom::StringAttribute::kName))
return base::ASCIIToUTF16("region");
default:
return {};
}
}
std::u16string TestAXNodeWrapper::GetLocalizedStringForRoleDescription() const {
const AXNodeData& data = GetData();
switch (data.role) {
case ax::mojom::Role::kArticle:
return base::ASCIIToUTF16("article");
case ax::mojom::Role::kAudio:
return base::ASCIIToUTF16("audio");
case ax::mojom::Role::kCode:
return base::ASCIIToUTF16("code");
case ax::mojom::Role::kColorWell:
return base::ASCIIToUTF16("color picker");
case ax::mojom::Role::kContentInfo:
return base::ASCIIToUTF16("content information");
case ax::mojom::Role::kDate:
return base::ASCIIToUTF16("date picker");
case ax::mojom::Role::kDateTime: {
std::string input_type;
if (data.GetStringAttribute(ax::mojom::StringAttribute::kInputType,
&input_type)) {
if (input_type == "datetime-local") {
return base::ASCIIToUTF16("local date and time picker");
} else if (input_type == "week") {
return base::ASCIIToUTF16("week picker");
}
}
return {};
}
case ax::mojom::Role::kDetails:
return base::ASCIIToUTF16("details");
case ax::mojom::Role::kEmphasis:
return base::ASCIIToUTF16("emphasis");
case ax::mojom::Role::kFigure:
return base::ASCIIToUTF16("figure");
case ax::mojom::Role::kFooter:
case ax::mojom::Role::kFooterAsNonLandmark:
return base::ASCIIToUTF16("footer");
case ax::mojom::Role::kHeader:
case ax::mojom::Role::kHeaderAsNonLandmark:
return base::ASCIIToUTF16("header");
case ax::mojom::Role::kMark:
return base::ASCIIToUTF16("highlight");
case ax::mojom::Role::kMeter:
return base::ASCIIToUTF16("meter");
case ax::mojom::Role::kSearchBox:
return base::ASCIIToUTF16("search box");
case ax::mojom::Role::kSection: {
if (data.HasStringAttribute(ax::mojom::StringAttribute::kName))
return base::ASCIIToUTF16("section");
return {};
}
case ax::mojom::Role::kStatus:
return base::ASCIIToUTF16("output");
case ax::mojom::Role::kStrong:
return base::ASCIIToUTF16("strong");
case ax::mojom::Role::kTextField: {
std::string input_type;
if (data.GetStringAttribute(ax::mojom::StringAttribute::kInputType,
&input_type)) {
if (input_type == "email") {
return base::ASCIIToUTF16("email");
} else if (input_type == "tel") {
return base::ASCIIToUTF16("telephone");
} else if (input_type == "url") {
return base::ASCIIToUTF16("url");
}
}
return {};
}
case ax::mojom::Role::kTime:
return base::ASCIIToUTF16("time");
default:
return {};
}
}
std::u16string TestAXNodeWrapper::GetLocalizedStringForImageAnnotationStatus(
ax::mojom::ImageAnnotationStatus status) const {
switch (status) {
case ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation:
return base::ASCIIToUTF16(
"To get missing image descriptions, open the context menu.");
case ax::mojom::ImageAnnotationStatus::kAnnotationPending:
return base::ASCIIToUTF16("Getting description...");
case ax::mojom::ImageAnnotationStatus::kAnnotationAdult:
return base::ASCIIToUTF16(
"Appears to contain adult content. No description available.");
case ax::mojom::ImageAnnotationStatus::kAnnotationEmpty:
case ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed:
return base::ASCIIToUTF16("No description available.");
case ax::mojom::ImageAnnotationStatus::kNone:
case ax::mojom::ImageAnnotationStatus::kWillNotAnnotateDueToScheme:
case ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation:
case ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation:
case ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded:
return std::u16string();
}
BASE_UNREACHABLE();
return std::u16string();
}
std::u16string TestAXNodeWrapper::GetStyleNameAttributeAsLocalizedString()
const {
AXNode* current_node = node_;
while (current_node) {
if (current_node->data().role == ax::mojom::Role::kMark)
return base::ASCIIToUTF16("mark");
current_node = current_node->parent();
}
return std::u16string();
}
bool TestAXNodeWrapper::ShouldIgnoreHoveredStateForTesting() {
return true;
}
bool TestAXNodeWrapper::HasVisibleCaretOrSelection() const {
ui::AXTree::Selection unignored_selection = GetUnignoredSelection();
int32_t focus_id = unignored_selection.focus_object_id;
AXNode* focus_object = tree_->GetFromId(focus_id);
if (!focus_object)
return false;
// Selection or caret will be visible in a focused editable area.
if (GetData().HasState(ax::mojom::State::kEditable)) {
return GetData().IsPlainTextField() ? focus_object == node_
: focus_object->IsDescendantOf(node_);
}
// The selection will be visible in non-editable content only if it is not
// collapsed into a caret.
return (focus_id != unignored_selection.anchor_object_id ||
unignored_selection.focus_offset !=
unignored_selection.anchor_offset) &&
focus_object->IsDescendantOf(node_);
}
std::set<AXPlatformNode*> TestAXNodeWrapper::GetReverseRelations(
ax::mojom::IntAttribute attr) {
BASE_DCHECK(IsNodeIdIntAttribute(attr));
return GetNodesForNodeIds(tree_->GetReverseRelations(attr, GetData().id));
}
std::set<AXPlatformNode*> TestAXNodeWrapper::GetReverseRelations(
ax::mojom::IntListAttribute attr) {
BASE_DCHECK(IsNodeIdIntListAttribute(attr));
return GetNodesForNodeIds(tree_->GetReverseRelations(attr, GetData().id));
}
const ui::AXUniqueId& TestAXNodeWrapper::GetUniqueId() const {
return unique_id_;
}
TestAXNodeWrapper::TestAXNodeWrapper(AXTree* tree, AXNode* node)
: tree_(tree), node_(node), platform_node_(AXPlatformNode::Create(this)) {
#if defined(OS_WIN)
native_event_target_ = gfx::kMockAcceleratedWidget;
#else
native_event_target_ = gfx::kNullAcceleratedWidget;
#endif
}
bool TestAXNodeWrapper::IsOrderedSetItem() const {
return node_->IsOrderedSetItem();
}
bool TestAXNodeWrapper::IsOrderedSet() const {
return node_->IsOrderedSet();
}
std::optional<int> TestAXNodeWrapper::GetPosInSet() const {
return node_->GetPosInSet();
}
std::optional<int> TestAXNodeWrapper::GetSetSize() const {
return node_->GetSetSize();
}
gfx::RectF TestAXNodeWrapper::GetLocation() const {
return GetData().relative_bounds.bounds;
}
int TestAXNodeWrapper::InternalChildCount() const {
return static_cast<int>(node_->GetUnignoredChildCount());
}
TestAXNodeWrapper* TestAXNodeWrapper::InternalGetChild(int index) const {
BASE_CHECK(index >= 0);
BASE_CHECK(index < InternalChildCount());
return GetOrCreate(
tree_, node_->GetUnignoredChildAtIndex(static_cast<size_t>(index)));
}
// Recursive helper function for GetUIADescendants. Aggregates all of the
// descendants for a given node within the descendants vector.
void TestAXNodeWrapper::UIADescendants(
const AXNode* node,
std::vector<gfx::NativeViewAccessible>* descendants) const {
if (ShouldHideChildrenForUIA(node))
return;
for (auto it = node->UnignoredChildrenBegin();
it != node->UnignoredChildrenEnd(); ++it) {
descendants->emplace_back(ax_platform_node()
->GetDelegate()
->GetFromNodeID(it->id())
->GetNativeViewAccessible());
UIADescendants(it.get(), descendants);
}
}
const std::vector<gfx::NativeViewAccessible>
TestAXNodeWrapper::GetUIADescendants() const {
std::vector<gfx::NativeViewAccessible> descendants;
UIADescendants(node_, &descendants);
return descendants;
}
// static
// Needs to stay in sync with AXPlatformNodeWin::ShouldHideChildrenForUIA.
bool TestAXNodeWrapper::ShouldHideChildrenForUIA(const AXNode* node) {
if (!node)
return false;
auto role = node->data().role;
if (ui::HasPresentationalChildren(role))
return true;
switch (role) {
case ax::mojom::Role::kLink:
case ax::mojom::Role::kTextField:
return true;
default:
return false;
}
}
gfx::RectF TestAXNodeWrapper::GetInlineTextRect(const int start_offset,
const int end_offset) const {
BASE_DCHECK(start_offset >= 0 && end_offset >= 0 &&
start_offset <= end_offset);
const std::vector<int32_t>& character_offsets = GetData().GetIntListAttribute(
ax::mojom::IntListAttribute::kCharacterOffsets);
gfx::RectF location = GetLocation();
gfx::RectF bounds;
switch (static_cast<ax::mojom::WritingDirection>(
GetData().GetIntAttribute(ax::mojom::IntAttribute::kTextDirection))) {
// Currently only kNone and kLtr are supported text direction.
case ax::mojom::WritingDirection::kNone:
case ax::mojom::WritingDirection::kLtr: {
int start_pixel_offset =
start_offset > 0 ? character_offsets[start_offset - 1] : location.x();
int end_pixel_offset =
end_offset > 0 ? character_offsets[end_offset - 1] : location.x();
bounds =
gfx::RectF(start_pixel_offset, location.y(),
end_pixel_offset - start_pixel_offset, location.height());
break;
}
default:
BASE_UNREACHABLE();
}
return bounds;
}
AXOffscreenResult TestAXNodeWrapper::DetermineOffscreenResult(
gfx::RectF bounds) const {
if (!tree_ || !tree_->root())
return AXOffscreenResult::kOnscreen;
const AXNodeData& root_web_area_node_data = tree_->root()->data();
gfx::RectF root_web_area_bounds =
root_web_area_node_data.relative_bounds.bounds;
// For testing, we only look at the current node's bound relative to the root
// web area bounds to determine offscreen status. We currently do not look at
// the bounds of the immediate parent of the node for determining offscreen
// status.
// We only determine offscreen result if the root web area bounds is actually
// set in the test. We default the offscreen result of every other situation
// to AXOffscreenResult::kOnscreen.
if (!root_web_area_bounds.IsEmpty()) {
bounds.Intersect(root_web_area_bounds);
if (bounds.IsEmpty())
return AXOffscreenResult::kOffscreen;
}
return AXOffscreenResult::kOnscreen;
}
} // namespace ui
| engine/third_party/accessibility/ax/platform/test_ax_node_wrapper.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/test_ax_node_wrapper.cc",
"repo_id": "engine",
"token_count": 13281
} | 448 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "logging.h"
#include <algorithm>
#include <iostream>
#include "ax_build/build_config.h"
// #include "log_settings.h"
#if defined(OS_ANDROID)
#include <android/log.h>
#elif defined(OS_IOS)
#include <syslog.h>
#endif
namespace base {
namespace {
const char* StripPath(const char* path) {
auto* p = strrchr(path, '/');
if (p) {
return p + 1;
}
return path;
}
} // namespace
LogMessage::LogMessage(const char* file,
int line,
const char* condition,
bool killProcess)
: file_(file), line_(line), killProcess_(killProcess) {
stream_ << "[ERROR:" << StripPath(file_) << "(" << line_ << ")] ";
if (condition) {
stream_ << "Check failed: " << condition << ". ";
}
}
LogMessage::~LogMessage() {
stream_ << std::endl;
#if defined(OS_ANDROID)
android_LogPriority priority = ANDROID_LOG_ERROR __android_log_write(
priority, "flutter", stream_.str().c_str());
#elif defined(OS_IOS)
syslog(LOG_ALERT, "%s", stream_.str().c_str());
#else
std::cerr << stream_.str();
std::cerr.flush();
#endif
if (killProcess_)
KillProcess();
}
void KillProcess() {
abort();
}
} // namespace base
| engine/third_party/accessibility/base/logging.cc/0 | {
"file_path": "engine/third_party/accessibility/base/logging.cc",
"repo_id": "engine",
"token_count": 550
} | 449 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_NUMERICS_SAFE_MATH_H_
#define BASE_NUMERICS_SAFE_MATH_H_
#include "base/numerics/checked_math.h"
#include "base/numerics/clamped_math.h"
#include "base/numerics/safe_conversions.h"
#endif // BASE_NUMERICS_SAFE_MATH_H_
| engine/third_party/accessibility/base/numerics/safe_math.h/0 | {
"file_path": "engine/third_party/accessibility/base/numerics/safe_math.h",
"repo_id": "engine",
"token_count": 149
} | 450 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/win/display.h"
namespace base {
namespace win {
namespace {
template <typename T>
bool AssignProcAddress(HMODULE comBaseModule, const char* name, T*& outProc) {
outProc = reinterpret_cast<T*>(GetProcAddress(comBaseModule, name));
return *outProc != nullptr;
}
// Helper class for supporting display scale factor lookup across Windows
// versions, with fallbacks where these lookups are unavailable.
class ScaleHelperWin32 {
public:
ScaleHelperWin32();
~ScaleHelperWin32();
/// Returns the scale factor for the specified monitor. Sets |scale| to
/// SCALE_100_PERCENT if the API is not available.
HRESULT GetScaleFactorForMonitor(HMONITOR hmonitor,
DEVICE_SCALE_FACTOR* scale) const;
private:
using GetScaleFactorForMonitor_ =
HRESULT __stdcall(HMONITOR hmonitor, DEVICE_SCALE_FACTOR* scale);
GetScaleFactorForMonitor_* get_scale_factor_for_monitor_ = nullptr;
HMODULE shlib_module_ = nullptr;
bool scale_factor_for_monitor_supported_ = false;
};
ScaleHelperWin32::ScaleHelperWin32() {
if ((shlib_module_ = LoadLibraryA("Shcore.dll")) != nullptr) {
scale_factor_for_monitor_supported_ =
AssignProcAddress(shlib_module_, "GetScaleFactorForMonitor",
get_scale_factor_for_monitor_);
}
}
ScaleHelperWin32::~ScaleHelperWin32() {
if (shlib_module_ != nullptr) {
FreeLibrary(shlib_module_);
}
}
HRESULT ScaleHelperWin32::GetScaleFactorForMonitor(
HMONITOR hmonitor,
DEVICE_SCALE_FACTOR* scale) const {
if (hmonitor == nullptr || scale == nullptr) {
return E_INVALIDARG;
}
if (!scale_factor_for_monitor_supported_) {
*scale = SCALE_100_PERCENT;
return S_OK;
}
return get_scale_factor_for_monitor_(hmonitor, scale);
}
ScaleHelperWin32* GetHelper() {
static ScaleHelperWin32* helper = new ScaleHelperWin32();
return helper;
}
} // namespace
float GetScaleFactorForHWND(HWND hwnd) {
HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
DEVICE_SCALE_FACTOR scale = DEVICE_SCALE_FACTOR_INVALID;
if (SUCCEEDED(GetHelper()->GetScaleFactorForMonitor(monitor, &scale))) {
return ScaleFactorToFloat(scale);
}
return 1.0f;
}
float ScaleFactorToFloat(DEVICE_SCALE_FACTOR scale_factor) {
switch (scale_factor) {
case SCALE_100_PERCENT:
return 1.0f;
case SCALE_120_PERCENT:
return 1.2f;
case SCALE_125_PERCENT:
return 1.25f;
case SCALE_140_PERCENT:
return 1.4f;
case SCALE_150_PERCENT:
return 1.5f;
case SCALE_160_PERCENT:
return 1.6f;
case SCALE_175_PERCENT:
return 1.75f;
case SCALE_180_PERCENT:
return 1.8f;
case SCALE_200_PERCENT:
return 2.0f;
case SCALE_225_PERCENT:
return 2.25f;
case SCALE_250_PERCENT:
return 2.5f;
case SCALE_300_PERCENT:
return 3.0f;
case SCALE_350_PERCENT:
return 3.5f;
case SCALE_400_PERCENT:
return 4.0f;
case SCALE_450_PERCENT:
return 4.5f;
case SCALE_500_PERCENT:
return 5.0f;
default:
return 1.0f;
}
}
} // namespace win
} // namespace base
| engine/third_party/accessibility/base/win/display.cc/0 | {
"file_path": "engine/third_party/accessibility/base/win/display.cc",
"repo_id": "engine",
"token_count": 1337
} | 451 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_WIN_VARIANT_VECTOR_H_
#define BASE_WIN_VARIANT_VECTOR_H_
#include <objbase.h>
#include <oleauto.h>
#include <type_traits>
#include <utility>
#include <vector>
#include "base/base_export.h"
#include "base/logging.h"
#include "base/win/scoped_variant.h"
#include "base/win/variant_util.h"
namespace base {
namespace win {
// This class has RAII semantics and is used to build a vector for a specific
// OLE VARTYPE, and handles converting the data to a VARIANT or VARIANT
// SAFEARRAY. It can be populated similarly to a STL vector<T>, but without the
// compile-time requirement of knowing what element type the VariantVector will
// store. The VariantVector only allows one variant type to be stored at a time.
//
// This class can release ownership of its contents to a VARIANT, and will
// automatically allocate + populate a SAFEARRAY as needed or when explicitly
// requesting that the results be released as a SAFEARRAY.
class BASE_EXPORT VariantVector final {
public:
VariantVector();
VariantVector(VariantVector&& other);
VariantVector& operator=(VariantVector&& other);
VariantVector(const VariantVector&) = delete;
VariantVector& operator=(const VariantVector&) = delete;
~VariantVector();
bool operator==(const VariantVector& other) const;
bool operator!=(const VariantVector& other) const;
// Returns the variant type for data stored in the VariantVector.
VARTYPE Type() const { return vartype_; }
// Returns the number of elements in the VariantVector.
size_t Size() const { return vector_.size(); }
// Returns whether or not there are any elements.
bool Empty() const { return vector_.empty(); }
// Resets VariantVector to its default state, releasing any managed content.
void Reset();
// Helper template method for selecting the correct |Insert| call based
// on the underlying type that is expected for a VARTYPE.
template <VARTYPE ExpectedVartype,
std::enable_if_t<ExpectedVartype != VT_BOOL, int> = 0>
void Insert(typename internal::VariantUtil<ExpectedVartype>::Type value) {
if (vartype_ == VT_EMPTY)
vartype_ = ExpectedVartype;
AssertVartype<ExpectedVartype>();
ScopedVariant scoped_variant;
scoped_variant.Set(value);
vector_.push_back(std::move(scoped_variant));
}
// Specialize VT_BOOL to accept a bool type instead of VARIANT_BOOL,
// this is to make calling insert with VT_BOOL safer.
template <VARTYPE ExpectedVartype,
std::enable_if_t<ExpectedVartype == VT_BOOL, int> = 0>
void Insert(bool value) {
if (vartype_ == VT_EMPTY)
vartype_ = ExpectedVartype;
AssertVartype<ExpectedVartype>();
ScopedVariant scoped_variant;
scoped_variant.Set(value);
vector_.push_back(std::move(scoped_variant));
}
// Specialize VT_DATE because ScopedVariant has a separate SetDate method,
// this is because VT_R8 and VT_DATE share the same underlying type.
template <>
void Insert<VT_DATE>(typename internal::VariantUtil<VT_DATE>::Type value) {
if (vartype_ == VT_EMPTY)
vartype_ = VT_DATE;
AssertVartype<VT_DATE>();
ScopedVariant scoped_variant;
scoped_variant.SetDate(value);
vector_.push_back(std::move(scoped_variant));
}
// Populates a VARIANT based on what is stored, transferring ownership
// of managed contents.
// This is only valid when the VariantVector is empty or has a single element.
// The VariantVector is then reset.
VARIANT ReleaseAsScalarVariant();
// Populates a VARIANT as a SAFEARRAY, even if there is only one element.
// The VariantVector is then reset.
VARIANT ReleaseAsSafearrayVariant();
// Lexicographical comparison between a VariantVector and a VARIANT.
// The return value is 0 if the variants are equal, 1 if this object is
// greater than |other|, -1 if it is smaller.
int Compare(const VARIANT& other, bool ignore_case = false) const;
// Lexicographical comparison between a VariantVector and a SAFEARRAY.
int Compare(SAFEARRAY* safearray, bool ignore_case = false) const;
// Lexicographical comparison between two VariantVectors.
int Compare(const VariantVector& other, bool ignore_case = false) const;
private:
// Returns true if the current |vartype_| is compatible with |ExpectedVartype|
// for inserting into |vector_|.
template <VARTYPE ExpectedVartype>
void AssertVartype() const {
BASE_DCHECK(
internal::VariantUtil<ExpectedVartype>::IsConvertibleTo(vartype_))
<< "Type mismatch, " << ExpectedVartype << " is not convertible to "
<< Type();
}
// Creates a SAFEARRAY and populates it with the values held by each VARIANT
// in |vector_|, transferring ownership to the new SAFEARRAY.
// The VariantVector is reset when successful.
template <VARTYPE ElementVartype>
SAFEARRAY* CreateAndPopulateSafearray();
VARTYPE vartype_ = VT_EMPTY;
std::vector<ScopedVariant> vector_;
};
} // namespace win
} // namespace base
#endif // BASE_WIN_VARIANT_VECTOR_H_
| engine/third_party/accessibility/base/win/variant_vector.h/0 | {
"file_path": "engine/third_party/accessibility/base/win/variant_vector.h",
"repo_id": "engine",
"token_count": 1680
} | 452 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "rect.h"
#include <algorithm>
#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_IOS)
#include <CoreGraphics/CoreGraphics.h>
#elif defined(OS_APPLE)
#include <ApplicationServices/ApplicationServices.h>
#endif
#include "ax_build/build_config.h"
#include "base/logging.h"
#include "base/numerics/clamped_math.h"
#include "base/string_utils.h"
#include "insets.h"
namespace gfx {
#if defined(OS_WIN)
Rect::Rect(const RECT& r)
: origin_(r.left, r.top),
size_(std::abs(r.right - r.left), std::abs(r.bottom - r.top)) {}
#elif defined(OS_APPLE)
Rect::Rect(const CGRect& r)
: origin_(r.origin.x, r.origin.y), size_(r.size.width, r.size.height) {}
#endif
#if defined(OS_WIN)
RECT Rect::ToRECT() const {
RECT r;
r.left = x();
r.right = right();
r.top = y();
r.bottom = bottom();
return r;
}
#elif defined(OS_APPLE)
CGRect Rect::ToCGRect() const {
return CGRectMake(x(), y(), width(), height());
}
#endif
void AdjustAlongAxis(int dst_origin, int dst_size, int* origin, int* size) {
*size = std::min(dst_size, *size);
if (*origin < dst_origin)
*origin = dst_origin;
else
*origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
}
} // namespace gfx
namespace gfx {
// This is the per-axis heuristic for picking the most useful origin and
// width/height to represent the input range.
static void SaturatedClampRange(int min, int max, int* origin, int* span) {
if (max < min) {
*span = 0;
*origin = min;
return;
}
int effective_span = base::ClampSub(max, min);
int span_loss = base::ClampSub(max, min + effective_span);
// If the desired width is within the limits of ints, we can just
// use the simple computations to represent the range precisely.
if (span_loss == 0) {
*span = effective_span;
*origin = min;
return;
}
// Now we have to approximate. If one of min or max is close enough
// to zero we choose to represent that one precisely. The other side is
// probably practically "infinite", so we move it.
constexpr unsigned kMaxDimension = std::numeric_limits<int>::max() / 2;
if (base::SafeUnsignedAbs(max) < kMaxDimension) {
// Maintain origin + span == max.
*span = effective_span;
*origin = max - effective_span;
} else if (base::SafeUnsignedAbs(min) < kMaxDimension) {
// Maintain origin == min.
*span = effective_span;
*origin = min;
} else {
// Both are big, so keep the center.
*span = effective_span;
*origin = min + span_loss / 2;
}
}
void Rect::SetByBounds(int left, int top, int right, int bottom) {
int x, y;
int width, height;
SaturatedClampRange(left, right, &x, &width);
SaturatedClampRange(top, bottom, &y, &height);
origin_.SetPoint(x, y);
size_.SetSize(width, height);
}
void Rect::Inset(const Insets& insets) {
Inset(insets.left(), insets.top(), insets.right(), insets.bottom());
}
void Rect::Inset(int left, int top, int right, int bottom) {
origin_ += Vector2d(left, top);
// left+right might overflow/underflow, but width() - (left+right) might
// overflow as well.
set_width(base::ClampSub(width(), base::ClampAdd(left, right)));
set_height(base::ClampSub(height(), base::ClampAdd(top, bottom)));
}
void Rect::Offset(int horizontal, int vertical) {
origin_ += Vector2d(horizontal, vertical);
// Ensure that width and height remain valid.
set_width(width());
set_height(height());
}
void Rect::operator+=(const Vector2d& offset) {
origin_ += offset;
// Ensure that width and height remain valid.
set_width(width());
set_height(height());
}
void Rect::operator-=(const Vector2d& offset) {
origin_ -= offset;
}
Insets Rect::InsetsFrom(const Rect& inner) const {
return Insets(inner.y() - y(), inner.x() - x(), bottom() - inner.bottom(),
right() - inner.right());
}
bool Rect::operator<(const Rect& other) const {
if (origin_ == other.origin_) {
if (width() == other.width()) {
return height() < other.height();
} else {
return width() < other.width();
}
} else {
return origin_ < other.origin_;
}
}
bool Rect::Contains(int point_x, int point_y) const {
return (point_x >= x()) && (point_x < right()) && (point_y >= y()) &&
(point_y < bottom());
}
bool Rect::Contains(const Rect& rect) const {
return (rect.x() >= x() && rect.right() <= right() && rect.y() >= y() &&
rect.bottom() <= bottom());
}
bool Rect::Intersects(const Rect& rect) const {
return !(IsEmpty() || rect.IsEmpty() || rect.x() >= right() ||
rect.right() <= x() || rect.y() >= bottom() || rect.bottom() <= y());
}
void Rect::Intersect(const Rect& rect) {
if (IsEmpty() || rect.IsEmpty()) {
SetRect(0, 0, 0, 0); // Throws away empty position.
return;
}
int left = std::max(x(), rect.x());
int top = std::max(y(), rect.y());
int new_right = std::min(right(), rect.right());
int new_bottom = std::min(bottom(), rect.bottom());
if (left >= new_right || top >= new_bottom) {
SetRect(0, 0, 0, 0); // Throws away empty position.
return;
}
SetByBounds(left, top, new_right, new_bottom);
}
void Rect::Union(const Rect& rect) {
if (IsEmpty()) {
*this = rect;
return;
}
if (rect.IsEmpty())
return;
SetByBounds(std::min(x(), rect.x()), std::min(y(), rect.y()),
std::max(right(), rect.right()),
std::max(bottom(), rect.bottom()));
}
void Rect::Subtract(const Rect& rect) {
if (!Intersects(rect))
return;
if (rect.Contains(*this)) {
SetRect(0, 0, 0, 0);
return;
}
int rx = x();
int ry = y();
int rr = right();
int rb = bottom();
if (rect.y() <= y() && rect.bottom() >= bottom()) {
// complete intersection in the y-direction
if (rect.x() <= x()) {
rx = rect.right();
} else if (rect.right() >= right()) {
rr = rect.x();
}
} else if (rect.x() <= x() && rect.right() >= right()) {
// complete intersection in the x-direction
if (rect.y() <= y()) {
ry = rect.bottom();
} else if (rect.bottom() >= bottom()) {
rb = rect.y();
}
}
SetByBounds(rx, ry, rr, rb);
}
void Rect::AdjustToFit(const Rect& rect) {
int new_x = x();
int new_y = y();
int new_width = width();
int new_height = height();
AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width);
AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height);
SetRect(new_x, new_y, new_width, new_height);
}
Point Rect::CenterPoint() const {
return Point(x() + width() / 2, y() + height() / 2);
}
void Rect::ClampToCenteredSize(const Size& size) {
int new_width = std::min(width(), size.width());
int new_height = std::min(height(), size.height());
int new_x = x() + (width() - new_width) / 2;
int new_y = y() + (height() - new_height) / 2;
SetRect(new_x, new_y, new_width, new_height);
}
void Rect::Transpose() {
SetRect(y(), x(), height(), width());
}
void Rect::SplitVertically(Rect* left_half, Rect* right_half) const {
BASE_DCHECK(left_half);
BASE_DCHECK(right_half);
left_half->SetRect(x(), y(), width() / 2, height());
right_half->SetRect(left_half->right(), y(), width() - left_half->width(),
height());
}
bool Rect::SharesEdgeWith(const Rect& rect) const {
return (y() == rect.y() && height() == rect.height() &&
(x() == rect.right() || right() == rect.x())) ||
(x() == rect.x() && width() == rect.width() &&
(y() == rect.bottom() || bottom() == rect.y()));
}
int Rect::ManhattanDistanceToPoint(const Point& point) const {
int x_distance =
std::max<int>(0, std::max(x() - point.x(), point.x() - right()));
int y_distance =
std::max<int>(0, std::max(y() - point.y(), point.y() - bottom()));
return x_distance + y_distance;
}
int Rect::ManhattanInternalDistance(const Rect& rect) const {
Rect c(*this);
c.Union(rect);
int x = std::max(0, c.width() - width() - rect.width() + 1);
int y = std::max(0, c.height() - height() - rect.height() + 1);
return x + y;
}
std::string Rect::ToString() const {
return base::StringPrintf("%s %s", origin().ToString().c_str(),
size().ToString().c_str());
}
bool Rect::ApproximatelyEqual(const Rect& rect, int tolerance) const {
return std::abs(x() - rect.x()) <= tolerance &&
std::abs(y() - rect.y()) <= tolerance &&
std::abs(right() - rect.right()) <= tolerance &&
std::abs(bottom() - rect.bottom()) <= tolerance;
}
Rect operator+(const Rect& lhs, const Vector2d& rhs) {
Rect result(lhs);
result += rhs;
return result;
}
Rect operator-(const Rect& lhs, const Vector2d& rhs) {
Rect result(lhs);
result -= rhs;
return result;
}
Rect IntersectRects(const Rect& a, const Rect& b) {
Rect result = a;
result.Intersect(b);
return result;
}
Rect UnionRects(const Rect& a, const Rect& b) {
Rect result = a;
result.Union(b);
return result;
}
Rect SubtractRects(const Rect& a, const Rect& b) {
Rect result = a;
result.Subtract(b);
return result;
}
Rect BoundingRect(const Point& p1, const Point& p2) {
Rect result;
result.SetByBounds(std::min(p1.x(), p2.x()), std::min(p1.y(), p2.y()),
std::max(p1.x(), p2.x()), std::max(p1.y(), p2.y()));
return result;
}
} // namespace gfx
| engine/third_party/accessibility/gfx/geometry/rect.cc/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/rect.cc",
"repo_id": "engine",
"token_count": 3649
} | 453 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "vector2d_conversions.h"
#include "base/numerics/safe_conversions.h"
namespace gfx {
Vector2d ToFlooredVector2d(const Vector2dF& vector2d) {
return Vector2d(base::ClampFloor(vector2d.x()),
base::ClampFloor(vector2d.y()));
}
Vector2d ToCeiledVector2d(const Vector2dF& vector2d) {
return Vector2d(base::ClampCeil(vector2d.x()), base::ClampCeil(vector2d.y()));
}
Vector2d ToRoundedVector2d(const Vector2dF& vector2d) {
return Vector2d(base::ClampRound(vector2d.x()),
base::ClampRound(vector2d.y()));
}
} // namespace gfx
| engine/third_party/accessibility/gfx/geometry/vector2d_conversions.cc/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/vector2d_conversions.cc",
"repo_id": "engine",
"token_count": 308
} | 454 |
// Copyright 2013 The Flutter 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_TRANSFORM_H_
#define UI_GFX_TRANSFORM_H_
#include <iosfwd>
#include <string>
#include "geometry/rect_f.h"
#include "gfx_export.h"
namespace gfx {
class RectF;
// 4x4 transformation matrix. Transform is cheap and explicitly allows
// copy/assign.
class GFX_EXPORT Transform {
public:
Transform();
Transform(float col1row1,
float col2row1,
float col3row1,
float col4row1,
float col1row2,
float col2row2,
float col3row2,
float col4row2,
float col1row3,
float col2row3,
float col3row3,
float col4row3,
float col1row4,
float col2row4,
float col3row4,
float col4row4);
// Constructs a transform from explicit 2d elements. All other matrix
// elements remain the same as the corresponding elements of an identity
// matrix.
Transform(float col1row1,
float col2row1,
float col1row2,
float col2row2,
float x_translation,
float y_translation);
bool operator==(const Transform& rhs) const;
bool operator!=(const Transform& rhs) const { return !(*this == rhs); };
float operator[](int index) const {
BASE_DCHECK((unsigned)index < 16);
return matrix_[index];
}
// Returns true if this is the identity matrix.
bool IsIdentity() const;
// Applies the current transformation on a scaling and assigns the result
// to |this|.
void Scale(float x, float y);
// Applies transformation on the given rect. After the function completes,
// |rect| will be the smallest axis aligned bounding rect containing the
// transformed rect.
void TransformRect(RectF* rect) const;
// Applies transformation on the given point
void TransformPoint(PointF* point) const;
std::string ToString() const;
private:
// Row-major array
float matrix_[16];
bool is_identity_;
void UpdateIdentity();
};
// 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 Transform& transform, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_TRANSFORM_H_
| engine/third_party/accessibility/gfx/transform.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/transform.h",
"repo_id": "engine",
"token_count": 933
} | 455 |
// Copyright 2013 The Flutter 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_LIBRARY_NATIVES_H_
#define LIB_TONIC_DART_LIBRARY_NATIVES_H_
#include <initializer_list>
#include <string>
#include <unordered_map>
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/common/macros.h"
namespace tonic {
class DartLibraryNatives {
public:
DartLibraryNatives();
~DartLibraryNatives();
struct Entry {
const char* symbol;
Dart_NativeFunction native_function;
int argument_count;
bool auto_setup_scope;
};
void Register(std::initializer_list<Entry> entries);
Dart_NativeFunction GetNativeFunction(Dart_Handle name,
int argument_count,
bool* auto_setup_scope);
const uint8_t* GetSymbol(Dart_NativeFunction native_function);
private:
std::unordered_map<std::string, Entry> entries_;
std::unordered_map<Dart_NativeFunction, const char*> symbols_;
TONIC_DISALLOW_COPY_AND_ASSIGN(DartLibraryNatives);
};
} // namespace tonic
#endif // LIB_TONIC_DART_LIBRARY_NATIVES_H_
| engine/third_party/tonic/dart_library_natives.h/0 | {
"file_path": "engine/third_party/tonic/dart_library_natives.h",
"repo_id": "engine",
"token_count": 476
} | 456 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tonic/file_loader/file_loader.h"
#include <iostream>
#include <memory>
#include <utility>
#include "tonic/common/macros.h"
#include "tonic/converter/dart_converter.h"
#include "tonic/filesystem/filesystem/file.h"
#include "tonic/filesystem/filesystem/path.h"
#include "tonic/filesystem/filesystem/portable_unistd.h"
#include "tonic/parsers/packages_map.h"
namespace tonic {
namespace {
constexpr char kDartScheme[] = "dart:";
constexpr char kFileScheme[] = "file:";
constexpr size_t kFileSchemeLength = sizeof(kFileScheme) - 1;
constexpr char kPackageScheme[] = "package:";
constexpr size_t kPackageSchemeLength = sizeof(kPackageScheme) - 1;
// Extract the scheme prefix ('package:' or 'file:' from )
std::string ExtractSchemePrefix(std::string url) {
if (url.find(kPackageScheme) == 0u)
return kPackageScheme;
if (url.find(kFileScheme) == 0u)
return kFileScheme;
return std::string();
}
// Extract the path from a package: or file: url.
std::string ExtractPath(std::string url) {
if (url.find(kPackageScheme) == 0u)
return url.substr(kPackageSchemeLength);
if (url.find(kFileScheme) == 0u)
return url.substr(kFileSchemeLength);
return url;
}
} // namespace
FileLoader::FileLoader(int dirfd) : dirfd_(dirfd) {}
FileLoader::~FileLoader() {
for (auto kernel_buffer : kernel_buffers_)
free(kernel_buffer);
if (dirfd_ >= 0)
close(dirfd_);
}
std::string FileLoader::SanitizeURIEscapedCharacters(const std::string& str) {
std::string result;
result.reserve(str.size());
for (std::string::size_type i = 0; i < str.size(); ++i) {
if (str[i] == '%') {
if (i > str.size() - 3 || !isxdigit(str[i + 1]) || !isxdigit(str[i + 2]))
return "";
const std::string hex = str.substr(i + 1, 2);
const unsigned char c = strtoul(hex.c_str(), nullptr, 16);
if (!c)
return "";
result += c;
i += 2;
} else {
result += str[i];
}
}
return result;
}
bool FileLoader::LoadPackagesMap(const std::string& packages) {
packages_ = packages;
std::string packages_source;
if (!ReadFileToString(packages_, &packages_source)) {
tonic::Log("error: Unable to load .packages file '%s'.", packages_.c_str());
return false;
}
packages_map_.reset(new PackagesMap());
std::string error;
if (!packages_map_->Parse(packages_source, &error)) {
tonic::Log("error: Unable to parse .packages file '%s'. %s",
packages_.c_str(), error.c_str());
return false;
}
return true;
}
std::string FileLoader::GetFilePathForPackageURL(std::string url) {
if (!packages_map_)
return std::string();
TONIC_DCHECK(url.find(kPackageScheme) == 0u);
url = url.substr(kPackageSchemeLength);
size_t slash = url.find(FileLoader::kPathSeparator);
if (slash == std::string::npos)
return std::string();
std::string package = url.substr(0, slash);
std::string library_path = url.substr(slash + 1);
std::string package_path = packages_map_->Resolve(package);
if (package_path.empty())
return std::string();
if (package_path.find(FileLoader::kFileURLPrefix) == 0u)
return SanitizePath(package_path.substr(FileLoader::kFileURLPrefixLength) +
library_path);
return filesystem::GetDirectoryName(filesystem::AbsolutePath(packages_)) +
FileLoader::kPathSeparator + package_path +
FileLoader::kPathSeparator + library_path;
}
Dart_Handle FileLoader::HandleLibraryTag(Dart_LibraryTag tag,
Dart_Handle library,
Dart_Handle url) {
TONIC_DCHECK(Dart_IsNull(library) || Dart_IsLibrary(library) ||
Dart_IsString(library));
TONIC_DCHECK(Dart_IsString(url));
if (tag == Dart_kCanonicalizeUrl)
return CanonicalizeURL(library, url);
if (tag == Dart_kKernelTag)
return Kernel(url);
if (tag == Dart_kImportTag)
return Import(url);
return Dart_NewApiError("Unknown library tag.");
}
Dart_Handle FileLoader::CanonicalizeURL(Dart_Handle library, Dart_Handle url) {
std::string string = StdStringFromDart(url);
if (string.find(kDartScheme) == 0u)
return url;
if (string.find(kPackageScheme) == 0u)
return StdStringToDart(SanitizePath(string));
if (string.find(kFileScheme) == 0u) {
return StdStringToDart(SanitizeURIEscapedCharacters(string));
}
std::string library_url = StdStringFromDart(Dart_LibraryUrl(library));
std::string prefix = ExtractSchemePrefix(library_url);
std::string base_path = ExtractPath(library_url);
std::string simplified_path =
filesystem::SimplifyPath(filesystem::GetDirectoryName(base_path) +
FileLoader::kPathSeparator + string);
return StdStringToDart(SanitizePath(prefix + simplified_path));
}
std::string FileLoader::GetFilePathForURL(std::string url) {
if (url.find(kPackageScheme) == 0u)
return GetFilePathForPackageURL(std::move(url));
if (url.find(kFileScheme) == 0u)
return GetFilePathForFileURL(std::move(url));
return url;
}
Dart_Handle FileLoader::FetchBytes(const std::string& url,
uint8_t*& buffer,
intptr_t& buffer_size) {
buffer = nullptr;
buffer_size = -1;
std::string path = filesystem::SimplifyPath(GetFilePathForURL(url));
if (path.empty()) {
std::string error_message = "error: Unable to read '" + url + "'.";
return Dart_NewUnhandledExceptionError(
Dart_NewStringFromCString(error_message.c_str()));
}
std::string absolute_path = filesystem::GetAbsoluteFilePath(path);
auto result = filesystem::ReadFileToBytes(absolute_path);
if (result.first == nullptr) {
std::string error_message =
"error: Unable to read '" + absolute_path + "'.";
return Dart_NewUnhandledExceptionError(
Dart_NewStringFromCString(error_message.c_str()));
}
buffer = result.first;
buffer_size = result.second;
return Dart_True();
}
Dart_Handle FileLoader::Import(Dart_Handle url) {
std::string url_string = StdStringFromDart(url);
uint8_t* buffer = nullptr;
intptr_t buffer_size = -1;
Dart_Handle result = FetchBytes(url_string, buffer, buffer_size);
if (Dart_IsError(result)) {
return result;
}
// The embedder must keep the buffer alive until isolate shutdown.
kernel_buffers_.push_back(buffer);
return Dart_LoadLibraryFromKernel(buffer, buffer_size);
}
namespace {
void MallocFinalizer(void* isolate_callback_data, void* peer) {
free(peer);
}
} // namespace
Dart_Handle FileLoader::Kernel(Dart_Handle url) {
std::string url_string = StdStringFromDart(url);
uint8_t* buffer = nullptr;
intptr_t buffer_size = -1;
Dart_Handle result = FetchBytes(url_string, buffer, buffer_size);
if (Dart_IsError(result)) {
return result;
}
result =
Dart_NewExternalTypedData(Dart_TypedData_kUint8, buffer, buffer_size);
Dart_NewFinalizableHandle(result, buffer, buffer_size, MallocFinalizer);
return result;
}
// This is invoked upon a reload request.
void FileLoader::SetPackagesUrl(Dart_Handle url) {
if (url == Dart_Null()) {
// No packages url specified.
LoadPackagesMap(packages());
return;
}
const std::string& packages_url = StdStringFromDart(url);
LoadPackagesMap(packages_url);
}
std::string FileLoader::GetFilePathForFileURL(std::string url) {
TONIC_DCHECK(url.find(FileLoader::kFileURLPrefix) == 0u);
return SanitizePath(url.substr(FileLoader::kFileURLPrefixLength));
}
std::string FileLoader::GetFileURLForPath(const std::string& path) {
return std::string(FileLoader::kFileURLPrefix) + path;
}
} // namespace tonic
| engine/third_party/tonic/file_loader/file_loader.cc/0 | {
"file_path": "engine/third_party/tonic/file_loader/file_loader.cc",
"repo_id": "engine",
"token_count": 2995
} | 457 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "filesystem/directory.h"
#include "filesystem/path.h"
#include "filesystem/scoped_temp_dir.h"
#include "gtest/gtest.h"
namespace filesystem {
TEST(Directory, CreateDirectory) {
std::string cwd = GetCurrentDirectory();
ScopedTempDir dir;
EXPECT_TRUE(IsDirectory(dir.path()));
EXPECT_EQ(0, chdir(dir.path().c_str()));
EXPECT_TRUE(CreateDirectory("foo/bar"));
EXPECT_TRUE(IsDirectory("foo"));
EXPECT_TRUE(IsDirectory("foo/bar"));
EXPECT_FALSE(IsDirectory("foo/bar/baz"));
EXPECT_TRUE(CreateDirectory("foo/bar/baz"));
EXPECT_TRUE(IsDirectory("foo/bar/baz"));
EXPECT_TRUE(CreateDirectory("qux"));
EXPECT_TRUE(IsDirectory("qux"));
EXPECT_EQ(0, chdir(cwd.c_str()));
std::string abs_path = dir.path() + "/another/one";
EXPECT_TRUE(CreateDirectory(abs_path));
EXPECT_TRUE(IsDirectory(abs_path));
}
} // namespace filesystem
| engine/third_party/tonic/filesystem/tests/directory_unittest.cc/0 | {
"file_path": "engine/third_party/tonic/filesystem/tests/directory_unittest.cc",
"repo_id": "engine",
"token_count": 379
} | 458 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/testing/dart_isolate_runner.h"
#include "flutter/testing/fixture_test.h"
namespace flutter {
namespace testing {
class DartPersistentHandleTest : public FixtureTest {
public:
DartPersistentHandleTest()
: settings_(CreateSettingsForFixture()),
vm_(DartVMRef::Create(settings_)),
thread_(CreateNewThread()),
task_runners_(GetCurrentTestName(),
thread_,
thread_,
thread_,
thread_) {}
~DartPersistentHandleTest() = default;
[[nodiscard]] bool RunWithEntrypoint(const std::string& entrypoint) {
if (running_isolate_) {
return false;
}
auto isolate =
RunDartCodeInIsolate(vm_, settings_, task_runners_, entrypoint, {},
GetDefaultKernelFilePath());
if (!isolate || isolate->get()->GetPhase() != DartIsolate::Phase::Running) {
return false;
}
running_isolate_ = std::move(isolate);
return true;
}
protected:
Settings settings_;
DartVMRef vm_;
std::unique_ptr<AutoIsolateShutdown> running_isolate_;
fml::RefPtr<fml::TaskRunner> thread_;
TaskRunners task_runners_;
FML_DISALLOW_COPY_AND_ASSIGN(DartPersistentHandleTest);
};
TEST_F(DartPersistentHandleTest, ClearAfterShutdown) {
auto persistent_value = tonic::DartPersistentValue();
fml::AutoResetWaitableEvent event;
AddNativeCallback("GiveObjectToNative",
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
auto dart_state = tonic::DartState::Current();
ASSERT_TRUE(dart_state);
ASSERT_TRUE(tonic::DartState::Current());
persistent_value.Set(dart_state, handle);
event.Signal();
}));
ASSERT_TRUE(RunWithEntrypoint("callGiveObjectToNative"));
event.Wait();
running_isolate_->Shutdown();
fml::AutoResetWaitableEvent clear;
task_runners_.GetUITaskRunner()->PostTask([&] {
persistent_value.Clear();
clear.Signal();
});
clear.Wait();
}
} // namespace testing
} // namespace flutter
| engine/third_party/tonic/tests/dart_persistent_handle_unittest.cc/0 | {
"file_path": "engine/third_party/tonic/tests/dart_persistent_handle_unittest.cc",
"repo_id": "engine",
"token_count": 1016
} | 459 |
// Copyright 2013 The Flutter 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 <TargetConditionals.h>
#include "flutter/fml/platform/darwin/cf_utils.h"
#include "flutter/fml/platform/darwin/platform_version.h"
#include "third_party/skia/include/ports/SkFontMgr_mac_ct.h"
#include "third_party/skia/include/ports/SkTypeface_mac.h"
#include "txt/platform.h"
#include "txt/platform_mac.h"
#if TARGET_OS_EMBEDDED || TARGET_OS_SIMULATOR
#include <UIKit/UIKit.h>
#define FONT_CLASS UIFont
#else // TARGET_OS_EMBEDDED
#include <AppKit/AppKit.h>
#define FONT_CLASS NSFont
#endif // TARGET_OS_EMBEDDED
// Apple system font larger than size 29 returns SFProDisplay typeface.
static const CGFloat kSFProDisplayBreakPoint = 29;
// Font name represents the "SF Pro Display" system font on Apple platforms.
static const std::string kSFProDisplayName = "CupertinoSystemDisplay";
// Font weight representing Regular
float kNormalWeightValue = 400;
namespace txt {
const FourCharCode kWeightTag = 'wght';
std::vector<std::string> GetDefaultFontFamilies() {
if (fml::IsPlatformVersionAtLeast(9)) {
return {[FONT_CLASS systemFontOfSize:14].familyName.UTF8String};
} else {
return {"Helvetica"};
}
}
sk_sp<SkFontMgr> GetDefaultFontManager(uint32_t font_initialization_data) {
static sk_sp<SkFontMgr> mgr = SkFontMgr_New_CoreText(nullptr);
return mgr;
}
fml::CFRef<CTFontRef> MatchSystemUIFont(float desired_weight, float size) {
fml::CFRef<CTFontRef> ct_font(
CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, size, nullptr));
if (desired_weight == kNormalWeightValue) {
return ct_font;
}
fml::CFRef<CFMutableDictionaryRef> variations(CFDictionaryCreateMutable(
kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks));
auto add_axis_to_variations = [&variations](const FourCharCode tag,
float desired_value,
float normal_value) {
if (desired_value != normal_value) {
fml::CFRef<CFNumberRef> tag_number(
CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &tag));
fml::CFRef<CFNumberRef> value_number(CFNumberCreate(
kCFAllocatorDefault, kCFNumberFloatType, &desired_value));
CFDictionarySetValue(variations, tag_number, value_number);
}
};
add_axis_to_variations(kWeightTag, desired_weight, kNormalWeightValue);
fml::CFRef<CFMutableDictionaryRef> attributes(CFDictionaryCreateMutable(
kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks));
CFDictionarySetValue(attributes, kCTFontVariationAttribute, variations);
fml::CFRef<CTFontDescriptorRef> var_font_desc(
CTFontDescriptorCreateWithAttributes(attributes));
return fml::CFRef<CTFontRef>(
CTFontCreateCopyWithAttributes(ct_font, size, nullptr, var_font_desc));
}
void RegisterSystemFonts(const DynamicFontManager& dynamic_font_manager) {
// iOS loads different system fonts when size is greater than 28 or lower
// than 17. The "familyName" property returned from CoreText stays the same
// despite the typeface is different.
//
// Below code manually loads and registers the larger font. The existing
// fallback correctly loads the smaller font. The code also iterates through
// the possible font weights from 100 - 900 to correctly load all of them, as
// a CTFont object for the large system font does not include all of the font
// weights by default.
//
// Darwin system fonts from 17 to 28 also have dynamic spacing based on sizes.
// These two fonts do not match the spacings when sizes are from 17 to 28.
// The spacing should be handled by the app or the framework.
//
// See https://www.wwdcnotes.com/notes/wwdc20/10175/ for Apple's document on
// this topic.
auto register_weighted_font = [&dynamic_font_manager](const int weight) {
sk_sp<SkTypeface> large_system_font_weighted = SkMakeTypefaceFromCTFont(
MatchSystemUIFont(weight, kSFProDisplayBreakPoint));
if (large_system_font_weighted) {
dynamic_font_manager.font_provider().RegisterTypeface(
large_system_font_weighted, kSFProDisplayName);
}
};
for (int i = 0; i < 8; i++) {
const int font_weight = i * 100;
register_weighted_font(font_weight);
}
// The value 780 returns a font weight of 800.
register_weighted_font(780);
// The value of 810 returns a font weight of 900.
register_weighted_font(810);
}
} // namespace txt
| engine/third_party/txt/src/txt/platform_mac.mm/0 | {
"file_path": "engine/third_party/txt/src/txt/platform_mac.mm",
"repo_id": "engine",
"token_count": 1639
} | 460 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "display_list/dl_color.h"
#include "display_list/dl_paint.h"
#include "display_list/dl_tile_mode.h"
#include "display_list/effects/dl_color_source.h"
#include "display_list/utils/dl_receiver_utils.h"
#include "gtest/gtest.h"
#include "include/core/SkScalar.h"
#include "runtime/test_font_data.h"
#include "skia/paragraph_builder_skia.h"
#include "testing/canvas_test.h"
namespace flutter {
namespace testing {
//------------------------------------------------------------------------------
/// @brief A custom |DlOpReceiver| that records some |DlOps| it receives.
class DlOpRecorder final : public virtual DlOpReceiver,
private IgnoreAttributeDispatchHelper,
private IgnoreClipDispatchHelper,
private IgnoreDrawDispatchHelper,
private IgnoreTransformDispatchHelper {
public:
int lineCount() const { return lines_.size(); }
int rectCount() const { return rects_.size(); }
int pathCount() const { return paths_.size(); }
int textFrameCount() const { return text_frames_.size(); }
int blobCount() const { return blobs_.size(); }
bool hasPathEffect() const { return path_effect_ != nullptr; }
private:
void drawLine(const SkPoint& p0, const SkPoint& p1) override {
lines_.emplace_back(p0, p1);
}
void drawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame,
SkScalar x,
SkScalar y) override {
text_frames_.push_back(text_frame);
}
void drawTextBlob(const sk_sp<SkTextBlob> blob,
SkScalar x,
SkScalar y) override {
blobs_.push_back(blob);
}
void drawRect(const SkRect& rect) override { rects_.push_back(rect); }
void drawPath(const SkPath& path) override { paths_.push_back(path); }
void setPathEffect(const DlPathEffect* effect) override {
path_effect_ = effect;
}
std::vector<std::shared_ptr<impeller::TextFrame>> text_frames_;
std::vector<sk_sp<SkTextBlob>> blobs_;
std::vector<std::pair<SkPoint, SkPoint>> lines_;
std::vector<SkRect> rects_;
std::vector<SkPath> paths_;
const DlPathEffect* path_effect_;
};
template <typename T>
class PainterTestBase : public CanvasTestBase<T> {
public:
PainterTestBase() = default;
void PretendImpellerIsEnabled(bool impeller) { impeller_ = impeller; }
protected:
txt::TextStyle makeDecoratedStyle(txt::TextDecorationStyle style) {
auto t_style = txt::TextStyle();
t_style.color = SK_ColorBLACK; // default
t_style.font_weight = txt::FontWeight::w400; // normal
t_style.font_size = 14; // default
t_style.decoration = txt::TextDecoration::kUnderline;
t_style.decoration_style = style;
t_style.decoration_color = SK_ColorBLACK;
t_style.font_families.push_back("ahem");
return t_style;
}
txt::TextStyle makeStyle() {
auto t_style = txt::TextStyle();
t_style.color = SK_ColorBLACK; // default
t_style.font_weight = txt::FontWeight::w400; // normal
t_style.font_size = 14; // default
t_style.font_families.push_back("ahem");
return t_style;
}
sk_sp<DisplayList> draw(txt::TextStyle style) const {
auto pb_skia = makeParagraphBuilder();
pb_skia.PushStyle(style);
pb_skia.AddText(u"Hello World!");
pb_skia.Pop();
auto builder = DisplayListBuilder();
auto paragraph = pb_skia.Build();
paragraph->Layout(10000);
paragraph->Paint(&builder, 0, 0);
return builder.Build();
}
private:
std::shared_ptr<txt::FontCollection> makeFontCollection() const {
auto f_collection = std::make_shared<txt::FontCollection>();
auto font_provider = std::make_unique<txt::TypefaceFontAssetProvider>();
for (auto& font : GetTestFontData()) {
font_provider->RegisterTypeface(font);
}
auto manager = sk_make_sp<txt::AssetFontManager>(std::move(font_provider));
f_collection->SetAssetFontManager(manager);
return f_collection;
}
txt::ParagraphBuilderSkia makeParagraphBuilder() const {
auto p_style = txt::ParagraphStyle();
auto f_collection = makeFontCollection();
return txt::ParagraphBuilderSkia(p_style, f_collection, impeller_);
}
bool impeller_ = false;
};
using PainterTest = PainterTestBase<::testing::Test>;
TEST_F(PainterTest, DrawsSolidLineSkia) {
PretendImpellerIsEnabled(false);
auto recorder = DlOpRecorder();
draw(makeDecoratedStyle(txt::TextDecorationStyle::kSolid))
->Dispatch(recorder);
// Skia may draw a solid underline as a filled rectangle:
// https://skia.googlesource.com/skia/+/refs/heads/main/modules/skparagraph/src/Decorations.cpp#91
EXPECT_EQ(recorder.rectCount(), 1);
EXPECT_FALSE(recorder.hasPathEffect());
}
TEST_F(PainterTest, DrawDashedLineSkia) {
PretendImpellerIsEnabled(false);
auto recorder = DlOpRecorder();
draw(makeDecoratedStyle(txt::TextDecorationStyle::kDashed))
->Dispatch(recorder);
// Skia draws a dashed underline as a filled rectangle with a path effect.
EXPECT_EQ(recorder.lineCount(), 1);
EXPECT_TRUE(recorder.hasPathEffect());
}
#ifdef IMPELLER_SUPPORTS_RENDERING
TEST_F(PainterTest, DrawsSolidLineImpeller) {
PretendImpellerIsEnabled(true);
auto recorder = DlOpRecorder();
draw(makeDecoratedStyle(txt::TextDecorationStyle::kSolid))
->Dispatch(recorder);
// Skia may draw a solid underline as a filled rectangle:
// https://skia.googlesource.com/skia/+/refs/heads/main/modules/skparagraph/src/Decorations.cpp#91
EXPECT_EQ(recorder.rectCount(), 1);
EXPECT_FALSE(recorder.hasPathEffect());
}
TEST_F(PainterTest, DrawDashedLineImpeller) {
PretendImpellerIsEnabled(true);
auto recorder = DlOpRecorder();
draw(makeDecoratedStyle(txt::TextDecorationStyle::kDashed))
->Dispatch(recorder);
// Impeller draws a dashed underline as a path.
EXPECT_EQ(recorder.pathCount(), 1);
EXPECT_FALSE(recorder.hasPathEffect());
}
TEST_F(PainterTest, DrawTextFrameImpeller) {
PretendImpellerIsEnabled(true);
auto recorder = DlOpRecorder();
draw(makeStyle())->Dispatch(recorder);
EXPECT_EQ(recorder.textFrameCount(), 1);
EXPECT_EQ(recorder.blobCount(), 0);
}
TEST_F(PainterTest, DrawStrokedTextImpeller) {
PretendImpellerIsEnabled(true);
auto style = makeStyle();
// What is your shtyle?
DlPaint foreground;
foreground.setDrawStyle(DlDrawStyle::kStroke);
style.foreground = foreground;
auto recorder = DlOpRecorder();
draw(style)->Dispatch(recorder);
EXPECT_EQ(recorder.textFrameCount(), 0);
EXPECT_EQ(recorder.blobCount(), 0);
EXPECT_EQ(recorder.pathCount(), 1);
}
TEST_F(PainterTest, DrawTextWithGradientImpeller) {
PretendImpellerIsEnabled(true);
auto style = makeStyle();
// how do you like my shtyle?
DlPaint foreground;
std::vector<DlColor> colors = {DlColor::kRed(), DlColor::kCyan()};
std::vector<float> stops = {0.0, 1.0};
foreground.setColorSource(DlColorSource::MakeLinear(
SkPoint::Make(0, 0), SkPoint::Make(100, 100), 2, colors.data(),
stops.data(), DlTileMode::kClamp));
style.foreground = foreground;
auto recorder = DlOpRecorder();
draw(style)->Dispatch(recorder);
EXPECT_EQ(recorder.textFrameCount(), 0);
EXPECT_EQ(recorder.blobCount(), 0);
EXPECT_EQ(recorder.pathCount(), 1);
}
TEST_F(PainterTest, DrawTextBlobNoImpeller) {
PretendImpellerIsEnabled(false);
auto recorder = DlOpRecorder();
draw(makeStyle())->Dispatch(recorder);
EXPECT_EQ(recorder.textFrameCount(), 0);
EXPECT_EQ(recorder.blobCount(), 1);
}
#endif // IMPELLER_SUPPORTS_RENDERING
} // namespace testing
} // namespace flutter
| engine/third_party/txt/tests/paragraph_unittests.cc/0 | {
"file_path": "engine/third_party/txt/tests/paragraph_unittests.cc",
"repo_id": "engine",
"token_count": 2983
} | 461 |
//---------------------------------------------------------------------------------------------
// Copyright (c) 2022 Google LLC
// Licensed under the MIT License. See License.txt in the project root for license information.
//--------------------------------------------------------------------------------------------*/
// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT
//
// This file is auto generated by flutter/engine:flutter/tools/gen_web_keyboard_keymap based on
// https://github.com/microsoft/vscode/tree/422b581e3802e30cfb780c21d9cc1a2cd0c9f0aa/src/vs/workbench/services/keybinding/browser/keyboardLayouts
//
// Edit the following files instead:
//
// - Script: lib/main.dart
// - Templates: data/*.tmpl
//
// See flutter/engine:flutter/tools/gen_web_locale_keymap/README.md for more information.
/// Used in the final mapping indicating the logical key should be derived from
/// KeyboardEvent.keyCode.
///
/// This value is chosen because it's a printable character within EASCII that
/// will never be mapped to (checked in the marshalling algorithm).
const int kUseKeyCode = 0xFF;
/// Used in the final mapping indicating the event key is 'Dead', the dead key.
final String _kUseDead = String.fromCharCode(0xFE);
/// The KeyboardEvent.key for a dead key.
const String _kEventKeyDead = 'Dead';
/// A map of all goals from the scan codes to their mapped value in US layout.
const Map<String, String> kLayoutGoals = <String, String>{
'KeyA': 'a',
'KeyB': 'b',
'KeyC': 'c',
'KeyD': 'd',
'KeyE': 'e',
'KeyF': 'f',
'KeyG': 'g',
'KeyH': 'h',
'KeyI': 'i',
'KeyJ': 'j',
'KeyK': 'k',
'KeyL': 'l',
'KeyM': 'm',
'KeyN': 'n',
'KeyO': 'o',
'KeyP': 'p',
'KeyQ': 'q',
'KeyR': 'r',
'KeyS': 's',
'KeyT': 't',
'KeyU': 'u',
'KeyV': 'v',
'KeyW': 'w',
'KeyX': 'x',
'KeyY': 'y',
'KeyZ': 'z',
'Digit1': '1',
'Digit2': '2',
'Digit3': '3',
'Digit4': '4',
'Digit5': '5',
'Digit6': '6',
'Digit7': '7',
'Digit8': '8',
'Digit9': '9',
'Digit0': '0',
'Minus': '-',
'Equal': '=',
'BracketLeft': '[',
'BracketRight': ']',
'Backslash': r'\',
'Semicolon': ';',
'Quote': "'",
'Backquote': '`',
'Comma': ',',
'Period': '.',
'Slash': '/',
};
final int _kLowerA = 'a'.codeUnitAt(0);
final int _kUpperA = 'A'.codeUnitAt(0);
final int _kLowerZ = 'z'.codeUnitAt(0);
final int _kUpperZ = 'Z'.codeUnitAt(0);
bool _isAscii(int charCode) {
// 0x20 is the first printable character in ASCII.
return charCode >= 0x20 && charCode <= 0x7F;
}
/// Returns whether the `char` is a single character of a letter or a digit.
bool isLetter(int charCode) {
return (charCode >= _kLowerA && charCode <= _kLowerZ)
|| (charCode >= _kUpperA && charCode <= _kUpperZ);
}
/// A set of rules that can derive a large number of logical keys simply from
/// the event's code and key.
///
/// This greatly reduces the entries needed in the final mapping.
int? heuristicMapper(String code, String key) {
// Digit code: return the digit by event code.
if (code.startsWith('Digit')) {
assert(code.length == 6);
return code.codeUnitAt(5); // The character immediately after 'Digit'
}
final int charCode = key.codeUnitAt(0);
// Non-ascii: return the goal (i.e. US mapping by event code).
if (key.length > 1 || !_isAscii(charCode)) {
return kLayoutGoals[code]?.codeUnitAt(0);
}
// Letter key: return the event key letter.
if (isLetter(charCode)) {
return key.toLowerCase().codeUnitAt(0);
}
return null;
}
// Maps an integer to a printable EASCII character by adding it to this value.
//
// We could've chosen 0x20, the first printable character, for a slightly bigger
// range, but it's prettier this way and sufficient.
final int _kMarshallIntBase = '0'.codeUnitAt(0);
class _StringStream {
_StringStream(this._data) : _offset = 0;
final String _data;
final Map<int, String> _goalToEventCode = Map<int, String>.fromEntries(
kLayoutGoals
.entries
.map((MapEntry<String, String> beforeEntry) =>
MapEntry<int, String>(beforeEntry.value.codeUnitAt(0), beforeEntry.key))
);
int get offest => _offset;
int _offset;
int readIntAsVerbatim() {
final int result = _data.codeUnitAt(_offset);
_offset += 1;
assert(result >= _kMarshallIntBase);
return result - _kMarshallIntBase;
}
int readIntAsChar() {
final int result = _data.codeUnitAt(_offset);
_offset += 1;
return result;
}
String readEventKey() {
final String char = String.fromCharCode(readIntAsChar());
if (char == _kUseDead) {
return _kEventKeyDead;
} else {
return char;
}
}
String readEventCode() {
final int charCode = _data.codeUnitAt(_offset);
_offset += 1;
return _goalToEventCode[charCode]!;
}
}
Map<String, int> _unmarshallCodeMap(_StringStream stream) {
final int entryNum = stream.readIntAsVerbatim();
return <String, int>{
for (int i = 0; i < entryNum; i++)
stream.readEventKey(): stream.readIntAsChar(),
};
}
/// Decode a key mapping data out of the string.
Map<String, Map<String, int>> unmarshallMappingData(String compressed) {
final _StringStream stream = _StringStream(compressed);
final int eventCodeNum = stream.readIntAsVerbatim();
return <String, Map<String, int>>{
for (int i = 0; i < eventCodeNum; i++)
stream.readEventCode() : _unmarshallCodeMap(stream),
};
}
/// Data for [LocaleKeymap] on Windows.
///
/// Do not use this value, but [LocaleKeymap.win] instead.
///
/// The keys are `KeyboardEvent.code` and then `KeyboardEvent.key`. The values
/// are logical keys or [kUseKeyCode]. Entries that can be derived using
/// heuristics have been omitted.
Map<String, Map<String, int>> getMappingDataWin() {
return unmarshallMappingData(
r';'
r'b1{b'
r'c1&c'
r'f1[f'
r'g1]g'
r'm2<m?m'
r'n1}n'
r'q3/q@q\q'
r'v1@v'
r'w3"w?w|w'
r'x2#x)x'
r'z2(z>y'
); // 59 characters
}
/// Data for [LocaleKeymap] on Linux.
///
/// Do not use this value, but [LocaleKeymap.linux] instead.
///
/// The keys are `KeyboardEvent.code` and then `KeyboardEvent.key`. The values
/// are logical keys or [kUseKeyCode]. Entries that can be derived using
/// heuristics have been omitted.
Map<String, Map<String, int>> getMappingDataLinux() {
return unmarshallMappingData(
r'8'
r'a2@qΩq'
r'k1&k'
r'q3@qÆaæa'
r'w2<z«z'
r'x1>x'
r'y2¥ÿ←ÿ'
r'z5<z»yŁwłw›y'
r';2µmºm'
); // 53 characters
}
/// Data for [LocaleKeymap] on Darwin.
///
/// Do not use this value, but [LocaleKeymap.darwin] instead.
///
/// The keys are `KeyboardEvent.code` and then `KeyboardEvent.key`. The values
/// are logical keys or [kUseKeyCode]. Entries that can be derived using
/// heuristics have been omitted.
Map<String, Map<String, int>> getMappingDataDarwin() {
return unmarshallMappingData(
r'M'
r',2„w∑w'
r'a2Ωq‡q'
r'b2˛x≈x'
r'c3 cÔj∆j'
r'd2þe´e'
r'f2þu¨u'
r'g2þÿˆi'
r'h3 hÎÿ∂d'
r'i3 iÇcçc'
r'j2Óh˙h'
r'k2ˇÿ†t'
r'l5 l@lþÿ|l˜n'
r'm1~m'
r'n3 nıÿ∫b'
r'o2®r‰r'
r'p2¬lÒl'
r'q2Æaæa'
r'r3 rπp∏p'
r's3 sØoøo'
r't2¥yÁy'
r'u3 u©g˝g'
r'v2˚kk'
r'w2ÂzÅz'
r'x2Œqœq'
r'y5 yÏfƒfˇzΩz'
r'z5 z¥y‡y‹ÿ›w'
r'.2√v◊v'
r';4µmÍsÓmßs'
r'/2¸zΩz'
); // 209 characters
}
| engine/third_party/web_locale_keymap/lib/web_locale_keymap/key_mappings.g.dart/0 | {
"file_path": "engine/third_party/web_locale_keymap/lib/web_locale_keymap/key_mappings.g.dart",
"repo_id": "engine",
"token_count": 3057
} | 462 |
name: web_unicode
publish_to: none
environment:
sdk: '>=3.2.0-0 <4.0.0'
dev_dependencies:
args: any
path: any
| engine/third_party/web_unicode/pubspec.yaml/0 | {
"file_path": "engine/third_party/web_unicode/pubspec.yaml",
"repo_id": "engine",
"token_count": 58
} | 463 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' show LineSplitter;
import 'dart:io';
import 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/analysis_context_collection.dart';
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/analysis/utilities.dart';
import 'package:analyzer/dart/ast/ast.dart';
/// Returns all indexed fields in [className].
///
/// Field names are expected to be of the form `kFooBarIndex`; prefixed with a
/// `k` and terminated in `Index`.
List<String> getDartClassFields({
required String sourcePath,
required String className,
}) {
final List<String> includedPaths = <String>[sourcePath];
final AnalysisContextCollection collection = AnalysisContextCollection(includedPaths: includedPaths);
final AnalysisContext context = collection.contextFor(sourcePath);
final AnalysisSession session = context.currentSession;
final SomeParsedUnitResult result = session.getParsedUnit(sourcePath);
if (result is! ParsedUnitResult) {
return <String>[];
}
// Locate all fields matching the expression in the class.
final RegExp fieldExp = RegExp(r'_k(\w*)Index');
final List<String> fields = <String>[];
for (final CompilationUnitMember unitMember in result.unit.declarations) {
if (unitMember is ClassDeclaration && unitMember.name.lexeme == className) {
for (final ClassMember classMember in unitMember.members) {
if (classMember is FieldDeclaration) {
for (final VariableDeclaration field in classMember.fields.variables) {
final String fieldName = field.name.lexeme;
final RegExpMatch? match = fieldExp.firstMatch(fieldName);
if (match != null) {
fields.add(match.group(1)!);
}
}
}
}
}
}
return fields;
}
/// Returns all values in [enumName].
///
/// Enum values are expected to be of the form `kEnumNameFooBar`; prefixed with
/// `kEnumName`.
List<String> getCppEnumValues({
required String sourcePath,
required String enumName,
}) {
final List<String> lines = File(sourcePath).readAsLinesSync();
final int enumEnd = lines.indexOf('} $enumName;');
if (enumEnd < 0) {
return <String>[];
}
final int enumStart = lines.lastIndexOf('typedef enum {', enumEnd);
if (enumStart < 0 || enumStart >= enumEnd) {
return <String>[];
}
final RegExp valueExp = RegExp('^\\s*k$enumName(\\w*)');
return _extractMatchingExpression(
lines: lines.sublist(enumStart + 1, enumEnd),
regexp: valueExp,
);
}
/// Returns all values in [enumName].
///
/// Enum values are expected to be of the form `kFooBar`; prefixed with `k`.
List<String> getCppEnumClassValues({
required String sourcePath,
required String enumName,
}) {
final List<String> lines = _getBlockStartingWith(
source: File(sourcePath).readAsStringSync(),
startExp: RegExp('enum class $enumName .* {'),
);
final RegExp valueExp = RegExp(r'^\s*k(\w*)');
return _extractMatchingExpression(lines: lines, regexp: valueExp);
}
/// Returns all values in [enumName].
///
/// Enum value declarations are expected to be of the form `FOO_BAR(1 << N)`;
/// in all caps.
List<String> getJavaEnumValues({
required String sourcePath,
required String enumName,
}) {
final List<String> lines = _getBlockStartingWith(
source: File(sourcePath).readAsStringSync(),
startExp: RegExp('enum $enumName {'),
);
final RegExp valueExp = RegExp(r'^\s*([A-Z_]*)\(');
return _extractMatchingExpression(lines: lines, regexp: valueExp);
}
/// Returns all values in [lines] whose line of code matches [regexp].
///
/// The contents of the first match group in [regexp] is returned; therefore
/// it must contain a match group.
List<String> _extractMatchingExpression({
required Iterable<String> lines,
required RegExp regexp,
}) {
final List<String> values = <String>[];
for (final String line in lines) {
final RegExpMatch? match = regexp.firstMatch(line);
if (match != null) {
values.add(match.group(1)!);
}
}
return values;
}
/// Returns all lines of the block starting with [startString].
///
/// [startString] MUST end with '{'.
List<String> _getBlockStartingWith({
required String source,
required RegExp startExp,
}) {
assert(startExp.pattern.endsWith('{'));
final int blockStart = source.indexOf(startExp);
if (blockStart < 0) {
return <String>[];
}
// Find start of block.
int pos = blockStart;
while (pos < source.length && source[pos] != '{') {
pos++;
}
int braceCount = 1;
// Count braces until end of block.
pos++;
while (pos < source.length && braceCount > 0) {
if (source[pos] == '{') {
braceCount++;
} else if (source[pos] == '}') {
braceCount--;
}
pos++;
}
final int blockEnd = pos;
return LineSplitter.split(source, blockStart, blockEnd).toList();
}
/// Apply a visitor to all compilation units in the dart:ui library.
void visitUIUnits(String flutterRoot, AstVisitor<void> visitor) {
final String uiRoot = '$flutterRoot/lib/ui';
final FeatureSet analyzerFeatures = FeatureSet.latestLanguageVersion();
final ParseStringResult uiResult = parseFile(path: '$uiRoot/ui.dart', featureSet: analyzerFeatures);
for (final PartDirective part in uiResult.unit.directives.whereType<PartDirective>()) {
final String partPath = part.uri.stringValue!;
final ParseStringResult partResult = parseFile(path: '$uiRoot/$partPath', featureSet: analyzerFeatures);
for (final CompilationUnitMember unitMember in partResult.unit.declarations) {
unitMember.accept(visitor);
}
}
}
| engine/tools/api_check/lib/apicheck.dart/0 | {
"file_path": "engine/tools/api_check/lib/apicheck.dart",
"repo_id": "engine",
"token_count": 1974
} | 464 |
# clang_tidy
A wrapper library and program that runs `clang_tidy` on the Flutter engine repo.
```shell
# Assuming you are in the `flutter` root of the engine repo.
dart ./tools/clang_tidy/bin/main.dart
```
By default, the linter runs over _modified_[^1] files in the _latest_[^2] build
of the engine.
A subset of checks can also be fixed automatically by passing `--fix`:
```shell
dart ./tools/clang_tidy/bin/main.dart --fix
```
To configure what lints are enabled, see [`.clang-tidy`](../../.clang-tidy).
> **💡 TIP**: If you're looking for the git pre-commit hook configuration, see
> [`githooks`](../githooks).
## Advanced Usage
Some common use cases are described below, or use `--help` to see all options.
### Run with checks added or removed
To run adding a check _not_ specified in `.clang-tidy`:
```shell
dart ./tools/clang_tidy/bin/main.dart --checks="<check-name-to-run>"
```
It's possible also to use wildcards to add multiple checks:
```shell
dart ./tools/clang_tidy/bin/main.dart --checks="readability-*"
```
To remove a specific check:
```shell
dart ./tools/clang_tidy/bin/main.dart --checks="-<check-name-to-remove>"
```
To remove multiple checks:
```shell
dart ./tools/clang_tidy/bin/main.dart --checks="-readability-*"
```
To remove _all_ checks (usually to add a specific check):
```shell
dart ./tools/clang_tidy/bin/main.dart --checks="-*,<only-check-to-run>"
```
### Specify a specific build
There are some rules that are only applicable to certain builds, or to check
a difference in behavior between two builds.
Use `--target-variant` to specify a build:
```shell
dart ./tools/clang_tidy/bin/main.dart --target-variant <engine-variant>
```
For example, to check the `android_debug_unopt` build:
```shell
dart ./tools/clang_tidy/bin/main.dart --target-variant android_debug_unopt
```
In rarer cases, for example comparing two different checkouts of the engine,
use `--src-dir=<path/to/engine/src>`.
### Lint entire repository
When adding a new lint rule, or when checking lint rules that impact files that
have not changed.
Use `--lint-all` to lint all files in the repo:
```shell
dart ./tools/clang_tidy/bin/main.dart --lint-all
```
Or, provide a regular expression to lint files that match:
```shell
dart ./tools/clang_tidy/bin/main.dart --lint-regex=".*test.*\.cc"
```
> **⚠️ WARNING**: This may take a long time to run if a pattern is not provided
> or if the pattern matches a large number of files, i.e. on the order of
> thousands of files could take 30 minutes or more to run and lock your
> machine.
[^1]: Modified files are determined by a `git diff` command compared to `HEAD`.
[^2]: Latest build is the last updated directory in `src/out/`.
| engine/tools/clang_tidy/README.md/0 | {
"file_path": "engine/tools/clang_tidy/README.md",
"repo_id": "engine",
"token_count": 929
} | 465 |
// Copyright 2013 The Flutter 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:engine_build_configs/engine_build_configs.dart';
import '../build_utils.dart';
import 'command.dart';
import 'flags.dart';
/// The root 'build' command.
final class BuildCommand extends CommandBase {
/// Constructs the 'build' command.
BuildCommand({
required super.environment,
required Map<String, BuilderConfig> configs,
}) {
builds = runnableBuilds(environment, configs);
debugCheckBuilds(builds);
argParser.addOption(
configFlag,
abbr: 'c',
defaultsTo: 'host_debug',
help: 'Specify the build config to use',
allowed: <String>[
for (final Build config in runnableBuilds(environment, configs))
config.name,
],
allowedHelp: <String, String>{
for (final Build config in runnableBuilds(environment, configs))
config.name: config.gn.join(' '),
},
);
argParser.addFlag(
rbeFlag,
defaultsTo: true,
help: 'RBE is enabled by default when available. Use --no-rbe to '
'disable it.',
);
}
/// List of compatible builds.
late final List<Build> builds;
@override
String get name => 'build';
@override
String get description => 'Builds the engine';
@override
Future<int> run() async {
final String configName = argResults![configFlag] as String;
final bool useRbe = argResults![rbeFlag] as bool;
final Build? build =
builds.where((Build build) => build.name == configName).firstOrNull;
if (build == null) {
environment.logger.error('Could not find config $configName');
return 1;
}
final List<String> extraGnArgs = <String>[
if (!useRbe) '--no-rbe',
];
// TODO(loic-sharma): Fetch dependencies if needed.
return runBuild(environment, build, extraGnArgs: extraGnArgs);
}
}
| engine/tools/engine_tool/lib/src/commands/build_command.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/commands/build_command.dart",
"repo_id": "engine",
"token_count": 733
} | 466 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'environment.dart';
/// A WorkerTask.
abstract class WorkerTask {
/// WorkerTask with a name.
WorkerTask(this.name);
/// Name of worker task.
final String name;
/// Run the task which is complete when the returned future completes.
/// Returns true if successful.
Future<bool> run();
/// Returns the run time of this task.
Duration get runTime {
if (_startTime == null || _finishTime == null) {
return Duration.zero;
}
return _finishTime!.difference(_startTime!);
}
// When did this task start running?
DateTime? _startTime;
// When did this task finish running?
DateTime? _finishTime;
}
/// A pool of worker tasks that will run numWorkers tasks at a time
/// until all of the tasks are finished.
class WorkerPool {
/// Construct a worker pool with a specific reporter and max concurrency
/// limit.
WorkerPool(this._environment, this._reporter, [this._maxConcurrency = 4]);
final Environment _environment;
final WorkerPoolProgressReporter _reporter;
final int _maxConcurrency;
late Completer<bool> _runCompleter;
bool _anyFailed = false;
final Set<WorkerTask> _running = <WorkerTask>{};
final Set<WorkerTask> _pending = <WorkerTask>{};
final Set<WorkerTask> _finished = <WorkerTask>{};
/// Run all tasks in the pool. Report progress via reporter.
/// Returns 0 on success and non-zero on failure.
Future<bool> run(Set<WorkerTask> tasks) async {
_environment.logger.info('Running ${tasks.length}');
_runCompleter = Completer<bool>();
_reporter.onRun(tasks);
_pending.addAll(tasks);
_runQueue();
return _runCompleter.future;
}
/// Returns the current set of pending tasks.
UnmodifiableSetView<WorkerTask> get pending {
return UnmodifiableSetView<WorkerTask>(_pending);
}
/// Returns the current set of running tasks.
UnmodifiableSetView<WorkerTask> get running {
return UnmodifiableSetView<WorkerTask>(_running);
}
/// Returns the current set of finished tasks.
UnmodifiableSetView<WorkerTask> get finished {
return UnmodifiableSetView<WorkerTask>(_finished);
}
void _runQueue() {
if (_pending.isEmpty && _running.isEmpty) {
_reporter.onFinish();
// Nothing left to do or running.
_runCompleter.complete(!_anyFailed);
return;
}
while (_running.length < _maxConcurrency && _pending.isNotEmpty) {
final WorkerTask task = _pending.elementAt(0);
_pending.remove(task);
_runTask(task);
}
}
Future<void> _runTask(WorkerTask task) async {
task._startTime = DateTime.now();
final Future<bool> result = task.run();
_running.add(task);
_reporter.onTaskStart(this, task);
Object? err;
late final bool r;
try {
r = await result;
} catch (e) {
err = e;
r = false;
}
_anyFailed = _anyFailed || !r;
task._finishTime = DateTime.now();
_running.remove(task);
_finished.add(task);
_reporter.onTaskDone(this, task, err);
// Kick the queue again.
_runQueue();
}
}
/// WorkerPoolProgressReporter can be used to monitor worker pool progress.
abstract class WorkerPoolProgressReporter {
/// Invoked when [WorkerPool.run] is invoked.
void onRun(Set<WorkerTask> tasks);
/// Invoked right before [WorkerPool.run] is returned from.
void onFinish();
/// Invoked right after a task has been started.
void onTaskStart(WorkerPool pool, WorkerTask task);
/// Invoked right after a task has finished.
void onTaskDone(WorkerPool pool, WorkerTask task, [Object? err]);
}
/// Useful for tests.
class NoopWorkerPoolProgressReporter implements WorkerPoolProgressReporter {
@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]) {}
}
| engine/tools/engine_tool/lib/src/worker_pool.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/worker_pool.dart",
"repo_id": "engine",
"token_count": 1378
} | 467 |
#!/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.
""" Gather the build_id, prefix_dir, and exec_name given the path to executable
also copies to the specified destination.
The structure of debug symbols is as follows:
.build-id/<prefix>/<exec_name>[.debug]
"""
import argparse
import errno
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import time
def HashFile(filepath):
"""Calculates the hash of a file without reading it all in memory at once."""
digest = hashlib.sha1()
with open(filepath, 'rb') as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
def Touch(fname):
with open(fname, 'a'):
os.utime(fname, None)
def GetBuildIdParts(exec_path, read_elf):
sha1_pattern = re.compile(r'[0-9a-fA-F\-]+')
file_out = subprocess.check_output([read_elf, '-n', exec_path])
build_id_line = file_out.splitlines()[-1].split()
if (build_id_line[0] != b'Build' or build_id_line[1] != b'ID:' or
not sha1_pattern.match(str(build_id_line[-1])) or not len(build_id_line[-1]) > 2):
raise Exception(
'Expected the last line of llvm-readelf to match "Build ID <Hex String>" Got: %s' % file_out
)
build_id = build_id_line[-1]
return {
'build_id': build_id.decode('utf-8'), 'prefix_dir': build_id[:2].decode('utf-8'),
'exec_name': build_id[2:].decode('utf-8')
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--executable-name',
dest='exec_name',
action='store',
required=True,
help='This is the name of the executable that we wish to layout debug symbols for.'
)
parser.add_argument(
'--executable-path',
dest='exec_path',
action='store',
required=True,
help='Path to the executable on the filesystem.'
)
parser.add_argument(
'--destination-base',
dest='dest',
action='store',
required=True,
help='Path to the base directory where the debug symbols are to be laid out.'
)
parser.add_argument(
'--stripped',
dest='stripped',
action='store_true',
default=True,
help='Executable at the specified path is stripped.'
)
parser.add_argument(
'--unstripped',
dest='stripped',
action='store_false',
help='Executable at the specified path is unstripped.'
)
parser.add_argument(
'--read-elf',
dest='read_elf',
action='store',
required=True,
help='Path to read-elf executable.'
)
args = parser.parse_args()
assert os.path.exists(args.exec_path), ('exec_path "%s" does not exist' % args.exec_path)
assert os.path.exists(args.dest), ('dest "%s" does not exist' % args.dest)
assert os.path.exists(args.read_elf), ('read_elf "%s" does not exist' % args.read_elf)
parts = GetBuildIdParts(args.exec_path, args.read_elf)
dbg_prefix_base = os.path.join(args.dest, parts['prefix_dir'])
# Multiple processes may be trying to create the same directory.
# TODO(dnfield): use exist_ok when we upgrade to python 3, rather than try
try:
os.makedirs(dbg_prefix_base)
except OSError as e:
if e.errno != errno.EEXIST:
raise
if not os.path.exists(dbg_prefix_base):
print('Unable to create directory: %s.' % dbg_prefix_base)
return 1
dbg_suffix = ''
if not args.stripped:
dbg_suffix = '.debug'
dbg_file_name = '%s%s' % (parts['exec_name'], dbg_suffix)
dbg_file_path = os.path.join(dbg_prefix_base, dbg_file_name)
# If the debug file hasn't changed, don't rewrite the debug and completion
# file, speeding up incremental builds.
if os.path.exists(dbg_file_path) and HashFile(args.exec_path) == HashFile(dbg_file_path):
return 0
shutil.copyfile(args.exec_path, dbg_file_path)
# Note this needs to be in sync with fuchsia_debug_symbols.gni
completion_file = os.path.join(args.dest, '.%s_dbg_success' % args.exec_name)
Touch(completion_file)
return 0
if __name__ == '__main__':
sys.exit(main())
| engine/tools/fuchsia/copy_debug_symbols.py/0 | {
"file_path": "engine/tools/fuchsia/copy_debug_symbols.py",
"repo_id": "engine",
"token_count": 1632
} | 468 |
#!/usr/bin/env python3
"""Merges sources of a Dart target and its dependencies"""
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import json
import os
import sys
def main():
parser = argparse.ArgumentParser(
'Merges sources of a Dart target and its dependencies', fromfile_prefix_chars='@'
)
parser.add_argument(
'--output', help='Path to output the final list', type=argparse.FileType('w'), required=True
)
parser.add_argument(
'--depfile',
help='Path to the depfile to generate',
type=argparse.FileType('w'),
required=True
)
parser.add_argument(
'--sources',
help='Sources of this target',
nargs='*',
)
parser.add_argument('--source_lists', help='Files containing lists of Dart sources', nargs='*')
args = parser.parse_args()
args.depfile.write('{}: {}\n'.format(args.output.name, ' '.join(args.source_lists)))
# Merges sources of this target, and all of its dependencies.
all_sources = set(args.sources)
for f in args.source_lists:
with open(f, 'r') as f:
all_sources.update(json.load(f))
json.dump(sorted(all_sources), args.output)
if __name__ == '__main__':
sys.exit(main())
| engine/tools/fuchsia/dart/merge_deps_sources.py/0 | {
"file_path": "engine/tools/fuchsia/dart/merge_deps_sources.py",
"repo_id": "engine",
"token_count": 462
} | 469 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/tools/fuchsia/dart/dart.gni")
import("//flutter/tools/fuchsia/dart/dart_library.gni")
import("//flutter/tools/fuchsia/flutter/config.gni")
import("//flutter/tools/fuchsia/flutter/internal/flutter_dart_component.gni")
# Defines a Flutter component which can be used in a fuchsia package
#
# Flutter components require at least one library which contains a main
# entry point. The library should be defined using the dart_library.gni.
#
# ```
# dart_library("lib") {
# package_name = "my_library"
# sources = [ "main.dart" ]
# deps = [ "$dart_src-pkg/git/flutter/packages/flutter" ]
# }
# ```
#
# Once a library is defined a flutter component can be created which
# depends on this package. If the component needs any other resources they may
# be defined in the `resources` variable.
#
# ```
# flutter_component("my-component") {
# manifest = "meta/my-component.cmx"
# main_package = "my_library"
# resources = [
# {
# path = "text_file.txt"
# dest = "data/text_file.txt"
# },
# ]
# deps = [
# ":lib",
# ":text-file",
# ]
# }
# ```
#
# Once a component is defined it can be added as a dep of a fuchsia_package
# ```
# fuchsia_package("my-package") {
# deps = [
# ":my-component",
# ]
# }
# ```
#
# Parameters
#
# manifest (required)
# The component manifest
# Type: path
#
# main_package (optional)
# The name of the package containing main_dart
# Type: string
# Default: component_name with dashes replaced by underscores, if defined.
# Otherwise, the target_name with dashes replaced by underscores will be
# used.
#
# component_name (optional)
# The name of the component.
# Type: string
# Default: target_name
#
# main_dart (optional)
# File containing the main function of the component.
# Type: string
# Default: main.dart
#
# package_root (optional)
# The root of the package generated for this component. Each component must
# have a unique package_root. For each component, there must be a
# pubspec.yaml and an analysis_options.yaml at the package root.
# Type: path
# Default: "."
#
# build_cfg (optional)
# Specifies the parameters for building the component.
# See //flutter/tools/fuchsia/flutter/flutter_build_config.gni for predefined configs.
#
# deps
# testonly
# visibility
template("flutter_component") {
assert(defined(invoker.manifest), "Must define manifest")
_component_deps = []
if (defined(invoker.deps)) {
_component_deps += invoker.deps
}
if (defined(invoker.build_cfg)) {
_build_cfg = invoker.build_cfg
} else {
_build_cfg = flutter_default_build_cfg
}
if (defined(invoker.component_name)) {
_component_name = invoker.component_name
} else {
_component_name = target_name
}
if (defined(invoker.main_package)) {
_main_package = invoker.main_package
} else {
_main_package = string_replace(_component_name, "-", "_")
}
if (defined(invoker.main_dart)) {
_main_dart = invoker.main_dart
} else {
_main_dart = "main.dart"
}
# We need to specify the runner as a dependency (at least when running a
# flutter/engine-built package using a flutter/engine-built runner). Add it
# to `deps` so the runner will also be built, and available to serve to
# fuchsia, alongside the flutter_component's package.
_component_deps += [ _build_cfg.runner_dep ]
flutter_dart_component(target_name) {
forward_variables_from(invoker,
"*",
[
"build_cfg",
"deps",
"main_dart",
"main_package",
"component_name",
"resources",
])
deps = _component_deps
main_dart = _main_dart
main_package = _main_package
component_name = _component_name
build_cfg = _build_cfg
}
}
| engine/tools/fuchsia/flutter/flutter_component.gni/0 | {
"file_path": "engine/tools/fuchsia/flutter/flutter_component.gni",
"repo_id": "engine",
"token_count": 1686
} | 470 |
#!/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.
"""Emulation of `rm -f out && cp -af` in out. This is necessary on Mac in order
to preserve nanoseconds of mtime. See https://fxbug.dev/56376#c5."""
import os
import shutil
import sys
def main():
if len(sys.argv) != 3:
print('usage: copy.py source dest', file=sys.stderr)
return 1
source = sys.argv[1]
dest = sys.argv[2]
if os.path.isdir(source):
print(f'{source} is a directory, tool "copy" does not support directory copies')
return 1
if os.path.exists(dest):
if os.path.isdir(dest):
def _on_error(fn, path, dummy_excinfo):
# The operation failed, possibly because the file is set to
# read-only. If that's why, make it writable and try the op
# again.
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWRITE)
fn(path)
shutil.rmtree(dest, onerror=_on_error)
else:
if not os.access(dest, os.W_OK):
# Attempt to make the file writable before deleting it.
os.chmod(dest, stat.S_IWRITE)
os.unlink(dest)
shutil.copy2(source, dest)
if __name__ == '__main__':
main()
| engine/tools/fuchsia/toolchain/copy.py/0 | {
"file_path": "engine/tools/fuchsia/toolchain/copy.py",
"repo_id": "engine",
"token_count": 521
} | 471 |
// 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.
/// The platform that the browser is running on.
enum LayoutPlatform {
/// Windows.
win,
/// Linux.
linux,
/// MacOS or iOS.
darwin,
}
// The length of [LayoutEntry.printable].
const int _kPrintableLength = 4;
/// Describes the characters that a physical keyboard key will be mapped to
/// under different modifier states, for a given language on a given
/// platform.
class LayoutEntry {
/// Create a layout entry.
LayoutEntry(this.printables)
: assert(printables.length == _kPrintableLength);
/// The printable characters that a key should be mapped to under different
/// modifier states.
///
/// The [printables] always have a length of 4, corresponding to "without any
/// modifiers", "with Shift", "with AltGr", and "with Shift and AltGr"
/// respectively.
///
/// Some values might be empty. It doesn't mean that these combinations will
/// have an empty KeyboardKey.key, but usually these values are trivial,
/// i.e. same as their non-modified counterparts.
///
/// Some other values can be [kDeadKey]s. Dead keys are non-printable accents
/// that will be combined into the following letter character.
final List<String> printables;
/// An empty [LayoutEntry] that produces dead keys under all conditions.
static final LayoutEntry empty = LayoutEntry(
const <String>['', '', '', '']);
/// The value of KeyboardEvent.key for dead keys.
static const String kDeadKey = 'Dead';
}
/// Describes the characters that all goal keys will be mapped to for a given
/// language on a given platform.
class Layout {
/// Create a [Layout].
const Layout(this.language, this.platform, this.entries);
/// The language being used.
final String language;
/// The platform that the browser is running on.
final LayoutPlatform platform;
/// Maps from DOM `KeyboardKey.code`s to the characters they produce.
final Map<String, LayoutEntry> entries;
}
| engine/tools/gen_web_locale_keymap/lib/layout_types.dart/0 | {
"file_path": "engine/tools/gen_web_locale_keymap/lib/layout_types.dart",
"repo_id": "engine",
"token_count": 560
} | 472 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:githooks/githooks.dart';
import 'package:litetest/litetest.dart';
void main() {
test('Fails gracefully without a command', () async {
int? result;
try {
result = await run(<String>[]);
} catch (e, st) {
fail('Unexpected exception: $e\n$st');
}
expect(result, equals(1));
});
test('Fails gracefully with an unknown command', () async {
int? result;
try {
result = await run(<String>['blah']);
} catch (e, st) {
fail('Unexpected exception: $e\n$st');
}
expect(result, equals(1));
});
test('Fails gracefully without --flutter', () async {
int? result;
try {
result = await run(<String>['pre-push']);
} catch (e, st) {
fail('Unexpected exception: $e\n$st');
}
expect(result, equals(1));
});
test('Fails gracefully when --flutter is not an absolute path', () async {
int? result;
try {
result = await run(<String>[
'pre-push',
'--flutter',
'non/absolute',
]);
} catch (e, st) {
fail('Unexpected exception: $e\n$st');
}
expect(result, equals(1));
});
test('Fails gracefully when --flutter does not exist', () async {
int? result;
try {
result = await run(<String>[
'pre-push',
'--flutter',
if (io.Platform.isWindows) r'C:\does\not\exist'
else '/does/not/exist',
]);
} catch (e, st) {
fail('Unexpected exception: $e\n$st');
}
expect(result, equals(1));
});
test('post-merge runs successfully', () async {
int? result;
try {
final io.Directory flutterPath = io.File(io.Platform.script.path)
.parent.parent.parent;
result = await run(<String>[
'post-merge',
'--flutter',
flutterPath.path,
]);
} catch (e, st) {
fail('Unexpected exception: $e\n$st');
}
expect(result, equals(0));
});
test('pre-rebase runs successfully', () async {
int? result;
try {
final io.Directory flutterPath = io.File(io.Platform.script.path)
.parent.parent.parent;
result = await run(<String>[
'pre-rebase',
'--flutter',
flutterPath.path,
]);
} catch (e, st) {
fail('Unexpected exception: $e\n$st');
}
expect(result, equals(0));
});
test('post-checkout runs successfully', () async {
int? result;
try {
final io.Directory flutterPath = io.File(io.Platform.script.path)
.parent.parent.parent;
result = await run(<String>[
'post-checkout',
'--flutter',
flutterPath.path,
]);
} catch (e, st) {
fail('Unexpected exception: $e\n$st');
}
expect(result, equals(0));
});
}
| engine/tools/githooks/test/githooks_test.dart/0 | {
"file_path": "engine/tools/githooks/test/githooks_test.dart",
"repo_id": "engine",
"token_count": 1262
} | 473 |
// Copyright 2013 The Flutter 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:collection';
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
import 'src/header_file.dart';
/// Checks C++ header files for header guards.
@immutable
final class HeaderGuardCheck {
/// Creates a new header guard checker.
HeaderGuardCheck({
required this.source,
required this.exclude,
this.include = const <String>[],
this.fix = false,
StringSink? stdOut,
StringSink? stdErr,
}) : _stdOut = stdOut ?? io.stdout, _stdErr = stdErr ?? io.stderr;
/// Parses the command line arguments and creates a new header guard checker.
factory HeaderGuardCheck.fromCommandLine(List<String> arguments) {
final ArgResults argResults = _parser.parse(arguments);
return HeaderGuardCheck(
source: Engine.fromSrcPath(argResults['root'] as String),
include: argResults['include'] as List<String>,
exclude: argResults['exclude'] as List<String>,
fix: argResults['fix'] as bool,
);
}
/// Engine source root.
final Engine source;
/// Whether to automatically fix most header guards.
final bool fix;
/// Path directories to include in the check.
final List<String> include;
/// Path directories to exclude from the check.
final List<String> exclude;
/// Stdout.
final StringSink _stdOut;
/// Stderr.
final StringSink _stdErr;
/// Runs the header guard check.
Future<int> run() async {
final List<HeaderFile> badFiles = _checkFiles(_findIncludedHeaderFiles()).toList();
if (badFiles.isNotEmpty) {
_stdOut.writeln('The following ${badFiles.length} files have invalid header guards:');
for (final HeaderFile headerFile in badFiles) {
_stdOut.writeln(' ${headerFile.path}');
}
// If we're fixing, fix the files.
if (fix) {
for (final HeaderFile headerFile in badFiles) {
headerFile.fix(engineRoot: source.flutterDir.path);
}
_stdOut.writeln('Fixed ${badFiles.length} files.');
return 0;
}
return 1;
}
return 0;
}
Iterable<io.File> _findIncludedHeaderFiles() sync* {
final Queue<String> queue = Queue<String>();
final Set<String> yielded = <String>{};
if (include.isEmpty) {
queue.add(source.flutterDir.path);
} else {
queue.addAll(include);
}
while (queue.isNotEmpty) {
final String path = queue.removeFirst();
if (path.endsWith('.h')) {
if (!_isExcluded(path) && yielded.add(path)) {
yield io.File(path);
}
} else if (io.FileSystemEntity.isDirectorySync(path)) {
if (_isExcluded(path)) {
continue;
}
final io.Directory directory = io.Directory(path);
for (final io.FileSystemEntity entity in directory.listSync(recursive: true)) {
if (entity is io.File && entity.path.endsWith('.h')) {
queue.add(entity.path);
}
}
} else {
// Neither a header file nor a directory that might contain header files.
}
}
}
bool _isExcluded(String path) {
for (final String excludePath in exclude) {
final String relativePath = p.relative(excludePath, from: source.flutterDir.path);
if (p.isWithin(relativePath, path) || p.equals(relativePath, path)) {
return true;
}
}
return false;
}
Iterable<HeaderFile> _checkFiles(Iterable<io.File> headers) sync* {
for (final io.File header in headers) {
final HeaderFile headerFile = HeaderFile.parse(header.path);
if (headerFile.pragmaOnce != null) {
_stdErr.writeln(headerFile.pragmaOnce!.message('Unexpected #pragma once'));
yield headerFile;
continue;
}
if (headerFile.guard == null) {
_stdErr.writeln('Missing header guard in ${headerFile.path}');
yield headerFile;
continue;
}
final String expectedGuard = headerFile.computeExpectedName(engineRoot: source.flutterDir.path);
if (headerFile.guard!.ifndefValue != expectedGuard) {
_stdErr.writeln(headerFile.guard!.ifndefSpan!.message('Expected #ifndef $expectedGuard'));
yield headerFile;
continue;
}
if (headerFile.guard!.defineValue != expectedGuard) {
_stdErr.writeln(headerFile.guard!.defineSpan!.message('Expected #define $expectedGuard'));
yield headerFile;
continue;
}
if (headerFile.guard!.endifValue != expectedGuard) {
_stdErr.writeln(headerFile.guard!.endifSpan!.message('Expected #endif // $expectedGuard'));
yield headerFile;
continue;
}
}
}
}
final Engine? _engine = Engine.tryFindWithin(p.dirname(p.fromUri(io.Platform.script)));
final ArgParser _parser = ArgParser()
..addFlag(
'fix',
help: 'Automatically fixes most header guards.',
)
..addOption(
'root',
abbr: 'r',
help: 'Path to the engine source root.',
valueHelp: 'path/to/engine/src',
defaultsTo: _engine?.srcDir.path,
)
..addMultiOption(
'include',
abbr: 'i',
help: 'Paths to include in the check.',
valueHelp: 'path/to/dir/or/file (relative to the engine root)',
defaultsTo: <String>[],
)
..addMultiOption(
'exclude',
abbr: 'e',
help: 'Paths to exclude from the check.',
valueHelp: 'path/to/dir/or/file (relative to the engine root)',
defaultsTo: _engine != null ? <String>[
'build',
'impeller/compiler/code_gen_template.h',
'prebuilts',
'third_party',
] : null,
);
| engine/tools/header_guard_check/lib/header_guard_check.dart/0 | {
"file_path": "engine/tools/header_guard_check/lib/header_guard_check.dart",
"repo_id": "engine",
"token_count": 2248
} | 474 |
GCC RUNTIME LIBRARY EXCEPTION
Version 3.1, 31 March 2009
Copyright (C) 2009 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
This GCC Runtime Library Exception ("Exception") is an additional
permission under section 7 of the GNU General Public License, version
3 ("GPLv3"). It applies to a given file (the "Runtime Library") that
bears a notice placed by the copyright holder of the file stating that
the file is governed by GPLv3 along with this Exception.
When you use GCC to compile a program, GCC may combine portions of
certain GCC header files and runtime libraries with the compiled
program. The purpose of this Exception is to allow compilation of
non-GPL (including proprietary) programs to use, in this way, the
header files and runtime libraries covered by this Exception.
0. Definitions.
A file is an "Independent Module" if it either requires the Runtime
Library for execution after a Compilation Process, or makes use of an
interface provided by the Runtime Library, but is not otherwise based
on the Runtime Library.
"GCC" means a version of the GNU Compiler Collection, with or without
modifications, governed by version 3 (or a specified later version) of
the GNU General Public License (GPL) with the option of using any
subsequent versions published by the FSF.
"GPL-compatible Software" is software whose conditions of propagation,
modification and use would permit combination with GCC in accord with
the license of GCC.
"Target Code" refers to output from any compiler for a real or virtual
target processor architecture, in executable form or suitable for
input to an assembler, loader, linker and/or execution
phase. Notwithstanding that, Target Code does not include data in any
format that is used as a compiler intermediate representation, or used
for producing a compiler intermediate representation.
The "Compilation Process" transforms code entirely represented in
non-intermediate languages designed for human-written code, and/or in
Java Virtual Machine byte code, into Target Code. Thus, for example,
use of source code generators and preprocessors need not be considered
part of the Compilation Process, since the Compilation Process can be
understood as starting with the output of the generators or
preprocessors.
A Compilation Process is "Eligible" if it is done using GCC, alone or
with other GPL-compatible software, or if it is done without using any
work based on GCC. For example, using non-GPL-compatible Software to
optimize any GCC intermediate representations would not qualify as an
Eligible Compilation Process.
1. Grant of Additional Permission.
You have permission to propagate a work of Target Code formed by
combining the Runtime Library with Independent Modules, even if such
propagation would otherwise violate the terms of GPLv3, provided that
all Target Code was generated by Eligible Compilation Processes. You
may then convey such a combination under terms of your choice,
consistent with the licensing of the Independent Modules.
2. No Weakening of GCC Copyleft.
The availability of this Exception does not imply any general
presumption that third-party software is unaffected by the copyleft
requirements of the license of GCC.
| engine/tools/licenses/data/gpl-gcc-exception-3.1/0 | {
"file_path": "engine/tools/licenses/data/gpl-gcc-exception-3.1",
"repo_id": "engine",
"token_count": 754
} | 475 |
// Copyright 2013 The Flutter 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 'regexp_debug.dart';
// Directories or files that are not included in the final binaries.
//
// These are absolute paths relative to the root of the buildroot repository
// as checked out after gclient imports all the dependencies.
//
// Do not provide trailing slashes for directories.
//
// Including a directory in this list excludes the entire subtree rooted at
// that directory.
//
// Keep this list in lexical order.
final Set<String> skippedPaths = <String>{
r'README.md',
r'build', // only used by build
r'build_overrides', // only used by build
r'buildtools', // only used by build
r'flutter/build',
r'flutter/build_overrides', // only used by build
r'flutter/ci',
r'flutter/docs',
r'flutter/flutter_frontend_server',
r'flutter/impeller/docs',
r'flutter/lib/web_ui/build', // this is compiler-generated output
r'flutter/lib/web_ui/dev', // these are build tools; they do not end up in Engine artifacts
r'flutter/prebuilts',
r'flutter/sky/packages/sky_engine/LICENSE',
r'flutter/third_party/angle/android',
r'flutter/third_party/angle/doc',
r'flutter/third_party/angle/extensions',
r'flutter/third_party/angle/infra',
r'flutter/third_party/angle/scripts',
r'flutter/third_party/angle/src/libANGLE/renderer/metal/doc',
r'flutter/third_party/angle/src/libANGLE/renderer/vulkan/doc',
r'flutter/third_party/angle/src/third_party/volk', // We don't use Vulkan in our ANGLE build.
r'flutter/third_party/angle/third_party', // Unused by Flutter: BUILD files with forwarding targets (but no code).
r'flutter/third_party/angle/tools', // These are build-time tools, and aren't shipped.
r'flutter/third_party/angle/util',
r'flutter/third_party/benchmark', // only used by tests
r'flutter/third_party/boringssl/src/crypto/err/err_data_generate.go',
r'flutter/third_party/boringssl/src/fuzz', // testing tools, not shipped
r'flutter/third_party/boringssl/src/rust', // rust-related code is not shipped
r'flutter/third_party/boringssl/src/util', // code generators, not shipped
r'flutter/third_party/depot_tools', // only used for the Windows build system.
r'flutter/third_party/expat/expat/doc',
r'flutter/third_party/expat/expat/win32/expat.iss',
r'flutter/third_party/flatbuffers/android',
r'flutter/third_party/flatbuffers/benchmarks',
r'flutter/third_party/flatbuffers/docs',
r'flutter/third_party/flatbuffers/go',
r'flutter/third_party/flatbuffers/net',
r'flutter/third_party/flatbuffers/php',
r'flutter/third_party/flatbuffers/python',
r'flutter/third_party/flatbuffers/rust',
r'flutter/third_party/flatbuffers/ts',
r'flutter/third_party/freetype2/builds',
r'flutter/third_party/freetype2/src/tools',
r'flutter/third_party/glfw/deps', // Only used by examples and tests; not linked in build.
r'flutter/third_party/glfw/docs',
r'flutter/third_party/gn',
r'flutter/third_party/google_fonts_for_unit_tests', // only used in web unit tests
r'flutter/third_party/harfbuzz/docs',
r'flutter/third_party/harfbuzz/util', // utils are command line tools that do not end up in the binary
r'flutter/third_party/icu/filters',
r'flutter/third_party/icu/fuzzers',
r'flutter/third_party/icu/scripts',
r'flutter/third_party/icu/source/common/unicode/uvernum.h', // this file contains strings that confuse the analysis
r'flutter/third_party/icu/source/config',
r'flutter/third_party/icu/source/data/brkitr/dictionaries/burmesedict.txt', // explicitly handled by ICU license
r'flutter/third_party/icu/source/data/brkitr/dictionaries/cjdict.txt', // explicitly handled by ICU license
r'flutter/third_party/icu/source/data/brkitr/dictionaries/laodict.txt', // explicitly handled by ICU license
r'flutter/third_party/icu/source/data/dtd',
r'flutter/third_party/imgui',
r'flutter/third_party/inja/doc', // documentation
r'flutter/third_party/inja/third_party/amalgamate', // only used at build time
r'flutter/third_party/inja/third_party/include/doctest', // seems to be a unit test library
r'flutter/third_party/json/docs',
r'flutter/third_party/libpng/contrib', // not linked in
r'flutter/third_party/libpng/mips', // not linked in
r'flutter/third_party/libpng/powerpc', // not linked in
r'flutter/third_party/libpng/projects', // not linked in
r'flutter/third_party/libpng/scripts', // not linked in
r'flutter/third_party/libtess2/Contrib/nanosvg.c', // only used by the ../Example
r'flutter/third_party/libtess2/Contrib/nanosvg.h', // only used by the ../Example
r'flutter/third_party/libtess2/Example',
r'flutter/third_party/libwebp/doc',
r'flutter/third_party/libwebp/gradle', // not included in our build
r'flutter/third_party/libwebp/swig', // not included in our build
r'flutter/third_party/libwebp/webp_js',
r'flutter/third_party/ninja', // build system
r'flutter/third_party/ocmock', // only used for tests
r'flutter/third_party/perfetto/debian', // contains nothing that ends up in the binary executable
r'flutter/third_party/perfetto/infra', // contains nothing that ends up in the binary executable
r'flutter/third_party/perfetto/protos', // contains nothing that ends up in the binary executable
r'flutter/third_party/perfetto/python/perfetto/trace_processor', // contains nothing that ends up in the binary executable
r'flutter/third_party/perfetto/src/ipc', // contains nothing that ends up in the binary executable
r'flutter/third_party/perfetto/src/profiling/memory', // contains nothing that ends up in the binary executable
r'flutter/third_party/perfetto/src/tools', // contains nothing that ends up in the binary executable
r'flutter/third_party/perfetto/src/trace_processor', // contains nothing that ends up in the binary executable
r'flutter/third_party/perfetto/src/traced', // contains nothing that ends up in the binary executable
r'flutter/third_party/perfetto/src/tracing', // contains nothing that ends up in the binary executable
r'flutter/third_party/pkg/archive', // contains nothing that ends up in the binary executable
r'flutter/third_party/pkg/equatable',
r'flutter/third_party/pkg/flutter_packages',
r'flutter/third_party/pkg/gcloud',
r'flutter/third_party/pkg/googleapis',
r'flutter/third_party/pkg/platform',
r'flutter/third_party/pkg/process',
r'flutter/third_party/pkg/process_runner',
r'flutter/third_party/pkg/vector_math',
r'flutter/third_party/protobuf', // build-time dependency only
r'flutter/third_party/pyyaml', // build-time dependency only
r'flutter/third_party/rapidjson/contrib', // contains nothing that ends up in the binary executable
r'flutter/third_party/rapidjson/doc', // documentation
r'flutter/third_party/shaderc/third_party/LICENSE.glslang', // unclear what the purpose of this file is
r'flutter/third_party/shaderc/third_party/LICENSE.spirv-tools', // unclear what the purpose of this file is
r'flutter/third_party/skia/bazel', // contains nothing that ends up in the binary executable
r'flutter/third_party/skia/bench',
r'flutter/third_party/skia/demos.skia.org',
r'flutter/third_party/skia/docs',
r'flutter/third_party/skia/experimental',
r'flutter/third_party/skia/infra', // contains nothing that ends up in the binary executable
r'flutter/third_party/skia/modules/canvaskit/go/gold_test_env',
r'flutter/third_party/skia/platform_tools', // contains nothing that ends up in the binary executable
r'flutter/third_party/skia/resources', // contains nothing that ends up in the binary executable
r'flutter/third_party/skia/samplecode',
r'flutter/third_party/skia/site',
r'flutter/third_party/skia/specs',
r'flutter/third_party/skia/third_party/freetype2', // we use our own version
r'flutter/third_party/skia/third_party/icu', // we use our own version
r'flutter/third_party/skia/third_party/libjpeg-turbo', // we use our own version
r'flutter/third_party/skia/third_party/libpng', // we use our own version
r'flutter/third_party/skia/third_party/lua', // not linked in
r'flutter/third_party/skia/third_party/vello', // not linked in
r'flutter/third_party/skia/tools', // contains nothing that ends up in the binary executable
r'flutter/third_party/stb',
r'flutter/third_party/swiftshader', // only used on hosts for tests
r'flutter/third_party/test_shaders', // for tests only
r'flutter/third_party/tinygltf',
r'flutter/third_party/txt/third_party/fonts',
r'flutter/third_party/vulkan-deps/glslang/LICENSE', // excluded to make sure we don't accidentally apply it as a default license
r'flutter/third_party/vulkan-deps/glslang/src/LICENSE.txt', // redundant with licenses inside files
r'flutter/third_party/vulkan-deps/glslang/src/glslang/OSDependent/Web', // we only use glslang in impellerc, not in web apps
r'flutter/third_party/vulkan-deps/glslang/src/kokoro', // only build files
r'flutter/third_party/vulkan-deps/spirv-cross/src/LICENSES', // directory with license templates
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders-hlsl', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders-hlsl-no-opt', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders-msl', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders-msl-no-opt', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders-no-opt', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders-other', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders-reflection', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders-ue4', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-cross/src/shaders-ue4-no-opt', // used by regression tests
r'flutter/third_party/vulkan-deps/spirv-headers', // only used on hosts for tests
r'flutter/third_party/vulkan-deps/spirv-tools', // only used on hosts for tests
r'flutter/third_party/vulkan-deps/vulkan-headers/src/LICENSE.md', // redundant with licenses inside files
r'flutter/third_party/vulkan-deps/vulkan-headers/src/registry',
r'flutter/third_party/vulkan-deps/vulkan-loader', // on hosts for tests
r'flutter/third_party/vulkan-deps/vulkan-tools', // on hosts for tests
r'flutter/third_party/vulkan-deps/vulkan-utility-libraries/src/LICENSE.md', // redundant with licenses inside files
r'flutter/third_party/vulkan-deps/vulkan-validation-layers/src/docs',
r'flutter/third_party/vulkan_memory_allocator/bin',
r'flutter/third_party/vulkan_memory_allocator/docs',
r'flutter/third_party/vulkan_memory_allocator/media',
r'flutter/third_party/vulkan_memory_allocator/src',
r'flutter/third_party/vulkan_memory_allocator/tools',
r'flutter/third_party/wuffs/docs',
r'flutter/third_party/wuffs/script',
r'flutter/third_party/yapf', // only used for code formatting
r'flutter/tools',
r'flutter/web_sdk', // this code is not linked into Flutter apps; it's only used by engine tests and tools
r'fuchsia/sdk/linux/docs',
r'fuchsia/sdk/linux/meta',
r'fuchsia/sdk/linux/NOTICE.fuchsia', // covers things that contribute to the Fuchsia SDK; see fxb/94240
r'fuchsia/sdk/linux/packages/blobs', // See https://github.com/flutter/flutter/issues/134042.
r'fuchsia/sdk/linux/tools',
r'fuchsia/sdk/mac/docs',
r'fuchsia/sdk/mac/meta',
r'fuchsia/sdk/mac/NOTICE.fuchsia',
r'fuchsia/sdk/mac/tools',
r'out', // output of build
r'third_party/android_embedding_dependencies', // Not shipped. Used only for the build-time classpath, and for the in-tree testing framework for Android
r'third_party/android_tools', // excluded on advice
r'third_party/dart/benchmarks', // not shipped in binary
r'third_party/dart/build', // not shipped in binary
r'third_party/dart/docs', // not shipped in binary
r'third_party/dart/pkg', // packages that don't become part of the binary (e.g. the analyzer)
r'third_party/dart/runtime/bin/ffi_test',
r'third_party/dart/runtime/docs',
r'third_party/dart/runtime/vm/service',
r'third_party/dart/sdk/lib/html/doc',
r'third_party/dart/sdk/lib/svg/dart2js', // generated from other sources
r'third_party/dart/third_party/binary_size', // not linked in
r'third_party/dart/third_party/binaryen', // not linked in
r'third_party/dart/third_party/d3', // Siva says "that is the charting library used by the binary size tool"
r'third_party/dart/third_party/d8', // testing tool for dart2js
r'third_party/dart/third_party/devtools', // not linked in
r'third_party/dart/third_party/fallback_root_certificates/certdata.pem',
r'third_party/dart/third_party/fallback_root_certificates/certdata.txt',
r'third_party/dart/third_party/firefox_jsshell', // testing tool for dart2js
r'third_party/dart/third_party/pkg',
r'third_party/dart/third_party/pkg_tested',
r'third_party/dart/third_party/requirejs', // only used by DDC
r'third_party/dart/tools', // not shipped in binary
r'third_party/gradle',
r'third_party/java', // only used for Android builds
r'third_party/libcxx/benchmarks',
r'third_party/libcxx/docs',
r'third_party/libcxx/src/support/solaris',
r'third_party/libcxx/utils',
r'third_party/libcxxabi/www',
r'third_party/libxml', // dependency of the testing system that we don't actually use
r'third_party/web_dependencies/canvaskit', // redundant; covered by Skia dependencies
r'third_party/zlib/contrib/minizip/miniunz.c', // sample file
r'third_party/zlib/contrib/minizip/minizip.c', // sample file
r'tools', // not distributed in binary
};
// Directories that should be skipped anywhere we find them.
//
// Any directory whose name matches one of these strings is skipped, including
// its entire subtree.
//
// Keep this list in lexical order.
final Set<String> skippedCommonDirectories = <String>{
r'.bazelci',
r'.build-id',
r'.ccls-cache',
r'.cipd',
r'.dart_tool',
r'.git',
r'.github',
r'.reuse',
r'.versions',
r'.vscode',
r'CMake',
r'Test',
r'cmake',
r'example',
r'examples',
r'fixtures',
r'googletest',
r'javatests',
r'jvmTest',
r'playground',
r'samples',
r'test',
r'test.disabled',
r'test_runner',
r'test_support',
r'testdata',
r'testing',
r'tests',
r'unit_tests',
};
// Filenames of files we never look at.
//
// Any file with a name in this list is skipped.
//
// Be careful about adding files like "LICENSE" or "README" (and such
// variants) to this list as many packages put important license text in those
// files and we don't want to skip them. Only include files here whose names
// we would want to skip in ANY package.
//
// Keep this list in lexical order.
final Set<String> skippedCommonFiles = <String>{
r'.DS_Store',
r'.appveyor.yml',
r'.bazelrc',
r'.bazelversion',
r'.clang-format',
r'.clang-tidy',
r'.editorconfig',
r'.eslintrc.js',
r'.gitattributes',
r'.gitconfig',
r'.gitignore',
r'.gitlab-ci.yml',
r'.gitmodules',
r'.gn',
r'.lgtm.yml',
r'.mailmap',
r'.packages',
r'.project',
r'.style.yapf',
r'.travis.yml',
r'.vpython',
r'.vpython3',
r'.yapfignore',
r'ABSEIL_ISSUE_TEMPLATE.md',
r'ANNOUNCE',
r'API-CONVENTIONS.md',
r'AUTHORS',
r'BREAKING-CHANGES.md',
r'BUILD.bazel',
r'BUILD.md',
r'BUILDING.md',
r'Brewfile',
r'CHANGES',
r'CHANGES.md',
r'CITATION.cff',
r'CMake.README',
r'CMakeLists.txt',
r'CODEOWNERS',
r'CODE_CONVENTIONS.md',
r'CODE_OF_CONDUCT.adoc',
r'CODE_OF_CONDUCT.md',
r'CONFIG.md',
r'CONTRIBUTORS',
r'CONTRIBUTORS.md',
r'CPPLINT.cfg',
r'CQ_COMMITTERS',
r'CREDITS.TXT',
r'Changes',
r'CodingStandard.md',
r'DEPS',
r'DIR_METADATA',
r'Dockerfile',
r'Doxyfile',
r'FAQ.md',
r'FIPS.md',
r'FUZZING.md',
r'FeatureSupportGL.md',
r'FormatTables.md',
r'Formatters.md',
r'GIT_REVISION',
r'HACKING.md',
r'INCORPORATING.md',
r'LAYER_CONFIGURATION.md',
r'LOCALE_DEPS.json',
r'MANIFEST.in',
r'MANIFEST.txt',
r'METADATA',
r'NEWS',
r'OWNERS',
r'OWNERS.android',
r'PATENT_GRANT',
r'PORTING.md',
r'README.asciidoc',
r'RELEASE_NOTES.TXT',
r'RELEASING.md',
r'RapidJSON.pc.in',
r'RapidJSONConfig.cmake.in',
r'RapidJSONConfigVersion.cmake.in',
r'SANDBOXING.md',
r'SECURITY.md',
r'STYLE.md',
r'TESTING.md',
r'THANKS',
r'TODO',
r'TODO.TXT',
r'TRADEMARK',
r'UPGRADES.md',
r'UniformBlockToStructuredBufferTranslation.md',
r'WATCHLISTS',
r'WORKSPACE',
r'WORKSPACE.bazel',
r'_config.yml',
r'additional_readme_paths.json',
r'alg_outline.md',
r'allowed_experiments.json',
r'amalgamate_config.json',
r'api_readme.md',
r'appveyor-reqs-install.cmd',
r'appveyor.yml',
r'build.xml',
r'codereview.settings',
r'coderules.txt',
r'configure-ac-style.md',
r'doxygen.config',
r'example.html',
r'gerrit.md',
r'gradle.properties',
r'include_dirs.js',
r'known_good.json',
r'known_good_khr.json',
r'libraries.json',
r'library.json',
r'license-checker.cfg',
r'license.html',
r'memory-sanitizer-blacklist.txt',
r'meson.build',
r'meta.json',
r'minizip.md',
r'package.json',
r'pkgdataMakefile.in',
r'pom.xml',
r'pubspec.lock',
r'requirements-dev.txt',
r'requirements.txt',
r'sources.txt',
r'structure.txt',
r'swift.swiftformat',
r'sync.txt',
r'unit_tests.md',
r'version',
r'version_history.json',
r'vms_make.com',
r'vmservice_libraries.json',
};
// Extensions that we just never look at.
//
// We explicitly do not exclude .txt, .md, .TXT, and .MD files because it is common
// for licenses to be in such files.
//
// This list only works for extensions with a single dot.
//
// Keep this list in lexical order.
final Set<String> skippedCommonExtensions = <String>{
r'.1',
r'.3',
r'.5',
r'.autopkg',
r'.build',
r'.bzl',
r'.cmake',
r'.css',
r'.gn',
r'.gni',
r'.gradle',
r'.log',
r'.m4',
r'.mk',
r'.pl',
r'.py',
r'.pyc',
r'.pylintrc',
r'.sha1',
r'.yaml',
r'.~',
};
// Patterns for files and directories we should skip.
//
// Keep this list to a minimum, preferring all the other lists
// in this file. Testing patterns is more expensive.
//
// Keep this list in lexical order.
final List<Pattern> skippedFilePatterns = <Pattern>[
RegExp(r'\.[1-8]\.in$'), // man page source files (e.g. foo.1.in)
RegExp(r'/(?:_|\b)CONTRIBUTING(?:_|\b)[^/]*$'),
RegExp(r'/(?:_|\b)LAST_UPDATE(?:_|\b)[^/]*$'),
RegExp(r'/(?:_|\b)PATENTS(?:_|\b)[^/]*$'),
RegExp(r'/(?:_|\b)README(?!\.IJG)(?:_|\b)[^/]*$', caseSensitive: false),
RegExp(r'/(?:_|\b)VERSION(?:_|\b)[^/]*$'),
RegExp(r'/CHANGELOG(?:\.[.A-Z0-9]+)?$', caseSensitive: false),
RegExp(r'/INSTALL(?:\.[a-zA-Z0-9]+)?$'),
RegExp(r'/Makefile(?:\.[.A-Z0-9]+)?$', caseSensitive: false),
RegExp(r'\.~[0-9]+~$', expectNoMatch: true), // files that end in ".~1~", a backup convention of some IDEs
RegExp(r'\bmanual\.txt$'),
RegExp(r'^flutter/(?:.+/)*[^/]+_unittests?\.[^/]+$'),
RegExp(r'^flutter/lib/web_ui/lib/assets/ahem\.ttf$', expectNoMatch: true), // this gitignored file exists only for testing purposes
RegExp(r'^flutter/sky/packages/sky_engine/LICENSE$'), // that is the output of this script
RegExp(r'^flutter/third_party/abseil-cpp/(?:.+/)*[^/]+_test\.[^/]+$'),
RegExp(r'^flutter/third_party/angle/(?:.+/)*[^/]+_unittest\.[^/]+$'),
RegExp(r'^flutter/third_party/boringssl/(?:.+/)*[^/]+_test\.[^/]+$'),
RegExp(r'^flutter/third_party/boringssl/src/crypto/fipsmodule/bn/[^/]+.go$'),
RegExp(r'^flutter/third_party/boringssl/src/crypto/fipsmodule/ec/[^/]+.go$'),
RegExp(r'^flutter/third_party/freetype2/docs/(?!FTL\.TXT$).+'), // ignore all documentation except the license
RegExp(r'^third_party/dart/(?:.+/)*[^/]+_test\.[^/]+$'),
RegExp(r'^third_party/zlib/(?:.+/)*[^/]+_unittest\.[^/]+$'),
];
| engine/tools/licenses/lib/paths.dart/0 | {
"file_path": "engine/tools/licenses/lib/paths.dart",
"repo_id": "engine",
"token_count": 7705
} | 476 |
// Copyright 2013 The Flutter 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;
import 'dart:io' as io;
import 'package:engine_build_configs/engine_build_configs.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:path/path.dart' as p;
import 'package:platform/platform.dart';
import 'package:process_runner/process_runner.dart';
// This is an example of how to use the APIs of this library to parse and
// execute the build configurations json files under ci/builders.
//
// Usage:
// $ dart bin/run.dart [build config name] [build name]
// For example:
// $ dart bin/run.dart mac_unopt host_debug_unopt
//
// The build config names are the names of the json files under ci/builders
// The build names are the "name" fields of the maps in the list of "builds".
void main(List<String> args) async {
final String? configName;
final String? buildName;
if (args.length >= 2) {
configName = args[0];
buildName = args[1];
} else {
io.stderr.writeln(r'''
Usage:
$ dart bin/run.dart [build config name] [build name]
For example:
$ dart bin/run.dart mac_unopt host_debug_unopt
The build config names are the names of the json files under ci/builders.
The build names are the "name" fields of the maps in the list of "builds".
''');
io.exitCode = 1;
return;
}
// Find the engine repo.
final Engine engine;
try {
engine = Engine.findWithin();
} catch (e) {
io.stderr.writeln(e);
io.exitCode = 1;
return;
}
// Find and parse the engine build configs.
final io.Directory buildConfigsDir = io.Directory(p.join(
engine.flutterDir.path,
'ci',
'builders',
));
final BuildConfigLoader loader = BuildConfigLoader(
buildConfigsDir: buildConfigsDir,
);
// Treat it as an error if no build configs were found. The caller likely
// expected to find some.
final Map<String, BuilderConfig> configs = loader.configs;
if (configs.isEmpty) {
io.stderr.writeln(
'Error: No build configs found under ${buildConfigsDir.path}',
);
io.exitCode = 1;
return;
}
if (loader.errors.isNotEmpty) {
loader.errors.forEach(io.stderr.writeln);
io.exitCode = 1;
}
// Check the parsed build configs for validity.
final BuilderConfig? targetConfig = configs[configName];
if (targetConfig == null) {
io.stderr.writeln('Build config "$configName" not found.');
io.exitCode = 1;
return;
}
final List<String> buildConfigErrors = targetConfig.check(configName);
if (buildConfigErrors.isNotEmpty) {
io.stderr.writeln('Errors in "$configName":');
for (final String error in buildConfigErrors) {
io.stderr.writeln(' $error');
}
io.exitCode = 1;
return;
}
Build? targetBuild;
for (int i = 0; i < targetConfig.builds.length; i++) {
final Build build = targetConfig.builds[i];
if (build.name == buildName) {
targetBuild = build;
}
}
if (targetBuild == null) {
io.stderr.writeln(
'Target build not found. No build called $buildName in $configName',
);
io.exitCode = 1;
return;
}
// If RBE config files aren't in the tree, then disable RBE.
final String rbeConfigPath = p.join(
engine.srcDir.path,
'flutter',
'build',
'rbe',
);
final List<String> extraGnArgs = <String>[
if (!io.Directory(rbeConfigPath).existsSync()) '--no-rbe',
];
final BuildRunner buildRunner = BuildRunner(
platform: const LocalPlatform(),
processRunner: ProcessRunner(),
abi: ffi.Abi.current(),
engineSrcDir: engine.srcDir,
build: targetBuild,
extraGnArgs: extraGnArgs,
runGenerators: false,
runTests: false,
);
void handler(RunnerEvent event) {
switch (event) {
case RunnerStart():
io.stdout.writeln('$event: ${event.command.join(' ')}');
case RunnerProgress(done: true):
io.stdout.writeln(event);
case RunnerProgress(done: false):
{
final int width = io.stdout.terminalColumns;
final String percent = '${event.percent.toStringAsFixed(1)}%';
final String fraction = '(${event.completed}/${event.total})';
final String prefix = '[${event.name}] $percent $fraction ';
final int remainingSpace = width - prefix.length;
final String what;
if (remainingSpace >= event.what.length) {
what = event.what;
} else {
what = event.what.substring(event.what.length - remainingSpace + 1);
}
final String spaces = ' ' * width;
io.stdout.write('$spaces\r'); // Erase the old line.
io.stdout.write('$prefix$what\r'); // Print the new line.
}
default:
io.stdout.writeln(event);
}
}
final bool buildResult = await buildRunner.run(handler);
io.exitCode = buildResult ? 0 : 1;
}
| engine/tools/pkg/engine_build_configs/bin/run.dart/0 | {
"file_path": "engine/tools/pkg/engine_build_configs/bin/run.dart",
"repo_id": "engine",
"token_count": 1870
} | 477 |
# `git_repo_tools`
This is a repo-internal library for `flutter/engine`, that contains shared code
for writing tools that want to interact with the `git` repository. For example,
finding all changed files in the current branch:
```dart
import 'dart:io' as io show File, Platform;
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:git_repo_tools/git_repo_tools.dart';
import 'package:path/path.dart' as path;
void main() async {
// Finds the root of the engine repository from the current script.
final Engine engine = Engine.findWithin(path.dirname(path.fromUri(io.Platform.script)));
final GitRepo gitRepo = GitRepo(engine.flutterDir);
for (final io.File file in gitRepo.changedFiles) {
print('Changed file: ${file.path}');
}
}
```
| engine/tools/pkg/git_repo_tools/README.md/0 | {
"file_path": "engine/tools/pkg/git_repo_tools/README.md",
"repo_id": "engine",
"token_count": 252
} | 478 |
// Copyright 2013 The Flutter 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_DEVICE_H_
#define FLUTTER_VULKAN_VULKAN_DEVICE_H_
#include <vector>
#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/macros.h"
#include "flutter/vulkan/procs/vulkan_handle.h"
namespace vulkan {
class VulkanProcTable;
class VulkanSurface;
class VulkanDevice {
public:
/// @brief Create a new VkDevice with a resolved VkQueue suitable for
/// rendering with Skia.
///
VulkanDevice(VulkanProcTable& vk,
VulkanHandle<VkPhysicalDevice> physical_device,
bool enable_validation_layers);
/// @brief Wrap an existing VkDevice and VkQueue.
///
VulkanDevice(VulkanProcTable& vk,
VulkanHandle<VkPhysicalDevice> physical_device,
VulkanHandle<VkDevice> device,
uint32_t queue_family_index,
VulkanHandle<VkQueue> queue);
~VulkanDevice();
bool IsValid() const;
const VulkanHandle<VkDevice>& GetHandle() const;
const VulkanHandle<VkPhysicalDevice>& GetPhysicalDeviceHandle() const;
const VulkanHandle<VkQueue>& GetQueueHandle() const;
const VulkanHandle<VkCommandPool>& GetCommandPool() const;
uint32_t GetGraphicsQueueIndex() const;
void ReleaseDeviceOwnership();
[[nodiscard]] bool GetSurfaceCapabilities(
const VulkanSurface& surface,
VkSurfaceCapabilitiesKHR* capabilities) const;
[[nodiscard]] bool GetPhysicalDeviceFeatures(
VkPhysicalDeviceFeatures* features) const;
[[nodiscard]] bool GetPhysicalDeviceFeaturesSkia(
uint32_t* /* mask of GrVkFeatureFlags */ features) const;
[[nodiscard]] int ChooseSurfaceFormat(
const VulkanSurface& surface,
const std::vector<VkFormat>& desired_formats,
VkSurfaceFormatKHR* format) const;
[[nodiscard]] bool ChoosePresentMode(const VulkanSurface& surface,
VkPresentModeKHR* present_mode) const;
[[nodiscard]] bool QueueSubmit(
std::vector<VkPipelineStageFlags> wait_dest_pipeline_stages,
const std::vector<VkSemaphore>& wait_semaphores,
const std::vector<VkSemaphore>& signal_semaphores,
const std::vector<VkCommandBuffer>& command_buffers,
const VulkanHandle<VkFence>& fence) const;
[[nodiscard]] bool WaitIdle() const;
private:
VulkanProcTable& vk_;
VulkanHandle<VkPhysicalDevice> physical_device_;
VulkanHandle<VkDevice> device_;
VulkanHandle<VkQueue> queue_;
VulkanHandle<VkCommandPool> command_pool_;
uint32_t graphics_queue_index_;
bool valid_;
bool InitializeCommandPool();
std::vector<VkQueueFamilyProperties> GetQueueFamilyProperties() const;
FML_DISALLOW_COPY_AND_ASSIGN(VulkanDevice);
};
} // namespace vulkan
#endif // FLUTTER_VULKAN_VULKAN_DEVICE_H_
| engine/vulkan/vulkan_device.h/0 | {
"file_path": "engine/vulkan/vulkan_device.h",
"repo_id": "engine",
"token_count": 1096
} | 479 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "vulkan_utilities.h"
#include <algorithm>
#include <unordered_set>
#include "flutter/fml/build_config.h"
namespace vulkan {
// Whether to show Vulkan validation layer info messages in addition
// to the error messages.
bool ValidationLayerInfoMessagesEnabled() {
return false;
}
bool ValidationErrorsFatal() {
#if OS_FUCHSIA
return false;
#endif
return true;
}
static std::vector<std::string> InstanceOrDeviceLayersToEnable(
const VulkanProcTable& vk,
VkPhysicalDevice physical_device,
bool enable_validation_layers) {
if (!enable_validation_layers) {
return {};
}
// NOTE: The loader is sensitive to the ordering here. Please do not rearrange
// this list.
#if OS_FUCHSIA
// The other layers in the Fuchsia SDK seem to have a bug right now causing
// crashes, so it is only recommended that we use VK_LAYER_KHRONOS_validation
// until we have a confirmation that they are fixed.
const std::vector<std::string> candidates = {"VK_LAYER_KHRONOS_validation"};
#else
const std::vector<std::string> candidates = {
"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation",
"VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation",
"VK_LAYER_LUNARG_device_limits", "VK_LAYER_LUNARG_image",
"VK_LAYER_LUNARG_swapchain", "VK_LAYER_GOOGLE_unique_objects"};
#endif
uint32_t count = 0;
if (physical_device == VK_NULL_HANDLE) {
if (VK_CALL_LOG_ERROR(vk.EnumerateInstanceLayerProperties(
&count, nullptr)) != VK_SUCCESS) {
return {};
}
} else {
if (VK_CALL_LOG_ERROR(vk.EnumerateDeviceLayerProperties(
physical_device, &count, nullptr)) != VK_SUCCESS) {
return {};
}
}
std::vector<VkLayerProperties> properties;
properties.resize(count);
if (physical_device == VK_NULL_HANDLE) {
if (VK_CALL_LOG_ERROR(vk.EnumerateInstanceLayerProperties(
&count, properties.data())) != VK_SUCCESS) {
return {};
}
} else {
if (VK_CALL_LOG_ERROR(vk.EnumerateDeviceLayerProperties(
physical_device, &count, properties.data())) != VK_SUCCESS) {
return {};
}
}
std::unordered_set<std::string> available_extensions;
for (size_t i = 0; i < count; i++) {
available_extensions.emplace(properties[i].layerName);
}
std::vector<std::string> available_candidates;
for (const auto& candidate : candidates) {
auto found = available_extensions.find(candidate);
if (found != available_extensions.end()) {
available_candidates.emplace_back(candidate);
}
}
return available_candidates;
}
std::vector<std::string> InstanceLayersToEnable(const VulkanProcTable& vk,
bool enable_validation_layers) {
return InstanceOrDeviceLayersToEnable(vk, VK_NULL_HANDLE,
enable_validation_layers);
}
std::vector<std::string> DeviceLayersToEnable(
const VulkanProcTable& vk,
const VulkanHandle<VkPhysicalDevice>& physical_device,
bool enable_validation_layers) {
if (!physical_device) {
return {};
}
return InstanceOrDeviceLayersToEnable(vk, physical_device,
enable_validation_layers);
}
} // namespace vulkan
| engine/vulkan/vulkan_utilities.cc/0 | {
"file_path": "engine/vulkan/vulkan_utilities.cc",
"repo_id": "engine",
"token_count": 1384
} | 480 |
body {
margin: 0;
padding: 0;
}
iframe {
border: none;
}
| engine/web_sdk/web_engine_tester/lib/static/host.css/0 | {
"file_path": "engine/web_sdk/web_engine_tester/lib/static/host.css",
"repo_id": "engine",
"token_count": 29
} | 481 |
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="CanBeFinal" enabled="false" level="WARNING" enabled_by_default="false">
<option name="REPORT_CLASSES" value="false" />
<option name="REPORT_METHODS" value="false" />
<option name="REPORT_FIELDS" value="true" />
</inspection_tool>
<inspection_tool class="CodeBlock2Expr" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="ConstantConditions" enabled="true" level="WARNING" enabled_by_default="true">
<option name="SUGGEST_NULLABLE_ANNOTATIONS" value="true" />
<option name="DONT_REPORT_TRUE_ASSERT_STATEMENTS" value="false" />
<option name="TREAT_UNKNOWN_MEMBERS_AS_NULLABLE" value="true" />
</inspection_tool>
<inspection_tool class="FieldCanBeLocal" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="FieldMayBeFinal" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="HardCodedStringLiteral" enabled="false" level="WARNING" enabled_by_default="false">
<option name="ignoreForAssertStatements" value="true" />
<option name="ignoreForExceptionConstructors" value="true" />
<option name="ignoreForSpecifiedExceptionConstructors" value="" />
<option name="ignoreForJUnitAsserts" value="true" />
<option name="ignoreForClassReferences" value="true" />
<option name="ignoreForPropertyKeyReferences" value="true" />
<option name="ignoreForNonAlpha" value="true" />
<option name="ignoreAssignedToConstants" value="true" />
<option name="ignoreToString" value="true" />
<option name="nonNlsCommentPattern" value="NON-NLS" />
<option name="ignoreForEnumConstant" value="true" />
</inspection_tool>
<inspection_tool class="LocalCanBeFinal" enabled="false" level="WARNING" enabled_by_default="false">
<option name="REPORT_VARIABLES" value="true" />
<option name="REPORT_PARAMETERS" value="false" />
<option name="REPORT_CATCH_PARAMETERS" value="false" />
<option name="REPORT_FOREACH_PARAMETERS" value="false" />
</inspection_tool>
<inspection_tool class="NoLabelFor" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SameParameterValue" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
<inspection_tool class="XmlUnboundNsPrefix" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="unused" enabled="false" level="WARNING" enabled_by_default="false">
<option name="LOCAL_VARIABLE" value="true" />
<option name="FIELD" value="true" />
<option name="METHOD" value="true" />
<option name="CLASS" value="true" />
<option name="PARAMETER" value="true" />
<option name="REPORT_PARAMETER_FOR_PUBLIC_METHODS" value="true" />
<option name="ADD_MAINS_TO_ENTRIES" value="true" />
<option name="ADD_APPLET_TO_ENTRIES" value="true" />
<option name="ADD_SERVLET_TO_ENTRIES" value="true" />
<option name="ADD_NONJAVA_TO_ENTRIES" value="true" />
</inspection_tool>
</profile>
</component>
| flutter-intellij/.idea/inspectionProfiles/Project_Default.xml/0 | {
"file_path": "flutter-intellij/.idea/inspectionProfiles/Project_Default.xml",
"repo_id": "flutter-intellij",
"token_count": 1279
} | 482 |
# 78.4
- Use Dart plugin's DevTools instance with DTD (#7264)
# 78.2, 78.3
- Fix debugger variable information (#7228)
# 78, 78.1
- Fix DevTools Inspector for all Android Studio users (#7147)
# 77.2
- Update the vendor information for the JetBrains plugin marketplace (#7193)
# 77, 77.1
- Report IDE feature source when opening DevTools (#7108)
- Remove listener for file path on project dispose (#7093)
- Dispose SDK config correctly on app ending (#7064)
- Remove deprecated notification group usage from deep link (#7061)
- Update plugin for Android Studio 2023.3 (Iguana) and IntelliJ 2023.3 (#7113)
# 76.3
- Unmigrate change to use the new ActionListener API from IntelliJ as it introduced an issue with FlutterReloadManager (#6996)
- Remove JX Browser usages and references (#7059)
- Log and show link to open DevTools in separate browser if JCEF fails (#7057)
# 76.2
- Fix for IndexOutOfBounds on startup (#6942)
# 76.1
- Fix for JXBrowser key not provided (#6992)
# 76
- Widget inspector doesn't jump to source code (#6875)
- Change to use `org.apache.commons.lang3.*`, from `org.apache.commons.lang.*` (#6933)
# 75
- Use pooled thread to find location of Android Studio (#6849)
- Update build script for AS canary and IJ stable (#6846)
- Remove isEnableEmbeddedBrowsers setting (#6845)
- Stop showing an error after running tests with coverage (#6843)
- Add gradle to ignore list (#6839)
- Update VM service protocol to 4.11 (#6838)
- Make AS 2022.2 the oldest supported platform (#6837)
- Clear browser tabs when window closes (#6835)
- Use BGT to update UI during reload/restart (#6836)
- Default to JCEF browser (#6834)
- Debug with 2023.2 (#6826)
- Update Java, Gradle, plugins, and clean up (#6825)
- Use EAP to run unit tests (#6822)
- FlutterSdkVersion.version needs to be nullable (#6821)
- Update build for latest EAP (#6820)
- Disable Java indexing in AS canary (#6815)
- add Open in Xcode for macOS (#6791)
- Remove deprecated strong-mode entry in analysis options (#6800)
- Update EAP build (#6797)
- Add JCEF browser (#6787)
# 74
- Support multiple running instance for inspectors (#6772)
- Add Short super.key (#6757)
- Enable envars for run configs (#6765)
- Save pub root for attach (#6764)
- Build for 2023.2 EAP (#6763)
- Use VM service URI instead of observatory URI for bazel test startup (#6742)
- Reorg CONTRIBUTING.md (#6740)
- Improve run configurations (#6739)
- Allow making the plugin from multiple platforms (#6730)
- Delete `flutter-idea/artifacts` link (#6729)
- Remove use of legacy inspector (#6728)
- Use BGT to update UI for restart/reload (#6727)
- Update versions in build script (#6721)
- Update Dart version for latest EAP build (#6720)
- Fix generation of presubmit.yaml (#6708)
- Add a readme for kokoro (#6707)
- Fix typo in icon file name (#6705)
- Fix presubmit template (#6706)
# 73.1
- Build for Android Studio Hedgehog
# 73
- Prevent NPE when process is stopped while record fields are displayed
- Check lcov files for files with no test coverage (#6692)
- Add FLUTTER_SDK to setup instructions (#6684)
- Fix DevTools opening for bazel workspaces (#6682)
- Eliminate the dependency on artifacts (#6681)
- Update Refresh on BGT (#6679)
- Run unit tests on linux bots (#6675)
- Follow-up on #6500, don't use setExceptionPauseMode() if possible (#6674)
- Run unit tests on Linux (#6669)
- Add the run configuration to make the plugin (#6639)
- Remove some obsolete code (#6667)
- Update on BGT (#6664)
- Update VM service protocol (#6653)
- Use 2023.1 to build (#6651)
- Use 2022.3 for building (#6496)
- Use `Directory.delete` instead of `rm` (#6649)
- Always use `Utf8Codec` for plugin logs (#6648)
- Use `FLUTTER_STORAGE_BASE_URL` for `ArtifactManager` (#6647)
- Always open Android module in new window (#6646)
- View record fields in the debugger (#6638)
- Update CONTRIBUTING.md (#6637)
- Update VM service protocol to 4.2 (#6636)
- Fix debugger and BoundField.getName() (#6630)
- Use setIsolatePauseMode (#6629)
- Update VM service protocol to spec version 4.1 (#6628)
# 72.1
- Eliminate more potentially nested service creations (#6626)
- Create only a single service at a time (#6618)
- Use reflection to find EmulatorSettings in both IDEs (#6625)
- Check version of SDK for forming DevTools URL (#6614)
- Open chrome devtools from JxBrowser (#6615)
- Attempt to fix error email (#6605)
- Fix debugger display of Uint8List elements (#6603)
# 72.0
- Build 2023.1 (#6593)
- Update settings to emphasize global options (#6592)-
- Run update() on BGT (#6556)
- Build AS canary with 2022.3 (#6583)
- Catch UnsatisfiedLinkError for inspector (#6585)
- Stop logging to improve completion times (#6584)
- Allow auto pre-commit test to run prior to git commit (#6557)
- Ignore disposed project in FlutterAppManager (#6554)
- Ignore empty files that the Dart plugin says have errors (#6553)
- Fix creating package project (#6542)
# 71.3
- Fix the "Empty menu item text" problem
# 71.2
- Always show device selector in IntelliJ 2022.3 due to: https://youtrack.jetbrains.com/issue/IDEA-308897/IntelliJ-2022.3-causes-custom-toolbar-widget-to-flash?s=IntelliJ-2022.3-causes-custom-toolbar-widget-to-flash
- Re-enable embedded DevTools
# 71.1
- Tweak device selector code
- Add new project types plugin_ffi and empty (#6433)
- Update device selector in background (#6429)
- Catch exception if default project was disposed (#6401)
- Fix test coverage for monorepo projects (#6391)
- Permit attach in bazel context (#6389)
- Change Container to Placeholder in live templates (#6390)
- Move tests to 2022.2 (#6386)
- Remove some deprecated API uses (#6383)
# 71.0
- Remove the process listener after emulator termination (#6377)
- Remove obsolete code from NPW (#6374)
- Check for disposed project (#6371)
- Remove platform availability channel warning (#6356)
- Show values of TypedDataList in debugger (#6369)
# 70.0
- Respect embedded emulator settings (#6279)
- Update to JX Browser 7.27 and change linux mode (#6283)
- Guard against JSON file problems (#6273)
- Add missing null check (#6268)
- Check for disposed editor (#6265)
- Log bazel mapping differences from analyzer (#6263)
- Update icon version (#6262)
- Use new flutter.json file location (#6261)
- Delete FlutterBazelSettingsNotificationProvider (#6256)
# 69.0
- Build for canary 221 (#6248)
- Revert "Delete code duplicated from Dart (#6113)" (#6246)
- Update .iml for 221 (#6241)
- Disable reader mode for Flutter plugins (#6238)
- Update the build for 2022.2 EAP (#6224)
- Avoid using canonical path for bazel (#6227)
- Reduce error logging for not-useful errors (#6221)
- Ensure disconnect even if import cancelled (#6220)
- Improve import for monorepo projects (#6217)
- Update Flutter commands on Build and Tools menu to run for all Flutter modules (#6215)
- Change how Open in Xcode determines what to open (#6211)
- Update survey announcement (#6210)
# 68.0
- Use distributed icons for current SDK (#6208)
- Update icons (#6207)
- Enable stable platforms (#6202)
- Use correct code to shut down process (#6201)
- Use canonical paths to map symlinks(#6203)
- Enable Windows platform for Flutter 2.10+ (#6195)
- Escape spaces for VM mapping (#6194)
- Stop relying only on .packages for pub banner (#6188)
- Update icon previews to handle new format (#6186)
- Fix typo in actions (#6180)
- Send timing data as a GA event (#6179)
- Check for project disposal before download (#6173)
- Add default token permissions values + pin dependencies (#6152)
- Show meaningful device names (#6158)
- Specify dart bin path (#6153)
- Update CONTRIBUTING.md (#6146)
# 67.1
- Specify dart bin path (#6153)
# 67.0
- Disable new analytics for M67 (#6142)
- Stop running setup on the bots (#6141)
- Update Dart plugin version (#6139)
- Change setting on EDT (#6137)
- Stop using a deprecated method (#6132)
- Refactor Transport for easier logging while debugging (#6129)
- Fix child lines when folding code (#6128)
- Fix analytics (#6119)
- Fix disposer bug (#6120)
- Remove the 30-char limit for project names (#6121)
- Use devtools script to launch bazel devtools (#6115)
- Report flutter SDK version on startup (#6114)
- Add dart devtools for starting server (#6112)
- Delete code duplicated from Dart (#6113)
- Update web URI mapping version (#6110)
- Work around Kokoro Dart plugin problem (#6109)
- Plugin tool improvements (#6106)
- Fix layout issue (#6105)
- Clean up edit.dart (#6104)
- Add more analytics (#5985)
- Update build for 2022.1 (#6102)
- Enable Dart with multiple modules (#6099)
- Look for a single module by name (#6098)
- Add links to 3P plugin docs (#6090)
- Fix config to load into 2021.3 (#6088)
- Move third-party binaries into third_party (#6087)
- This will allow us to assess the security posture of this repository. (#6047)
- Update CONTRIBUTING.md (#6074)
| flutter-intellij/CHANGELOG.md/0 | {
"file_path": "flutter-intellij/CHANGELOG.md",
"repo_id": "flutter-intellij",
"token_count": 2650
} | 483 |
rootProject.name = 'flutter-gui-tests'
| flutter-intellij/flutter-gui-tests/settings.gradle/0 | {
"file_path": "flutter-intellij/flutter-gui-tests/settings.gradle",
"repo_id": "flutter-intellij",
"token_count": 14
} | 484 |
package icons;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
public class FlutterIcons {
private static Icon load(String path) {
return IconLoader.getIcon(path, FlutterIcons.class);
}
public static final Icon Flutter_13 = load("/icons/flutter_13.png");
public static final Icon Flutter_13_2x = load("/icons/[email protected]");
public static final Icon Flutter_64 = load("/icons/flutter_64.png");
public static final Icon Flutter_64_2x = load("/icons/[email protected]");
public static final Icon Flutter = load("/icons/flutter.png");
public static final Icon Flutter_2x = load("/icons/[email protected]");
public static final Icon Flutter_inspect = load("/icons/flutter_inspect.png");
public static final Icon Flutter_test = load("/icons/flutter_test.png");
public static final Icon Flutter_badge = load("/icons/flutter_badge.png");
public static final Icon Phone = load("/icons/phone.png");
public static final Icon Feedback = load("/icons/feedback.png");
public static final Icon RefreshItems = load("/icons/refresh_items.png");
public static final Icon Dart_16 = load("/icons/dart_16.svg");
public static final Icon HotReload = load("/icons/hot-reload.png");
public static final Icon HotRestart = load("/icons/hot-restart.png");
public static final Icon HotReloadRun = load("/icons/reload_run.png");
public static final Icon HotReloadDebug = load("/icons/reload_debug.png");
public static final Icon DebugBanner = load("/icons/debugBanner.png");
public static final Icon DebugPaint = load("/icons/debugPaint.png");
public static final Icon RepaintRainbow = load("/icons/repaintRainbow.png");
public static final Icon BazelRun = load("/icons/bazel_run.png");
public static final Icon CustomClass = load("/icons/custom/class.png");
public static final Icon CustomClassAbstract = load("/icons/custom/class_abstract.png");
public static final Icon CustomFields = load("/icons/custom/fields.png");
public static final Icon CustomInterface = load("/icons/custom/interface.png");
public static final Icon CustomMethod = load("/icons/custom/method.png");
public static final Icon CustomMethodAbstract = load("/icons/custom/method_abstract.png");
public static final Icon CustomProperty = load("/icons/custom/property.png");
public static final Icon CustomInfo = load("/icons/custom/info.png");
public static final Icon AndroidStudioNewProject = load("/icons/template_new_project.png");
public static final Icon AndroidStudioNewPackage = load("/icons/template_new_package.png");
public static final Icon AndroidStudioNewPlugin = load("/icons/template_new_plugin.png");
public static final Icon AndroidStudioNewModule = load("/icons/template_new_module.png");
public static final Icon AttachDebugger = load("/icons/attachDebugger.png");
// Flutter Inspector Widget Icons.
public static final Icon Accessibility = load("/icons/inspector/balloonInformation.png");
public static final Icon Animation = load("/icons/inspector/resume.png");
public static final Icon Assets = load("/icons/inspector/any_type.png");
public static final Icon Async = load("/icons/inspector/threads.png");
public static final Icon Diagram = load("/icons/inspector/diagram.png");
public static final Icon Input = load("/icons/inspector/renderer.png");
public static final Icon Painting = load("/icons/inspector/colors.png");
public static final Icon Scrollbar = load("/icons/inspector/scrollbar.png");
public static final Icon Stack = load("/icons/inspector/value.png");
public static final Icon Styling = load("/icons/inspector/atrule.png");
public static final Icon Text = load("/icons/inspector/textArea.png");
public static final Icon ExpandProperty = load("/icons/inspector/expand_property.png");
public static final Icon CollapseProperty = load("/icons/inspector/collapse_property.png");
// Flutter Outline Widget Icons.
public static final Icon Column = load("/icons/preview/column.png");
public static final Icon Padding = load("/icons/preview/padding.png");
public static final Icon RemoveWidget = load("/icons/preview/remove_widget.png");
public static final Icon Row = load("/icons/preview/row.png");
public static final Icon Center = load("/icons/preview/center.png");
public static final Icon Container = load("/icons/preview/container.png");
public static final Icon Up = load("/icons/preview/up.png");
public static final Icon Down = load("/icons/preview/down.png");
public static final Icon ExtractMethod = load("/icons/preview/extract_method.png");
// Flutter profiler
public static final Icon Snapshot = load("/icons/profiler/snapshot_color_1x_24dp.png");
public static final Icon ResetMemoryStats = load("/icons/profiler/reset_icon.png");
public static class State {
public static final Icon RedProgr = load("/icons/perf/RedProgr.png"); // 16x16
public static final Icon RedProgr_1 = load("/icons/perf/RedProgr_1.png"); // 16x16
public static final Icon RedProgr_2 = load("/icons/perf/RedProgr_2.png"); // 16x16
public static final Icon RedProgr_3 = load("/icons/perf/RedProgr_3.png"); // 16x16
public static final Icon RedProgr_4 = load("/icons/perf/RedProgr_4.png"); // 16x16
public static final Icon RedProgr_5 = load("/icons/perf/RedProgr_5.png"); // 16x16
public static final Icon RedProgr_6 = load("/icons/perf/RedProgr_6.png"); // 16x16
public static final Icon RedProgr_7 = load("/icons/perf/RedProgr_7.png"); // 16x16
public static final Icon RedProgr_8 = load("/icons/perf/RedProgr_8.png"); // 16x16
public static final Icon YellowProgr = load("/icons/perf/YellowProgr.png"); // 16x16
public static final Icon YellowProgr_1 = load("/icons/perf/YellowProgr_1.png"); // 16x16
public static final Icon YellowProgr_2 = load("/icons/perf/YellowProgr_2.png"); // 16x16
public static final Icon YellowProgr_3 = load("/icons/perf/YellowProgr_3.png"); // 16x16
public static final Icon YellowProgr_4 = load("/icons/perf/YellowProgr_4.png"); // 16x16
public static final Icon YellowProgr_5 = load("/icons/perf/YellowProgr_5.png"); // 16x16
public static final Icon YellowProgr_6 = load("/icons/perf/YellowProgr_6.png"); // 16x16
public static final Icon YellowProgr_7 = load("/icons/perf/YellowProgr_7.png"); // 16x16
public static final Icon YellowProgr_8 = load("/icons/perf/YellowProgr_8.png"); // 16x16
public static final Icon GreyProgr_1 = load("/icons/perf/GreyProgr_1.png"); // 16x16
public static final Icon GreyProgr_2 = load("/icons/perf/GreyProgr_2.png"); // 16x16
public static final Icon GreyProgr_3 = load("/icons/perf/GreyProgr_3.png"); // 16x16
public static final Icon GreyProgr_4 = load("/icons/perf/GreyProgr_4.png"); // 16x16
public static final Icon GreyProgr_5 = load("/icons/perf/GreyProgr_5.png"); // 16x16
public static final Icon GreyProgr_6 = load("/icons/perf/GreyProgr_6.png"); // 16x16
public static final Icon GreyProgr_7 = load("/icons/perf/GreyProgr_7.png"); // 16x16
public static final Icon GreyProgr_8 = load("/icons/perf/GreyProgr_8.png"); // 16x16
}
}
| flutter-intellij/flutter-idea/src/icons/FlutterIcons.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/icons/FlutterIcons.java",
"repo_id": "flutter-intellij",
"token_count": 2297
} | 485 |
/*
* 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.CommonBundle;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.ui.DocumentAdapter;
import com.intellij.util.ui.JBUI;
import com.jetbrains.lang.dart.ide.refactoring.ServerRefactoringDialog;
import com.jetbrains.lang.dart.ide.refactoring.status.RefactoringStatus;
import io.flutter.FlutterUtils;
import io.flutter.refactoring.ExtractWidgetRefactoring;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.*;
public class ExtractWidgetAction extends DumbAwareAction {
@Override
public void actionPerformed(AnActionEvent event) {
final DataContext dataContext = event.getDataContext();
final Project project = dataContext.getData(PlatformDataKeys.PROJECT);
final VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
final Editor editor = dataContext.getData(PlatformDataKeys.EDITOR);
final Caret caret = dataContext.getData(PlatformDataKeys.CARET);
if (project != null && file != null && editor != null && caret != null) {
final int offset = caret.getSelectionStart();
final int length = caret.getSelectionEnd() - offset;
final ExtractWidgetRefactoring refactoring = new ExtractWidgetRefactoring(project, file, offset, length);
// Validate the initial status.
final RefactoringStatus initialStatus = refactoring.checkInitialConditions();
if (initialStatus == null) {
return;
}
if (initialStatus.hasError()) {
final String message = initialStatus.getMessage();
assert message != null;
CommonRefactoringUtil.showErrorHint(project, editor, message, CommonBundle.getErrorTitle(), null);
return;
}
new ExtractWidgetDialog(project, editor, refactoring).show();
}
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setVisible(isVisibleFor(e));
super.update(e);
}
protected static boolean isVisibleFor(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
final Project project = dataContext.getData(PlatformDataKeys.PROJECT);
final VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
return file != null && FlutterUtils.isDartFile(file);
}
}
class ExtractWidgetDialog extends ServerRefactoringDialog<ExtractWidgetRefactoring> {
@NotNull final ExtractWidgetRefactoring myRefactoring;
private final JTextField myNameField = new JTextField();
public ExtractWidgetDialog(@NotNull Project project,
@Nullable Editor editor,
@NotNull ExtractWidgetRefactoring refactoring) {
super(project, editor, refactoring);
myRefactoring = refactoring;
setTitle("Extract Widget");
init();
myNameField.setText("NewWidget");
myNameField.selectAll();
myNameField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(@NotNull DocumentEvent event) {
updateRefactoringOptions();
}
});
updateRefactoringOptions();
}
private void updateRefactoringOptions() {
myRefactoring.setName(myNameField.getText());
myRefactoring.sendOptions();
}
@Override
protected JComponent createCenterPanel() {
return null;
}
@Override
protected JComponent createNorthPanel() {
final JPanel panel = new JPanel(new GridBagLayout());
final GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.insets = JBUI.insetsBottom(4);
gbConstraints.gridx = 0;
gbConstraints.gridy = 0;
gbConstraints.gridwidth = 1;
gbConstraints.weightx = 0;
gbConstraints.weighty = 0;
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.anchor = GridBagConstraints.WEST;
final JLabel nameLabel = new JLabel("Widget name:");
panel.add(nameLabel, gbConstraints);
gbConstraints.insets = JBUI.insets(0, 4, 4, 0);
gbConstraints.gridx = 1;
gbConstraints.gridy = 0;
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.weightx = 1;
gbConstraints.weighty = 0;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.anchor = GridBagConstraints.WEST;
panel.add(myNameField, gbConstraints);
myNameField.setPreferredSize(new Dimension(200, myNameField.getPreferredSize().height));
return panel;
}
@Nullable
@Override
public JComponent getPreferredFocusedComponent() {
return myNameField;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/ExtractWidgetAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/ExtractWidgetAction.java",
"repo_id": "flutter-intellij",
"token_count": 1826
} | 486 |
/*
* Copyright 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.actions;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.ColoredProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.FlutterBundle;
import io.flutter.FlutterMessages;
import io.flutter.FlutterUtils;
import io.flutter.pub.PubRoot;
import io.flutter.pub.PubRoots;
import io.flutter.sdk.FlutterSdk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
public class OpenInAndroidStudioAction extends AnAction {
private static final String LABEL_FILE = FlutterBundle.message("flutter.androidstudio.open.file.text");
private static final String DESCR_FILE = FlutterBundle.message("flutter.androidstudio.open.file.description");
private static final String LABEL_MODULE = FlutterBundle.message("flutter.androidstudio.open.module.text");
private static final String DESCR_MODULE = FlutterBundle.message("flutter.androidstudio.open.module.description");
private static final Logger LOG = Logger.getInstance(OpenInAndroidStudioAction.class);
@Override
public void update(@NotNull AnActionEvent event) {
updatePresentation(event, event.getPresentation());
}
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
@Nullable final Project project = event.getProject();
if (FlutterUtils.isAndroidStudio()) {
try {
//noinspection unchecked
final Class<OpenInAndroidStudioAction> opener =
(Class<OpenInAndroidStudioAction>)Class.forName("io.flutter.actions.OpenAndroidModule");
opener.newInstance().actionPerformed(event);
return;
}
catch (ClassNotFoundException | IllegalAccessException | InstantiationException ignored) {
}
}
ApplicationManager.getApplication().executeOnPooledThread(() -> {
final String androidStudioPath = findAndroidStudio(project);
if (androidStudioPath == null) {
FlutterMessages.showError(
"Unable to locate Android Studio",
"You can configure the Android Studio location via 'flutter config --android-studio-dir path-to-android-studio'.",
project);
return;
}
final VirtualFile projectFile = findProjectFile(event);
if (projectFile == null) {
FlutterMessages.showError("Error Opening Android Studio", "Project not found.", project);
return;
}
final VirtualFile sourceFile = event.getData(CommonDataKeys.VIRTUAL_FILE);
final String sourceFilePath = sourceFile == null ? null : sourceFile.isDirectory() ? null : sourceFile.getPath();
final Integer line;
final Integer column;
final Editor editor = getCurrentEditor(project, sourceFile);
if (editor != null) {
final CaretModel caretModel = editor.getCaretModel();
line = caretModel.getLogicalPosition().line + 1;
column = caretModel.getLogicalPosition().column;
}
else {
line = column = null;
}
openFileInStudio(androidStudioPath, project, projectFile.getPath(), sourceFilePath, line, column);
});
}
@Nullable
private static Editor getCurrentEditor(@NotNull Project project, @Nullable VirtualFile file) {
if (file == null) return null;
final FileEditor fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(file);
if (fileEditor instanceof TextEditor) {
final TextEditor textEditor = (TextEditor)fileEditor;
final Editor editor = textEditor.getEditor();
if (!editor.isDisposed()) {
return editor;
}
}
return null;
}
private static void updatePresentation(AnActionEvent event, Presentation state) {
if (findProjectFile(event) == null) {
state.setVisible(false);
}
else {
final VirtualFile file = event.getData(CommonDataKeys.VIRTUAL_FILE);
final String label;
final String descr;
if (file != null && !file.isDirectory()) {
// The file will be opened in an editor in the new IDE window.
label = LABEL_FILE;
descr = DESCR_FILE;
}
else {
// The new IDE window will be opened on the Android module but there is no file selected for editing.
label = LABEL_MODULE;
descr = DESCR_MODULE;
}
state.setVisible(true);
state.setText(label);
state.setDescription(descr);
}
}
protected static boolean isProjectFileName(String name) {
// Note: If the project content is rearranged to have the android module file within the android directory, this will fail.
return name.endsWith("_android.iml");
}
// A plugin contains an example app, which needs to be opened when the native Android is to be edited.
// In the case of an app that contains a plugin the flutter_app/flutter_plugin/example/android should be opened when
// 'Open in Android Studio' is requested.
protected static VirtualFile findProjectFile(@Nullable AnActionEvent e) {
if (e != null) {
final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
if (file != null && file.exists()) {
// We have a selection. Check if it is within a plugin.
final Project project = e.getProject();
assert (project != null);
// Return null if this is an ios folder.
if (FlutterExternalIdeActionGroup.isWithinIOsDirectory(file, project)) {
return null;
}
final VirtualFile projectDir = project.getBaseDir();
for (PubRoot root : PubRoots.forProject(project)) {
if (root.isFlutterPlugin()) {
final VirtualFile rootFile = root.getRoot();
VirtualFile aFile = file;
while (aFile != null) {
if (aFile.equals(rootFile)) {
// We know a plugin resource is selected. Find the example app for it.
for (VirtualFile child : rootFile.getChildren()) {
if (isExampleWithAndroidWithApp(child)) {
return child.findChild("android");
}
}
}
if (aFile.equals(projectDir)) {
aFile = null;
}
else {
aFile = aFile.getParent();
}
}
}
}
if (isProjectFileName(file.getName())) {
return getProjectForFile(file);
}
}
final Project project = e.getProject();
if (project != null) {
return getProjectForFile(findStudioProjectFile(project));
}
}
return null;
}
private static void openFileInStudio(@NotNull String androidStudioPath,
@NotNull Project project,
@NotNull String projectPath,
@Nullable String sourceFile,
@Nullable Integer line,
@Nullable Integer column) {
try {
final GeneralCommandLine cmd;
if (SystemInfo.isMac) {
cmd = new GeneralCommandLine().withExePath("open")
.withParameters("-a", androidStudioPath, "--args", projectPath);
}
else {
if (SystemInfo.isWindows) {
androidStudioPath += "\\bin\\studio.bat";
}
else {
androidStudioPath += "/bin/studio.sh";
}
cmd = new GeneralCommandLine().withExePath(androidStudioPath)
.withParameters(projectPath);
}
if (sourceFile != null) {
if (line != null) {
cmd.addParameters("--line", line.toString());
if (column != null) {
cmd.addParameters("--column", column.toString());
}
}
cmd.addParameter(sourceFile);
}
final ColoredProcessHandler handler = new ColoredProcessHandler(cmd);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(@NotNull final ProcessEvent event) {
if (event.getExitCode() != 0) {
FlutterMessages.showError("Error Opening", projectPath, project);
}
}
});
handler.startNotify();
}
catch (ExecutionException ex) {
FlutterMessages.showError(
"Error Opening",
"Exception: " + ex.getMessage(),
project);
}
}
@Nullable
private static VirtualFile findStudioProjectFile(@NotNull Project project) {
for (PubRoot root : PubRoots.forProject(project)) {
for (VirtualFile child : root.getRoot().getChildren()) {
if (isProjectFileName(child.getName())) {
return child;
}
if (FlutterExternalIdeActionGroup.isAndroidDirectory(child)) {
for (VirtualFile androidChild : child.getChildren()) {
if (isProjectFileName(androidChild.getName())) {
return androidChild;
}
}
}
}
}
return null;
}
@Nullable
private static String findAndroidStudio(@Nullable Project project) {
if (project == null) {
return null;
}
final FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(project);
if (flutterSdk != null) {
String androidSdkLocation = flutterSdk.queryFlutterConfig("android-studio-dir", true);
if (androidSdkLocation != null && !new File(androidSdkLocation).exists()) {
androidSdkLocation = flutterSdk.queryFlutterConfig("android-studio-dir", false);
}
if (androidSdkLocation != null) {
if (androidSdkLocation.contains("/Android Studio 2.")) {
Messages.showErrorDialog(FlutterBundle.message("old.android.studio.message", File.separator),
FlutterBundle.message("old.android.studio.title"));
return null;
}
if (androidSdkLocation.endsWith("/")) {
androidSdkLocation = androidSdkLocation.substring(0, androidSdkLocation.length() - 1);
}
// On a mac, trim off "/Contents".
final String contents = "/Contents";
if (SystemInfo.isMac && androidSdkLocation.endsWith(contents)) {
return androidSdkLocation.substring(0, androidSdkLocation.length() - contents.length());
}
return androidSdkLocation;
}
}
return null;
}
@Nullable
private static VirtualFile getProjectForFile(@Nullable VirtualFile file) {
// Expect true: isProjectFileName(file.getName()), but some flexibility is allowed.
if (file == null) {
return null;
}
if (file.isDirectory()) {
return isAndroidWithApp(file) ? file : null;
}
final VirtualFile dir = file.getParent();
if (isAndroidWithApp(dir)) {
// In case someone moves the .iml file, or the project organization gets rationalized.
return dir;
}
VirtualFile project = dir.findChild("android");
if (project != null && isAndroidWithApp(project)) {
return project;
}
project = dir.findChild(".android");
if (project != null && isAndroidWithApp(project)) {
return project;
}
return null;
}
// Return true if the directory is named android and contains either an app (for applications) or a src (for plugins) directory.
private static boolean isAndroidWithApp(@NotNull VirtualFile file) {
return FlutterExternalIdeActionGroup.isAndroidDirectory(file) && (file.findChild("app") != null || file.findChild("src") != null);
}
// Return true if the directory has the structure of a plugin example application: a pubspec.yaml and an
// android directory with an app. The example app directory name is not specified in case it gets renamed.
private static boolean isExampleWithAndroidWithApp(@NotNull VirtualFile file) {
boolean hasPubspec = false;
boolean hasAndroid = false;
for (VirtualFile candidate : file.getChildren()) {
if (isAndroidWithApp(candidate)) hasAndroid = true;
if (candidate.getName().equals("pubspec.yaml")) hasPubspec = true;
if (hasAndroid && hasPubspec) {
return true;
}
}
return false;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/OpenInAndroidStudioAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/OpenInAndroidStudioAction.java",
"repo_id": "flutter-intellij",
"token_count": 5029
} | 487 |
/*
* Copyright 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.actions;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.wm.ToolWindowId;
import io.flutter.FlutterBundle;
import io.flutter.run.FlutterLaunchMode;
public class RunReleaseFlutterApp extends RunFlutterAction {
public static final String TEXT = FlutterBundle.message("app.release.action.text");
public static final String DESCRIPTION = FlutterBundle.message("app.release.action.description");
private static final String TEXT_DETAIL_MSG_KEY = "app.release.config.action.text";
public RunReleaseFlutterApp() {
super(TEXT, TEXT_DETAIL_MSG_KEY, DESCRIPTION, AllIcons.Actions.Execute, FlutterLaunchMode.RELEASE, ToolWindowId.RUN);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/RunReleaseFlutterApp.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/RunReleaseFlutterApp.java",
"repo_id": "flutter-intellij",
"token_count": 264
} | 488 |
/*
* Copyright 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.console;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.process.ColoredProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.content.MessageView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A console showing output from a Flutter command.
*/
class FlutterConsole {
@NotNull final ConsoleView view;
@NotNull final Content content;
@NotNull final Project project;
@Nullable final Module module;
@Nullable
private Runnable cancelProcessSubscription;
private FlutterConsole(@NotNull ConsoleView view, @NotNull Content content, @NotNull Project project, @Nullable Module module) {
this.view = view;
this.content = content;
this.project = project;
this.module = module;
}
@NotNull
static FlutterConsole create(@NotNull Project project, @Nullable Module module) {
final TextConsoleBuilder builder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
builder.setViewer(true);
if (module != null) {
builder.addFilter(new FlutterConsoleFilter(module));
}
final ConsoleView view = builder.getConsole();
final SimpleToolWindowPanel panel = new SimpleToolWindowPanel(false, true);
panel.setContent(view.getComponent());
final String title = module != null ? "[" + module.getName() + "] Flutter" : "Flutter";
final Content content = ContentFactory.getInstance().createContent(panel.getComponent(), title, true);
Disposer.register(content, view);
return new FlutterConsole(view, content, project, module);
}
/**
* Starts displaying the output of a different process.
*/
void watchProcess(@NotNull ColoredProcessHandler process) {
if (cancelProcessSubscription != null) {
cancelProcessSubscription.run();
cancelProcessSubscription = null;
}
view.clear();
view.attachToProcess(process);
// Print exit code.
final ProcessAdapter listener = new ProcessAdapter() {
@Override
public void processTerminated(final ProcessEvent event) {
view.print(
"Process finished with exit code " + event.getExitCode(),
ConsoleViewContentType.SYSTEM_OUTPUT);
}
};
process.addProcessListener(listener);
cancelProcessSubscription = () -> process.removeProcessListener(listener);
}
/**
* Moves this console to the end of the tool window's tab list, selects it, and shows the tool window.
*/
void bringToFront() {
// Move the tab to be last and select it.
final MessageView messageView = MessageView.getInstance(project);
final ContentManager contentManager = messageView.getContentManager();
contentManager.addContent(content);
contentManager.setSelectedContent(content);
// Show the panel.
final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.MESSAGES_WINDOW);
if (toolWindow != null) {
toolWindow.activate(null, true);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/console/FlutterConsole.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/console/FlutterConsole.java",
"repo_id": "flutter-intellij",
"token_count": 1223
} | 489 |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.editor;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.ui.popup.Balloon;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
public interface ColorPickerProvider {
ExtensionPointName<ColorPickerProvider> EP_NAME = ExtensionPointName.create("io.flutter.colorPickerProvider");
interface ColorListener {
void colorChanged(@Nullable Color var1, Object var2);
}
void show(Color initialColor,
JComponent component,
Point offset,
Balloon.Position position,
ColorListener colorListener,
Runnable onCancel,
Runnable onOk);
void dispose();
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/ColorPickerProvider.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/ColorPickerProvider.java",
"repo_id": "flutter-intellij",
"token_count": 311
} | 490 |
/*
* Copyright 2022 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.actions.ReaderModeMatcher;
import com.intellij.codeInsight.actions.ReaderModeProvider;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.pub.PubRoot;
import io.flutter.utils.FlutterModuleUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class FlutterReaderModeMatcher implements ReaderModeMatcher {
@Nullable
@Override
public Boolean matches(@NotNull Project project,
@NotNull VirtualFile file,
@Nullable Editor editor,
@NotNull ReaderModeProvider.ReaderMode mode) {
if (ReaderModeProvider.ReaderMode.READ_ONLY == mode) {
return null;
}
List<Module> contents = FlutterModuleUtils.findModulesWithFlutterContents(project);
if (contents.isEmpty()) {
return null;
}
PubRoot root = PubRoot.forDescendant(file, project);
if (root == null) {
return null;
}
return false;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterReaderModeMatcher.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterReaderModeMatcher.java",
"repo_id": "flutter-intellij",
"token_count": 499
} | 491 |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.editor;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.editor.markup.*;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Segment;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.ui.paint.LinePainter2D;
import com.intellij.util.DocumentUtil;
import com.intellij.util.text.CharArrayUtil;
import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService;
import com.jetbrains.lang.dart.psi.DartCallExpression;
import io.flutter.dart.FlutterDartAnalysisServer;
import io.flutter.inspector.InspectorGroupManagerService;
import io.flutter.settings.FlutterSettings;
import org.dartlang.analysis.server.protocol.FlutterOutline;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.util.List;
import java.util.*;
import static java.lang.Math.*;
// Instructions for how this code should be tested:
// This code could be tested by true integration tests or better yet by
// unittests that are able to create Editor object instances. Testing this
// code does not require running a Flutter application but it does require
// creating Editor object instances and would benefit from creating a live
// Dart analysis server to communicate with.
//
// Suggested steps to test this code:
// Create a representative Dart file containing a a couple build methods with
// deeply nested widget trees.
// Create an Editor instance from the dart file.
// Get a Flutter outline from that file or inject a snapshotted Flutter outline
// iof it isn't feasible to get a true Flutter outline.
// Verify that calling
// pass = new WidgetIndentsHighlightingPass(project, editor);
// pass.setOutline(flutterOutline);
// results in adding highlights to the expected ranges. Highlighters can be
// found querying the editor directly or calling.
// final CustomHighlighterRenderer renderer = highlighter.getCustomRenderer();
// ((WidgetCustomHighlighterRenderer)renderer).dispose();
// You could then even call the render method on a highlighter if you wanted
// a golden image that just contained the widget indent tree diagram. In
// practice it would be sufficient to get the WidgetIndentGuideDescriptor from
// the renderer and verify that the child locations are correct. The
// important piece to test is that the child widget locations are acurate even
// after making some edits to the document which brings to the next step:
// Make a couple edits to the document and verify that the widget indents are
// still accurate even after the change. The machinery in Editor will track the
// edits and update the widget indents appropriately even before a new
// FlutterOutline is available.
//
// Final step: create a new FlutterOutline and verify passing it in updates the
// widget guides removing guides not part of the outline. For example, Add a
// character to a constructor name so the constructor is not a Widget subclass.
// That will cause the outermost guide in the tree to be removed. Alternately,
// add another widget to the list of children for a widget.
//
// You could also performa golden image integration test to verify that the
// actual render of the text editor matched what was expected but changes
// in font rendering would make that tricky.
/**
* A WidgetIndentsHighlightingPass draws UI as Code Guides for a code editor using a
* FlutterOutline.
* <p>
* This class is similar to a TextEditorHighlightingPass but doesn't actually
* implement TextEditorHighlightingPass as it is driven by changes to the
* FlutterOutline which is only available when the AnalysisServer computes a
* new outline while TextEditorHighlightingPass assumes all information needed
* is available immediately.
*/
public class WidgetIndentsHighlightingPass {
private static final Logger LOG = Logger.getInstance(WidgetIndentsHighlightingPass.class);
// Delta between the start of a column and where indent guides should start;
public static int INDENT_GUIDE_DELTA = -2;
private final static Stroke SOLID_STROKE = new BasicStroke(1);
private final static JBColor VERY_LIGHT_GRAY = new JBColor(Gray._224, Gray._80);
private final static JBColor SHADOW_GRAY = new JBColor(Gray._192, Gray._100);
private final static JBColor OUTLINE_LINE_COLOR = new JBColor(Gray._128, Gray._128);
private final static JBColor OUTLINE_LINE_COLOR_PAST_BLOCK = new JBColor(new Color(128, 128, 128, 65), new Color(128, 128, 128, 65));
private static final Key<WidgetIndentsPassData> INDENTS_PASS_DATA_KEY = Key.create("INDENTS_PASS_DATA_KEY");
/**
* When this debugging flag is true, problematic text ranges are reported.
*/
private final static boolean DEBUG_WIDGET_INDENTS = false;
private static class WidgetCustomHighlighterRenderer implements CustomHighlighterRenderer {
@NotNull private final WidgetIndentGuideDescriptor descriptor;
@NotNull private final Document document;
private boolean isSelected = false;
WidgetCustomHighlighterRenderer(@NotNull WidgetIndentGuideDescriptor descriptor, @NotNull Document document) {
this.descriptor = descriptor;
this.document = document;
descriptor.trackLocations(document);
}
void dispose() {
// Descriptors must be disposed so they stop getting notified about
// changes to the Editor.
descriptor.dispose();
}
boolean setSelection(boolean value) {
if (value == isSelected) return false;
isSelected = value;
return true;
}
boolean updateSelected(@NotNull Editor editor, @NotNull RangeHighlighter highlighter, Caret carat) {
if (carat == null) {
return setSelection(false);
}
final CaretModel caretModel = editor.getCaretModel();
final int startOffset = highlighter.getStartOffset();
final Document doc = highlighter.getDocument();
final int caretOffset = carat.getOffset();
if (startOffset < 0 || startOffset >= doc.getTextLength()) {
return setSelection(false);
}
final int endOffset = highlighter.getEndOffset();
int off;
int startLine = doc.getLineNumber(startOffset);
{
final CharSequence chars = doc.getCharsSequence();
do {
final int start = doc.getLineStartOffset(startLine);
final int end = doc.getLineEndOffset(startLine);
off = CharArrayUtil.shiftForward(chars, start, end, " \t");
startLine--;
}
while (startLine > 1 && off < doc.getTextLength() && chars.charAt(off) == '\n');
}
final VisualPosition startPosition = editor.offsetToVisualPosition(off);
final int indentColumn = startPosition.column;
final LogicalPosition logicalPosition = caretModel.getLogicalPosition();
if (logicalPosition.line == startLine + 1 && descriptor.widget != null) {
// Be more permissive about what constitutes selection for the first
// line within a widget constructor.
return setSelection(caretModel.getLogicalPosition().column >= indentColumn);
}
return setSelection(
caretOffset >= off && caretOffset < endOffset && caretModel.getLogicalPosition().column == indentColumn);
}
@Override
public void paint(@NotNull Editor editor, @NotNull RangeHighlighter highlighter, @NotNull Graphics g) {
if (!highlighter.isValid()) {
return;
}
if (!descriptor.widget.isValid()) {
return;
}
final FlutterSettings settings = FlutterSettings.getInstance();
final Graphics2D g2d = (Graphics2D)g.create();
// Required to render colors with an alpha channel. Rendering with an
// alpha chanel makes it easier to keep relationships between shadows
// and lines looking consistent when the background color changes such
// as in the case of selection or a different highlighter turning the
// background yellow.
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1));
final int startOffset = highlighter.getStartOffset();
final Document doc = highlighter.getDocument();
final int textLength = doc.getTextLength();
if (startOffset >= textLength) return;
final int endOffset = min(highlighter.getEndOffset(), textLength);
int off;
int startLine = doc.getLineNumber(startOffset);
final CharSequence chars = doc.getCharsSequence();
do {
final int start = doc.getLineStartOffset(startLine);
final int end = doc.getLineEndOffset(startLine);
off = CharArrayUtil.shiftForward(chars, start, end, " \t");
startLine--;
}
while (startLine > 1 && off < doc.getTextLength() && chars.charAt(off) == '\n');
final VisualPosition startPosition = editor.offsetToVisualPosition(off);
int indentColumn = startPosition.column;
// It's considered that indent guide can cross not only white space but comments, javadoc etc. Hence, there is a possible
// case that the first indent guide line is, say, single-line comment where comment symbols ('//') are located at the first
// visual column. We need to calculate correct indent guide column then.
int lineShift = 1;
if (indentColumn <= 0) {
indentColumn = descriptor.indentLevel;
lineShift = 0;
}
if (indentColumn <= 0) return;
final FoldingModel foldingModel = editor.getFoldingModel();
if (foldingModel.isOffsetCollapsed(off)) return;
final FoldRegion headerRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(doc.getLineNumber(off)));
final FoldRegion tailRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineStartOffset(doc.getLineNumber(endOffset)));
if (tailRegion != null && tailRegion == headerRegion) return;
final CaretModel caretModel = editor.getCaretModel();
final int caretOffset = caretModel.getOffset();
// updateSelected(editor, highlighter, caretOffset);
final boolean selected = isSelected;
final Point start = editor.visualPositionToXY(new VisualPosition(startPosition.line + lineShift, indentColumn));
final VisualPosition endPosition = editor.offsetToVisualPosition(endOffset);
final ArrayList<OutlineLocation> childLines = descriptor.childLines;
final Point end = editor.visualPositionToXY(endPosition);
double splitY = -1;
int maxY = end.y;
boolean includeLastLine = false;
if (endPosition.line == editor.offsetToVisualPosition(doc.getTextLength()).line) {
includeLastLine = true;
}
int endLine = doc.getLineNumber(endOffset);
if (childLines != null && !childLines.isEmpty()) {
final VisualPosition endPositionLastChild = editor.offsetToVisualPosition(childLines.get(childLines.size() - 1).getGuideOffset());
if (endPositionLastChild.line == endPosition.line) {
// The last child is on the same line as the end of the block.
// This happens if code wasn't formatted with flutter style, for example:
// Center(
// child: child);
includeLastLine = true;
// TODO(jacobr): make sure we don't run off the edge of the document.
if ((endLine + 1) < document.getLineCount()) {
endLine++;
}
}
}
// By default we stop at the start of the last line instead of the end of the last line in the range.
if (includeLastLine) {
maxY += editor.getLineHeight();
}
final Rectangle clip = g2d.getClipBounds();
if (clip != null) {
if (clip.y > maxY || clip.y + clip.height < start.y) {
return;
}
maxY = min(maxY, clip.y + clip.height);
}
final EditorColorsScheme scheme = editor.getColorsScheme();
final JBColor lineColor = selected ? JBColor.BLUE : OUTLINE_LINE_COLOR;
g2d.setColor(lineColor);
final Color pastBlockColor = selected ? scheme.getColor(EditorColors.SELECTED_INDENT_GUIDE_COLOR) : OUTLINE_LINE_COLOR_PAST_BLOCK;
// TODO(jacobr): this logic for softwraps is duplicated for the FilteredIndentsHighlightingPass
// and may be more conservative than sensible for WidgetIndents.
// There is a possible case that indent line intersects soft wrap-introduced text. Example:
// this is a long line <soft-wrap>
// that| is soft-wrapped
// |
// | <- vertical indent
//
// Also it's possible that no additional intersections are added because of soft wrap:
// this is a long line <soft-wrap>
// | that is soft-wrapped
// |
// | <- vertical indent
// We want to use the following approach then:
// 1. Show only active indent if it crosses soft wrap-introduced text;
// 2. Show indent as is if it doesn't intersect with soft wrap-introduced text;
int y = start.y;
int newY = start.y;
final int maxYWithChildren = y;
final SoftWrapModel softWrapModel = editor.getSoftWrapModel();
final int lineHeight = editor.getLineHeight();
int iChildLine = 0;
for (int i = max(0, startLine + lineShift); i < endLine && newY < maxY; i++) {
OutlineLocation childLine = null;
if (childLines != null) {
while (iChildLine < childLines.size()) {
final OutlineLocation currentChildLine = childLines.get(iChildLine);
if (currentChildLine.isValid()) {
if (currentChildLine.getLine() > i) {
// We haven't reached child line yet.
break;
}
if (currentChildLine.getLine() == i) {
childLine = currentChildLine;
iChildLine++;
if (iChildLine >= childLines.size()) {
splitY = newY + (lineHeight * 0.5);
}
break;
}
}
iChildLine++;
}
if (childLine != null) {
final int childIndent = childLine.getIndent();
// Draw horizontal line to the child.
final GuidelineOffsetDetail guidelineOffsetDetail = getGuidelineOffsetDetail(childLine, editor, doc, chars);
final VisualPosition widgetVisualPosition = editor.offsetToVisualPosition(guidelineOffsetDetail.textStartOffset);
final Point widgetPoint = editor.visualPositionToXY(widgetVisualPosition);
final int deltaX = widgetPoint.x - start.x;
// We add a larger amount of panding at the end of the line if the indent is larger up until a max of 6 pixels which is the max
// amount that looks reasonable. We could remove this and always used a fixed padding.
final int padding = max(min(abs(deltaX) / 3, 6), 2);
if (deltaX > 0) {
// This is the normal case where we draw a foward line to the connected child.
LinePainter2D.paint(
g2d,
start.x + INDENT_GUIDE_DELTA,
newY + lineHeight * 0.5,
//start.x + charWidth * childIndent - padding,
widgetPoint.x - padding,
newY + lineHeight * 0.5
);
}
else {
// If there are other characters on the same line as the widget,
// avoid drawing a backwards line.
if (guidelineOffsetDetail.textStartOffset != guidelineOffsetDetail.offset) {
return;
}
// Edge case where we draw a backwards line to clarify
// that the node is still a child even though the line is in
// the wrong direction. This is mainly for debugging but could help
// users fix broken UI.
// We draw this line so it is inbetween the lines of text so it
// doesn't get in the way.
final int loopBackLength = 6;
// int endX = start.x + charWidth * (childIndent -1) - padding - loopBackLength;
final int endX = widgetPoint.x - padding;
LinePainter2D.paint(
g2d,
start.x + INDENT_GUIDE_DELTA,
newY,
endX,
newY
);
LinePainter2D.paint(
g2d,
endX,
newY,
endX,
newY + lineHeight * 0.5
);
LinePainter2D.paint(
g2d,
endX,
newY + lineHeight * 0.5,
endX + loopBackLength,
newY + lineHeight * 0.5
);
}
}
}
final FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(i));
if (foldRegion != null && foldRegion.getEndOffset() < doc.getTextLength()) {
i = doc.getLineNumber(foldRegion.getEndOffset()) - 1;
continue;
}
final List<? extends SoftWrap> softWraps = softWrapModel.getSoftWrapsForLine(i);
int logicalLineHeight = softWraps.size() * lineHeight;
if (i > startLine + lineShift) {
logicalLineHeight += lineHeight; // We assume that initial 'y' value points just below the target line.
}
if (!softWraps.isEmpty() && softWraps.get(0).getIndentInColumns() < indentColumn) {
if (y < newY || i > startLine + lineShift) { // There is a possible case that soft wrap is located on indent start line.
drawVerticalLineHelper(g2d, lineColor, start.x, y, newY + lineHeight, childLines);
}
newY += logicalLineHeight;
y = newY;
}
else {
newY += logicalLineHeight;
}
}
if (childLines != null && iChildLine < childLines.size() && splitY == -1) {
// Clipped rectangle is all within the main body.
splitY = maxY;
}
if (y < maxY) {
if (splitY != -1) {
drawVerticalLineHelper(g2d, lineColor, start.x, y, splitY, childLines);
g2d.setColor(pastBlockColor);
g2d.drawLine(start.x + INDENT_GUIDE_DELTA, (int)splitY + 1, start.x + INDENT_GUIDE_DELTA, maxY);
}
else {
g2d.setColor(pastBlockColor);
g2d.drawLine(start.x + INDENT_GUIDE_DELTA, y, start.x + INDENT_GUIDE_DELTA, maxY);
}
}
g2d.dispose();
}
private static class GuidelineOffsetDetail {
// This is the offset of the widget.
final int offset;
// This is the offset of the start of text in the line of the widget (which may differ from offset).
final int textStartOffset;
GuidelineOffsetDetail(int offset, int textStartOffset) {
this.offset = offset;
this.textStartOffset = textStartOffset;
}
}
private GuidelineOffsetDetail getGuidelineOffsetDetail(OutlineLocation childLine,
Editor editor,
Document doc,
CharSequence chars) {
// This additional point is computed because sometimes there are other
// characters on a line before the widget, e.g. if a widget has been moved
// to a line with other code but the new outline has not been received yet
// (see issue #4297). We want to compute the earliest position to avoid
// drawing a line through any characters before the widget if they're
// present.
final int startIndex = doc.getLineStartOffset(childLine.getLine());
final int endIndex = doc.getLineEndOffset(childLine.getLine());
int firstCharPosition = 0;
while (startIndex + firstCharPosition < endIndex && Character.isWhitespace(chars.charAt(startIndex + firstCharPosition))) {
firstCharPosition += 1;
}
return new GuidelineOffsetDetail(
childLine.getGuideOffset(),
editor.logicalPositionToOffset(new LogicalPosition(childLine.getLine(), firstCharPosition))
);
}
}
private final EditorEx myEditor;
private final Document myDocument;
private final Project myProject;
private final VirtualFile myFile;
private final boolean convertOffsets;
private final PsiFile psiFile;
private final EditorMouseEventService editorEventService;
private final WidgetEditingContext context;
WidgetIndentsHighlightingPass(
@NotNull Project project,
@NotNull EditorEx editor,
boolean convertOffsets,
FlutterDartAnalysisServer flutterDartAnalysisService,
InspectorGroupManagerService inspectorGroupManagerService,
EditorMouseEventService editorEventService,
EditorPositionService editorPositionService
) {
this.myDocument = editor.getDocument();
this.myEditor = editor;
this.myProject = project;
this.myFile = editor.getVirtualFile();
this.convertOffsets = convertOffsets;
this.editorEventService = editorEventService;
context = new WidgetEditingContext(
project, flutterDartAnalysisService, inspectorGroupManagerService, editorPositionService);
psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myDocument);
final WidgetIndentsPassData data = getIndentsPassData();
setIndentsPassData(editor, data);
}
private static void drawVerticalLineHelper(
Graphics2D g,
Color lineColor,
int x,
double yStart,
double yEnd,
ArrayList<OutlineLocation> childLines
) {
g.setColor(lineColor);
g.drawLine(x + INDENT_GUIDE_DELTA, (int)yStart, x + INDENT_GUIDE_DELTA, (int)yEnd + 1);
}
public static int compare(@NotNull TextRangeDescriptorPair r, @NotNull RangeHighlighter h) {
int answer = r.range.getStartOffset() - h.getStartOffset();
if (answer != 0) {
return answer;
}
answer = r.range.getEndOffset() - h.getEndOffset();
if (answer != 0) {
return answer;
}
final CustomHighlighterRenderer renderer = h.getCustomRenderer();
if (renderer instanceof WidgetCustomHighlighterRenderer) {
final WidgetCustomHighlighterRenderer widgetRenderer = (WidgetCustomHighlighterRenderer)renderer;
return widgetRenderer.descriptor.compareTo(r.descriptor);
}
return -1;
}
/**
* Indent guides are hidden if they overlap with a widget indent guide.
*/
public static boolean isIndentGuideHidden(@NotNull Editor editor, @NotNull LineRange lineRange) {
final WidgetIndentsPassData data = getIndentsPassData(editor);
return data != null && isIndentGuideHidden(data.hitTester, lineRange);
}
public static boolean isIndentGuideHidden(WidgetIndentHitTester hitTester, @NotNull LineRange lineRange) {
return hitTester != null && hitTester.intersects(lineRange);
}
public static void onCaretPositionChanged(EditorEx editor, Caret caret) {
final WidgetIndentsPassData data = getIndentsPassData(editor);
if (data == null || data.highlighters == null) return;
for (RangeHighlighter h : data.highlighters) {
if (h.getCustomRenderer() instanceof WidgetIndentsHighlightingPass.WidgetCustomHighlighterRenderer) {
final WidgetIndentsHighlightingPass.WidgetCustomHighlighterRenderer renderer =
(WidgetIndentsHighlightingPass.WidgetCustomHighlighterRenderer)h.getCustomRenderer();
final boolean changed = renderer.updateSelected(editor, h, caret);
if (changed) {
editor.repaint(h.getStartOffset(), h.getEndOffset());
}
}
}
}
private static WidgetIndentsPassData getIndentsPassData(Editor editor) {
if (editor == null) return null;
return editor.getUserData(INDENTS_PASS_DATA_KEY);
}
public static void disposeHighlighter(RangeHighlighter highlighter) {
final CustomHighlighterRenderer renderer = highlighter.getCustomRenderer();
if (renderer instanceof WidgetCustomHighlighterRenderer) {
((WidgetCustomHighlighterRenderer)renderer).dispose();
}
highlighter.dispose();
}
public static void cleanupHighlighters(Editor editor) {
final WidgetIndentsPassData data = getIndentsPassData(editor);
if (data == null) return;
final List<RangeHighlighter> oldHighlighters = data.highlighters;
if (oldHighlighters != null) {
for (RangeHighlighter highlighter : oldHighlighters) {
disposeHighlighter(highlighter);
}
}
setIndentsPassData(editor, null);
}
public static void run(@NotNull Project project,
@NotNull EditorEx editor,
@NotNull FlutterOutline outline,
FlutterDartAnalysisServer flutterDartAnalysisService,
InspectorGroupManagerService inspectorGroupManagerService,
EditorMouseEventService editorEventService,
EditorPositionService editorPositionService,
boolean convertOffsets
) {
final WidgetIndentsHighlightingPass widgetIndentsHighlightingPass = new WidgetIndentsHighlightingPass(
project,
editor,
convertOffsets,
flutterDartAnalysisService,
inspectorGroupManagerService,
editorEventService,
editorPositionService
);
widgetIndentsHighlightingPass.setOutline(outline);
}
/**
* This method must be called on the main UI thread.
* <p>
* Some of this logic would appear to be safe to call on a background thread but
* there are race conditions where the data will be out of order if the document
* is being edited while the code is executing.
* <p>
* If there are performance concerns we can work to perform more of this
* computation on a separate thread.
*/
public void setOutline(FlutterOutline outline) {
assert (outline != null);
final WidgetIndentsPassData data = getIndentsPassData();
if (data.outline == outline) {
// The outline has not changed. There is nothing we need to do.
return;
}
final ArrayList<WidgetIndentGuideDescriptor> descriptors = new ArrayList<>();
buildWidgetDescriptors(descriptors, outline, null);
updateHitTester(new WidgetIndentHitTester(descriptors, myDocument), data);
// TODO(jacobr): we need to trigger a rerender of highlighters that will render differently due to the changes in highlighters?
data.myDescriptors = descriptors;
doCollectInformationUpdateOutline(data);
doApplyIndentInformationToEditor(data);
setIndentsPassData(data);
updatePreviewHighlighter(myEditor.getMarkupModel(), data);
}
private void updateHitTester(WidgetIndentHitTester hitTester, WidgetIndentsPassData data) {
if (Objects.equals(data.hitTester, hitTester)) {
return;
}
FilteredIndentsHighlightingPass.onWidgetIndentsChanged(myEditor, data.hitTester, hitTester);
data.hitTester = hitTester;
}
private WidgetIndentsPassData getIndentsPassData() {
WidgetIndentsPassData data = getIndentsPassData(myEditor);
if (data == null) {
data = new WidgetIndentsPassData();
}
return data;
}
static void setIndentsPassData(Editor editor, WidgetIndentsPassData data) {
editor.putUserData(INDENTS_PASS_DATA_KEY, data);
}
void setIndentsPassData(WidgetIndentsPassData data) {
setIndentsPassData(myEditor, data);
}
public void doCollectInformationUpdateOutline(WidgetIndentsPassData data) {
assert myDocument != null;
if (data.myDescriptors != null) {
final ArrayList<TextRangeDescriptorPair> ranges = new ArrayList<>();
for (WidgetIndentGuideDescriptor descriptor : data.myDescriptors) {
ProgressManager.checkCanceled();
final TextRange range;
if (descriptor.widget != null) {
range = descriptor.widget.getFullRange();
}
else {
final int endOffset =
descriptor.endLine < myDocument.getLineCount() ? myDocument.getLineStartOffset(descriptor.endLine) : myDocument.getTextLength();
range = new TextRange(myDocument.getLineStartOffset(descriptor.startLine), endOffset);
}
// TODO(jacobr): calling trackLocations multiple times is harmless
// but we should still audit where we are calling it so that we
// only call it once on each descriptor for typical use cases.
descriptor.trackLocations(myDocument);
ranges.add(new TextRangeDescriptorPair(range, descriptor));
}
ranges.sort((a, b) -> Segment.BY_START_OFFSET_THEN_END_OFFSET.compare(a.range, b.range));
data.myRangesWidgets = ranges;
}
}
public void doApplyIndentInformationToEditor(WidgetIndentsPassData data) {
final MarkupModel mm = myEditor.getMarkupModel();
final List<RangeHighlighter> oldHighlighters = data.highlighters;
final List<RangeHighlighter> newHighlighters = new ArrayList<>();
int curRange = 0;
final List<TextRangeDescriptorPair> ranges = data.myRangesWidgets;
if (oldHighlighters != null) {
// after document change some range highlighters could have become
// invalid, or the order could have been broken.
// This is similar to logic in FilteredIndentsHighlightingPass.java that also attempts to
// only update highlighters that have actually changed.
oldHighlighters.sort(Comparator.comparing((RangeHighlighter h) -> !h.isValid())
.thenComparing(Segment.BY_START_OFFSET_THEN_END_OFFSET));
int curHighlight = 0;
// It is fine if we cleanupHighlighters and update some old highlighters that are
// still valid but it is not ok if we leave even one highlighter that
// really changed as that will cause rendering artifacts.
while (curRange < ranges.size() && curHighlight < oldHighlighters.size()) {
final TextRangeDescriptorPair entry = ranges.get(curRange);
final RangeHighlighter highlighter = oldHighlighters.get(curHighlight);
if (!highlighter.isValid()) break;
final int cmp = compare(entry, highlighter);
if (cmp < 0) {
newHighlighters.add(createHighlighter(mm, entry, data));
curRange++;
}
else if (cmp > 0) {
disposeHighlighter(highlighter);
curHighlight++;
}
else {
newHighlighters.add(highlighter);
curHighlight++;
curRange++;
}
}
for (; curHighlight < oldHighlighters.size(); curHighlight++) {
final RangeHighlighter highlighter = oldHighlighters.get(curHighlight);
if (!highlighter.isValid()) break;
disposeHighlighter(highlighter);
}
}
final int startRangeIndex = curRange;
assert myDocument != null;
DocumentUtil.executeInBulk(myDocument, ranges.size() > 10000, () -> {
for (int i = startRangeIndex; i < ranges.size(); i++) {
newHighlighters.add(createHighlighter(mm, ranges.get(i), data));
}
});
data.highlighters = newHighlighters;
}
private DartAnalysisServerService getAnalysisService() {
return DartAnalysisServerService.getInstance(myProject);
}
/**
* All calls to convert offsets for indent highlighting must go through this method.
* <p>
* Sometimes we need to use the raw offsets and sometimes we need
* to use the converted offsets depending on whether the FlutterOutline
* matches the current document or the expectations given by the
*
* @param node the FlutterOutline to retreive the offset for
*/
int getConvertedOffset(FlutterOutline node) {
return getConvertedOffset(node.getOffset());
}
int getConvertedOffset(int offset) {
return convertOffsets ? getAnalysisService().getConvertedOffset(myFile, offset) : offset;
}
private OutlineLocation computeLocation(FlutterOutline node) {
assert (myDocument != null);
final int documentLength = myDocument.getTextLength();
final int rawOffset = getConvertedOffset(node);
final int nodeOffset = min(rawOffset, documentLength);
final int line = myDocument.getLineNumber(nodeOffset);
final int lineStartOffset = myDocument.getLineStartOffset(line);
final int column = nodeOffset - lineStartOffset;
final CharSequence chars = myDocument.getCharsSequence();
int indent;
// TODO(jacobr): we only really want to include the previous token (e.g.
// "child: " instead of the entire line). That won't matter much but could
// lead to slightly better results on code edits.
for (indent = 0; indent < column; indent++) {
if (!Character.isWhitespace(chars.charAt(lineStartOffset + indent))) {
break;
}
}
return new OutlineLocation(node, line, column, indent, myFile, this);
}
DartCallExpression getCallExpression(PsiElement element) {
if (element == null) {
return null;
}
if (element instanceof DartCallExpression) {
return (DartCallExpression)element;
}
return getCallExpression(element.getParent());
}
private void buildWidgetDescriptors(
final List<WidgetIndentGuideDescriptor> widgetDescriptors,
FlutterOutline outlineNode,
WidgetIndentGuideDescriptor parent
) {
if (outlineNode == null) return;
final String kind = outlineNode.getKind();
final boolean widgetConstructor = "NEW_INSTANCE".equals(kind) || (parent != null && ("VARIABLE".equals(kind)));
final List<FlutterOutline> children = outlineNode.getChildren();
if (children == null || children.isEmpty()) return;
if (widgetConstructor) {
final OutlineLocation location = computeLocation(outlineNode);
int minChildIndent = Integer.MAX_VALUE;
final ArrayList<OutlineLocation> childrenLocations = new ArrayList<>();
int endLine = location.getLine();
for (FlutterOutline child : children) {
final OutlineLocation childLocation = computeLocation(child);
if (childLocation.getLine() <= location.getLine()) {
// Skip children that don't actually occur on a later line. There is no
// way for us to draw good looking line art for them.
// TODO(jacobr): consider adding these children anyway so we can render
// them if there are edits and they are now properly formatted.
continue;
}
minChildIndent = min(minChildIndent, childLocation.getIndent());
endLine = max(endLine, childLocation.getLine());
childrenLocations.add(childLocation);
}
final Set<Integer> childrenOffsets = new HashSet<>();
for (OutlineLocation childLocation : childrenLocations) {
childrenOffsets.add(childLocation.getGuideOffset());
}
final PsiElement element = psiFile.findElementAt(location.getGuideOffset());
if (!childrenLocations.isEmpty()) {
// The indent is only used for sorting and disambiguating descriptors
// as at render time we will pick the real indent for the outline based
// on local edits that may have been made since the outline was computed.
final int lineIndent = location.getIndent();
final WidgetIndentGuideDescriptor descriptor = new WidgetIndentGuideDescriptor(
parent,
lineIndent,
location.getLine(),
endLine + 1,
childrenLocations,
location,
outlineNode
);
if (!descriptor.childLines.isEmpty()) {
widgetDescriptors.add(descriptor);
parent = descriptor;
}
}
}
for (FlutterOutline child : children) {
buildWidgetDescriptors(widgetDescriptors, child, parent);
}
}
@NotNull
private RangeHighlighter createHighlighter(MarkupModel mm, TextRangeDescriptorPair entry, WidgetIndentsPassData data) {
final TextRange range = entry.range;
final FlutterSettings settings = FlutterSettings.getInstance();
if (range.getEndOffset() >= myDocument.getTextLength() && DEBUG_WIDGET_INDENTS) {
LOG.info("Warning: highlighter extends past the end of document.");
}
final RangeHighlighter highlighter = mm.addRangeHighlighter(
Math.max(range.getStartOffset(), 0),
Math.min(range.getEndOffset(), myDocument.getTextLength()),
HighlighterLayer.FIRST,
null,
HighlighterTargetArea.EXACT_RANGE
);
highlighter.setCustomRenderer(new WidgetCustomHighlighterRenderer(entry.descriptor, myDocument));
return highlighter;
}
private void updatePreviewHighlighter(MarkupModel mm, WidgetIndentsPassData data) {
final FlutterSettings settings = FlutterSettings.getInstance();
if (!settings.isEnableHotUiInCodeEditor()) return;
if (data.previewsForEditor == null && myEditor instanceof EditorImpl) {
// TODO(jacobr): is there a way to get access to a disposable that will
// trigger when the editor disposes than casting to EditorImpl?
final Disposable parentDisposable = ((EditorImpl)myEditor).getDisposable();
final TextRange range = new TextRange(0, Integer.MAX_VALUE);
final RangeHighlighter highlighter =
mm.addRangeHighlighter(
0,
myDocument.getTextLength(),
HighlighterLayer.FIRST,
null,
HighlighterTargetArea.LINES_IN_RANGE
);
data.previewsForEditor = new PreviewsForEditor(context, editorEventService, myEditor, parentDisposable);
highlighter.setCustomRenderer(data.previewsForEditor);
}
if (data.previewsForEditor != null) {
data.previewsForEditor.outlinesChanged(data.myDescriptors);
}
}
}
class TextRangeDescriptorPair {
@NotNull final TextRange range;
@NotNull final WidgetIndentGuideDescriptor descriptor;
TextRangeDescriptorPair(@NotNull TextRange range, @NotNull WidgetIndentGuideDescriptor descriptor) {
this.range = range;
this.descriptor = descriptor;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentsHighlightingPass.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentsHighlightingPass.java",
"repo_id": "flutter-intellij",
"token_count": 14150
} | 492 |
/*
* 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.inspector;
/**
* An exception that can occur from calls to eval() from the Inspector codebase.
*/
public class EvalException extends Exception {
public final String expression;
public final String errorCode;
public final String errorMessage;
public EvalException(String expression, String errorCode, String errorMessage) {
this.expression = expression;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
@Override
public String toString() {
return "expression=" + expression + ",errorCode=" + errorCode + ",errorMessage=" + errorMessage;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/inspector/EvalException.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/EvalException.java",
"repo_id": "flutter-intellij",
"token_count": 209
} | 493 |
/*
* 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.inspector;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import io.flutter.utils.math.Matrix4;
import java.awt.geom.Rectangle2D;
public class TransformedRect {
final JsonObject json;
public TransformedRect(JsonObject json) {
this.json = json;
}
public Rectangle2D getRectangle() {
return new Rectangle2D.Double(
json.getAsJsonPrimitive("left").getAsDouble(),
json.getAsJsonPrimitive("top").getAsDouble(),
json.getAsJsonPrimitive("width").getAsDouble(),
json.getAsJsonPrimitive("height").getAsDouble()
);
}
public Matrix4 getTransform() {
final JsonArray data = json.getAsJsonArray("transform");
final double[] storage = new double[16];
for (int i = 0; i < 16; i++) {
storage[i] = data.get(i).getAsDouble();
}
return new Matrix4(storage);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/inspector/TransformedRect.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/TransformedRect.java",
"repo_id": "flutter-intellij",
"token_count": 375
} | 494 |
/*
* Copyright 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.module;
import io.flutter.FlutterBundle;
public enum FlutterProjectType {
APP(FlutterBundle.message("flutter.module.create.settings.type.application"), "app", true),
PLUGIN(FlutterBundle.message("flutter.module.create.settings.type.plugin"), "plugin", true),
PACKAGE(FlutterBundle.message("flutter.module.create.settings.type.package"), "package", false),
MODULE(FlutterBundle.message("flutter.module.create.settings.type.module"), "module", false),
SKELETON("Skeleton", "skeleton", true),
PLUGIN_FFI("FFI Plugin", "plugin_ffi", true),
EMPTY_PROJECT("Empty Project", "--empty", true),
IMPORT(FlutterBundle.message("flutter.module.create.settings.type.import_module"), "module", false);
final public String title;
final public String arg;
final public boolean requiresPlatform;
FlutterProjectType(String title, String arg, boolean requiresPlatform) {
this.title = title;
this.arg = arg;
this.requiresPlatform = requiresPlatform;
}
public String toString() {
return title;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/module/FlutterProjectType.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/FlutterProjectType.java",
"repo_id": "flutter-intellij",
"token_count": 376
} | 495 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.perf;
/**
* Statistics summarizing how frequently an event has occurred overall and in
* the past second.
*/
public class SummaryStats {
private final PerfReportKind kind;
private final SlidingWindowStatsSummary entry;
private final String description;
boolean active = true;
SummaryStats(PerfReportKind kind, SlidingWindowStatsSummary entry, String description) {
this.kind = kind;
this.entry = entry;
this.description = description;
}
public PerfReportKind getKind() {
return kind;
}
public int getValue(PerfMetric metric) {
if (metric.timeIntervalMetric && !active) {
return 0;
}
return entry.getValue(metric);
}
public void markAppIdle() {
active = false;
}
public String getDescription() {
return description;
}
public Location getLocation() {
return entry.getLocation();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/perf/SummaryStats.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/SummaryStats.java",
"repo_id": "flutter-intellij",
"token_count": 322
} | 496 |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.preview;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService;
import org.dartlang.analysis.server.protocol.FlutterOutline;
public class OutlineOffsetConverter {
private final VirtualFile currentFile;
private final Project project;
public OutlineOffsetConverter(Project project, VirtualFile currentFile) {
this.project = project;
this.currentFile = currentFile;
}
public int getConvertedFileOffset(int offset) {
return DartAnalysisServerService.getInstance(project).getConvertedOffset(currentFile, offset);
}
public int getConvertedOutlineOffset(FlutterOutline outline) {
final int offset = outline.getOffset();
return getConvertedFileOffset(offset);
}
public int getConvertedOutlineEnd(FlutterOutline outline) {
final int end = outline.getOffset() + outline.getLength();
return getConvertedFileOffset(end);
}
// TODO(jacobr): move this method to a different class or rename this class.
public FlutterOutline findOutlineAtOffset(FlutterOutline outline, int offset) {
if (outline == null) {
return null;
}
if (getConvertedOutlineOffset(outline) <= offset && offset <= getConvertedOutlineEnd(outline)) {
if (outline.getChildren() != null) {
for (FlutterOutline child : outline.getChildren()) {
final FlutterOutline foundChild = findOutlineAtOffset(child, offset);
if (foundChild != null) {
return foundChild;
}
}
}
return outline;
}
return null;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/preview/OutlineOffsetConverter.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/preview/OutlineOffsetConverter.java",
"repo_id": "flutter-intellij",
"token_count": 601
} | 497 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run;
// RunContentManager
import com.intellij.concurrency.JobScheduler;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.RunContentManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.utils.EventStream;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class FlutterAppManager implements Disposable {
@Nullable
public static FlutterAppManager getInstance(@NotNull Project project) {
return project.getService(FlutterAppManager.class);
}
@NotNull
private final Project project;
private final EventStream<FlutterApp> activeAppSteam = new EventStream<>();
private final ScheduledFuture task;
private FlutterApp lastActiveApp;
private FlutterAppManager(@NotNull Project project) {
this.project = project;
// TODO This object shoud have a different disposable parent to enable dynamic plugin loading.
Disposer.register(project, this);
task = JobScheduler.getScheduler().scheduleWithFixedDelay(
this::updateActiveApp, 1, 1, TimeUnit.SECONDS);
}
@Override
public void dispose() {
task.cancel(false);
}
/**
* Return the active (front most in the UI) Flutter app.
* <p>
* This could return null even if there is a running Flutter app, if the front-most
* running process (focused in the Run or Debug view) is not a Flutter app instance.
*/
@Nullable
public FlutterApp getActiveApp() {
final RunContentManager mgr = getRunContentManager();
if (mgr == null) {
return null;
}
final RunContentDescriptor descriptor = mgr.getSelectedContent();
if (descriptor == null) {
return null;
}
final ProcessHandler process = descriptor.getProcessHandler();
if (process == null) {
return null;
}
final FlutterApp app = FlutterApp.fromProcess(process);
return app != null && app.isConnected() ? app : null;
}
public EventStream<FlutterApp> getActiveAppAsStream() {
return activeAppSteam;
}
/**
* Return the list of all running Flutter apps.
*/
public List<FlutterApp> getApps() {
final List<FlutterApp> apps = new ArrayList<>();
final RunContentManager mgr = getRunContentManager();
if (mgr == null) {
return apps;
}
final List<RunContentDescriptor> runningProcesses = mgr.getAllDescriptors();
for (RunContentDescriptor descriptor : runningProcesses) {
final ProcessHandler process = descriptor.getProcessHandler();
if (process != null) {
final FlutterApp app = FlutterApp.fromProcess(process);
if (app != null && app.isConnected()) {
apps.add(app);
}
}
}
return apps;
}
private void updateActiveApp() {
final FlutterApp activeApp = getActiveApp();
if (activeApp != lastActiveApp) {
lastActiveApp = activeApp;
activeAppSteam.setValue(activeApp);
}
}
@Nullable
private RunContentManager getRunContentManager() {
if (project.isDisposed()) {
return null;
}
// Creating a RunContentManager causes a blank window to appear, so don't create it here.
// See https://github.com/flutter/flutter-intellij/issues/4217
if (ServiceManager.getServiceIfCreated(project, RunContentManager.class) == null) {
return null;
}
return ExecutionManager.getInstance(project).getContentManager();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/FlutterAppManager.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/FlutterAppManager.java",
"repo_id": "flutter-intellij",
"token_count": 1336
} | 498 |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run;
import com.intellij.ide.browsers.BrowserLauncher;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import icons.FlutterIcons;
import io.flutter.FlutterInitializer;
import io.flutter.ObservatoryConnector;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.devtools.DevToolsIdeFeature;
import io.flutter.devtools.DevToolsUrl;
import io.flutter.run.daemon.DevToolsService;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.sdk.FlutterSdk;
import io.flutter.utils.AsyncUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class OpenDevToolsAction extends DumbAwareAction {
private static final Logger LOG = Logger.getInstance(OpenDevToolsAction.class);
private static final String title = "Open Flutter DevTools";
private final @Nullable ObservatoryConnector myConnector;
private final Computable<Boolean> myIsApplicable;
public OpenDevToolsAction() {
myConnector = null;
myIsApplicable = null;
}
public OpenDevToolsAction(@NotNull final FlutterApp app, @NotNull final Computable<Boolean> isApplicable) {
this(app.getConnector(), isApplicable);
}
public OpenDevToolsAction(@NotNull final ObservatoryConnector connector, @NotNull final Computable<Boolean> isApplicable) {
super(title, title, FlutterIcons.Dart_16);
myConnector = connector;
myIsApplicable = isApplicable;
}
@Override
public void update(@NotNull final AnActionEvent e) {
if (myIsApplicable == null) {
e.getPresentation().setEnabled(true);
}
else {
e.getPresentation().setEnabled(myIsApplicable.compute());
}
}
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
FlutterInitializer.sendAnalyticsAction(this);
Project project = event.getProject();
if (project == null) {
return;
}
AsyncUtils.whenCompleteUiThread(DevToolsService.getInstance(project).getDevToolsInstance(), (instance, ex) -> {
if (project.isDisposed()) {
return;
}
if (ex != null) {
LOG.error(ex);
return;
}
final String serviceUrl = myConnector != null && myConnector.getBrowserUrl() != null ? myConnector.getBrowserUrl() : null;
FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(project);
BrowserLauncher.getInstance().browse(
(new DevToolsUrl(instance.host, instance.port, serviceUrl, null, false, null, null, flutterSdk == null ? null : flutterSdk.getVersion(), WorkspaceCache.getInstance(project), DevToolsIdeFeature.RUN_CONSOLE).getUrlString()),
null
);
});
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/OpenDevToolsAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/OpenDevToolsAction.java",
"repo_id": "flutter-intellij",
"token_count": 1020
} | 499 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run.bazelTest;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.CommandLineTokenizer;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.RuntimeConfigurationError;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.lang.dart.sdk.DartConfigurable;
import com.jetbrains.lang.dart.sdk.DartSdk;
import io.flutter.FlutterBundle;
import io.flutter.bazel.Workspace;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.dart.DartPlugin;
import io.flutter.run.MainFile;
import io.flutter.run.bazelTest.FlutterBazelTestConfigurationType.WatchFactory;
import io.flutter.run.common.RunMode;
import io.flutter.sdk.FlutterSettingsConfigurable;
import io.flutter.utils.ElementIO;
import io.flutter.utils.MostlySilentColoredProcessHandler;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* The fields in a Bazel test run configuration.
*/
public class BazelTestFields {
@Nullable private final String testName;
@Nullable private final String entryFile;
@Nullable private final String bazelTarget;
@Nullable private final String additionalArgs;
BazelTestFields(@Nullable String testName, @Nullable String entryFile, @Nullable String bazelTarget, @Nullable String additionalArgs) {
if (testName != null && entryFile == null) {
throw new IllegalArgumentException("testName must be specified with an entryFile");
}
this.testName = testName;
this.entryFile = entryFile;
this.bazelTarget = bazelTarget;
this.additionalArgs = additionalArgs;
}
/**
* Copy constructor
*/
BazelTestFields(@NotNull BazelTestFields template) {
this(template.testName, template.entryFile, template.bazelTarget, template.additionalArgs);
}
private String getTestScriptFromWorkspace(@NotNull Project project) {
final Workspace workspace = getWorkspace(project);
assert workspace != null;
String testScript = workspace.getTestScript();
assert testScript != null;
testScript = workspace.getRoot().getPath() + "/" + testScript;
return testScript;
}
/**
* Creates settings for running tests with the given name within a Dart file.
*/
@NotNull
public static BazelTestFields forTestName(@NotNull String testName, @NotNull String path, @Nullable String additionalArgs) {
return new BazelTestFields(testName, path, null, additionalArgs);
}
/**
* Creates settings for running all the tests in a Dart file.
*/
public static BazelTestFields forFile(@NotNull String path, @Nullable String additionalArgs) {
return new BazelTestFields(null, path, null, additionalArgs);
}
/**
* Creates settings for running all the tests in a Bazel target
*/
public static BazelTestFields forTarget(@NotNull String target, @Nullable String additionalArgs) {
return new BazelTestFields(null, null, target, additionalArgs);
}
@Nullable
public String getTestName() {
return testName;
}
/**
* The file containing the main function that starts the Flutter test.
*/
@Nullable
public String getEntryFile() {
return entryFile;
}
/**
* Returns the file or directory containing the tests to run, or null if it doesn't exist.
*/
@Nullable
public VirtualFile getFile() {
final String path = getEntryFile();
if (path == null) return null;
return LocalFileSystem.getInstance().findFileByPath(path);
}
@Nullable
public String getBazelTarget() {
return bazelTarget;
}
/**
* Parameters to pass to the test runner, such as --watch.
*/
@Nullable
public String getAdditionalArgs() {
return additionalArgs;
}
@NotNull
BazelTestFields copy() {
return new BazelTestFields(this);
}
@NotNull
BazelTestFields copyTemplateToNonTemplate(@NotNull final Project project) {
return new BazelTestFields(this);
}
/**
* Reports an error in the run config that the user should correct.
* <p>
* This will be called while the user is typing into a non-template run config.
* (See RunConfiguration.checkConfiguration.)
*
* @throws RuntimeConfigurationError for an error that that the user must correct before running.
*/
void checkRunnable(@NotNull final Project project) throws RuntimeConfigurationError {
// The UI only shows one error message at a time.
// The order we do the checks here determines priority.
final DartSdk sdk = DartPlugin.getDartSdk(project);
if (sdk == null) {
throw new RuntimeConfigurationError(FlutterBundle.message("dart.sdk.is.not.configured"),
() -> DartConfigurable.openDartSettings(project));
}
getScope(project).checkRunnable(this, project);
}
/**
* Starts running the tests.
*/
@NotNull
ProcessHandler run(@NotNull final Project project, @NotNull final RunMode mode) throws ExecutionException {
return new MostlySilentColoredProcessHandler(getLaunchCommand(project, mode));
}
/**
* Returns the command to use to launch the Flutter app. (Via running the Bazel target.)
*/
@NotNull
GeneralCommandLine getLaunchCommand(@NotNull final Project project,
@NotNull final RunMode mode) throws ExecutionException {
try {
checkRunnable(project);
}
catch (RuntimeConfigurationError e) {
throw new ExecutionException(e);
}
final Workspace workspace = getWorkspace(project);
final String launchingScript = getTestScriptFromWorkspace(project);
assert launchingScript != null; // already checked
final GeneralCommandLine commandLine = new GeneralCommandLine().withWorkDirectory(workspace.getRoot().getPath());
commandLine.setCharset(StandardCharsets.UTF_8);
commandLine.setExePath(FileUtil.toSystemDependentName(launchingScript));
final String nonNullArgs = StringUtil.notNullize(additionalArgs);
// User specified additional target arguments.
final CommandLineTokenizer testArgsTokenizer = new CommandLineTokenizer(nonNullArgs);
while (testArgsTokenizer.hasMoreTokens()) {
commandLine.addParameter(testArgsTokenizer.nextToken());
}
commandLine.addParameter(Flags.noColor);
// If the user did not turn the --machine flag off, we will pass it to the test runner.
if (!nonNullArgs.contains(Flags.noMachine)) {
commandLine.addParameter(Flags.machine);
}
final String relativeEntryFilePath = entryFile == null
? null
: FileUtil.getRelativePath(workspace.getRoot().getPath(), entryFile, '/');
switch (getScope(project)) {
case NAME:
commandLine.addParameters(Flags.name, testName);
commandLine.addParameter(relativeEntryFilePath);
break;
case FILE:
commandLine.addParameter(relativeEntryFilePath);
break;
case TARGET_PATTERN:
commandLine.addParameter(bazelTarget);
break;
}
if (mode == RunMode.DEBUG) {
commandLine.addParameters(Flags.separator, Flags.enableDebugging);
}
return commandLine;
}
@Nullable
protected Workspace getWorkspace(@NotNull Project project) {
return WorkspaceCache.getInstance(project).get();
}
protected void verifyMainFile(Project project) throws RuntimeConfigurationError {
final MainFile.Result main = MainFile.verify(entryFile, project);
if (!main.canLaunch()) {
throw new RuntimeConfigurationError(main.getError());
}
}
/**
* Checks if these fields provide a test-watching configuration (include the flag --watch).
* <p>
* See {@link BazelWatchTestConfigProducer} and {@link WatchFactory} for more information.
*/
public boolean isWatchConfig() {
return getAdditionalArgs() != null && getAdditionalArgs().contains(Flags.watch);
}
/**
* Determines the type of test invocation we need to run: test-by-name, test-by-file, or test-by-bazel-target.
*
* <p>
* We can assume the following about this BazelTestFields instance based on the Scope returned.
*
* <p>
* <ul>
* <li>Scope.NAME: The testName and entryFile fields are both non-null. The bazelTarget field may be null.</li>
* <li>Scope.FILE: The entryFile field is non-null. The bazelTarget field may be null.</li>
* <li>Scope.TARGET_PATTERN: The testName and entryFile fields may both be null. If the bazelTarget field is non-null, this target is
* runnable.</li>
* </ul>
*/
@NotNull
public Scope getScope(@NotNull Project project) {
if (testName != null && entryFile != null) {
return Scope.NAME;
}
if (entryFile != null) {
return Scope.FILE;
}
return Scope.TARGET_PATTERN;
}
public void writeTo(Element element) {
ElementIO.addOption(element, "testName", testName);
ElementIO.addOption(element, "entryFile", entryFile);
ElementIO.addOption(element, "bazelTarget", bazelTarget);
ElementIO.addOption(element, "additionalArgs", additionalArgs);
}
public static BazelTestFields readFrom(Element element) {
final Map<String, String> options = ElementIO.readOptions(element);
final String testName = options.get("testName");
final String entryFile = options.get("entryFile");
final String bazelTarget = options.get("bazelTarget");
final String additionalArgs = options.get("additionalArgs");
try {
return new BazelTestFields(testName, entryFile, bazelTarget, additionalArgs);
}
catch (IllegalArgumentException e) {
throw new InvalidDataException(e.getMessage());
}
}
public enum Scope {
NAME("Tests in file, filtered by name") {
@Override
public void checkRunnable(@NotNull BazelTestFields fields, @NotNull Project project) throws RuntimeConfigurationError {
FILE.checkRunnable(fields, project);
}
},
FILE("All tests in a file") {
@Override
public void checkRunnable(@NotNull BazelTestFields fields, @NotNull Project project) throws RuntimeConfigurationError {
// The new bazel test runner could not be found.
final Workspace workspace = fields.getWorkspace(project);
if (workspace == null || workspace.getTestScript() == null) {
throw new RuntimeConfigurationError(FlutterBundle.message("flutter.run.bazel.newBazelTestRunnerUnavailable"),
() -> FlutterSettingsConfigurable.openFlutterSettings(project));
}
fields.verifyMainFile(project);
}
},
TARGET_PATTERN("All tests in a bazel target or matching a bazel target pattern") {
@Override
public void checkRunnable(@NotNull BazelTestFields fields, @NotNull Project project) throws RuntimeConfigurationError {
// check that bazel target is not empty
if (StringUtil.isEmptyOrSpaces(fields.getBazelTarget())) {
throw new RuntimeConfigurationError(FlutterBundle.message("flutter.run.bazel.noTargetSet"));
}
// check that the bazel target starts with "//"
if (!fields.getBazelTarget().startsWith("//")) {
throw new RuntimeConfigurationError(FlutterBundle.message("flutter.run.bazel.startWithSlashSlash"));
}
}
};
private final String displayName;
Scope(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
public abstract void checkRunnable(@NotNull BazelTestFields fields, @NotNull Project project) throws RuntimeConfigurationError;
}
/**
* Flags and options that we pass on to the flutter runner or pay special attention to.
*/
final static class Flags {
/**
* Flag passed to the test runner script. Tells it to watch files, and re-run tests when the run completes.
*/
static String watch = "--watch";
/**
* Flag passed to the test runner script. Tells it to display results without any special text coloring.
*/
static String noColor = "--no-color";
/**
* Option passed to the test runner script. Tells it to only run tests matching a given name.
*/
static String name = "--name";
/**
* Flag passed to the bazel test runner. Tells it to allow the debugger to attach to the tests.
*/
static String enableDebugging = "--enable-debugging";
/**
* Separator between groups of flags. This distinguishes bazel args from additional args.
*/
static String separator = "--";
/**
* Option passed to the bazel test runner. Tells it to report test status in machine-readable JSON to show results in the UI.
*/
static String machine = "--machine";
/**
* Option passed to the bazel test runner. Tells it to report test status without machine-readable JSON and not show detailed results
* in the UI.
*/
static String noMachine = "--no-machine";
// Don't allow construction of this class.
private Flags() {
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelTestFields.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelTestFields.java",
"repo_id": "flutter-intellij",
"token_count": 4562
} | 500 |
/*
* 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.run.coverage;
import com.intellij.coverage.CoverageDataManager;
import com.intellij.coverage.CoverageExecutor;
import com.intellij.coverage.CoverageRunnerData;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.ConfigurationInfoProvider;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.configurations.RunnerSettings;
import com.intellij.execution.configurations.coverage.CoverageEnabledConfiguration;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.DefaultProgramRunnerKt;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.GenericProgramRunner;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import io.flutter.FlutterBundle;
import io.flutter.run.test.TestConfig;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FlutterCoverageProgramRunner extends GenericProgramRunner<RunnerSettings> {
private static final Logger LOG = Logger.getInstance(FlutterCoverageProgramRunner.class.getName());
private static final String ID = "FlutterCoverageProgramRunner";
private ProcessHandler handler;
private ProcessAdapter listener;
@Override
public @NotNull
@NonNls
String getRunnerId() {
return ID;
}
@Override
public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) {
return executorId.equals(CoverageExecutor.EXECUTOR_ID) && profile instanceof TestConfig;
}
@Override
public RunnerSettings createConfigurationData(@NotNull final ConfigurationInfoProvider settingsProvider) {
return new CoverageRunnerData();
}
@Override
@Nullable
protected RunContentDescriptor doExecute(final @NotNull RunProfileState state,
final @NotNull ExecutionEnvironment env) throws ExecutionException {
final RunContentDescriptor result = DefaultProgramRunnerKt.executeState(state, env, this);
if (result == null) {
return null;
}
handler = result.getProcessHandler();
if (handler != null) {
listener = new ProcessAdapter() {
@Override
public void processTerminated(@NotNull ProcessEvent event) {
ApplicationManager.getApplication().invokeLater(() -> processCoverage(env));
}
};
handler.addProcessListener(listener);
}
return result;
}
private void processCoverage(ExecutionEnvironment env) {
if (!(env.getRunProfile() instanceof TestConfig)) return;
final TestConfig runConfig = (TestConfig)env.getRunProfile();
final CoverageEnabledConfiguration configuration = CoverageEnabledConfiguration.getOrCreate(runConfig);
if (configuration.getCoverageFilePath() == null) return;
final Path path = Paths.get(configuration.getCoverageFilePath());
final Path cov = path.getParent();
VfsUtil.markDirtyAndRefresh(false, false, true, LocalFileSystem.getInstance().findFileByPath(cov.getParent().toString()));
VfsUtil.markDirtyAndRefresh(false, true, true, LocalFileSystem.getInstance().findFileByPath(cov.toString()));
if (Files.exists(path)) {
@Nullable final RunnerSettings settings = env.getRunnerSettings();
if (settings != null) {
CoverageDataManager.getInstance(env.getProject()).processGatheredCoverage(runConfig, settings);
handler.removeProcessListener(listener);
handler = null;
listener = null;
}
}
else {
LOG.error(FlutterBundle.message("coverage.path.not.found", path));
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/coverage/FlutterCoverageProgramRunner.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/coverage/FlutterCoverageProgramRunner.java",
"repo_id": "flutter-intellij",
"token_count": 1384
} | 501 |
/*
* Copyright 2022 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run.test;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.testframework.sm.runner.SMTRunnerConsoleProperties;
import org.jetbrains.annotations.NotNull;
/**
* This is required to enable the auto-test-before-commit feature in the VCS tool window.
*/
public class FlutterTestConsoleProperties extends SMTRunnerConsoleProperties {
public FlutterTestConsoleProperties(@NotNull RunConfiguration config, @NotNull Executor executor) {
super(config, "FlutterWidgetTests", executor);
}
@Override
public RunProfile getConfiguration() {
return getConfiguration();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestConsoleProperties.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestConsoleProperties.java",
"repo_id": "flutter-intellij",
"token_count": 264
} | 502 |
/*
* 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.sdk;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.libraries.LibraryEx;
import com.intellij.openapi.roots.libraries.*;
import com.intellij.openapi.util.text.StringUtil;
import io.flutter.utils.FlutterModuleUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* The shared code for managing a library. To use it, define a subclass that implements the required methods,
* and calls #updateLibraryContent() with the library URLs.
* It will need a LibraryType and LibraryProperties, which are registered in plugin.xml.
*
* @see FlutterPluginsLibraryManager
*/
public abstract class AbstractLibraryManager<K extends LibraryProperties> {
@NotNull
private final Project project;
public AbstractLibraryManager(@NotNull Project project) {
this.project = project;
}
protected void updateLibraryContent(@NotNull Set<String> contentUrls) {
if (!FlutterModuleUtils.declaresFlutter(project)) {
// If we have a Flutter library, remove it.
final LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project);
final Library existingLibrary = getLibraryByName(getLibraryName());
if (existingLibrary != null) {
WriteAction.compute(() -> {
final LibraryTable.ModifiableModel libraryTableModel = libraryTable.getModifiableModel();
libraryTableModel.removeLibrary(existingLibrary);
libraryTableModel.commit();
return null;
});
}
return;
}
updateLibraryContent(getLibraryName(), contentUrls, null);
}
protected void updateLibraryContent(@NotNull String name,
@NotNull Set<String> contentUrls,
@Nullable Set<String> sourceUrls) {
// TODO(messick) Add support for source URLs.
final LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project);
final Library existingLibrary = getLibraryByName(name);
final Library library = existingLibrary != null
? existingLibrary
: WriteAction.compute(() -> {
final LibraryTable.ModifiableModel libraryTableModel = libraryTable.getModifiableModel();
final Library lib = libraryTableModel.createLibrary(
name,
getLibraryKind());
libraryTableModel.commit();
return lib;
});
final Set<String> existingUrls = new HashSet<>(Arrays.asList(library.getUrls(OrderRootType.CLASSES)));
if (contentUrls.containsAll(existingUrls) && existingUrls.containsAll(contentUrls)) {
// No changes needed.
return;
}
ApplicationManager.getApplication().runWriteAction(() -> {
final LibraryEx.ModifiableModelEx model = (LibraryEx.ModifiableModelEx)library.getModifiableModel();
final Set<String> existingCopy = new HashSet<>(existingUrls);
existingUrls.removeAll(contentUrls);
contentUrls.removeAll(existingCopy);
for (String url : existingUrls) {
model.removeRoot(url, OrderRootType.CLASSES);
}
for (String url : contentUrls) {
model.addRoot(url, OrderRootType.CLASSES);
}
DumbService.getInstance(project).runWhenSmart(() -> {
ApplicationManager.getApplication().runWriteAction(model::commit);
});
});
updateModuleLibraryDependencies(library);
}
protected void updateModuleLibraryDependencies(@NotNull Library library) {
for (final Module module : ModuleManager.getInstance(project).getModules()) {
if (FlutterModuleUtils.declaresFlutter(module)) {
addFlutterLibraryDependency(module, library);
}
else {
removeFlutterLibraryDependency(module, library);
}
}
}
@NotNull
protected Project getProject() {
return project;
}
@NotNull
protected abstract String getLibraryName();
@NotNull
protected abstract PersistentLibraryKind<K> getLibraryKind();
protected static void addFlutterLibraryDependency(@NotNull Module module, @NotNull Library library) {
final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();
try {
for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
if (orderEntry instanceof LibraryOrderEntry &&
LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)orderEntry).getLibraryLevel()) &&
StringUtil.equals(library.getName(), ((LibraryOrderEntry)orderEntry).getLibraryName())) {
return; // dependency already exists
}
}
modifiableModel.addLibraryEntry(library);
ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(modifiableModel::commit));
}
finally {
if (!modifiableModel.isDisposed()) {
modifiableModel.dispose();
}
}
}
protected static void removeFlutterLibraryDependency(@NotNull Module module, @NotNull Library library) {
final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();
try {
boolean wasFound = false;
for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
if (orderEntry instanceof LibraryOrderEntry &&
LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)orderEntry).getLibraryLevel()) &&
StringUtil.equals(library.getName(), ((LibraryOrderEntry)orderEntry).getLibraryName())) {
wasFound = true;
modifiableModel.removeOrderEntry(orderEntry);
}
}
if (wasFound) {
ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(modifiableModel::commit));
}
}
finally {
if (!modifiableModel.isDisposed()) {
modifiableModel.dispose();
}
}
}
@Nullable
private Library getLibraryByName(String name) {
return LibraryTablesRegistrar.getInstance().getLibraryTable(project).getLibraryByName(name);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/sdk/AbstractLibraryManager.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/AbstractLibraryManager.java",
"repo_id": "flutter-intellij",
"token_count": 2465
} | 503 |
/*
* 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.sdk;
import com.intellij.execution.process.ProcessOutput;
import com.intellij.ide.actions.ShowSettingsUtilImpl;
import com.intellij.ide.actionsOnSave.ActionsOnSaveConfigurable;
import com.intellij.ide.browsers.BrowserLauncher;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.FixedSizeButton;
import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.ComboboxWithBrowseButton;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.components.ActionLink;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.labels.LinkLabel;
import com.intellij.util.PlatformIcons;
import icons.FlutterIcons;
import io.flutter.*;
import io.flutter.bazel.Workspace;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.font.FontPreviewProcessor;
import io.flutter.pub.PubRoot;
import io.flutter.pub.PubRoots;
import io.flutter.settings.FlutterSettings;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.text.JTextComponent;
import java.awt.datatransfer.StringSelection;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.Semaphore;
// Note: when updating the settings here, update FlutterSearchableOptionContributor as well.
public class FlutterSettingsConfigurable implements SearchableConfigurable {
public static final String FLUTTER_SETTINGS_PAGE_NAME = FlutterBundle.message("flutter.title");
private static final String FLUTTER_SETTINGS_HELP_TOPIC = "flutter.settings.help";
private JPanel mainPanel;
private ComboboxWithBrowseButton mySdkCombo;
private JBLabel myVersionLabel;
private JCheckBox myReportUsageInformationCheckBox;
private LinkLabel<?> myPrivacyPolicy;
private JCheckBox myHotReloadOnSaveCheckBox;
private JCheckBox myEnableVerboseLoggingCheckBox;
private JCheckBox myOpenInspectorOnAppLaunchCheckBox;
private JCheckBox myFormatCodeOnSaveCheckBox;
private JCheckBox myOrganizeImportsOnSaveCheckBox;
private JCheckBox myShowStructuredErrors;
private JCheckBox myIncludeAllStackTraces;
private JCheckBox mySyncAndroidLibrariesCheckBox;
private JCheckBox myEnableHotUiCheckBox;
private JCheckBox myEnableBazelHotRestartCheckBox;
private JCheckBox myShowAllRunConfigurationsInContextCheckBox;
private JCheckBox myEnableJcefBrowserCheckBox;
private JCheckBox myShowBuildMethodGuides;
private JCheckBox myShowClosingLabels;
private FixedSizeButton myCopyButton;
private JTextArea myFontPackagesTextArea; // This should be changed to a structured list some day.
private JCheckBox myAllowTestsInSourcesRoot;
private ActionLink settingsLink;
private JCheckBox myEnableLogsPreserveAfterHotReloadOrRestart;
private final @NotNull Project myProject;
private final WorkspaceCache workspaceCache;
private boolean ignoringSdkChanges = false;
private String fullVersionString;
private FlutterSdkVersion previousSdkVersion;
/**
* Semaphore used to synchronize flutter commands so we don't try to do two at once.
*/
private final Semaphore lock = new Semaphore(1, true);
private Process updater;
FlutterSettingsConfigurable(@NotNull Project project) {
this.myProject = project;
workspaceCache = WorkspaceCache.getInstance(project);
init();
myVersionLabel.setText(" ");
}
private void init() {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(myProject);
if (sdk != null) {
previousSdkVersion = sdk.getVersion();
}
mySdkCombo.getComboBox().setEditable(true);
myCopyButton.setSize(ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE);
myCopyButton.setIcon(PlatformIcons.COPY_ICON);
myCopyButton.addActionListener(e -> {
if (fullVersionString != null) {
CopyPasteManager.getInstance().setContents(new StringSelection(fullVersionString));
}
});
final JTextComponent sdkEditor = (JTextComponent)mySdkCombo.getComboBox().getEditor().getEditorComponent();
sdkEditor.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(@NotNull final DocumentEvent e) {
if (!ignoringSdkChanges) {
onVersionChanged();
}
}
});
workspaceCache.subscribe(this::onVersionChanged);
mySdkCombo.addBrowseFolderListener("Select Flutter SDK Path", null, null,
FileChooserDescriptorFactory.createSingleFolderDescriptor(),
TextComponentAccessor.STRING_COMBOBOX_WHOLE_TEXT);
myPrivacyPolicy.setListener((linkLabel, data) -> {
try {
BrowserLauncher.getInstance().browse(new URI(FlutterBundle.message("flutter.analytics.privacyUrl")));
}
catch (URISyntaxException ignore) {
}
}, null);
myFormatCodeOnSaveCheckBox.addChangeListener(
(e) -> myOrganizeImportsOnSaveCheckBox.setEnabled(myFormatCodeOnSaveCheckBox.isSelected()));
myShowStructuredErrors.addChangeListener(
(e) -> myIncludeAllStackTraces.setEnabled(myShowStructuredErrors.isSelected()));
// There are other experiments so it is alright to show the experiments
// panel even if the syncAndroidLibraries experiment is hidden.
// If there are only experiments available on Android studio then add back
// the following statement:
// experimentsPanel.setVisible(FlutterUtils.isAndroidStudio());
mySyncAndroidLibrariesCheckBox.setVisible(FlutterUtils.isAndroidStudio());
myEnableBazelHotRestartCheckBox.setVisible(WorkspaceCache.getInstance(myProject).isBazel());
}
private void createUIComponents() {
mySdkCombo = new ComboboxWithBrowseButton(new ComboBox<>());
settingsLink = ActionsOnSaveConfigurable.createGoToActionsOnSavePageLink();
}
@Override
@NotNull
public String getId() {
return FlutterConstants.FLUTTER_SETTINGS_PAGE_ID;
}
@Nullable
@Override
public Runnable enableSearch(String s) {
return null;
}
@Nullable
@Override
public JComponent createComponent() {
return mainPanel;
}
@Override
public boolean isModified() {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(myProject);
final FlutterSettings settings = FlutterSettings.getInstance();
final String sdkPathInModel = sdk == null ? "" : sdk.getHomePath();
final String sdkPathInUI = FileUtilRt.toSystemIndependentName(getSdkPathText());
if (!sdkPathInModel.equals(sdkPathInUI)) {
return true;
}
if (FlutterInitializer.getCanReportAnalytics() != myReportUsageInformationCheckBox.isSelected()) {
return true;
}
if (settings.isReloadOnSave() != myHotReloadOnSaveCheckBox.isSelected()) {
return true;
}
if (settings.isFormatCodeOnSave() != myFormatCodeOnSaveCheckBox.isSelected()) {
return true;
}
if (settings.isOrganizeImportsOnSave() != myOrganizeImportsOnSaveCheckBox.isSelected()) {
return true;
}
if (settings.isShowBuildMethodGuides() != myShowBuildMethodGuides.isSelected()) {
return true;
}
if (settings.isShowClosingLabels() != myShowClosingLabels.isSelected()) {
return true;
}
if (settings.isShowStructuredErrors() != myShowStructuredErrors.isSelected()) {
return true;
}
if (settings.isIncludeAllStackTraces() != myIncludeAllStackTraces.isSelected()) {
return true;
}
if (settings.isOpenInspectorOnAppLaunch() != myOpenInspectorOnAppLaunchCheckBox.isSelected()) {
return true;
}
if (settings.isPerserveLogsDuringHotReloadAndRestart() != myEnableLogsPreserveAfterHotReloadOrRestart.isSelected()) {
return true;
}
if (settings.isVerboseLogging() != myEnableVerboseLoggingCheckBox.isSelected()) {
return true;
}
if (settings.isSyncingAndroidLibraries() != mySyncAndroidLibrariesCheckBox.isSelected()) {
return true;
}
if (settings.isEnableHotUi() != myEnableHotUiCheckBox.isSelected()) {
return true;
}
if (settings.isEnableBazelHotRestart() != myEnableBazelHotRestartCheckBox.isSelected()) {
return true;
}
if (settings.isAllowTestsInSourcesRoot() != myAllowTestsInSourcesRoot.isSelected()) {
return true;
}
if (!settings.getFontPackages().equals(myFontPackagesTextArea.getText())) {
return true;
}
//noinspection RedundantIfStatement
if (settings.showAllRunConfigurationsInContext() != myShowAllRunConfigurationsInContextCheckBox.isSelected()) {
return true;
}
if (settings.isEnableJcefBrowser() != myEnableJcefBrowserCheckBox.isSelected()) {
return true;
}
return false;
}
@Override
public void apply() throws ConfigurationException {
// Bazel workspaces do not specify a sdk path so we do not need to update the sdk path if using
// a bazel workspace.
if (!workspaceCache.isBazel()) {
final String errorMessage = FlutterSdkUtil.getErrorMessageIfWrongSdkRootPath(getSdkPathText());
if (errorMessage != null) {
throw new ConfigurationException(errorMessage);
}
final String sdkHomePath = getSdkPathText();
if (FlutterSdkUtil.isFlutterSdkHome(sdkHomePath)) {
ApplicationManager.getApplication().runWriteAction(() -> {
FlutterSdkUtil.setFlutterSdkPath(myProject, sdkHomePath);
FlutterSdkUtil.enableDartSdk(myProject);
ApplicationManager.getApplication().executeOnPooledThread(() -> {
final FlutterSdk sdk = FlutterSdk.forPath(sdkHomePath);
if (sdk != null) {
try {
lock.acquire();
sdk.queryFlutterChannel(false);
lock.release();
}
catch (InterruptedException e) {
// do nothing
}
}
});
});
}
}
FlutterInitializer.setCanReportAnalytics(myReportUsageInformationCheckBox.isSelected());
final FlutterSettings settings = FlutterSettings.getInstance();
final String oldFontPackages = settings.getFontPackages();
settings.setReloadOnSave(myHotReloadOnSaveCheckBox.isSelected());
settings.setFormatCodeOnSave(myFormatCodeOnSaveCheckBox.isSelected());
settings.setOrganizeImportsOnSave(myOrganizeImportsOnSaveCheckBox.isSelected());
settings.setShowBuildMethodGuides(myShowBuildMethodGuides.isSelected());
settings.setShowClosingLabels(myShowClosingLabels.isSelected());
settings.setShowStructuredErrors(myShowStructuredErrors.isSelected());
settings.setIncludeAllStackTraces(myIncludeAllStackTraces.isSelected());
settings.setOpenInspectorOnAppLaunch(myOpenInspectorOnAppLaunchCheckBox.isSelected());
settings.setPerserveLogsDuringHotReloadAndRestart(myEnableLogsPreserveAfterHotReloadOrRestart.isSelected());
settings.setVerboseLogging(myEnableVerboseLoggingCheckBox.isSelected());
settings.setSyncingAndroidLibraries(mySyncAndroidLibrariesCheckBox.isSelected());
settings.setEnableHotUi(myEnableHotUiCheckBox.isSelected());
settings.setEnableBazelHotRestart(myEnableBazelHotRestartCheckBox.isSelected());
settings.setAllowTestsInSourcesRoot(myAllowTestsInSourcesRoot.isSelected());
settings.setShowAllRunConfigurationsInContext(myShowAllRunConfigurationsInContextCheckBox.isSelected());
settings.setFontPackages(myFontPackagesTextArea.getText());
settings.setEnableJcefBrowser(myEnableJcefBrowserCheckBox.isSelected());
reset(); // because we rely on remembering initial state
checkFontPackages(settings.getFontPackages(), oldFontPackages);
}
@Override
public void reset() {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(myProject);
final String path = sdk != null ? sdk.getHomePath() : "";
// Set this after populating the combo box to display correctly when the Flutter SDK is unset.
// (This can happen if the user changed the Dart SDK.)
try {
ignoringSdkChanges = true;
FlutterSdkUtil.addKnownSDKPathsToCombo(mySdkCombo.getComboBox());
mySdkCombo.getComboBox().getEditor().setItem(FileUtil.toSystemDependentName(path));
}
finally {
ignoringSdkChanges = false;
}
onVersionChanged();
if (sdk != null) {
if (previousSdkVersion != null) {
if (previousSdkVersion.compareTo(sdk.getVersion()) != 0) {
final List<PubRoot> roots = PubRoots.forProject(myProject);
try {
lock.acquire();
for (PubRoot root : roots) {
sdk.startPubGet(root, myProject);
}
lock.release();
}
catch (InterruptedException e) {
// do nothing
}
previousSdkVersion = sdk.getVersion();
}
}
}
else {
previousSdkVersion = null;
}
myReportUsageInformationCheckBox.setSelected(FlutterInitializer.getCanReportAnalytics());
final FlutterSettings settings = FlutterSettings.getInstance();
myHotReloadOnSaveCheckBox.setSelected(settings.isReloadOnSave());
myFormatCodeOnSaveCheckBox.setSelected(settings.isFormatCodeOnSave());
myOrganizeImportsOnSaveCheckBox.setSelected(settings.isOrganizeImportsOnSave());
myShowBuildMethodGuides.setSelected(settings.isShowBuildMethodGuides());
myShowClosingLabels.setSelected(settings.isShowClosingLabels());
myShowStructuredErrors.setSelected(settings.isShowStructuredErrors());
myIncludeAllStackTraces.setSelected(settings.isIncludeAllStackTraces());
myOpenInspectorOnAppLaunchCheckBox.setSelected(settings.isOpenInspectorOnAppLaunch());
myEnableLogsPreserveAfterHotReloadOrRestart.setSelected(settings.isPerserveLogsDuringHotReloadAndRestart());
myEnableVerboseLoggingCheckBox.setSelected(settings.isVerboseLogging());
mySyncAndroidLibrariesCheckBox.setSelected(settings.isSyncingAndroidLibraries());
myEnableHotUiCheckBox.setSelected(settings.isEnableHotUi());
myEnableBazelHotRestartCheckBox.setSelected(settings.isEnableBazelHotRestart());
myAllowTestsInSourcesRoot.setSelected(settings.isAllowTestsInSourcesRoot());
myOrganizeImportsOnSaveCheckBox.setEnabled(myFormatCodeOnSaveCheckBox.isSelected());
myIncludeAllStackTraces.setEnabled(myShowStructuredErrors.isSelected());
myShowAllRunConfigurationsInContextCheckBox.setSelected(settings.showAllRunConfigurationsInContext());
myEnableJcefBrowserCheckBox.setSelected(settings.isEnableJcefBrowser());
myFontPackagesTextArea.setText(settings.getFontPackages());
}
private void onVersionChanged() {
final Workspace workspace = workspaceCache.get();
if (workspaceCache.isBazel()) {
if (mySdkCombo.isEnabled()) {
// The workspace is not null if workspaceCache.isBazel() is true.
assert (workspace != null);
mySdkCombo.setEnabled(false);
mySdkCombo.getComboBox().getEditor()
.setItem(workspace.getRoot().getPath() + '/' + workspace.getSdkHome() + " <set by bazel project>");
}
}
else {
mySdkCombo.setEnabled(true);
}
final FlutterSdk sdk = FlutterSdk.forPath(getSdkPathText());
if (sdk == null) {
// Clear the label out with a non-empty string, so that the layout doesn't give this element 0 height.
myVersionLabel.setText(" ");
fullVersionString = null;
return;
}
// Moved launching the version updater to a background thread to avoid deadlock
// when the semaphone was locked for a long time on the EDT.
final ModalityState modalityState = ModalityState.current();
ApplicationManager.getApplication().executeOnPooledThread(() -> {
try {
if (updater != null) {
// If we get back here before the previous one finished then just kill it.
// This isn't perfect, but does help avoid printing this message most times:
// Waiting for another flutter command to release the startup lock...
updater.destroy();
lock.release();
}
Thread.sleep(100L);
lock.acquire();
ApplicationManager.getApplication().invokeLater(() -> {
// "flutter --version" can take a long time on a slow network.
updater = sdk.flutterVersion().start((ProcessOutput output) -> {
fullVersionString = output.getStdout();
final String[] lines = StringUtil.splitByLines(fullVersionString);
final String singleLineVersion = lines.length > 0 ? lines[0] : "";
ApplicationManager.getApplication().invokeLater(() -> {
updater = null;
lock.release();
updateVersionTextIfCurrent(sdk, singleLineVersion);
}, modalityState);
}, null);
}, modalityState);
}
catch (InterruptedException e) {
// do nothing
}
});
}
/***
* Sets the version text but only if we don't have stale data.
*
* @param sdk the SDK that was current at the time.
*/
private void updateVersionTextIfCurrent(@NotNull FlutterSdk sdk, @NotNull String value) {
final FlutterSdk current = FlutterSdk.forPath(getSdkPathText());
if (current == null) {
myVersionLabel.setText(" ");
}
else {
myVersionLabel.setText(value);
}
}
@Override
public void disposeUIResources() {
}
@Override
@Nls
public String getDisplayName() {
return FLUTTER_SETTINGS_PAGE_NAME;
}
@Nullable
@Override
public String getHelpTopic() {
return FLUTTER_SETTINGS_HELP_TOPIC;
}
@NotNull
private String getSdkPathText() {
return FileUtilRt.toSystemIndependentName(mySdkCombo.getComboBox().getEditor().getItem().toString().trim());
}
private void checkFontPackages(String value, String previous) {
if (value != null) {
final String[] packages = value.split(FontPreviewProcessor.PACKAGE_SEPARATORS);
for (String name : packages) {
final String message = FontPreviewProcessor.UNSUPPORTED_PACKAGES.get(name.trim());
if (message != null) {
displayNotification(message);
}
}
if (!value.equals(previous)) {
FontPreviewProcessor.reanalyze(myProject);
}
}
}
private void displayNotification(String message) {
final Notification notification = new Notification(
FlutterMessages.FLUTTER_LOGGING_NOTIFICATION_GROUP_ID,
FlutterBundle.message("icon.preview.disallow.package.title"),
message,
NotificationType.INFORMATION);
notification.setIcon(FlutterIcons.Flutter);
Notifications.Bus.notify(notification, myProject);
}
public static void openFlutterSettings(@NotNull final Project project) {
ShowSettingsUtilImpl.showSettingsDialog(project, FlutterConstants.FLUTTER_SETTINGS_PAGE_ID, "");
}
}
| flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSettingsConfigurable.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSettingsConfigurable.java",
"repo_id": "flutter-intellij",
"token_count": 7138
} | 504 |
/*
* Copyright 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.utils;
import com.intellij.ui.JBColor;
import com.intellij.util.ui.GraphicsUtil;
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class ColorIconMaker {
private final Map<Color, Icon> iconCache = new HashMap<>();
private static final int iconMargin = 3;
public Icon getCustomIcon(Color color) {
if (!iconCache.containsKey(color)) {
final Icon icon = new Icon() {
public void paintIcon(Component c, Graphics g, int x, int y) {
final Graphics2D g2 = (Graphics2D)g.create();
try {
GraphicsUtil.setupAAPainting(g2);
// draw a black and gray grid to use as the background to disambiguate
// opaque colors from translucent colors.
g2.setColor(JBColor.white);
g2.fillRect(x + iconMargin, y + iconMargin, getIconWidth() - iconMargin * 2, getIconHeight() - iconMargin * 2);
g2.setColor(JBColor.gray);
g2.fillRect(x + iconMargin, y + iconMargin, getIconWidth() / 2 - iconMargin, getIconHeight() / 2 - iconMargin);
g2.fillRect(x + getIconWidth() / 2, y + getIconHeight() / 2, getIconWidth() / 2 - iconMargin, getIconHeight() / 2 - iconMargin);
g2.setColor(color);
g2.fillRect(x + iconMargin, y + iconMargin, getIconWidth() - iconMargin * 2, getIconHeight() - iconMargin * 2);
g2.setColor(JBColor.black);
g2.drawRect(x + iconMargin, y + iconMargin, getIconWidth() - iconMargin * 2, getIconHeight() - iconMargin * 2);
}
finally {
g2.dispose();
}
}
public int getIconWidth() {
return 22; // TODO(jacob): customize the icon height based on the font size.
}
public int getIconHeight() {
return 22; // TODO(jacob): customize the icon height based on the font size.
}
};
iconCache.put(color, icon);
}
return iconCache.get(color);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/ColorIconMaker.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/ColorIconMaker.java",
"repo_id": "flutter-intellij",
"token_count": 909
} | 505 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.utils;
import com.intellij.openapi.Disposable;
import java.util.function.Consumer;
public class StreamSubscription<T> implements Disposable {
private final Consumer<T> onData;
/**
* Whether the onData callback should only be executed on the UI thread.
*/
protected final boolean onUIThread;
private EventStream<T> owner;
private volatile boolean disposed = false;
protected StreamSubscription(Consumer<T> onData, boolean onUIThread, EventStream<T> owner) {
this.onData = onData;
this.onUIThread = onUIThread;
this.owner = owner;
}
@Override
public void dispose() {
disposed = true;
if (owner != null) {
owner.removeSubscription(this);
owner = null;
}
}
protected void notify(T value) {
// There is a risk the call to dispose could have been interleaved
// with calls on a different thread adding values to the stream so we suppress
// calls to notify if the subscription has lready been closed so no events
// get through after the dispose method is called.
if (!disposed) {
onData.accept(value);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/StreamSubscription.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/StreamSubscription.java",
"repo_id": "flutter-intellij",
"token_count": 402
} | 506 |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.utils.math;
import java.util.Arrays;
/**
* This class is ported from the Vector2 class in the Dart vector_math
* package. The code is ported as is without concern for making the code
* consistent with Java api conventions to keep the code consistent with
* the Dart code to simplify using Transform Matrixes returned by Flutter.
*/
public class Vector2 implements Vector {
final double[] _v2storage;
/**
* Construct a new vector with the specified values.
*/
Vector2(double x, double y) {
_v2storage = new double[]{x, y};
}
/**
* Zero vector.
*/
public Vector2() {
_v2storage = new double[2];
}
/**
* Set the values of [result] to the minimum of [a] and [b] for each line.
*/
static void min(Vector2 a, Vector2 b, Vector2 result) {
result.setX(Math.min(a.getX(), b.getX()));
result.setY(Math.min(a.getY(), b.getY()));
}
/**
* Set the values of [result] to the maximum of [a] and [b] for each line.
*/
static void max(Vector2 a, Vector2 b, Vector2 result) {
result
.setX(Math.max(a.getX(), b.getX()));
result
.setY(Math.max(a.getY(), b.getY()));
}
/**
* Interpolate between [min] and [max] with the amount of [a] using a linear
* interpolation and store the values in [result].
*/
static void mix(Vector2 min, Vector2 max, double a, Vector2 result) {
result.setX(min.getX() + a * (max.getX() - min.getX()));
result.setY(min.getY() + a * (max.getY()) - min.getY());
}
/**
* Splat [value] into all lanes of the vector.
*/
static Vector2 all(double value) {
final Vector2 ret = new Vector2();
ret.splat(value);
return ret;
}
/**
* Copy of [other].
*/
static Vector2 copy(Vector2 other) {
final Vector2 ret = new Vector2();
ret.setFrom(other);
return ret;
}
/**
* The components of the vector.
*/
@Override()
public double[] getStorage() {
return _v2storage;
}
/**
* Set the values of the vector.
*/
public void setValues(double x_, double y_) {
_v2storage[0] = x_;
_v2storage[1] = y_;
}
/**
* Zero the vector.
*/
public void setZero() {
_v2storage[0] = 0.0;
_v2storage[1] = 0.0;
}
/**
* Set the values by copying them from [other].
*/
public void setFrom(Vector2 other) {
final double[] otherStorage = other._v2storage;
_v2storage[1] = otherStorage[1];
_v2storage[0] = otherStorage[0];
}
/**
* Splat [arg] into all lanes of the vector.
*/
public void splat(double arg) {
_v2storage[0] = arg;
_v2storage[1] = arg;
}
/**
* Returns a printable string
*/
@Override()
public String toString() {
return "[" + _v2storage[0] + "," + _v2storage[1] + "]";
}
/**
* Check if two vectors are the same.
*/
@Override()
public boolean equals(Object other) {
if (!(other instanceof Vector2)) return false;
Vector2 otherV = (Vector2)other;
return (_v2storage[0] == otherV._v2storage[0]) &&
(_v2storage[1] == otherV._v2storage[1]);
}
@Override()
public int hashCode() {
return Arrays.hashCode(_v2storage);
}
/**
* Negate.
*/
Vector2 operatorNegate() {
final Vector2 ret = clone();
ret.negate();
return ret;
}
/**
* Subtract two vectors.
*/
public Vector2 operatorSub(Vector2 other) {
final Vector2 ret = clone();
ret.sub(other);
return ret;
}
/**
* Add two vectors.
*/
public Vector2 operatorAdd(Vector2 other) {
final Vector2 ret = clone();
ret.add(other);
return ret;
}
/**
* Scale.
*/
public Vector2 operatorDiv(double scale) {
final Vector2 ret = clone();
ret.scale(1.0 / scale);
return ret;
}
/**
* Scale.
*/
public Vector2 operatorScale(double scale) {
final Vector2 ret = clone();
ret.scale(scale);
return ret;
}
/**
* Length.
*/
public double getLength() {
return Math.sqrt(getLength2());
}
/**
* Set the length of the vector. A negative [value] will change the vectors
* orientation and a [value] of zero will set the vector to zero.
*/
public void setLength(double value) {
if (value == 0.0) {
setZero();
}
else {
double l = getLength();
if (l == 0.0) {
return;
}
l = value / l;
_v2storage[0] *= l;
_v2storage[1] *= l;
}
}
/**
* Length squared.
*/
public double getLength2() {
double sum;
sum = (_v2storage[0] * _v2storage[0]);
sum += (_v2storage[1] * _v2storage[1]);
return sum;
}
/**
* Normalize [this].
*/
public double normalize() {
final double l = getLength();
if (l == 0.0) {
return 0.0;
}
final double d = 1.0 / l;
_v2storage[0] *= d;
_v2storage[1] *= d;
return l;
}
/**
* Normalized copy of [this].
*/
public Vector2 normalized() {
final Vector2 ret = clone();
ret.normalize();
return ret;
}
/**
* Normalize vector into [out].
*/
public Vector2 normalizeInto(Vector2 out) {
out.setFrom(this);
out.normalize();
return out;
}
/**
* Distance from [this] to [arg]
*/
public double distanceTo(Vector2 arg) {
return Math.sqrt(distanceToSquared(arg));
}
/**
* Squared distance from [this] to [arg]
*/
public double distanceToSquared(Vector2 arg) {
final double dx = getX() - arg.getX();
final double dy = getY() - arg.getY();
return dx * dx + dy * dy;
}
/**
* Returns the angle between [this] vector and [other] in radians.
*/
public double angleTo(Vector2 other) {
final double[] otherStorage = other._v2storage;
if (_v2storage[0] == otherStorage[0] && _v2storage[1] == otherStorage[1]) {
return 0.0;
}
final double d = dot(other) / (getLength() * other.getLength());
return Math.acos(VectorUtil.clamp(d, -1.0, 1.0));
}
/**
* Returns the signed angle between [this] and [other] in radians.
*/
public double angleToSigned(Vector2 other) {
final double[] otherStorage = other._v2storage;
if (_v2storage[0] == otherStorage[0] && _v2storage[1] == otherStorage[1]) {
return 0.0;
}
final double s = cross(other);
final double c = dot(other);
return Math.atan2(s, c);
}
/**
* Inner product.
*/
public double dot(Vector2 other) {
final double[] otherStorage = other._v2storage;
double sum;
sum = _v2storage[0] * otherStorage[0];
sum += _v2storage[1] * otherStorage[1];
return sum;
}
/**
* Cross product.
*/
public double cross(Vector2 other) {
final double[] otherStorage = other._v2storage;
return _v2storage[0] * otherStorage[1] - _v2storage[1] * otherStorage[0];
}
/**
* Rotate [this] by 90 degrees then scale it. Store result in [out]. Return [out].
*/
public Vector2 scaleOrthogonalInto(double scale, Vector2 out) {
out.setValues(-scale * _v2storage[1], scale * _v2storage[0]);
return out;
}
/**
* Reflect [this].
*/
public void reflect(Vector2 normal) {
sub(normal.scaled(2.0 * normal.dot(this)));
}
/**
* Reflected copy of [this].
*/
public Vector2 reflected(Vector2 normal) {
final Vector2 ret = clone();
ret.reflect(normalized());
return ret;
}
/**
* Relative error between [this] and [correct]
*/
public double relativeError(Vector2 correct) {
final double correct_norm = correct.getLength();
final double diff_norm = (this.operatorSub(correct)).getLength();
return diff_norm / correct_norm;
}
/**
* Absolute error between [this] and [correct]
*/
public double absoluteError(Vector2 correct) {
return operatorSub(correct).getLength();
}
/**
* True if any component is infinite.
*/
public boolean isInfinite() {
boolean is_infinite = Double.isInfinite(_v2storage[0]);
is_infinite = is_infinite || Double.isInfinite(_v2storage[1]);
return is_infinite;
}
/**
* True if any component is NaN.
*/
public boolean isNaN() {
boolean is_nan = Double.isNaN(_v2storage[0]);
is_nan = is_nan || Double.isNaN(_v2storage[1]);
return is_nan;
}
/**
* Add [arg] to [this].
*/
public void add(Vector2 arg) {
final double[] argStorage = arg._v2storage;
_v2storage[0] = _v2storage[0] + argStorage[0];
_v2storage[1] = _v2storage[1] + argStorage[1];
}
/**
* Add [arg] scaled by [factor] to [this].
*/
public void addScaled(Vector2 arg, double factor) {
final double[] argStorage = arg._v2storage;
_v2storage[0] = _v2storage[0] + argStorage[0] * factor;
_v2storage[1] = _v2storage[1] + argStorage[1] * factor;
}
/**
* Subtract [arg] from [this].
*/
public void sub(Vector2 arg) {
final double[] argStorage = arg._v2storage;
_v2storage[0] = _v2storage[0] - argStorage[0];
_v2storage[1] = _v2storage[1] - argStorage[1];
}
/**
* Multiply entries in [this] with entries in [arg].
*/
public void multiply(Vector2 arg) {
final double[] argStorage = arg._v2storage;
_v2storage[0] = _v2storage[0] * argStorage[0];
_v2storage[1] = _v2storage[1] * argStorage[1];
}
/**
* Divide entries in [this] with entries in [arg].
*/
public void divide(Vector2 arg) {
final double[] argStorage = arg._v2storage;
_v2storage[0] = _v2storage[0] / argStorage[0];
_v2storage[1] = _v2storage[1] / argStorage[1];
}
/**
* Scale [this] by [arg].
*/
public void scale(double arg) {
_v2storage[1] = _v2storage[1] * arg;
_v2storage[0] = _v2storage[0] * arg;
}
/**
* Return a copy of [this] scaled by [arg].
*/
public Vector2 scaled(double arg) {
final Vector2 ret = clone();
ret.scale(arg);
return ret;
}
/**
* Negate.
*/
public void negate() {
_v2storage[1] = -_v2storage[1];
_v2storage[0] = -_v2storage[0];
}
/**
* Absolute value.
*/
public void absolute() {
_v2storage[1] = Math.abs(_v2storage[1]);
_v2storage[0] = Math.abs(_v2storage[0]);
}
/**
* Clamp each entry n in [this] in the range [min[n]]-[max[n]].
*/
public void clamp(Vector2 min, Vector2 max) {
final double[] minStorage = min.getStorage();
final double[] maxStorage = max.getStorage();
_v2storage[0] =
VectorUtil.clamp(_v2storage[0], minStorage[0], maxStorage[0]);
_v2storage[1] =
VectorUtil.clamp(_v2storage[1], minStorage[1], maxStorage[1]);
}
/**
* Clamp entries [this] in the range [min]-[max].
*/
public void clampScalar(double min, double max) {
_v2storage[0] = VectorUtil.clamp(_v2storage[0], min, max);
_v2storage[1] = VectorUtil.clamp(_v2storage[1], min, max);
}
/**
* Floor entries in [this].
*/
public void floor() {
_v2storage[0] = Math.floor(_v2storage[0]);
_v2storage[1] = Math.floor(_v2storage[1]);
}
/**
* Ceil entries in [this].
*/
public void ceil() {
_v2storage[0] = Math.ceil(_v2storage[0]);
_v2storage[1] = Math.ceil(_v2storage[1]);
}
/**
* Round entries in [this].
*/
public void round() {
_v2storage[0] = Math.round(_v2storage[0]);
_v2storage[1] = Math.round(_v2storage[1]);
}
/**
* Round entries in [this] towards zero.
*/
public void roundToZero() {
_v2storage[0] = _v2storage[0] < 0.0
? Math.ceil(_v2storage[0])
: Math.floor(_v2storage[0]);
_v2storage[1] = _v2storage[1] < 0.0
? Math.ceil(_v2storage[1])
: Math.floor(_v2storage[1]);
}
/**
* Clone of [this].
*/
@SuppressWarnings("MethodDoesntCallSuperMethod")
@Override
public Vector2 clone() {
final Vector2 ret = new Vector2();
ret.setFrom(this);
return ret;
}
/**
* Copy [this] into [arg]. Returns [arg].
*/
public Vector2 copyInto(Vector2 arg) {
final double[] argStorage = arg._v2storage;
argStorage[1] = _v2storage[1];
argStorage[0] = _v2storage[0];
return arg;
}
public double getX() {
return _v2storage[0];
}
public void setX(double arg) {
_v2storage[0] = arg;
}
public double getY() {
return _v2storage[1];
}
public void setY(double arg) {
_v2storage[1] = arg;
}
} | flutter-intellij/flutter-idea/src/io/flutter/utils/math/Vector2.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/math/Vector2.java",
"repo_id": "flutter-intellij",
"token_count": 4974
} | 507 |
/*
* Copyright 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.view;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.actionSystem.Toggleable;
import com.intellij.openapi.application.ApplicationManager;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.utils.StreamSubscription;
import io.flutter.vmService.ServiceExtensionState;
import io.flutter.vmService.ToggleableServiceExtensionDescription;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
abstract class FlutterViewToggleableAction<T> extends FlutterViewAction implements Toggleable, Disposable {
private final ToggleableServiceExtensionDescription<T> extensionDescription;
private StreamSubscription<ServiceExtensionState> currentValueSubscription;
private StreamSubscription<Boolean> enabledSubscription;
FlutterViewToggleableAction(@NotNull FlutterApp app,
@Nullable Icon icon,
ToggleableServiceExtensionDescription<T> extensionDescription) {
// Assume the button is not enabled by default and pass disabledText here.
super(app, extensionDescription.getDisabledText(), null, icon);
this.extensionDescription = extensionDescription;
}
@Override
public final void update(@NotNull AnActionEvent e) {
// selected
final boolean selected = this.isSelected();
final Presentation presentation = e.getPresentation();
presentation.putClientProperty("selected", selected);
if (!app.isSessionActive()) {
dispose();
e.getPresentation().setEnabled(false);
return;
}
if (currentValueSubscription == null) {
currentValueSubscription =
app.getVMServiceManager().getServiceExtensionState(extensionDescription.getExtension()).listen((state) -> {
if (presentation.getClientProperty("selected") != (Boolean)state.isEnabled()) {
presentation.putClientProperty("selected", state.isEnabled());
}
}, true);
enabledSubscription = app.hasServiceExtension(extensionDescription.getExtension(), (enabled) -> {
presentation.setEnabled(app.isSessionActive() && enabled);
});
}
presentation.setText(
isSelected()
? extensionDescription.getEnabledText()
: extensionDescription.getDisabledText());
}
@Override
public void dispose() {
if (currentValueSubscription != null) {
currentValueSubscription.dispose();
currentValueSubscription = null;
}
if (enabledSubscription != null) {
enabledSubscription.dispose();
enabledSubscription = null;
}
}
@Override
protected void perform(AnActionEvent event) {
if (app.isSessionActive()) {
app.callBooleanExtension(extensionDescription.getExtension(), isSelected());
}
}
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
this.setSelected(event, !isSelected());
super.actionPerformed(event);
}
public boolean isSelected() {
return app.getVMServiceManager().getServiceExtensionState(extensionDescription.getExtension()).getValue().isEnabled();
}
public void setSelected(@Nullable AnActionEvent event, boolean selected) {
app.getVMServiceManager().setServiceExtensionState(
extensionDescription.getExtension(),
selected,
selected ? extensionDescription.getEnabledValue() : extensionDescription.getDisabledValue());
if (event != null) {
ApplicationManager.getApplication().invokeLater(() -> this.update(event));
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewToggleableAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewToggleableAction.java",
"repo_id": "flutter-intellij",
"token_count": 1239
} | 508 |
/*
* Copyright 2020 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.vmService;
import com.google.gson.JsonObject;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.filters.OpenFileHyperlinkInfo;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.BitUtil;
import com.intellij.util.TimeoutUtil;
import com.intellij.xdebugger.*;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator;
import com.intellij.xdebugger.frame.XStackFrame;
import com.intellij.xdebugger.frame.XSuspendContext;
import com.jetbrains.lang.dart.ide.runner.actions.DartPopFrameAction;
import com.jetbrains.lang.dart.ide.runner.base.DartDebuggerEditorsProvider;
import com.jetbrains.lang.dart.util.DartUrlResolver;
import gnu.trove.THashMap;
import gnu.trove.TIntObjectHashMap;
import io.flutter.FlutterBundle;
import io.flutter.FlutterInitializer;
import io.flutter.FlutterUtils;
import io.flutter.ObservatoryConnector;
import io.flutter.run.FlutterLaunchMode;
import io.flutter.vmService.frame.DartVmServiceEvaluator;
import io.flutter.vmService.frame.DartVmServiceStackFrame;
import io.flutter.vmService.frame.DartVmServiceSuspendContext;
import org.dartlang.vm.service.VmService;
import org.dartlang.vm.service.consumer.GetObjectConsumer;
import org.dartlang.vm.service.consumer.VMConsumer;
import org.dartlang.vm.service.element.Event;
import org.dartlang.vm.service.element.*;
import org.dartlang.vm.service.logging.Logging;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.*;
import java.util.concurrent.CompletableFuture;
public abstract class DartVmServiceDebugProcess extends XDebugProcess {
private static final Logger LOG = Logger.getInstance(DartVmServiceDebugProcess.class.getName());
@NotNull private final ExecutionResult myExecutionResult;
@NotNull private final DartUrlResolver myDartUrlResolver;
@NotNull private final XBreakpointHandler[] myBreakpointHandlers;
private final IsolatesInfo myIsolatesInfo;
@NotNull private final Map<String, CompletableFuture<Object>> mySuspendedIsolateIds = Collections.synchronizedMap(new HashMap<>());
private final Map<String, LightVirtualFile> myScriptIdToContentMap = new THashMap<>();
private final Map<String, TIntObjectHashMap<Pair<Integer, Integer>>> myScriptIdToLinesAndColumnsMap = new THashMap<>();
@Nullable private final VirtualFile myCurrentWorkingDirectory;
@NotNull private final ObservatoryConnector myConnector;
@NotNull private final ExecutionEnvironment executionEnvironment;
@NotNull private final PositionMapper mapper;
@Nullable protected String myRemoteProjectRootUri;
private boolean myVmConnected = false;
private VmServiceWrapper myVmServiceWrapper;
private String myLatestCurrentIsolateId;
public DartVmServiceDebugProcess(@NotNull final ExecutionEnvironment executionEnvironment,
@NotNull final XDebugSession session,
@NotNull final ExecutionResult executionResult,
@NotNull final DartUrlResolver dartUrlResolver,
@NotNull final ObservatoryConnector connector,
@NotNull final PositionMapper mapper) {
super(session);
myExecutionResult = executionResult;
myDartUrlResolver = dartUrlResolver;
myCurrentWorkingDirectory = null;
myIsolatesInfo = new IsolatesInfo();
myBreakpointHandlers = new XBreakpointHandler[]{
new DartVmServiceBreakpointHandler(this),
new DartExceptionBreakpointHandler(this)
};
session.setPauseActionSupported(true);
session.addSessionListener(new XDebugSessionListener() {
@Override
public void sessionPaused() {
// This can be removed if XFramesView starts popping the project window to the top of the z-axis stack.
final Project project = getSession().getProject();
focusProject(project);
stackFrameChanged();
}
@Override
public void stackFrameChanged() {
final XStackFrame stackFrame = getSession().getCurrentStackFrame();
myLatestCurrentIsolateId =
stackFrame instanceof DartVmServiceStackFrame ? ((DartVmServiceStackFrame)stackFrame).getIsolateId() : null;
}
});
this.executionEnvironment = executionEnvironment;
this.mapper = mapper;
myConnector = connector;
setLogger();
final Runnable resumeCallback = () -> {
if (session.isPaused()) {
session.resume();
}
};
session.addSessionListener(new XDebugSessionListener() {
@Override
public void sessionPaused() {
stackFrameChanged();
connector.onDebuggerPaused(resumeCallback);
}
@Override
public void sessionResumed() {
connector.onDebuggerResumed();
}
@Override
public void stackFrameChanged() {
final XStackFrame stackFrame = getSession().getCurrentStackFrame();
myLatestCurrentIsolateId =
stackFrame instanceof DartVmServiceStackFrame ? ((DartVmServiceStackFrame)stackFrame).getIsolateId() : null;
}
});
scheduleConnect();
}
public ExceptionPauseMode getBreakOnExceptionMode() {
return DartExceptionBreakpointHandler
.getBreakOnExceptionMode(getSession(),
DartExceptionBreakpointHandler.getDefaultExceptionBreakpoint(getSession().getProject()));
}
public VmServiceWrapper getVmServiceWrapper() {
return myVmServiceWrapper;
}
public Collection<IsolatesInfo.IsolateInfo> getIsolateInfos() {
return myIsolatesInfo.getIsolateInfos();
}
private void setLogger() {
Logging.setLogger(new org.dartlang.vm.service.logging.Logger() {
@Override
public void logError(final String message) {
if (message.contains("\"code\":102,")) { // Cannot add breakpoint, already logged in logInformation()
return;
}
if (message.contains("\"method\":\"removeBreakpoint\"")) { // That's expected because we set one breakpoint twice
return;
}
if (message.contains("\"type\":\"Sentinel\"")) { // Ignore unwanted message
return;
}
getSession().getConsoleView().print(message.trim() + "\n", ConsoleViewContentType.ERROR_OUTPUT);
LOG.warn(message);
}
@Override
public void logError(final String message, final Throwable exception) {
if (!getVmConnected() || getSession() == null) {
return;
}
if (message != null) {
getSession().getConsoleView().print(message.trim() + "\n", ConsoleViewContentType.ERROR_OUTPUT);
}
LOG.warn(message, exception);
}
@Override
public void logInformation(String message) {
if (message.length() > 500) {
message = message.substring(0, 300) + "..." + message.substring(message.length() - 200);
}
LOG.debug(message);
}
@Override
public void logInformation(final String message, final Throwable exception) {
LOG.debug(message, exception);
}
});
}
public void scheduleConnect() {
ApplicationManager.getApplication().executeOnPooledThread(() -> {
// Poll, waiting for "flutter run" to give us a websocket.
// Don't use a timeout - the user can cancel manually the operation.
String url = myConnector.getWebSocketUrl();
while (url == null) {
if (getSession().isStopped()) return;
TimeoutUtil.sleep(100);
url = myConnector.getWebSocketUrl();
}
if (getSession().isStopped()) {
return;
}
// "flutter run" has given us a websocket; we can assume it's ready immediately, because
// "flutter run" has already connected to it.
final VmService vmService;
try {
vmService = VmService.connect(url);
}
catch (IOException | RuntimeException e) {
onConnectFailed("Failed to connect to the VM observatory service at: " + url + "\n"
+ e + "\n" + formatStackTraces(e));
return;
}
onConnectSucceeded(vmService);
});
}
private void connect(@NotNull final String url) throws IOException {
final VmService vmService = VmService.connect(url);
final DartVmServiceListener vmServiceListener =
new DartVmServiceListener(this, (DartVmServiceBreakpointHandler)myBreakpointHandlers[0]);
vmService.addVmServiceListener(vmServiceListener);
myVmServiceWrapper =
new VmServiceWrapper(this, vmService, vmServiceListener, myIsolatesInfo, (DartVmServiceBreakpointHandler)myBreakpointHandlers[0]);
myVmServiceWrapper.handleDebuggerConnected();
myVmConnected = true;
}
@Override
protected ProcessHandler doGetProcessHandler() {
return myExecutionResult.getProcessHandler();
}
@NotNull
@Override
public ExecutionConsole createConsole() {
return myExecutionResult.getExecutionConsole();
}
@NotNull
@Override
public XDebuggerEditorsProvider getEditorsProvider() {
return new DartDebuggerEditorsProvider();
}
@Override
@NotNull
public XBreakpointHandler<?> @NotNull [] getBreakpointHandlers() {
return myBreakpointHandlers;
}
public void guessRemoteProjectRoot(@NotNull final ElementList<LibraryRef> libraries) {
// TODO(skybrian) do we need to handle multiple isolates?
mapper.onLibrariesDownloaded(libraries);
}
@Override
public void startStepOver(@Nullable XSuspendContext context) {
if (myLatestCurrentIsolateId != null && mySuspendedIsolateIds.containsKey(myLatestCurrentIsolateId)) {
final DartVmServiceSuspendContext suspendContext = (DartVmServiceSuspendContext)context;
final StepOption stepOption = suspendContext != null && suspendContext.getAtAsyncSuspension() ? StepOption.OverAsyncSuspension
: StepOption.Over;
myVmServiceWrapper.resumeIsolate(myLatestCurrentIsolateId, stepOption);
}
}
@Override
public void startStepInto(@Nullable XSuspendContext context) {
if (myLatestCurrentIsolateId != null && mySuspendedIsolateIds.containsKey(myLatestCurrentIsolateId)) {
myVmServiceWrapper.resumeIsolate(myLatestCurrentIsolateId, StepOption.Into);
}
}
@Override
public void startStepOut(@Nullable XSuspendContext context) {
if (myLatestCurrentIsolateId != null && mySuspendedIsolateIds.containsKey(myLatestCurrentIsolateId)) {
myVmServiceWrapper.resumeIsolate(myLatestCurrentIsolateId, StepOption.Out);
}
}
public void dropFrame(DartVmServiceStackFrame frame) {
myVmServiceWrapper.dropFrame(frame.getIsolateId(), frame.getFrameIndex() + 1);
}
@Override
public void stop() {
myVmConnected = false;
mapper.shutdown();
if (myVmServiceWrapper != null) {
Disposer.dispose(myVmServiceWrapper);
}
}
@Override
public void resume(@Nullable XSuspendContext context) {
for (String isolateId : new ArrayList<>(mySuspendedIsolateIds.keySet())) {
myVmServiceWrapper.resumeIsolate(isolateId, null);
}
}
@Override
public void startPausing() {
for (IsolatesInfo.IsolateInfo info : getIsolateInfos()) {
if (!mySuspendedIsolateIds.containsKey(info.getIsolateId())) {
myVmServiceWrapper.pauseIsolate(info.getIsolateId());
}
}
}
@Override
public void runToPosition(@NotNull XSourcePosition position, @Nullable XSuspendContext context) {
if (myLatestCurrentIsolateId != null && mySuspendedIsolateIds.containsKey(myLatestCurrentIsolateId)) {
// Set a temporary breakpoint and resume.
myVmServiceWrapper.addTemporaryBreakpoint(position, myLatestCurrentIsolateId);
myVmServiceWrapper.resumeIsolate(myLatestCurrentIsolateId, null);
}
}
public void isolateSuspended(@NotNull final IsolateRef isolateRef) {
final String id = isolateRef.getId();
assert (!mySuspendedIsolateIds.containsKey(id));
if (!mySuspendedIsolateIds.containsKey(id)) {
mySuspendedIsolateIds.put(id, new CompletableFuture<>());
}
}
public boolean isIsolateSuspended(@NotNull final String isolateId) {
return mySuspendedIsolateIds.containsKey(isolateId);
}
public CompletableFuture<?> whenIsolateResumed(String isolateId) {
final CompletableFuture<?> future = mySuspendedIsolateIds.get(isolateId);
if (future == null) {
// Isolate wasn't actually suspended.
return CompletableFuture.completedFuture(null);
}
else {
return future;
}
}
public boolean isIsolateAlive(@NotNull final String isolateId) {
for (IsolatesInfo.IsolateInfo isolateInfo : myIsolatesInfo.getIsolateInfos()) {
if (isolateId.equals(isolateInfo.getIsolateId())) {
return true;
}
}
return false;
}
public void isolateResumed(@NotNull final IsolateRef isolateRef) {
final CompletableFuture<Object> future = mySuspendedIsolateIds.remove(isolateRef.getId());
if (future != null) {
future.complete(null); // Notify listeners that the isolate resumed.
}
}
public void isolateExit(@NotNull final IsolateRef isolateRef) {
myIsolatesInfo.deleteIsolate(isolateRef);
mySuspendedIsolateIds.remove(isolateRef.getId());
if (isolateRef.getId().equals(myLatestCurrentIsolateId)) {
resume(getSession().getSuspendContext()); // otherwise no way no resume them from UI
}
}
public void handleWriteEvent(String base64Data) {
final String message = new String(Base64.getDecoder().decode(base64Data), StandardCharsets.UTF_8);
getSession().getConsoleView().print(message, ConsoleViewContentType.NORMAL_OUTPUT);
}
@Override
public String getCurrentStateMessage() {
return getSession().isStopped()
? XDebuggerBundle.message("debugger.state.message.disconnected")
: myVmConnected
? XDebuggerBundle.message("debugger.state.message.connected")
: FlutterBundle.message("waiting.for.flutter");
}
@Override
public void registerAdditionalActions(@NotNull final DefaultActionGroup leftToolbar,
@NotNull final DefaultActionGroup topToolbar,
@NotNull final DefaultActionGroup settings) {
// For Run tool window this action is added in DartCommandLineRunningState.createActions()
topToolbar.addSeparator();
topToolbar.addAction(new DartPopFrameAction());
}
@NotNull
public Collection<String> getUrisForFile(@NotNull final VirtualFile file) {
return mapper.getBreakpointUris(file);
}
@Nullable
public XSourcePosition getSourcePosition(@NotNull final String isolateId, @NotNull final ScriptRef scriptRef, int tokenPos) {
CompletableFuture<String> fileFuture = myVmServiceWrapper.findResolvedFile(isolateId, scriptRef.getUri());
return mapper.getSourcePosition(isolateId, scriptRef, tokenPos, fileFuture);
}
@Nullable
public String getCurrentIsolateId() {
if (myLatestCurrentIsolateId != null) {
return myLatestCurrentIsolateId;
}
return getIsolateInfos().isEmpty() ? null : getIsolateInfos().iterator().next().getIsolateId();
}
@NotNull
public ExecutionEnvironment getExecutionEnvironment() {
return executionEnvironment;
}
@Nullable
public XDebuggerEvaluator getEvaluator() {
final XStackFrame frame = getSession().getCurrentStackFrame();
if (frame != null) {
return frame.getEvaluator();
}
return new DartVmServiceEvaluator(this);
}
@NotNull
private String formatStackTraces(Throwable e) {
final StringBuilder out = new StringBuilder();
Throwable cause = e.getCause();
while (cause != null) {
out.append("Caused by: ").append(cause).append("\n");
cause = cause.getCause();
}
return out.toString();
}
private void onConnectFailed(@NotNull String message) {
FlutterInitializer.getAnalytics().sendException(message, false);
if (!message.endsWith("\n")) {
message = message + "\n";
}
getSession().getConsoleView().print(message, ConsoleViewContentType.ERROR_OUTPUT);
getSession().stop();
}
private void onConnectSucceeded(VmService vmService) {
final DartVmServiceListener vmServiceListener =
new DartVmServiceListener(this, (DartVmServiceBreakpointHandler)myBreakpointHandlers[0]);
final DartVmServiceBreakpointHandler breakpointHandler = (DartVmServiceBreakpointHandler)myBreakpointHandlers[0];
myVmServiceWrapper = new VmServiceWrapper(this, vmService, vmServiceListener, myIsolatesInfo, breakpointHandler);
final ScriptProvider provider =
(isolateId, scriptId) -> myVmServiceWrapper.getScriptSync(isolateId, scriptId);
mapper.onConnect(provider, myConnector.getRemoteBaseUrl());
final FlutterLaunchMode launchMode = FlutterLaunchMode.fromEnv(executionEnvironment);
if (launchMode.supportsDebugConnection()) {
myVmServiceWrapper.handleDebuggerConnected();
// TODO(jacobr): the following code is a workaround for issues
// auto-resuming isolates paused at their creation while running in
// debug mode.
// The ideal fix would by to fix VMServiceWrapper so that it checks
// for already running isolates like we do here or to refactor where we
// create our VmServiceWrapper so we can listen for isolate creation soon
// enough that we never miss an isolate creation message.
vmService.getVM(new VMConsumer() {
@Override
public void received(VM vm) {
final ElementList<IsolateRef> isolates = vm.getIsolates();
// There is a risk the isolate we care about loaded before the call
// to handleDebuggerConnected was made and so
for (IsolateRef isolateRef : isolates) {
vmService.getIsolate(isolateRef.getId(), new VmServiceConsumers.GetIsolateConsumerWrapper() {
public void received(Isolate isolate) {
final Event event = isolate.getPauseEvent();
final EventKind eventKind = event.getKind();
if (eventKind == EventKind.PauseStart) {
ApplicationManager.getApplication().invokeLater(() -> {
// We are assuming it is safe to call handleIsolate multiple times.
myVmServiceWrapper.handleIsolate(isolateRef, true);
});
}
else if (eventKind == EventKind.Resume) {
// Currently true if we got here via 'flutter attach'
ApplicationManager.getApplication().invokeLater(() -> {
myVmServiceWrapper.attachIsolate(isolateRef, isolate);
});
}
}
});
}
}
@Override
public void onError(RPCError error) {
FlutterUtils.warn(LOG, error.toString());
}
});
}
vmService.addVmServiceListener(vmServiceListener);
myVmConnected = true;
getSession().rebuildViews();
onVmConnected(vmService);
}
private ScriptRef toScriptRef(Script script) {
final JsonObject elt = new JsonObject();
elt.addProperty("id", script.getId());
elt.addProperty("uri", script.getUri());
return new ScriptRef(elt);
}
// TODO(devoncarew): Re-implement this in terms of the generated vm service protocol library.
private void onOpenSourceLocationRequest(@NotNull String isolateId, @NotNull String scriptId, int tokenPos) {
myVmServiceWrapper.getObject(isolateId, scriptId, new GetObjectConsumer() {
@Override
public void received(Obj response) {
if (response instanceof Script) {
ApplicationManager.getApplication().executeOnPooledThread(() -> {
final XSourcePosition source =
getSourcePosition(isolateId, toScriptRef((Script)response), tokenPos);
if (source != null) {
final Project project = getSession().getProject();
final OpenFileHyperlinkInfo
info = new OpenFileHyperlinkInfo(project, source.getFile(), source.getLine());
ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> {
info.navigate(project);
ProjectUtil.focusProjectWindow(project, true);
}));
}
});
}
}
@Override
public void received(Sentinel response) {
// ignore
}
@Override
public void onError(RPCError error) {
// ignore
}
});
}
/**
* Callback for subclass.
*/
protected void onVmConnected(@NotNull VmService vmService) {
}
public boolean getVmConnected() {
return myVmConnected;
}
private static boolean isDartPatchUri(@NotNull final String uri) {
// dart:_builtin or dart:core-patch/core_patch.dart
return uri.startsWith("dart:_") || uri.startsWith("dart:") && uri.contains("-patch/");
}
@NotNull
private static TIntObjectHashMap<Pair<Integer, Integer>> createTokenPosToLineAndColumnMap(@NotNull final List<List<Integer>> tokenPosTable) {
// Each subarray consists of a line number followed by (tokenPos, columnNumber) pairs
// see https://github.com/dart-lang/vm_service_drivers/blob/master/dart/tool/service.md#script
final TIntObjectHashMap<Pair<Integer, Integer>> result = new TIntObjectHashMap<>();
for (List<Integer> lineAndPairs : tokenPosTable) {
final Iterator<Integer> iterator = lineAndPairs.iterator();
final int line = Math.max(0, iterator.next() - 1);
while (iterator.hasNext()) {
final int tokenPos = iterator.next();
final int column = Math.max(0, iterator.next() - 1);
result.put(tokenPos, Pair.create(line, column));
}
}
return result;
}
private static void focusProject(@NotNull Project project) {
final JFrame projectFrame = WindowManager.getInstance().getFrame(project);
if (projectFrame == null) {
return;
}
final int frameState = projectFrame.getExtendedState();
if (BitUtil.isSet(frameState, java.awt.Frame.ICONIFIED)) {
// restore the frame if it is minimized
projectFrame.setExtendedState(frameState ^ java.awt.Frame.ICONIFIED);
projectFrame.toFront();
}
else {
final JFrame anchor = new JFrame();
anchor.setType(Window.Type.UTILITY);
anchor.setUndecorated(true);
anchor.setSize(0, 0);
anchor.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
projectFrame.setVisible(true);
anchor.dispose();
}
@Override
public void windowDeactivated(WindowEvent e) {
}
});
anchor.pack();
anchor.setVisible(true);
anchor.toFront();
}
}
public interface PositionMapper {
void onConnect(ScriptProvider provider, String remoteBaseUrl);
// TODO(skybrian) this is called once per isolate. Should we pass in the isolate id?
/**
* Just after connecting, the debugger downloads the list of Dart libraries from Observatory and reports it here.
*/
void onLibrariesDownloaded(Iterable<LibraryRef> libraries);
/**
* Returns all possible Observatory URI's corresponding to a local file.
* <p>
* (A breakpoint will be set in all of them that exist.)
*/
Collection<String> getBreakpointUris(VirtualFile file);
/**
* Returns the local position (to display to the user) corresponding to a token position in Observatory.
*/
XSourcePosition getSourcePosition(String isolateId, ScriptRef scriptRef, int tokenPos, CompletableFuture<String> fileFuture);
/**
* Returns the local position (to display to the user) corresponding to a token position in Observatory.
*/
XSourcePosition getSourcePosition(String isolateId, Script script, int tokenPos);
void shutdown();
}
public interface ScriptProvider {
/**
* Downloads a script from observatory. Blocks until it's available.
*/
@Nullable
Script downloadScript(@NotNull String isolateId, @NotNull String scriptId);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/vmService/DartVmServiceDebugProcess.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/DartVmServiceDebugProcess.java",
"repo_id": "flutter-intellij",
"token_count": 9482
} | 509 |
package io.flutter.vmService.frame;
import com.intellij.xdebugger.XSourcePosition;
import io.flutter.vmService.DartVmServiceDebugProcess;
import org.dartlang.vm.service.element.Frame;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class DartVmServiceEvaluatorInFrame extends DartVmServiceEvaluator {
@NotNull private final String myIsolateId;
@NotNull private final Frame myFrame;
public DartVmServiceEvaluatorInFrame(@NotNull final DartVmServiceDebugProcess debugProcess,
@NotNull final String isolateId,
@NotNull final Frame vmFrame) {
super(debugProcess);
myIsolateId = isolateId;
myFrame = vmFrame;
}
@Override
public void evaluate(@NotNull final String expression,
@NotNull final XEvaluationCallback callback,
@Nullable final XSourcePosition expressionPosition) {
myDebugProcess.getVmServiceWrapper().evaluateInFrame(myIsolateId, myFrame, expression, callback);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartVmServiceEvaluatorInFrame.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartVmServiceEvaluatorInFrame.java",
"repo_id": "flutter-intellij",
"token_count": 416
} | 510 |
/*
* Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*
* This file has been automatically generated. Please do not edit it manually.
* To regenerate the file, use the script "pkg/analysis_server/tool/spec/generate_files".
*/
package org.dartlang.analysis.server.protocol;
/**
* An enumeration of the kinds of refactorings that can be created.
*
* @coverage dart.server.generated.types
*/
public class RefactoringKind {
public static final String CONVERT_GETTER_TO_METHOD = "CONVERT_GETTER_TO_METHOD";
public static final String CONVERT_METHOD_TO_GETTER = "CONVERT_METHOD_TO_GETTER";
public static final String EXTRACT_LOCAL_VARIABLE = "EXTRACT_LOCAL_VARIABLE";
public static final String EXTRACT_METHOD = "EXTRACT_METHOD";
public static final String EXTRACT_WIDGET = "EXTRACT_WIDGET";
public static final String INLINE_LOCAL_VARIABLE = "INLINE_LOCAL_VARIABLE";
public static final String INLINE_METHOD = "INLINE_METHOD";
public static final String MOVE_FILE = "MOVE_FILE";
public static final String RENAME = "RENAME";
}
| flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/RefactoringKind.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/RefactoringKind.java",
"repo_id": "flutter-intellij",
"token_count": 368
} | 511 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.