text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_EVENT_WATCHER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_EVENT_WATCHER_H_ #include <Windows.h> #include <functional> #include "flutter/fml/macros.h" namespace flutter { // A win32 `HANDLE` wrapper for use as a one-time callback. class EventWatcher { public: explicit EventWatcher(std::function<void()> callback); ~EventWatcher(); // Returns `HANDLE`, which can be used to register an event listener. HANDLE GetHandle(); private: static VOID CALLBACK CallbackForWait(PVOID context, BOOLEAN); std::function<void()> callback_; HANDLE handle_; HANDLE handle_for_wait_; FML_DISALLOW_COPY_AND_ASSIGN(EventWatcher); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EVENT_WATCHER_H_
engine/shell/platform/windows/event_watcher.h/0
{ "file_path": "engine/shell/platform/windows/event_watcher.h", "repo_id": "engine", "token_count": 325 }
379
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/flutter_window.h" #include "flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h" #include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h" #include "flutter/shell/platform/windows/testing/mock_window_binding_handler_delegate.h" #include "flutter/shell/platform/windows/testing/windows_test.h" #include "flutter/shell/platform/windows/testing/wm_builders.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace flutter { namespace testing { using ::testing::_; using ::testing::AnyNumber; using ::testing::Invoke; using ::testing::Return; namespace { static constexpr int32_t kDefaultPointerDeviceId = 0; class MockFlutterWindow : public FlutterWindow { public: MockFlutterWindow(bool reset_view_on_exit = true) : reset_view_on_exit_(reset_view_on_exit) { ON_CALL(*this, GetDpiScale()) .WillByDefault(Return(this->FlutterWindow::GetDpiScale())); } virtual ~MockFlutterWindow() { if (reset_view_on_exit_) { SetView(nullptr); } } // Wrapper for GetCurrentDPI() which is a protected method. UINT GetDpi() { return GetCurrentDPI(); } // Simulates a WindowProc message from the OS. LRESULT InjectWindowMessage(UINT const message, WPARAM const wparam, LPARAM const lparam) { return HandleMessage(message, wparam, lparam); } MOCK_METHOD(void, OnDpiScale, (unsigned int), (override)); MOCK_METHOD(void, OnResize, (unsigned int, unsigned int), (override)); MOCK_METHOD(void, OnPointerMove, (double, double, FlutterPointerDeviceKind, int32_t, int), (override)); MOCK_METHOD(void, OnPointerDown, (double, double, FlutterPointerDeviceKind, int32_t, UINT), (override)); MOCK_METHOD(void, OnPointerUp, (double, double, FlutterPointerDeviceKind, int32_t, UINT), (override)); MOCK_METHOD(void, OnPointerLeave, (double, double, FlutterPointerDeviceKind, int32_t), (override)); MOCK_METHOD(void, OnSetCursor, (), (override)); MOCK_METHOD(float, GetScrollOffsetMultiplier, (), (override)); MOCK_METHOD(float, GetDpiScale, (), (override)); MOCK_METHOD(void, UpdateCursorRect, (const Rect&), (override)); MOCK_METHOD(void, OnResetImeComposing, (), (override)); MOCK_METHOD(UINT, Win32DispatchMessage, (UINT, WPARAM, LPARAM), (override)); MOCK_METHOD(BOOL, Win32PeekMessage, (LPMSG, UINT, UINT, UINT), (override)); MOCK_METHOD(uint32_t, Win32MapVkToChar, (uint32_t), (override)); MOCK_METHOD(HWND, GetWindowHandle, (), (override)); MOCK_METHOD(ui::AXFragmentRootDelegateWin*, GetAxFragmentRootDelegate, (), (override)); MOCK_METHOD(void, OnWindowStateEvent, (WindowStateEvent), (override)); protected: // |KeyboardManager::WindowDelegate| LRESULT Win32DefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) override { return kWmResultDefault; } private: bool reset_view_on_exit_; FML_DISALLOW_COPY_AND_ASSIGN(MockFlutterWindow); }; class MockFlutterWindowsView : public FlutterWindowsView { public: MockFlutterWindowsView(FlutterWindowsEngine* engine, std::unique_ptr<WindowBindingHandler> window_binding) : FlutterWindowsView(kImplicitViewId, engine, std::move(window_binding)) { } ~MockFlutterWindowsView() {} MOCK_METHOD(void, NotifyWinEventWrapper, (ui::AXPlatformNodeWin*, ax::mojom::Event), (override)); private: FML_DISALLOW_COPY_AND_ASSIGN(MockFlutterWindowsView); }; class FlutterWindowTest : public WindowsTest {}; } // namespace TEST_F(FlutterWindowTest, CreateDestroy) { FlutterWindow window(800, 600); ASSERT_TRUE(TRUE); } TEST_F(FlutterWindowTest, OnBitmapSurfaceUpdated) { FlutterWindow win32window(100, 100); int old_handle_count = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS); constexpr size_t row_bytes = 100 * 4; constexpr size_t height = 100; std::array<char, row_bytes * height> allocation; win32window.OnBitmapSurfaceUpdated(allocation.data(), row_bytes, height); int new_handle_count = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS); // Check GDI resources leak EXPECT_EQ(old_handle_count, new_handle_count); } // Tests that composing rect updates are transformed from Flutter logical // coordinates to device coordinates and passed to the text input manager // when the DPI scale is 100% (96 DPI). TEST_F(FlutterWindowTest, OnCursorRectUpdatedRegularDPI) { MockFlutterWindow win32window; EXPECT_CALL(win32window, GetDpiScale()).WillOnce(Return(1.0)); Rect cursor_rect(Point(10, 20), Size(30, 40)); EXPECT_CALL(win32window, UpdateCursorRect(cursor_rect)).Times(1); win32window.OnCursorRectUpdated(cursor_rect); } // Tests that composing rect updates are transformed from Flutter logical // coordinates to device coordinates and passed to the text input manager // when the DPI scale is 150% (144 DPI). TEST_F(FlutterWindowTest, OnCursorRectUpdatedHighDPI) { MockFlutterWindow win32window; EXPECT_CALL(win32window, GetDpiScale()).WillOnce(Return(1.5)); Rect expected_cursor_rect(Point(15, 30), Size(45, 60)); EXPECT_CALL(win32window, UpdateCursorRect(expected_cursor_rect)).Times(1); Rect cursor_rect(Point(10, 20), Size(30, 40)); win32window.OnCursorRectUpdated(cursor_rect); } TEST_F(FlutterWindowTest, OnPointerStarSendsDeviceType) { FlutterWindow win32window(100, 100); MockWindowBindingHandlerDelegate delegate; EXPECT_CALL(delegate, OnWindowStateEvent).Times(AnyNumber()); win32window.SetView(&delegate); // Move EXPECT_CALL(delegate, OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, 0)) .Times(1); EXPECT_CALL(delegate, OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, 0)) .Times(1); EXPECT_CALL(delegate, OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, 0)) .Times(1); // Down EXPECT_CALL( delegate, OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); EXPECT_CALL( delegate, OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); EXPECT_CALL( delegate, OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); // Up EXPECT_CALL(delegate, OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); EXPECT_CALL(delegate, OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); EXPECT_CALL(delegate, OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); // Leave EXPECT_CALL(delegate, OnPointerLeave(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId)) .Times(1); EXPECT_CALL(delegate, OnPointerLeave(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId)) .Times(1); EXPECT_CALL(delegate, OnPointerLeave(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId)) .Times(1); win32window.OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, 0); win32window.OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerLeave(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId); // Touch win32window.OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, 0); win32window.OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerLeave(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId); // Pen win32window.OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, 0); win32window.OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerLeave(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId); // Destruction of win32window sends a HIDE update. In situ, the window is // owned by the delegate, and so is destructed first. Not so here. win32window.SetView(nullptr); } // Tests that calls to OnScroll in turn calls GetScrollOffsetMultiplier // for mapping scroll ticks to pixels. TEST_F(FlutterWindowTest, OnScrollCallsGetScrollOffsetMultiplier) { MockFlutterWindow win32window; MockWindowBindingHandlerDelegate delegate; EXPECT_CALL(win32window, OnWindowStateEvent).Times(AnyNumber()); win32window.SetView(&delegate); EXPECT_CALL(win32window, GetWindowHandle).WillOnce([&win32window]() { return win32window.FlutterWindow::GetWindowHandle(); }); EXPECT_CALL(win32window, GetScrollOffsetMultiplier).WillOnce(Return(120.0f)); EXPECT_CALL(delegate, OnScroll(_, _, 0, 0, 120.0f, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId)) .Times(1); win32window.OnScroll(0.0f, 0.0f, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId); } TEST_F(FlutterWindowTest, OnWindowRepaint) { MockFlutterWindow win32window; MockWindowBindingHandlerDelegate delegate; EXPECT_CALL(win32window, OnWindowStateEvent).Times(AnyNumber()); win32window.SetView(&delegate); EXPECT_CALL(delegate, OnWindowRepaint()).Times(1); win32window.InjectWindowMessage(WM_PAINT, 0, 0); } TEST_F(FlutterWindowTest, OnThemeChange) { MockFlutterWindow win32window; MockWindowBindingHandlerDelegate delegate; EXPECT_CALL(win32window, OnWindowStateEvent).Times(AnyNumber()); win32window.SetView(&delegate); EXPECT_CALL(delegate, OnHighContrastChanged).Times(1); win32window.InjectWindowMessage(WM_THEMECHANGED, 0, 0); } // The window should return no root accessibility node if // it isn't attached to a view. // Regression test for https://github.com/flutter/flutter/issues/129791 TEST_F(FlutterWindowTest, AccessibilityNodeWithoutView) { MockFlutterWindow win32window; EXPECT_EQ(win32window.GetNativeViewAccessible(), nullptr); } // Ensure that announcing the alert propagates the message to the alert node. // Different screen readers use different properties for alerts. TEST_F(FlutterWindowTest, AlertNode) { std::unique_ptr<FlutterWindowsEngine> engine = FlutterWindowsEngineBuilder{GetContext()}.Build(); auto win32window = std::make_unique<MockFlutterWindow>(); EXPECT_CALL(*win32window.get(), GetAxFragmentRootDelegate()) .WillRepeatedly(Return(nullptr)); EXPECT_CALL(*win32window.get(), OnWindowStateEvent).Times(AnyNumber()); EXPECT_CALL(*win32window.get(), GetWindowHandle).Times(AnyNumber()); MockFlutterWindowsView view{engine.get(), std::move(win32window)}; std::wstring message = L"Test alert"; EXPECT_CALL(view, NotifyWinEventWrapper(_, ax::mojom::Event::kAlert)) .Times(1); view.AnnounceAlert(message); IAccessible* alert = view.AlertNode(); VARIANT self{.vt = VT_I4, .lVal = CHILDID_SELF}; BSTR strptr; alert->get_accName(self, &strptr); EXPECT_EQ(message, strptr); alert->get_accDescription(self, &strptr); EXPECT_EQ(message, strptr); alert->get_accValue(self, &strptr); EXPECT_EQ(message, strptr); VARIANT role; alert->get_accRole(self, &role); EXPECT_EQ(role.vt, VT_I4); EXPECT_EQ(role.lVal, ROLE_SYSTEM_ALERT); } TEST_F(FlutterWindowTest, LifecycleFocusMessages) { MockFlutterWindow win32window; EXPECT_CALL(win32window, GetWindowHandle) .WillRepeatedly(Return(reinterpret_cast<HWND>(1))); MockWindowBindingHandlerDelegate delegate; WindowStateEvent last_event; EXPECT_CALL(delegate, OnWindowStateEvent) .WillRepeatedly([&last_event](HWND hwnd, WindowStateEvent event) { last_event = event; }); EXPECT_CALL(win32window, OnWindowStateEvent) .WillRepeatedly([&](WindowStateEvent event) { win32window.FlutterWindow::OnWindowStateEvent(event); }); EXPECT_CALL(win32window, OnResize).Times(AnyNumber()); win32window.SetView(&delegate); win32window.InjectWindowMessage(WM_SIZE, 0, 0); EXPECT_EQ(last_event, WindowStateEvent::kHide); win32window.InjectWindowMessage(WM_SIZE, 0, MAKEWORD(1, 1)); EXPECT_EQ(last_event, WindowStateEvent::kShow); win32window.InjectWindowMessage(WM_SETFOCUS, 0, 0); EXPECT_EQ(last_event, WindowStateEvent::kFocus); win32window.InjectWindowMessage(WM_KILLFOCUS, 0, 0); EXPECT_EQ(last_event, WindowStateEvent::kUnfocus); } TEST_F(FlutterWindowTest, CachedLifecycleMessage) { MockFlutterWindow win32window; EXPECT_CALL(win32window, GetWindowHandle) .WillRepeatedly(Return(reinterpret_cast<HWND>(1))); EXPECT_CALL(win32window, OnWindowStateEvent) .WillRepeatedly([&](WindowStateEvent event) { win32window.FlutterWindow::OnWindowStateEvent(event); }); EXPECT_CALL(win32window, OnResize).Times(1); // Restore win32window.InjectWindowMessage(WM_SIZE, 0, MAKEWORD(1, 1)); // Focus win32window.InjectWindowMessage(WM_SETFOCUS, 0, 0); MockWindowBindingHandlerDelegate delegate; bool focused = false; bool restored = false; EXPECT_CALL(delegate, OnWindowStateEvent) .WillRepeatedly([&](HWND hwnd, WindowStateEvent event) { if (event == WindowStateEvent::kFocus) { focused = true; } else if (event == WindowStateEvent::kShow) { restored = true; } }); win32window.SetView(&delegate); EXPECT_TRUE(focused); EXPECT_TRUE(restored); } TEST_F(FlutterWindowTest, UpdateCursor) { FlutterWindow win32window(100, 100); win32window.UpdateFlutterCursor("text"); HCURSOR cursor = ::GetCursor(); EXPECT_EQ(cursor, ::LoadCursor(nullptr, IDC_IBEAM)); } } // namespace testing } // namespace flutter
engine/shell/platform/windows/flutter_window_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/flutter_window_unittests.cc", "repo_id": "engine", "token_count": 6532 }
380
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_KEY_CHANNEL_HANDLER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_KEY_CHANNEL_HANDLER_H_ #include <deque> #include <memory> #include <string> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" #include "flutter/shell/platform/windows/keyboard_key_handler.h" #include "rapidjson/document.h" namespace flutter { // A delegate of |KeyboardKeyHandler| that handles events by sending the // raw information through the method channel. // // This class communicates with the RawKeyboard API in the framework. class KeyboardKeyChannelHandler : public KeyboardKeyHandler::KeyboardKeyHandlerDelegate { public: // Create a |KeyboardKeyChannelHandler| by specifying the messenger // through which the events are sent. explicit KeyboardKeyChannelHandler(flutter::BinaryMessenger* messenger); ~KeyboardKeyChannelHandler(); // |KeyboardKeyHandler::KeyboardKeyHandlerDelegate| void KeyboardHook(int key, int scancode, int action, char32_t character, bool extended, bool was_down, std::function<void(bool)> callback); void SyncModifiersIfNeeded(int modifiers_state); std::map<uint64_t, uint64_t> GetPressedState(); private: // The Flutter system channel for key event messages. std::unique_ptr<flutter::BasicMessageChannel<rapidjson::Document>> channel_; FML_DISALLOW_COPY_AND_ASSIGN(KeyboardKeyChannelHandler); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_KEY_CHANNEL_HANDLER_H_
engine/shell/platform/windows/keyboard_key_channel_handler.h/0
{ "file_path": "engine/shell/platform/windows/keyboard_key_channel_handler.h", "repo_id": "engine", "token_count": 689 }
381
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/platform_handler.h" #include <memory> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/json_method_codec.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" #include "flutter/shell/platform/windows/testing/engine_modifier.h" #include "flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h" #include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h" #include "flutter/shell/platform/windows/testing/test_binary_messenger.h" #include "flutter/shell/platform/windows/testing/windows_test.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "rapidjson/document.h" namespace flutter { namespace testing { namespace { using ::testing::_; using ::testing::NiceMock; using ::testing::Return; static constexpr char kChannelName[] = "flutter/platform"; static constexpr char kClipboardGetDataMessage[] = "{\"method\":\"Clipboard.getData\",\"args\":\"text/plain\"}"; static constexpr char kClipboardGetDataFakeContentTypeMessage[] = "{\"method\":\"Clipboard.getData\",\"args\":\"text/madeupcontenttype\"}"; static constexpr char kClipboardHasStringsMessage[] = "{\"method\":\"Clipboard.hasStrings\",\"args\":\"text/plain\"}"; static constexpr char kClipboardHasStringsFakeContentTypeMessage[] = "{\"method\":\"Clipboard.hasStrings\",\"args\":\"text/madeupcontenttype\"}"; static constexpr char kClipboardSetDataMessage[] = "{\"method\":\"Clipboard.setData\",\"args\":{\"text\":\"hello\"}}"; static constexpr char kClipboardSetDataNullTextMessage[] = "{\"method\":\"Clipboard.setData\",\"args\":{\"text\":null}}"; static constexpr char kClipboardSetDataUnknownTypeMessage[] = "{\"method\":\"Clipboard.setData\",\"args\":{\"madeuptype\":\"hello\"}}"; static constexpr char kSystemSoundTypeAlertMessage[] = "{\"method\":\"SystemSound.play\",\"args\":\"SystemSoundType.alert\"}"; static constexpr char kSystemExitApplicationRequiredMessage[] = "{\"method\":\"System.exitApplication\",\"args\":{\"type\":\"required\"," "\"exitCode\":1}}"; static constexpr char kSystemExitApplicationCancelableMessage[] = "{\"method\":\"System.exitApplication\",\"args\":{\"type\":\"cancelable\"," "\"exitCode\":2}}"; static constexpr char kExitResponseCancelMessage[] = "[{\"response\":\"cancel\"}]"; static constexpr char kExitResponseExitMessage[] = "[{\"response\":\"exit\"}]"; static constexpr int kAccessDeniedErrorCode = 5; static constexpr int kErrorSuccess = 0; static constexpr int kArbitraryErrorCode = 1; // Test implementation of PlatformHandler to allow testing the PlatformHandler // logic. class MockPlatformHandler : public PlatformHandler { public: explicit MockPlatformHandler( BinaryMessenger* messenger, FlutterWindowsEngine* engine, std::optional<std::function<std::unique_ptr<ScopedClipboardInterface>()>> scoped_clipboard_provider = std::nullopt) : PlatformHandler(messenger, engine, scoped_clipboard_provider) {} virtual ~MockPlatformHandler() = default; MOCK_METHOD(void, GetPlainText, (std::unique_ptr<MethodResult<rapidjson::Document>>, std::string_view key), (override)); MOCK_METHOD(void, GetHasStrings, (std::unique_ptr<MethodResult<rapidjson::Document>>), (override)); MOCK_METHOD(void, SetPlainText, (const std::string&, std::unique_ptr<MethodResult<rapidjson::Document>>), (override)); MOCK_METHOD(void, SystemSoundPlay, (const std::string&, std::unique_ptr<MethodResult<rapidjson::Document>>), (override)); MOCK_METHOD(void, QuitApplication, (std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, UINT exit_code), (override)); private: FML_DISALLOW_COPY_AND_ASSIGN(MockPlatformHandler); }; // A test version of the private ScopedClipboard. class MockScopedClipboard : public ScopedClipboardInterface { public: MockScopedClipboard() = default; virtual ~MockScopedClipboard() = default; MOCK_METHOD(int, Open, (HWND window), (override)); MOCK_METHOD(bool, HasString, (), (override)); MOCK_METHOD((std::variant<std::wstring, int>), GetString, (), (override)); MOCK_METHOD(int, SetString, (const std::wstring string), (override)); private: FML_DISALLOW_COPY_AND_ASSIGN(MockScopedClipboard); }; std::string SimulatePlatformMessage(TestBinaryMessenger* messenger, std::string message) { std::string result; EXPECT_TRUE(messenger->SimulateEngineMessage( kChannelName, reinterpret_cast<const uint8_t*>(message.c_str()), message.size(), [result = &result](const uint8_t* reply, size_t reply_size) { std::string response(reinterpret_cast<const char*>(reply), reply_size); *result = response; })); return result; } } // namespace class PlatformHandlerTest : public WindowsTest { public: PlatformHandlerTest() = default; virtual ~PlatformHandlerTest() = default; protected: FlutterWindowsEngine* engine() { return engine_.get(); } void UseHeadlessEngine() { FlutterWindowsEngineBuilder builder{GetContext()}; engine_ = builder.Build(); } void UseEngineWithView() { FlutterWindowsEngineBuilder builder{GetContext()}; auto window = std::make_unique<NiceMock<MockWindowBindingHandler>>(); engine_ = builder.Build(); view_ = std::make_unique<FlutterWindowsView>(kImplicitViewId, engine_.get(), std::move(window)); EngineModifier modifier{engine_.get()}; modifier.SetImplicitView(view_.get()); } private: std::unique_ptr<FlutterWindowsEngine> engine_; std::unique_ptr<FlutterWindowsView> view_; FML_DISALLOW_COPY_AND_ASSIGN(PlatformHandlerTest); }; TEST_F(PlatformHandlerTest, GetClipboardData) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kErrorSuccess)); EXPECT_CALL(*clipboard.get(), HasString).Times(1).WillOnce(Return(true)); EXPECT_CALL(*clipboard.get(), GetString) .Times(1) .WillOnce(Return(std::wstring(L"Hello world"))); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardGetDataMessage); EXPECT_EQ(result, "[{\"text\":\"Hello world\"}]"); } TEST_F(PlatformHandlerTest, GetClipboardDataRejectsUnknownContentType) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine()); // Requesting an unknown content type is an error. std::string result = SimulatePlatformMessage( &messenger, kClipboardGetDataFakeContentTypeMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Unknown clipboard format\",null]"); } TEST_F(PlatformHandlerTest, GetClipboardDataRequiresView) { UseHeadlessEngine(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine()); std::string result = SimulatePlatformMessage(&messenger, kClipboardGetDataMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Clipboard is not available in " "Windows headless mode\",null]"); } TEST_F(PlatformHandlerTest, GetClipboardDataReportsOpenFailure) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kArbitraryErrorCode)); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardGetDataMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Unable to open clipboard\",1]"); } TEST_F(PlatformHandlerTest, GetClipboardDataReportsGetDataFailure) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kErrorSuccess)); EXPECT_CALL(*clipboard.get(), HasString).Times(1).WillOnce(Return(true)); EXPECT_CALL(*clipboard.get(), GetString) .Times(1) .WillOnce(Return(kArbitraryErrorCode)); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardGetDataMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Unable to get clipboard data\",1]"); } TEST_F(PlatformHandlerTest, ClipboardHasStrings) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kErrorSuccess)); EXPECT_CALL(*clipboard.get(), HasString).Times(1).WillOnce(Return(true)); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardHasStringsMessage); EXPECT_EQ(result, "[{\"value\":true}]"); } TEST_F(PlatformHandlerTest, ClipboardHasStringsReturnsFalse) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kErrorSuccess)); EXPECT_CALL(*clipboard.get(), HasString).Times(1).WillOnce(Return(false)); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardHasStringsMessage); EXPECT_EQ(result, "[{\"value\":false}]"); } TEST_F(PlatformHandlerTest, ClipboardHasStringsRejectsUnknownContentType) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine()); std::string result = SimulatePlatformMessage( &messenger, kClipboardHasStringsFakeContentTypeMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Unknown clipboard format\",null]"); } TEST_F(PlatformHandlerTest, ClipboardHasStringsRequiresView) { UseHeadlessEngine(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine()); std::string result = SimulatePlatformMessage(&messenger, kClipboardHasStringsMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Clipboard is not available in Windows " "headless mode\",null]"); } // Regression test for https://github.com/flutter/flutter/issues/95817. TEST_F(PlatformHandlerTest, ClipboardHasStringsIgnoresPermissionErrors) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kAccessDeniedErrorCode)); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardHasStringsMessage); EXPECT_EQ(result, "[{\"value\":false}]"); } TEST_F(PlatformHandlerTest, ClipboardHasStringsReportsErrors) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kArbitraryErrorCode)); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardHasStringsMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Unable to open clipboard\",1]"); } TEST_F(PlatformHandlerTest, ClipboardSetData) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kErrorSuccess)); EXPECT_CALL(*clipboard.get(), SetString) .Times(1) .WillOnce([](std::wstring string) { EXPECT_EQ(string, L"hello"); return kErrorSuccess; }); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardSetDataMessage); EXPECT_EQ(result, "[null]"); } // Regression test for: https://github.com/flutter/flutter/issues/121976 TEST_F(PlatformHandlerTest, ClipboardSetDataTextMustBeString) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine()); std::string result = SimulatePlatformMessage(&messenger, kClipboardSetDataNullTextMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Unknown clipboard format\",null]"); } TEST_F(PlatformHandlerTest, ClipboardSetDataUnknownType) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine()); std::string result = SimulatePlatformMessage(&messenger, kClipboardSetDataUnknownTypeMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Unknown clipboard format\",null]"); } TEST_F(PlatformHandlerTest, ClipboardSetDataRequiresView) { UseHeadlessEngine(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine()); std::string result = SimulatePlatformMessage(&messenger, kClipboardSetDataMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Clipboard is not available in Windows " "headless mode\",null]"); } TEST_F(PlatformHandlerTest, ClipboardSetDataReportsOpenFailure) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kArbitraryErrorCode)); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardSetDataMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Unable to open clipboard\",1]"); } TEST_F(PlatformHandlerTest, ClipboardSetDataReportsSetDataFailure) { UseEngineWithView(); TestBinaryMessenger messenger; PlatformHandler platform_handler(&messenger, engine(), []() { auto clipboard = std::make_unique<MockScopedClipboard>(); EXPECT_CALL(*clipboard.get(), Open) .Times(1) .WillOnce(Return(kErrorSuccess)); EXPECT_CALL(*clipboard.get(), SetString) .Times(1) .WillOnce(Return(kArbitraryErrorCode)); return clipboard; }); std::string result = SimulatePlatformMessage(&messenger, kClipboardSetDataMessage); EXPECT_EQ(result, "[\"Clipboard error\",\"Unable to set clipboard data\",1]"); } TEST_F(PlatformHandlerTest, PlaySystemSound) { UseHeadlessEngine(); TestBinaryMessenger messenger; MockPlatformHandler platform_handler(&messenger, engine()); EXPECT_CALL(platform_handler, SystemSoundPlay("SystemSoundType.alert", _)) .WillOnce([](const std::string& sound, std::unique_ptr<MethodResult<rapidjson::Document>> result) { result->Success(); }); std::string result = SimulatePlatformMessage(&messenger, kSystemSoundTypeAlertMessage); EXPECT_EQ(result, "[null]"); } TEST_F(PlatformHandlerTest, SystemExitApplicationRequired) { UseHeadlessEngine(); UINT exit_code = 0; TestBinaryMessenger messenger([](const std::string& channel, const uint8_t* message, size_t size, BinaryReply reply) {}); MockPlatformHandler platform_handler(&messenger, engine()); ON_CALL(platform_handler, QuitApplication) .WillByDefault([&exit_code](std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, UINT ec) { exit_code = ec; }); EXPECT_CALL(platform_handler, QuitApplication).Times(1); std::string result = SimulatePlatformMessage( &messenger, kSystemExitApplicationRequiredMessage); EXPECT_EQ(result, "[{\"response\":\"exit\"}]"); EXPECT_EQ(exit_code, 1); } TEST_F(PlatformHandlerTest, SystemExitApplicationCancelableCancel) { UseHeadlessEngine(); bool called_cancel = false; TestBinaryMessenger messenger( [&called_cancel](const std::string& channel, const uint8_t* message, size_t size, BinaryReply reply) { reply(reinterpret_cast<const uint8_t*>(kExitResponseCancelMessage), sizeof(kExitResponseCancelMessage)); called_cancel = true; }); MockPlatformHandler platform_handler(&messenger, engine()); EXPECT_CALL(platform_handler, QuitApplication).Times(0); std::string result = SimulatePlatformMessage( &messenger, kSystemExitApplicationCancelableMessage); EXPECT_EQ(result, "[{\"response\":\"cancel\"}]"); EXPECT_TRUE(called_cancel); } TEST_F(PlatformHandlerTest, SystemExitApplicationCancelableExit) { UseHeadlessEngine(); bool called_cancel = false; UINT exit_code = 0; TestBinaryMessenger messenger( [&called_cancel](const std::string& channel, const uint8_t* message, size_t size, BinaryReply reply) { reply(reinterpret_cast<const uint8_t*>(kExitResponseExitMessage), sizeof(kExitResponseExitMessage)); called_cancel = true; }); MockPlatformHandler platform_handler(&messenger, engine()); ON_CALL(platform_handler, QuitApplication) .WillByDefault([&exit_code](std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, UINT ec) { exit_code = ec; }); EXPECT_CALL(platform_handler, QuitApplication).Times(1); std::string result = SimulatePlatformMessage( &messenger, kSystemExitApplicationCancelableMessage); EXPECT_EQ(result, "[{\"response\":\"cancel\"}]"); EXPECT_TRUE(called_cancel); EXPECT_EQ(exit_code, 2); } } // namespace testing } // namespace flutter
engine/shell/platform/windows/platform_handler_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/platform_handler_unittests.cc", "repo_id": "engine", "token_count": 6845 }
382
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TASK_RUNNER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TASK_RUNNER_H_ #include <chrono> #include <deque> #include <functional> #include <memory> #include <mutex> #include <queue> #include <variant> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/windows/task_runner_window.h" namespace flutter { typedef uint64_t (*CurrentTimeProc)(); // A custom task runner that integrates with user32 GetMessage semantics so // that host app can own its own message loop and flutter still gets to process // tasks on a timely basis. class TaskRunner : public TaskRunnerWindow::Delegate { public: using TaskTimePoint = std::chrono::steady_clock::time_point; using TaskExpiredCallback = std::function<void(const FlutterTask*)>; using TaskClosure = std::function<void()>; // Creates a new task runner with the current thread, current time // provider, and callback for tasks that are ready to be run. TaskRunner(CurrentTimeProc get_current_time, const TaskExpiredCallback& on_task_expired); virtual ~TaskRunner(); // Returns `true` if the current thread is this runner's thread. virtual bool RunsTasksOnCurrentThread() const; // Post a Flutter engine task to the event loop for delayed execution. void PostFlutterTask(FlutterTask flutter_task, uint64_t flutter_target_time_nanos); // Post a task to the event loop. void PostTask(TaskClosure task); // Post a task to the event loop or run it immediately if this is being called // from the runner's thread. void RunNowOrPostTask(TaskClosure task) { if (RunsTasksOnCurrentThread()) { task(); } else { PostTask(std::move(task)); } } // |TaskRunnerWindow::Delegate| std::chrono::nanoseconds ProcessTasks(); private: typedef std::variant<FlutterTask, TaskClosure> TaskVariant; struct Task { uint64_t order; TaskTimePoint fire_time; TaskVariant variant; struct Comparer { bool operator()(const Task& a, const Task& b) { if (a.fire_time == b.fire_time) { return a.order > b.order; } return a.fire_time > b.fire_time; } }; }; // Enqueues the given task. void EnqueueTask(Task task); // Schedules timers to call `ProcessTasks()` at the runner's thread. virtual void WakeUp(); // Returns the current TaskTimePoint that can be used to determine whether a // task is expired. // // Tests can override this to mock up the time. virtual TaskTimePoint GetCurrentTimeForTask() const { return TaskTimePoint::clock::now(); } // Returns a TaskTimePoint computed from the given target time from Flutter. TaskTimePoint TimePointFromFlutterTime( uint64_t flutter_target_time_nanos) const; CurrentTimeProc get_current_time_; TaskExpiredCallback on_task_expired_; std::mutex task_queue_mutex_; std::priority_queue<Task, std::deque<Task>, Task::Comparer> task_queue_; DWORD main_thread_id_; std::shared_ptr<TaskRunnerWindow> task_runner_window_; FML_DISALLOW_COPY_AND_ASSIGN(TaskRunner); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TASK_RUNNER_H_
engine/shell/platform/windows/task_runner.h/0
{ "file_path": "engine/shell/platform/windows/task_runner.h", "repo_id": "engine", "token_count": 1143 }
383
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_H_ #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/flutter_window.h" #include "flutter/shell/platform/windows/testing/test_keyboard.h" #include "gmock/gmock.h" namespace flutter { namespace testing { /// Mock for the |FlutterWindow| base class. class MockWindow : public FlutterWindow { public: MockWindow(); MockWindow(std::unique_ptr<WindowsProcTable> windows_proc_table, std::unique_ptr<TextInputManager> text_input_manager); virtual ~MockWindow(); // Wrapper for GetCurrentDPI() which is a protected method. UINT GetDpi(); // Set the Direct Manipulation owner for testing purposes. void SetDirectManipulationOwner( std::unique_ptr<DirectManipulationOwner> owner); // Simulates a WindowProc message from the OS. LRESULT InjectWindowMessage(UINT const message, WPARAM const wparam, LPARAM const lparam); void InjectMessageList(int count, const Win32Message* messages); MOCK_METHOD(void, OnDpiScale, (unsigned int), (override)); MOCK_METHOD(void, OnResize, (unsigned int, unsigned int), (override)); MOCK_METHOD(void, OnPaint, (), (override)); MOCK_METHOD(void, OnPointerMove, (double, double, FlutterPointerDeviceKind, int32_t, int), (override)); MOCK_METHOD(void, OnPointerDown, (double, double, FlutterPointerDeviceKind, int32_t, UINT), (override)); MOCK_METHOD(void, OnPointerUp, (double, double, FlutterPointerDeviceKind, int32_t, UINT), (override)); MOCK_METHOD(void, OnPointerLeave, (double, double, FlutterPointerDeviceKind, int32_t), (override)); MOCK_METHOD(void, OnSetCursor, (), (override)); MOCK_METHOD(void, OnText, (const std::u16string&), (override)); MOCK_METHOD(void, OnKey, (int, int, int, char32_t, bool, bool, KeyEventCallback), (override)); MOCK_METHOD(void, OnUpdateSemanticsEnabled, (bool), (override)); MOCK_METHOD(gfx::NativeViewAccessible, GetNativeViewAccessible, (), (override)); MOCK_METHOD(void, OnScroll, (double, double, FlutterPointerDeviceKind, int32_t), (override)); MOCK_METHOD(void, OnComposeBegin, (), (override)); MOCK_METHOD(void, OnComposeCommit, (), (override)); MOCK_METHOD(void, OnComposeEnd, (), (override)); MOCK_METHOD(void, OnComposeChange, (const std::u16string&, int), (override)); MOCK_METHOD(void, OnImeComposition, (UINT const, WPARAM const, LPARAM const), (override)); MOCK_METHOD(void, OnThemeChange, (), (override)); MOCK_METHOD(ui::AXFragmentRootDelegateWin*, GetAxFragmentRootDelegate, (), (override)); MOCK_METHOD(LRESULT, OnGetObject, (UINT, WPARAM, LPARAM), (override)); MOCK_METHOD(void, OnWindowStateEvent, (WindowStateEvent), (override)); void CallOnImeComposition(UINT const message, WPARAM const wparam, LPARAM const lparam); protected: LRESULT Win32DefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); private: FML_DISALLOW_COPY_AND_ASSIGN(MockWindow); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_H_
engine/shell/platform/windows/testing/mock_window.h/0
{ "file_path": "engine/shell/platform/windows/testing/mock_window.h", "repo_id": "engine", "token_count": 1630 }
384
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/testing/wm_builders.h" namespace flutter { namespace testing { Win32Message WmKeyDownInfo::Build(LRESULT expected_result) { LPARAM lParam = (repeat_count << 0) | (scan_code << 16) | (extended << 24) | (prev_state << 30); return Win32Message{ .message = WM_KEYDOWN, .wParam = key, .lParam = lParam, .expected_result = expected_result, }; } Win32Message WmKeyUpInfo::Build(LRESULT expected_result) { LPARAM lParam = (1 /* repeat_count */ << 0) | (scan_code << 16) | (extended << 24) | (!overwrite_prev_state_0 << 30) | (1 /* transition */ << 31); return Win32Message{ .message = WM_KEYUP, .wParam = key, .lParam = lParam, .expected_result = expected_result, }; } Win32Message WmCharInfo::Build(LRESULT expected_result) { LPARAM lParam = (repeat_count << 0) | (scan_code << 16) | (extended << 24) | (bit25 << 25) | (context << 29) | (prev_state << 30) | (transition << 31); return Win32Message{ .message = WM_CHAR, .wParam = char_code, .lParam = lParam, .expected_result = expected_result, }; } Win32Message WmSysKeyDownInfo::Build(LRESULT expected_result) { LPARAM lParam = (repeat_count << 0) | (scan_code << 16) | (extended << 24) | (context << 29) | (prev_state << 30) | (0 /* transition */ << 31); return Win32Message{ .message = WM_SYSKEYDOWN, .wParam = key, .lParam = lParam, .expected_result = expected_result, }; } Win32Message WmSysKeyUpInfo::Build(LRESULT expected_result) { LPARAM lParam = (1 /* repeat_count */ << 0) | (scan_code << 16) | (extended << 24) | (context << 29) | (1 /* prev_state */ << 30) | (1 /* transition */ << 31); return Win32Message{ .message = WM_SYSKEYUP, .wParam = key, .lParam = lParam, .expected_result = expected_result, }; } Win32Message WmDeadCharInfo::Build(LRESULT expected_result) { LPARAM lParam = (repeat_count << 0) | (scan_code << 16) | (extended << 24) | (context << 30) | (prev_state << 30) | (transition << 31); return Win32Message{ .message = WM_DEADCHAR, .wParam = char_code, .lParam = lParam, .expected_result = expected_result, }; } } // namespace testing } // namespace flutter
engine/shell/platform/windows/testing/wm_builders.cc/0
{ "file_path": "engine/shell/platform/windows/testing/wm_builders.cc", "repo_id": "engine", "token_count": 1114 }
385
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/windows_lifecycle_manager.h" #include "flutter/shell/platform/windows/testing/windows_test.h" #include "gtest/gtest.h" namespace flutter { namespace testing { class WindowsLifecycleManagerTest : public WindowsTest {}; TEST_F(WindowsLifecycleManagerTest, StateTransitions) { WindowsLifecycleManager manager(nullptr); HWND win1 = reinterpret_cast<HWND>(1); HWND win2 = reinterpret_cast<HWND>(2); // Hidden to inactive upon window shown. manager.SetLifecycleState(AppLifecycleState::kHidden); manager.OnWindowStateEvent(win1, WindowStateEvent::kShow); EXPECT_EQ(manager.GetLifecycleState(), AppLifecycleState::kInactive); // Showing a second window does not change state. manager.OnWindowStateEvent(win2, WindowStateEvent::kShow); EXPECT_EQ(manager.GetLifecycleState(), AppLifecycleState::kInactive); // Inactive to resumed upon window focus. manager.OnWindowStateEvent(win2, WindowStateEvent::kFocus); EXPECT_EQ(manager.GetLifecycleState(), AppLifecycleState::kResumed); // Showing a second window does not change state. manager.OnWindowStateEvent(win1, WindowStateEvent::kFocus); EXPECT_EQ(manager.GetLifecycleState(), AppLifecycleState::kResumed); // Unfocusing one window does not change state while another is focused. manager.OnWindowStateEvent(win1, WindowStateEvent::kUnfocus); EXPECT_EQ(manager.GetLifecycleState(), AppLifecycleState::kResumed); // Unfocusing final remaining focused window transitions to inactive. manager.OnWindowStateEvent(win2, WindowStateEvent::kUnfocus); EXPECT_EQ(manager.GetLifecycleState(), AppLifecycleState::kInactive); // Hiding one of two visible windows does not change state. manager.OnWindowStateEvent(win2, WindowStateEvent::kHide); EXPECT_EQ(manager.GetLifecycleState(), AppLifecycleState::kInactive); // Hiding only visible window transitions to hidden. manager.OnWindowStateEvent(win1, WindowStateEvent::kHide); EXPECT_EQ(manager.GetLifecycleState(), AppLifecycleState::kHidden); // Transition directly from resumed to hidden when the window is hidden. manager.OnWindowStateEvent(win1, WindowStateEvent::kShow); manager.OnWindowStateEvent(win1, WindowStateEvent::kFocus); manager.OnWindowStateEvent(win1, WindowStateEvent::kHide); EXPECT_EQ(manager.GetLifecycleState(), AppLifecycleState::kHidden); } } // namespace testing } // namespace flutter
engine/shell/platform/windows/windows_lifecycle_manager_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/windows_lifecycle_manager_unittests.cc", "repo_id": "engine", "token_count": 790 }
386
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/build/dart/dart.gni") declare_args() { engine_version = "" skia_version = "" dart_version = "" } _flutter_root = "//flutter" assert(engine_version != "", "The engine_version argument must be supplied") assert(skia_version != "", "The skia_version argument must be supplied") assert(dart_version != "", "The dart_version argument must be supplied")
engine/shell/version/version.gni/0
{ "file_path": "engine/shell/version/version.gni", "repo_id": "engine", "token_count": 166 }
387
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/build/dart/rules.gni") import("//flutter/lib/ui/dart_ui.gni") import("//flutter/web_sdk/web_sdk.gni") import("$dart_src/sdk/lib/_http/http_sources.gni") import("$dart_src/sdk/lib/_internal/js_runtime/interceptors_sources.gni") import("$dart_src/sdk/lib/_internal/js_shared/js_types_sources.gni") import("$dart_src/sdk/lib/_internal/vm/lib/vm_internal.gni") import("$dart_src/sdk/lib/async/async_sources.gni") import("$dart_src/sdk/lib/collection/collection_sources.gni") import("$dart_src/sdk/lib/convert/convert_sources.gni") import("$dart_src/sdk/lib/core/core_sources.gni") import("$dart_src/sdk/lib/developer/developer_sources.gni") import("$dart_src/sdk/lib/ffi/ffi_sources.gni") import("$dart_src/sdk/lib/html/html_sources.gni") import("$dart_src/sdk/lib/internal/internal_sources.gni") import("$dart_src/sdk/lib/io/io_sources.gni") import("$dart_src/sdk/lib/isolate/isolate_sources.gni") import("$dart_src/sdk/lib/js/js_annotations_sources.gni") import("$dart_src/sdk/lib/js/js_sources.gni") import("$dart_src/sdk/lib/js_interop/js_interop_sources.gni") import("$dart_src/sdk/lib/js_interop_unsafe/js_interop_unsafe_sources.gni") import("$dart_src/sdk/lib/js_util/js_util_sources.gni") import("$dart_src/sdk/lib/math/math_sources.gni") import("$dart_src/sdk/lib/typed_data/typed_data_sources.gni") if (is_fuchsia) { import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") } else { copy("copy_sky_engine_authors") { sources = [ "//AUTHORS" ] outputs = [ "$root_gen_dir/dart-pkg/sky_engine/{{source_file_part}}" ] } } dart_sdk_lib_path = rebase_path("$dart_src/sdk/lib") copy("async") { lib_path = rebase_path("async", "", dart_sdk_lib_path) sources = rebase_path(async_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/async/{{source_file_part}}" ] } copy("collection") { lib_path = rebase_path("collection", "", dart_sdk_lib_path) sources = rebase_path(collection_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/collection/{{source_file_part}}", ] } copy("convert") { lib_path = rebase_path("convert", "", dart_sdk_lib_path) sources = rebase_path(convert_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/convert/{{source_file_part}}" ] } copy("core") { lib_path = rebase_path("core", "", dart_sdk_lib_path) sources = rebase_path(core_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/core/{{source_file_part}}" ] } copy("developer") { lib_path = rebase_path("developer", "", dart_sdk_lib_path) sources = rebase_path(developer_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/developer/{{source_file_part}}" ] } copy("_http") { lib_path = rebase_path("_http", "", dart_sdk_lib_path) sources = rebase_path(http_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/_http/{{source_file_part}}" ] } copy("_interceptors") { lib_path = rebase_path("_internal/js_runtime", "", dart_sdk_lib_path) sources = rebase_path(interceptors_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/_interceptors/{{source_file_part}}", ] } copy("_js_annotations") { lib_path = rebase_path("js", "", dart_sdk_lib_path) sources = rebase_path(js_annotations_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/_js_annotations/{{source_file_part}}" ] } copy("_js_types") { lib_path = rebase_path("_internal/js_shared", "", dart_sdk_lib_path) sources = rebase_path(js_types_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/_js_types/{{source_file_part}}" ] } copy("internal") { lib_path = rebase_path("internal", "", dart_sdk_lib_path) sources = rebase_path(internal_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/internal/{{source_file_part}}" ] } copy("vm_internal") { lib_path = rebase_path("_internal/vm/lib/", "", dart_sdk_lib_path) sources = rebase_path(vm_internal_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/_internal/vm/lib/{{source_file_part}}" ] } copy("io") { lib_path = rebase_path("io", "", dart_sdk_lib_path) sources = rebase_path(io_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/io/{{source_file_part}}" ] } copy("ffi") { lib_path = rebase_path("ffi", "", dart_sdk_lib_path) sources = rebase_path(ffi_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/ffi/{{source_file_part}}" ] } copy("html") { lib_path = rebase_path("html", "", dart_sdk_lib_path) sources = rebase_path(html_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/html/{{source_file_part}}" ] } copy("isolate") { lib_path = rebase_path("isolate", "", dart_sdk_lib_path) sources = rebase_path(isolate_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/isolate/{{source_file_part}}" ] } copy("js") { lib_path = rebase_path("js", "", dart_sdk_lib_path) sources = rebase_path(js_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/js/{{source_file_part}}" ] } copy("js_interop") { lib_path = rebase_path("js_interop", "", dart_sdk_lib_path) sources = rebase_path(js_interop_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/js_interop/{{source_file_part}}", ] } copy("js_interop_unsafe") { lib_path = rebase_path("js_interop_unsafe", "", dart_sdk_lib_path) sources = rebase_path(js_interop_unsafe_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/js_interop_unsafe/{{source_file_part}}" ] } copy("js_util") { lib_path = rebase_path("js_util", "", dart_sdk_lib_path) sources = rebase_path(js_util_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/js_util/{{source_file_part}}" ] } copy("math") { lib_path = rebase_path("math", "", dart_sdk_lib_path) sources = rebase_path(math_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/math/{{source_file_part}}" ] } copy("typed_data") { lib_path = rebase_path("typed_data", "", dart_sdk_lib_path) sources = rebase_path(typed_data_sdk_sources, "", lib_path) outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/typed_data/{{source_file_part}}", ] } copy("copy_dart_ui") { sources = dart_ui_files outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/ui/{{source_file_part}}" ] } web_ui_ui_web_with_output("copy_dart_ui_web") { output_dir = "$root_gen_dir/dart-pkg/sky_engine/lib/ui_web/" } copy("copy_allowed_experiments") { sources = [ "$dart_src/sdk/lib/_internal/allowed_experiments.json" ] outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/_internal/allowed_experiments.json", ] } group("copy_dart_sdk") { deps = [ ":_http", ":_interceptors", ":_js_annotations", ":_js_types", ":async", ":collection", ":convert", ":copy_allowed_experiments", ":core", ":developer", ":ffi", ":html", ":internal", ":io", ":isolate", ":js", ":js_interop", ":js_interop_unsafe", ":js_util", ":math", ":typed_data", ":vm_internal", ] } generated_file("_embedder_yaml") { outputs = [ "$root_gen_dir/dart-pkg/sky_engine/lib/_embedder.yaml" ] contents = [ "# This file is generated by //flutter/sky/packages/sky_engine:_embedder_yaml", "# Do not modify this file directly. Instead, update the build file.", "", "embedded_libs:", " \"dart:async\": \"async/async.dart\"", " \"dart:collection\": \"collection/collection.dart\"", " \"dart:convert\": \"convert/convert.dart\"", " \"dart:core\": \"core/core.dart\"", " \"dart:developer\": \"developer/developer.dart\"", " \"dart:ffi\": \"ffi/ffi.dart\"", " \"dart:html\": \"html/html_dart2js.dart\"", " \"dart:io\": \"io/io.dart\"", " \"dart:isolate\": \"isolate/isolate.dart\"", " \"dart:js\": \"js/js.dart\"", " \"dart:js_interop\": \"js_interop/js_interop.dart\"", " \"dart:js_interop_unsafe\": \"js_interop_unsafe/js_interop_unsafe.dart\"", " \"dart:js_util\": \"js_util/js_util.dart\"", " \"dart:math\": \"math/math.dart\"", " \"dart:typed_data\": \"typed_data/typed_data.dart\"", " \"dart:ui\": \"ui/ui.dart\"", " \"dart:ui_web\": \"ui_web/ui_web.dart\"", "", " \"dart:_http\": \"_http/http.dart\"", " \"dart:_interceptors\": \"_interceptors/interceptors.dart\"", " # The _internal library is needed as some implementations bleed into the", " # public API, e.g. List being Iterable by virtue of implementing", " # EfficientLengthIterable. Not including this library yields analysis errors.", " \"dart:_internal\": \"internal/internal.dart\"", " # The _js_annotations library is also needed for the same reasons as _internal.", " \"dart:_js_annotations\": \"_js_annotations/_js_annotations.dart\"", " # The _js_types library is also needed for the same reasons as _internal.", " \"dart:_js_types\": \"_js_types/js_types.dart\"", " \"dart:nativewrappers\": \"_empty.dart\"", ] } action("sky_engine") { package_name = "sky_engine" pkg_directory = rebase_path("$root_gen_dir/dart-pkg") package_root = rebase_path("$root_gen_dir/dart-pkg/packages") stamp_file = "$root_gen_dir/dart-pkg/${package_name}.stamp" entries_file = "$root_gen_dir/dart-pkg/${package_name}.entries" sources = [ "LICENSE", "README.md", "lib/_empty.dart", "pubspec.yaml", ] deps = [ ":_embedder_yaml", ":copy_dart_sdk", ":copy_dart_ui", ":copy_dart_ui_web", ] if (!is_fuchsia) { deps += [ ":copy_sky_engine_authors" ] } service_isolate_dir = "$dart_src/sdk/lib/_internal/vm/bin/" sdk_ext_directory = [ "$root_gen_dir/sky/bindings" ] sdk_ext_files = [ "$service_isolate_dir/vmservice_io.dart", "$service_isolate_dir/vmservice_server.dart", ] outputs = [ "$root_gen_dir/dart-pkg/${package_name}", "$root_gen_dir/dart-pkg/${package_name}/pubspec.yaml", "$root_gen_dir/dart-pkg/packages/${package_name}", stamp_file, ] script = rebase_path("//flutter/build/dart/tools/dart_pkg.py", ".", "//") inputs = [ script ] + rebase_path(sources) args = [ "--package-name", package_name, "--dart-sdk", rebase_path(dart_sdk_root), "--pkg-directory", pkg_directory, "--package-root", package_root, "--stamp-file", rebase_path(stamp_file), "--entries-file", rebase_path(entries_file), "--package-sources", ] + rebase_path(sources) + [ "--sdk-ext-directories" ] + rebase_path(sdk_ext_directory) + [ "--sdk-ext-files" ] + rebase_path(sdk_ext_files) + [ "--sdk-ext-mappings" ] }
engine/sky/packages/sky_engine/BUILD.gn/0
{ "file_path": "engine/sky/packages/sky_engine/BUILD.gn", "repo_id": "engine", "token_count": 5004 }
388
python_version: "2.7" # Used by: # auth.py # gerrit_util.py # git_cl.py # my_activity.py # TODO(crbug.com/1002153): Add ninjalog_uploader.py wheel: < name: "infra/python/wheels/httplib2-py2_py3" version: "version:0.10.3" > # Used by: # my_activity.py wheel: < name: "infra/python/wheels/python-dateutil-py2_py3" version: "version:2.7.3" > wheel: < name: "infra/python/wheels/six-py2_py3" version: "version:1.10.0" > # Used by: # tests/auth_test.py # tests/detect_host_arch_test.py # tests/gclient_scm_test.py # tests/gclient_test.py # tests/gclient_utils_test.py # tests/gerrit_util_test.py # tests/git_cl_test.py # tests/git_drover_test.py # tests/git_footers_test.py # tests/metrics_test.py # tests/presubmit_unittest.py # tests/scm_unittest.py # tests/subprocess2_test.py # tests/watchlists_unittest.py wheel: < name: "infra/python/wheels/mock-py2_py3" version: "version:2.0.0" > wheel < name: "infra/python/wheels/funcsigs-py2_py3" version: "version:1.0.2" > wheel: < name: "infra/python/wheels/pbr-py2_py3" version: "version:3.0.0" > wheel: < name: "infra/python/wheels/six-py2_py3" version: "version:1.10.0" >
engine/testing/.vpython/0
{ "file_path": "engine/testing/.vpython", "repo_id": "engine", "token_count": 577 }
389
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_TESTING_ASSERTIONS_H_ #define FLUTTER_TESTING_ASSERTIONS_H_ #include <type_traits> namespace flutter { namespace testing { inline bool NumberNear(double a, double b) { static const double epsilon = 1e-3; return (a > (b - epsilon)) && (a < (b + epsilon)); } } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_ASSERTIONS_H_
engine/testing/assertions.h/0
{ "file_path": "engine/testing/assertions.h", "repo_id": "engine", "token_count": 188 }
390
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/build/dart/rules.gni") tests = [ "assets_test.dart", "canvas_test.dart", "channel_buffers_test.dart", "codec_test.dart", "color_filter_test.dart", "color_test.dart", "compositing_test.dart", "dart_test.dart", "encoding_test.dart", "fragment_shader_test.dart", "geometry_test.dart", "gesture_settings_test.dart", "gpu_test.dart", "gradient_test.dart", "http_allow_http_connections_test.dart", "http_disallow_http_connections_test.dart", "image_descriptor_test.dart", "image_dispose_test.dart", "image_events_test.dart", "image_filter_test.dart", "image_resize_test.dart", "image_shader_test.dart", "image_test.dart", "isolate_name_server_test.dart", "isolate_test.dart", "lerp_test.dart", "locale_test.dart", "mask_filter_test.dart", "painting_test.dart", "paragraph_builder_test.dart", "paragraph_test.dart", "path_test.dart", "picture_test.dart", "platform_dispatcher_test.dart", "platform_view_test.dart", "platform_isolate_test.dart", "platform_isolate_shutdown_test.dart", "plugin_utilities_test.dart", "semantics_test.dart", "serial_gc_test.dart", "spawn_helper.dart", "spawn_test.dart", "stringification_test.dart", "task_order_test.dart", "text_test.dart", "window_test.dart", ] foreach(test, tests) { flutter_build_dir = rebase_path("$root_gen_dir") flutter_src_dir = rebase_path("$root_out_dir/../../flutter") skia_gold_work_dir = rebase_path("$root_gen_dir/skia_gold_$test") flutter_frontend_server("compile_$test") { main_dart = test kernel_output = "$root_gen_dir/$test.dill" extra_args = [ "-DkFlutterSrcDirectory=$flutter_src_dir", "-DkFlutterBuildDirectory=$flutter_build_dir", "-DkSkiaGoldWorkDirectory=$skia_gold_work_dir", ] package_config = ".dart_tool/package_config.json" deps = [ "//flutter/third_party/txt:txt_fixtures" ] testonly = true } } group("dart") { testonly = true deps = [ "//flutter/testing/dart/observatory" ] foreach(test, tests) { deps += [ ":compile_$test" ] } }
engine/testing/dart/BUILD.gn/0
{ "file_path": "engine/testing/dart/BUILD.gn", "repo_id": "engine", "token_count": 957 }
391
// Copyright 2021 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:litetest/litetest.dart'; import 'http_disallow_http_connections_test.dart'; void main() { test('Normal HTTP request succeeds', () async { final String host = await getLocalHostIP(); await bindServerAndTest(host, (HttpClient httpClient, Uri uri) async { await httpClient.getUrl(uri); }); }); test('We can ban HTTP explicitly.', () async { final String host = await getLocalHostIP(); await bindServerAndTest(host, (HttpClient httpClient, Uri uri) async { asyncExpectThrows<UnsupportedError>( () async => runZoned(() => httpClient.getUrl(uri), zoneValues: <dynamic, dynamic>{#flutter.io.allow_http: false})); }); }); }
engine/testing/dart/http_allow_http_connections_test.dart/0
{ "file_path": "engine/testing/dart/http_allow_http_connections_test.dart", "repo_id": "engine", "token_count": 314 }
392
Tests in this folder need to be run with the observatory enabled, e.g. to make VM service method calls. The `run_tests.py` script disables the observatory for other tests in the parent directory.
engine/testing/dart/observatory/README.md/0
{ "file_path": "engine/testing/dart/observatory/README.md", "repo_id": "engine", "token_count": 52 }
393
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui'; import 'package:litetest/litetest.dart'; // The body of this file is the same as ../../lib/web_ui/test/engine/semantics/semantics_api_test.dart // Please keep them in sync. void main() { // This must match the number of flags in lib/ui/semantics.dart const int numSemanticsFlags = 28; test('SemanticsFlag.values refers to all flags.', () async { expect(SemanticsFlag.values.length, equals(numSemanticsFlags)); for (int index = 0; index < numSemanticsFlags; ++index) { final int flag = 1 << index; expect(SemanticsFlag.fromIndex(flag), isNotNull); expect(SemanticsFlag.fromIndex(flag).toString(), startsWith('SemanticsFlag.')); } }); // This must match the number of actions in lib/ui/semantics.dart const int numSemanticsActions = 22; test('SemanticsAction.values refers to all actions.', () async { expect(SemanticsAction.values.length, equals(numSemanticsActions)); for (int index = 0; index < numSemanticsActions; ++index) { final int flag = 1 << index; expect(SemanticsAction.fromIndex(flag), isNotNull); expect(SemanticsAction.fromIndex(flag).toString(), startsWith('SemanticsAction.')); } }); test('SpellOutStringAttribute.toString', () async { expect(SpellOutStringAttribute(range: const TextRange(start: 2, end: 5)).toString(), 'SpellOutStringAttribute(TextRange(start: 2, end: 5))'); }); test('LocaleStringAttribute.toString', () async { expect(LocaleStringAttribute(range: const TextRange(start: 2, end: 5), locale: const Locale('test')).toString(), 'LocaleStringAttribute(TextRange(start: 2, end: 5), test)'); }); }
engine/testing/dart/semantics_test.dart/0
{ "file_path": "engine/testing/dart/semantics_test.dart", "repo_id": "engine", "token_count": 588 }
394
// Copyright 2013 The Flutter 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_DISPLAY_LIST_TESTING_H_ #define FLUTTER_TESTING_DISPLAY_LIST_TESTING_H_ #include <ostream> #include "flutter/display_list/display_list.h" #include "flutter/display_list/dl_op_receiver.h" namespace flutter { namespace testing { bool DisplayListsEQ_Verbose(const DisplayList* a, const DisplayList* b); bool inline DisplayListsEQ_Verbose(const DisplayList& a, const DisplayList& b) { return DisplayListsEQ_Verbose(&a, &b); } bool inline DisplayListsEQ_Verbose(const sk_sp<const DisplayList>& a, const sk_sp<const DisplayList>& b) { return DisplayListsEQ_Verbose(a.get(), b.get()); } bool DisplayListsNE_Verbose(const DisplayList* a, const DisplayList* b); bool inline DisplayListsNE_Verbose(const DisplayList& a, const DisplayList& b) { return DisplayListsNE_Verbose(&a, &b); } bool inline DisplayListsNE_Verbose(const sk_sp<const DisplayList>& a, const sk_sp<const DisplayList>& b) { return DisplayListsNE_Verbose(a.get(), b.get()); } extern std::ostream& operator<<(std::ostream& os, const DisplayList& display_list); extern std::ostream& operator<<(std::ostream& os, const DlPaint& paint); extern std::ostream& operator<<(std::ostream& os, const DlBlendMode& mode); extern std::ostream& operator<<(std::ostream& os, const DlCanvas::ClipOp& op); extern std::ostream& operator<<(std::ostream& os, const DlCanvas::PointMode& op); extern std::ostream& operator<<(std::ostream& os, const DlCanvas::SrcRectConstraint& op); extern std::ostream& operator<<(std::ostream& os, const DlStrokeCap& cap); extern std::ostream& operator<<(std::ostream& os, const DlStrokeJoin& join); extern std::ostream& operator<<(std::ostream& os, const DlDrawStyle& style); extern std::ostream& operator<<(std::ostream& os, const DlBlurStyle& style); extern std::ostream& operator<<(std::ostream& os, const DlFilterMode& mode); extern std::ostream& operator<<(std::ostream& os, const DlColor& color); extern std::ostream& operator<<(std::ostream& os, DlImageSampling sampling); extern std::ostream& operator<<(std::ostream& os, const DlVertexMode& mode); extern std::ostream& operator<<(std::ostream& os, const DlTileMode& mode); extern std::ostream& operator<<(std::ostream& os, const DlImage* image); class DisplayListStreamDispatcher final : public DlOpReceiver { public: explicit DisplayListStreamDispatcher(std::ostream& os, int cur_indent = 2, int indent = 2) : os_(os), cur_indent_(cur_indent), indent_(indent) {} void setAntiAlias(bool aa) override; void setDrawStyle(DlDrawStyle style) override; void setColor(DlColor color) override; void setStrokeWidth(SkScalar width) override; void setStrokeMiter(SkScalar limit) override; void setStrokeCap(DlStrokeCap cap) override; void setStrokeJoin(DlStrokeJoin join) override; void setColorSource(const DlColorSource* source) override; void setColorFilter(const DlColorFilter* filter) override; void setInvertColors(bool invert) override; void setBlendMode(DlBlendMode mode) override; void setPathEffect(const DlPathEffect* effect) override; void setMaskFilter(const DlMaskFilter* filter) override; void setImageFilter(const DlImageFilter* filter) override; void save() override; void saveLayer(const SkRect& bounds, const SaveLayerOptions options, const DlImageFilter* backdrop) override; void restore() override; void translate(SkScalar tx, SkScalar ty) override; void scale(SkScalar sx, SkScalar sy) override; void rotate(SkScalar degrees) override; void skew(SkScalar sx, SkScalar sy) override; // clang-format off void transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myt) override; void transformFullPerspective( SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) override; // clang-format on void transformReset() override; void clipRect(const SkRect& rect, ClipOp clip_op, bool is_aa) override; void clipRRect(const SkRRect& rrect, ClipOp clip_op, bool is_aa) override; void clipPath(const SkPath& path, ClipOp clip_op, bool is_aa) override; void drawColor(DlColor color, DlBlendMode mode) override; void drawPaint() override; void drawLine(const SkPoint& p0, const SkPoint& p1) override; void drawRect(const SkRect& rect) override; void drawOval(const SkRect& bounds) override; void drawCircle(const SkPoint& center, SkScalar radius) override; void drawRRect(const SkRRect& rrect) override; void drawDRRect(const SkRRect& outer, const SkRRect& inner) override; void drawPath(const SkPath& path) override; void drawArc(const SkRect& oval_bounds, SkScalar start_degrees, SkScalar sweep_degrees, bool use_center) override; void drawPoints(PointMode mode, uint32_t count, const SkPoint points[]) override; void drawVertices(const DlVertices* vertices, DlBlendMode mode) override; void drawImage(const sk_sp<DlImage> image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) override; void drawImageRect(const sk_sp<DlImage> image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, bool render_with_attributes, SrcRectConstraint constraint) override; void drawImageNine(const sk_sp<DlImage> image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) override; void drawAtlas(const sk_sp<DlImage> atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const SkRect* cull_rect, bool render_with_attributes) override; void drawDisplayList(const sk_sp<DisplayList> display_list, SkScalar opacity) override; void drawTextBlob(const sk_sp<SkTextBlob> blob, SkScalar x, SkScalar y) override; void drawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame, SkScalar x, SkScalar y) override; void drawShadow(const SkPath& path, const DlColor color, const SkScalar elevation, bool transparent_occluder, SkScalar dpr) override; private: std::ostream& os_; int cur_indent_; int indent_; void indent() { indent(indent_); } void outdent() { outdent(indent_); } void indent(int spaces) { cur_indent_ += spaces; } void outdent(int spaces) { cur_indent_ -= spaces; } template <class T> std::ostream& out_array(std::string name, int count, const T array[]); std::ostream& startl(); void out(const DlColorFilter& filter); void out(const DlColorFilter* filter); void out(const DlImageFilter& filter); void out(const DlImageFilter* filter); }; } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_DISPLAY_LIST_TESTING_H_
engine/testing/display_list_testing.h/0
{ "file_path": "engine/testing/display_list_testing.h", "repo_id": "engine", "token_count": 3346 }
395
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_TESTING_MOCK_CANVAS_H_ #define FLUTTER_TESTING_MOCK_CANVAS_H_ #include <ostream> #include <variant> #include <vector> #include "flutter/display_list/dl_canvas.h" #include "flutter/display_list/utils/dl_matrix_clip_tracker.h" #include "gtest/gtest.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkCanvasVirtualEnforcer.h" #include "third_party/skia/include/core/SkClipOp.h" #include "third_party/skia/include/core/SkData.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkImageFilter.h" #include "third_party/skia/include/core/SkM44.h" #include "third_party/skia/include/core/SkPath.h" #include "third_party/skia/include/core/SkRRect.h" #include "third_party/skia/include/core/SkRect.h" #include "third_party/skia/include/utils/SkNWayCanvas.h" namespace flutter { namespace testing { static constexpr SkRect kEmptyRect = SkRect::MakeEmpty(); // Mock |SkCanvas|, useful for writing tests that use Skia but do not interact // with the GPU. // // The |MockCanvas| stores a list of |DrawCall| that the test can later verify // against the expected list of primitives to be drawn. class MockCanvas final : public DlCanvas { public: enum ClipEdgeStyle { kHardClipEdgeStyle, kSoftClipEdgeStyle, }; struct SaveData { int save_to_layer; }; struct SaveLayerData { SkRect save_bounds; DlPaint restore_paint; std::shared_ptr<DlImageFilter> backdrop_filter; int save_to_layer; }; struct RestoreData { int restore_to_layer; }; struct ConcatMatrixData { SkM44 matrix; }; struct SetMatrixData { SkM44 matrix; }; struct DrawRectData { SkRect rect; DlPaint paint; }; struct DrawPathData { SkPath path; DlPaint paint; }; struct DrawTextData { sk_sp<SkData> serialized_text; DlPaint paint; SkPoint offset; }; struct DrawImageDataNoPaint { sk_sp<DlImage> image; SkScalar x; SkScalar y; DlImageSampling options; }; struct DrawImageData { sk_sp<DlImage> image; SkScalar x; SkScalar y; DlImageSampling options; DlPaint paint; }; struct DrawDisplayListData { sk_sp<DisplayList> display_list; SkScalar opacity; }; struct DrawShadowData { SkPath path; DlColor color; SkScalar elevation; bool transparent_occluder; SkScalar dpr; }; struct ClipRectData { SkRect rect; ClipOp clip_op; ClipEdgeStyle style; }; struct ClipRRectData { SkRRect rrect; ClipOp clip_op; ClipEdgeStyle style; }; struct ClipPathData { SkPath path; ClipOp clip_op; ClipEdgeStyle style; }; struct DrawPaintData { DlPaint paint; }; // Discriminated union of all the different |DrawCall| types. It is roughly // equivalent to the different methods in |SkCanvas|' public API. using DrawCallData = std::variant<SaveData, SaveLayerData, RestoreData, ConcatMatrixData, SetMatrixData, DrawRectData, DrawPathData, DrawTextData, DrawImageDataNoPaint, DrawImageData, DrawDisplayListData, DrawShadowData, ClipRectData, ClipRRectData, ClipPathData, DrawPaintData>; // A single call made against this canvas. struct DrawCall { int layer; DrawCallData data; }; MockCanvas(); MockCanvas(int width, int height); ~MockCanvas(); const std::vector<DrawCall>& draw_calls() const { return draw_calls_; } void reset_draw_calls() { draw_calls_.clear(); } SkISize GetBaseLayerSize() const override; SkImageInfo GetImageInfo() const override; void Save() override; void SaveLayer(const SkRect* bounds, const DlPaint* paint = nullptr, const DlImageFilter* backdrop = nullptr) override; void Restore() override; int GetSaveCount() const { return current_layer_; } void RestoreToCount(int restore_count) { while (current_layer_ > restore_count) { Restore(); } } // clang-format off // 2x3 2D affine subset of a 4x4 transform in row major order void Transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myt) override; // full 4x4 transform in row major order void TransformFullPerspective( SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) override; // clang-format on void Translate(SkScalar tx, SkScalar ty) override; void Scale(SkScalar sx, SkScalar sy) override; void Rotate(SkScalar degrees) override; void Skew(SkScalar sx, SkScalar sy) override; void TransformReset() override; void Transform(const SkMatrix* matrix) override; void Transform(const SkM44* matrix44) override; void SetTransform(const SkMatrix* matrix) override; void SetTransform(const SkM44* matrix44) override; using DlCanvas::SetTransform; using DlCanvas::Transform; SkM44 GetTransformFullPerspective() const override; SkMatrix GetTransform() const override; void ClipRect(const SkRect& rect, ClipOp clip_op, bool is_aa) override; void ClipRRect(const SkRRect& rrect, ClipOp clip_op, bool is_aa) override; void ClipPath(const SkPath& path, ClipOp clip_op, bool is_aa) override; SkRect GetDestinationClipBounds() const override; SkRect GetLocalClipBounds() const override; bool QuickReject(const SkRect& bounds) const override; void DrawPaint(const DlPaint& paint) override; void DrawColor(DlColor color, DlBlendMode mode) override; void DrawLine(const SkPoint& p0, const SkPoint& p1, const DlPaint& paint) override; void DrawRect(const SkRect& rect, const DlPaint& paint) override; void DrawOval(const SkRect& bounds, const DlPaint& paint) override; void DrawCircle(const SkPoint& center, SkScalar radius, const DlPaint& paint) override; void DrawRRect(const SkRRect& rrect, const DlPaint& paint) override; void DrawDRRect(const SkRRect& outer, const SkRRect& inner, const DlPaint& paint) override; void DrawPath(const SkPath& path, const DlPaint& paint) override; void DrawArc(const SkRect& bounds, SkScalar start, SkScalar sweep, bool useCenter, const DlPaint& paint) override; void DrawPoints(PointMode mode, uint32_t count, const SkPoint pts[], const DlPaint& paint) override; void DrawVertices(const DlVertices* vertices, DlBlendMode mode, const DlPaint& paint) override; void DrawImage(const sk_sp<DlImage>& image, const SkPoint point, DlImageSampling sampling, const DlPaint* paint = nullptr) override; void DrawImageRect( const sk_sp<DlImage>& image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, const DlPaint* paint = nullptr, SrcRectConstraint constraint = SrcRectConstraint::kFast) override; void DrawImageNine(const sk_sp<DlImage>& image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, const DlPaint* paint = nullptr) override; void DrawAtlas(const sk_sp<DlImage>& atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const SkRect* cullRect, const DlPaint* paint = nullptr) override; void DrawDisplayList(const sk_sp<DisplayList> display_list, SkScalar opacity) override; void DrawTextBlob(const sk_sp<SkTextBlob>& blob, SkScalar x, SkScalar y, const DlPaint& paint) override; void DrawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame, SkScalar x, SkScalar y, const DlPaint& paint) override; void DrawShadow(const SkPath& path, const DlColor color, const SkScalar elevation, bool transparent_occluder, SkScalar dpr) override; void Flush() override; private: DisplayListMatrixClipTracker tracker_; std::vector<DrawCall> draw_calls_; int current_layer_; }; extern bool operator==(const MockCanvas::SaveData& a, const MockCanvas::SaveData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::SaveData& data); extern bool operator==(const MockCanvas::SaveLayerData& a, const MockCanvas::SaveLayerData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::SaveLayerData& data); extern bool operator==(const MockCanvas::RestoreData& a, const MockCanvas::RestoreData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::RestoreData& data); extern bool operator==(const MockCanvas::ConcatMatrixData& a, const MockCanvas::ConcatMatrixData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::ConcatMatrixData& data); extern bool operator==(const MockCanvas::SetMatrixData& a, const MockCanvas::SetMatrixData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::SetMatrixData& data); extern bool operator==(const MockCanvas::DrawRectData& a, const MockCanvas::DrawRectData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawRectData& data); extern bool operator==(const MockCanvas::DrawPathData& a, const MockCanvas::DrawPathData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawPathData& data); extern bool operator==(const MockCanvas::DrawTextData& a, const MockCanvas::DrawTextData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawTextData& data); extern bool operator==(const MockCanvas::DrawImageData& a, const MockCanvas::DrawImageData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawImageData& data); extern bool operator==(const MockCanvas::DrawImageDataNoPaint& a, const MockCanvas::DrawImageDataNoPaint& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawImageDataNoPaint& data); extern bool operator==(const MockCanvas::DrawDisplayListData& a, const MockCanvas::DrawDisplayListData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawDisplayListData& data); extern bool operator==(const MockCanvas::DrawShadowData& a, const MockCanvas::DrawShadowData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawShadowData& data); extern bool operator==(const MockCanvas::ClipRectData& a, const MockCanvas::ClipRectData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::ClipRectData& data); extern bool operator==(const MockCanvas::ClipRRectData& a, const MockCanvas::ClipRRectData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::ClipRRectData& data); extern bool operator==(const MockCanvas::ClipPathData& a, const MockCanvas::ClipPathData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::ClipPathData& data); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawCallData& data); extern bool operator==(const MockCanvas::DrawCall& a, const MockCanvas::DrawCall& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawCall& draw); extern bool operator==(const MockCanvas::DrawPaintData& a, const MockCanvas::DrawPaintData& b); extern std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawPaintData& data); } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_MOCK_CANVAS_H_
engine/testing/mock_canvas.h/0
{ "file_path": "engine/testing/mock_canvas.h", "repo_id": "engine", "token_count": 6255 }
396
#!/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. """ Invokes //gradle for building the Android apps from GN/Ninja. """ import os import sys import subprocess import platform SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)) BAT = '.bat' if sys.platform.startswith(('cygwin', 'win')) else '' GRADLE_BIN = os.path.normpath( os.path.join(SCRIPT_PATH, '..', '..', '..', 'third_party', 'gradle', 'bin', 'gradle%s' % BAT) ) ANDROID_HOME = os.path.normpath( os.path.join(SCRIPT_PATH, '..', '..', '..', 'third_party', 'android_tools', 'sdk') ) if platform.system() == 'Darwin': JAVA_HOME = os.path.normpath( os.path.join( SCRIPT_PATH, '..', '..', '..', 'third_party', 'java', 'openjdk', 'Contents', 'Home' ) ) else: JAVA_HOME = os.path.normpath( os.path.join(SCRIPT_PATH, '..', '..', '..', 'third_party', 'java', 'openjdk') ) def main(): if not os.path.isdir(ANDROID_HOME): raise Exception('%s (ANDROID_HOME) is not a directory' % ANDROID_HOME) android_dir = sys.argv[1] subprocess.check_output( args=[GRADLE_BIN] + sys.argv[2:], cwd=android_dir, env=dict(os.environ, ANDROID_HOME=ANDROID_HOME, JAVA_HOME=JAVA_HOME), ) return 0 if __name__ == '__main__': sys.exit(main())
engine/testing/rules/run_gradle.py/0
{ "file_path": "engine/testing/rules/run_gradle.py", "repo_id": "engine", "token_count": 585 }
397
// Copyright 2013 The Flutter 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; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.test.runner.AndroidJUnitRunner; import dev.flutter.scenariosui.ScreenshotUtil; import io.flutter.FlutterInjector; import io.flutter.embedding.engine.renderer.FlutterRenderer; public class TestRunner extends AndroidJUnitRunner { @Override public void onCreate(@Nullable Bundle arguments) { String[] engineArguments = null; assert arguments != null; if ("true".equals(arguments.getString("enable-impeller"))) { // Set up the global settings object so that Impeller is enabled for all tests. engineArguments = new String[] { "--enable-impeller=true", "--impeller-backend=" + arguments.getString("impeller-backend", "vulkan") }; } if ("true".equals(arguments.getString("force-surface-producer-surface-texture"))) { // Set a test flag to force the SurfaceProducer to use SurfaceTexture. FlutterRenderer.debugForceSurfaceProducerGlTextures = true; } // For consistency, just always initilaize FlutterJNI etc. FlutterInjector.instance().flutterLoader().startInitialization(getTargetContext()); FlutterInjector.instance() .flutterLoader() .ensureInitializationComplete(getTargetContext(), engineArguments); ScreenshotUtil.onCreate(); super.onCreate(arguments); } @Override public void finish(int resultCode, @Nullable Bundle results) { ScreenshotUtil.finish(); super.finish(resultCode, results); } }
engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/TestRunner.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/TestRunner.java", "repo_id": "engine", "token_count": 584 }
398
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="dev.flutter.scenarios"> <uses-permission android:name="android.permission.INTERNET" /> <application android:name="io.flutter.app.FlutterApplication" android:label="Scenarios App" android:supportsRtl="true" android:theme="@style/AppTheme" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/extraction_config_11_and_below" tools:ignore="UnusedAttribute"> <!-- Unused attribute to ignore dataExtractionRules and fullBackupContent --> <activity android:name=".PlatformViewsActivity" 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> <activity android:name=".SpawnedEngineActivity" 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="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SpawnMultiEngineActivity" 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="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ExternalTextureFlutterActivity" 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="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".StrictModeFlutterActivity" android:launchMode="singleTop" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:exported="true"> <intent-filter> <!-- TODO: https://github.com/flutter/flutter/issues/60635 --> <action android:name="dev.flutter.scenarios.STRICT_MODE" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".GetBitmapActivity" 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="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
engine/testing/scenario_app/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "engine/testing/scenario_app/android/app/src/main/AndroidManifest.xml", "repo_id": "engine", "token_count": 2065 }
399
<!-- Exclude all files from backup --> <full-backup-content> <exclude domain="root" path="."/> <exclude domain="file" path="."/> <exclude domain="database" path="."/> <exclude domain="sharedpref" path="."/> <exclude domain="external" path="."/> </full-backup-content>
engine/testing/scenario_app/android/app/src/main/res/xml/extraction_config_11_and_below.xml/0
{ "file_path": "engine/testing/scenario_app/android/app/src/main/res/xml/extraction_config_11_and_below.xml", "repo_id": "engine", "token_count": 104 }
400
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/build/dart/dart.gni") import("//flutter/testing/rules/runtime_mode.gni") import("$dart_src/build/dart/copy_tree.gni") _app_framework_dir = "$root_out_dir/scenario_app/Scenarios/App.framework" shared_library("app_framework_dylib") { visibility = [ ":*" ] output_name = "app" if (is_aot) { sources = [ "$target_gen_dir/snapshot_assembly.S" ] } else { sources = [ "app_stub.c" ] } ldflags = [ "-Wl,-install_name,@rpath/App.framework/App" ] deps = [ "//flutter/testing/scenario_app:scenario_app_snapshot" ] } copy("copy_dylib") { visibility = [ ":*" ] sources = [ "$root_out_dir/libapp.dylib" ] outputs = [ "$_app_framework_dir/App" ] deps = [ ":app_framework_dylib" ] } copy("copy_info_plist") { visibility = [ ":*" ] sources = [ "AppFrameworkInfo.plist" ] outputs = [ "$_app_framework_dir/Info.plist" ] } copy_trees("scenario_ios") { sources = [ { target = "copy_ios_xcodeproj" visibility = [ ":*" ] source = "." dest = "$root_out_dir/scenario_app" # Ignore any stale App.framework or Flutter.xcframework files from # historical builds. # This can eventually be set to "{}" when all CI builder caches have been # flushed that might still have these stale gitignored files from previous # build scripts. ignore_patterns = "*.*framework" }, ] } group("ios") { deps = [ ":app_framework_dylib", ":copy_dylib", ":copy_info_plist", ":copy_ios_xcodeproj", "//flutter/shell/platform/darwin/ios:flutter_framework", ] }
engine/testing/scenario_app/ios/BUILD.gn/0
{ "file_path": "engine/testing/scenario_app/ios/BUILD.gn", "repo_id": "engine", "token_count": 689 }
401
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "ShareViewController.h" @interface ShareViewController () @end @implementation ShareViewController - (instancetype)init { FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"FlutterControllerTest" project:nil]; [engine run]; self = [self initWithEngine:engine nibName:nil bundle:nil]; self.view.accessibilityIdentifier = @"flutter_view"; [engine.binaryMessenger setMessageHandlerOnChannel:@"waiting_for_status" binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply _Nonnull reply) { FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"driver" binaryMessenger:engine.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]; [channel invokeMethod:@"set_scenario" arguments:@{@"name" : @"app_extension"}]; }]; return self; } @end
engine/testing/scenario_app/ios/Scenarios/ScenariosShare/ShareViewController.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosShare/ShareViewController.m", "repo_id": "engine", "token_count": 421 }
402
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'dart:ui'; import 'package:vector_math/vector_math_64.dart'; import 'scenario.dart'; import 'scenarios.dart'; List<int> _to32(int value) { final Uint8List temp = Uint8List(4); temp.buffer.asByteData().setInt32(0, value, Endian.little); return temp; } List<int> _to64(num value) { final Uint8List temp = Uint8List(15); if (value is double) { temp.buffer.asByteData().setFloat64(7, value, Endian.little); } else if (value is int) { // ignore: avoid_double_and_int_checks temp.buffer.asByteData().setInt64(7, value, Endian.little); } return temp; } List<int> _encodeString(String value) { return <int>[ value.length, // This won't work if we use multi-byte characters. ...utf8.encode(value), ]; } /// A simple platform view. class PlatformViewScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewScenario( super.view, { required this.id, }); /// The platform view identifier. final int id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder(builder); } } /// A simple platform view. class NonFullScreenFlutterViewPlatformViewScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. NonFullScreenFlutterViewPlatformViewScenario( super.view, { required this.id, }); /// The platform view identifier. final int id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder(builder); } } /// A simple platform view with overlay that doesn't intersect with the platform view. class PlatformViewNoOverlayIntersectionScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewNoOverlayIntersectionScenario( super.view, { required this.id, }); /// The platform view identifier. final int id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder( builder, overlayOffset: const Offset(150, 350), ); } } /// A platform view that is larger than the display size. /// This is only applicable on Android while using virtual displays. /// Related issue: https://github.com/flutter/flutter/issues/28978. class PlatformViewLargerThanDisplaySize extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewLargerThanDisplaySize( super.view, { required this.id, }); /// The platform view identifier. final int id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, width: 15000, height: 60000, ); finishBuilder( builder, ); } } /// A simple platform view with an overlay that partially intersects with the platform view. class PlatformViewPartialIntersectionScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewPartialIntersectionScenario( super.view, { required this.id, }); /// The platform view identifier . final int id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder( builder, overlayOffset: const Offset(150, 240), ); } } /// A simple platform view with two overlays that intersect with each other and the platform view. class PlatformViewTwoIntersectingOverlaysScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewTwoIntersectingOverlaysScenario( super.view, { required this.id, }); /// The platform view identifier. final int id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawCircle( const Offset(50, 50), 50, Paint()..color = const Color(0xFFABCDEF), ); canvas.drawCircle( const Offset(100, 100), 50, Paint()..color = const Color(0xFFABCDEF), ); final Picture picture = recorder.endRecording(); builder.addPicture(const Offset(300, 300), picture); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// A simple platform view with one overlay and two overlays that intersect with each other and the platform view. class PlatformViewOneOverlayTwoIntersectingOverlaysScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewOneOverlayTwoIntersectingOverlaysScenario( super.view, { required this.id, }); /// The platform view identifier. final int id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawCircle( const Offset(50, 50), 50, Paint()..color = const Color(0xFFABCDEF), ); canvas.drawCircle( const Offset(100, 100), 50, Paint()..color = const Color(0xFFABCDEF), ); canvas.drawCircle( const Offset(-100, 200), 50, Paint()..color = const Color(0xFFABCDEF), ); final Picture picture = recorder.endRecording(); builder.addPicture(const Offset(300, 300), picture); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// Two platform views without an overlay intersecting either platform view. class MultiPlatformViewWithoutOverlaysScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. MultiPlatformViewWithoutOverlaysScenario( super.view, { required this.firstId, required this.secondId, }); /// The platform view identifier to use for the first platform view. final int firstId; /// The platform view identifier to use for the second platform view. final int secondId; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.pushOffset(0, 600); addPlatformView( firstId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 1', ); builder.pop(); addPlatformView( secondId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 2', ); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( const Rect.fromLTRB(0, 0, 100, 1000), Paint()..color = const Color(0xFFFF0000), ); final Picture picture = recorder.endRecording(); builder.addPicture(const Offset(580, 0), picture); builder.pop(); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// A simple platform view with too many overlays result in a single native view. class PlatformViewMaxOverlaysScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewMaxOverlaysScenario( super.view, { required this.id, }); /// The platform view identifier. final int id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawCircle( const Offset(50, 50), 50, Paint()..color = const Color(0xFFABCDEF), ); canvas.drawCircle( const Offset(100, 100), 50, Paint()..color = const Color(0xFFABCDEF), ); canvas.drawCircle( const Offset(-100, 200), 50, Paint()..color = const Color(0xFFABCDEF), ); canvas.drawCircle( const Offset(-100, -80), 50, Paint()..color = const Color(0xFFABCDEF), ); final Picture picture = recorder.endRecording(); builder.addPicture(const Offset(300, 300), picture); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// Builds a scene with 2 platform views. class MultiPlatformViewScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. MultiPlatformViewScenario( super.view, { required this.firstId, required this.secondId, }); /// The platform view identifier to use for the first platform view. final int firstId; /// The platform view identifier to use for the second platform view. final int secondId; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.pushOffset(0, 600); addPlatformView( firstId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 1', ); builder.pop(); addPlatformView( secondId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 2', ); finishBuilder(builder); } } /// Scenario for verifying platform views after background and foregrounding the app. /// /// Renders a frame with 2 platform views covered by a flutter drawn rectangle, /// when the app goes to the background and comes back to the foreground renders a new frame /// with the 2 platform views but without the flutter drawn rectangle. class MultiPlatformViewBackgroundForegroundScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. MultiPlatformViewBackgroundForegroundScenario( super.view, { required this.firstId, required this.secondId, }) { _nextFrame = _firstFrame; channelBuffers.setListener('flutter/lifecycle', _onPlatformMessage); } /// The platform view identifier to use for the first platform view. final int firstId; /// The platform view identifier to use for the second platform view. final int secondId; late void Function() _nextFrame; @override void onBeginFrame(Duration duration) { _nextFrame(); } void _firstFrame() { final SceneBuilder builder = SceneBuilder(); builder.pushOffset(50, 600); addPlatformView( firstId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 1', ); builder.pop(); builder.pushOffset(50, 0); addPlatformView( secondId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 2', ); builder.pop(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( const Rect.fromLTRB(0, 0, 500, 1000), Paint()..color = const Color(0xFFFF0000), ); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } void _secondFrame() { final SceneBuilder builder = SceneBuilder(); builder.pushOffset(0, 600); addPlatformView( firstId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 1', ); builder.pop(); addPlatformView( secondId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 2', ); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } String _lastLifecycleState = ''; void _onPlatformMessage( ByteData? data, PlatformMessageResponseCallback? callback, ) { final String message = utf8.decode(data!.buffer.asUint8List()); // The expected first event should be 'AppLifecycleState.resumed', but // occasionally it will receive 'AppLifecycleState.inactive' first. Skip // any messages until 'AppLifecycleState.resumed' is received. if (_lastLifecycleState.isEmpty && message != 'AppLifecycleState.resumed') { return; } if (_lastLifecycleState == 'AppLifecycleState.inactive' && message == 'AppLifecycleState.resumed') { _nextFrame = _secondFrame; view.platformDispatcher.scheduleFrame(); } _lastLifecycleState = message; } @override void unmount() { channelBuffers.clearListener('flutter/lifecycle'); super.unmount(); } } /// Platform view with clip rect. class PlatformViewClipRectScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Constructs a platform view with clip rect scenario. PlatformViewClipRectScenario( super.view, { required this.id, }); /// The platform view identifier. final int id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder() ..pushClipRect(const Rect.fromLTRB(100, 100, 400, 400)); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder(builder); } } /// Platform view with clip rect then the PlatformView is moved for 10 frames. /// /// The clip rect moves with the same transform matrix with the PlatformView. class PlatformViewClipRectAfterMovedScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Constructs a platform view with clip rect scenario. PlatformViewClipRectAfterMovedScenario( super.view, { required this.id, }); /// The platform view identifier. final int id; int _numberOfFrames = 0; double _y = 100.0; @override void onBeginFrame(Duration duration) { final Matrix4 translateMatrix = Matrix4.identity()..translate(0.0, _y); final SceneBuilder builder = SceneBuilder() ..pushTransform(translateMatrix.storage) ..pushClipRect(const Rect.fromLTRB(100, 100, 400, 400)); addPlatformView( _numberOfFrames == 10? 10000: id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); // Add a translucent rect that has the same size of PlatformView. final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( const Rect.fromLTWH(0, 0, 500, 500), Paint()..color = const Color(0x22FF0000), ); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); finishBuilder(builder); super.onBeginFrame(duration); } @override void onDrawFrame() { if (_numberOfFrames < 10) { _numberOfFrames ++; _y -= 10; view.platformDispatcher.scheduleFrame(); } super.onDrawFrame(); } } /// Platform view with clip rrect. class PlatformViewClipRRectScenario extends PlatformViewScenario { /// Constructs a platform view with clip rrect scenario. PlatformViewClipRRectScenario( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.pushClipRRect( RRect.fromLTRBAndCorners( 100, 100, 400, 400, topLeft: const Radius.circular(15), topRight: const Radius.circular(50), bottomLeft: const Radius.circular(50), ), ); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder(builder); } } /// Platform view with clip rrect. /// The bounding rect of the rrect is the same as PlatformView and only the corner radii clips the PlatformView. class PlatformViewLargeClipRRectScenario extends PlatformViewScenario { /// Constructs a platform view with large clip rrect scenario. PlatformViewLargeClipRRectScenario( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.pushClipRRect( RRect.fromLTRBAndCorners( 0, 0, 500, 500, topLeft: const Radius.circular(15), topRight: const Radius.circular(50), bottomLeft: const Radius.circular(50), ), ); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder(builder); } } /// Platform view with clip path. class PlatformViewClipPathScenario extends PlatformViewScenario { /// Constructs a platform view with clip path scenario. PlatformViewClipPathScenario( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final Path path = Path() ..moveTo(100, 100) ..quadraticBezierTo(50, 250, 100, 400) ..lineTo(350, 400) ..cubicTo(400, 300, 300, 200, 350, 100) ..close(); final SceneBuilder builder = SceneBuilder()..pushClipPath(path); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder(builder); } } /// Platform view with clip rect after transformed. class PlatformViewClipRectWithTransformScenario extends PlatformViewScenario { /// Constructs a platform view with clip rect with transform scenario. PlatformViewClipRectWithTransformScenario( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final Matrix4 matrix4 = Matrix4.identity() ..rotateZ(1) ..scale(0.5, 0.5, 1.0) ..translate(1000.0, 100.0); final SceneBuilder builder = SceneBuilder()..pushTransform(matrix4.storage); builder.pushClipRect(const Rect.fromLTRB(100, 100, 400, 400)); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); // Add a translucent rect that has the same size of PlatformView. final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( const Rect.fromLTWH(0, 0, 500, 500), Paint()..color = const Color(0x22FF0000), ); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); finishBuilder(builder); } } /// Platform view with clip rrect after transformed. class PlatformViewClipRRectWithTransformScenario extends PlatformViewScenario { /// Constructs a platform view with clip rrect with transform scenario. PlatformViewClipRRectWithTransformScenario( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final Matrix4 matrix4 = Matrix4.identity() ..rotateZ(1) ..scale(0.5, 0.5, 1.0) ..translate(1000.0, 100.0); final SceneBuilder builder = SceneBuilder()..pushTransform(matrix4.storage); builder.pushClipRRect( RRect.fromLTRBAndCorners( 100, 100, 400, 400, topLeft: const Radius.circular(15), topRight: const Radius.circular(50), bottomLeft: const Radius.circular(50), ), ); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); // Add a translucent rect that has the same size of PlatformView. final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( const Rect.fromLTWH(0, 0, 500, 500), Paint()..color = const Color(0x22FF0000), ); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); finishBuilder(builder); } } /// Platform view with clip rrect after transformed. /// The bounding rect of the rrect is the same as PlatformView and only the corner radii clips the PlatformView. class PlatformViewLargeClipRRectWithTransformScenario extends PlatformViewScenario { /// Constructs a platform view with large clip rrect with transform scenario. PlatformViewLargeClipRRectWithTransformScenario( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final Matrix4 matrix4 = Matrix4.identity() ..rotateZ(1) ..scale(0.5, 0.5, 1.0) ..translate(1000.0, 100.0); final SceneBuilder builder = SceneBuilder()..pushTransform(matrix4.storage); builder.pushClipRRect( RRect.fromLTRBAndCorners( 0, 0, 500, 500, topLeft: const Radius.circular(15), topRight: const Radius.circular(50), bottomLeft: const Radius.circular(50), ), ); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); // Add a translucent rect that has the same size of PlatformView. final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( const Rect.fromLTWH(0, 0, 500, 500), Paint()..color = const Color(0x22FF0000), ); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); finishBuilder(builder); } } /// Platform view with clip path after transformed. class PlatformViewClipPathWithTransformScenario extends PlatformViewScenario { /// Constructs a platform view with clip path with transform scenario. PlatformViewClipPathWithTransformScenario( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final Matrix4 matrix4 = Matrix4.identity() ..rotateZ(1) ..scale(0.5, 0.5, 1.0) ..translate(1000.0, 100.0); final SceneBuilder builder = SceneBuilder()..pushTransform(matrix4.storage); final Path path = Path() ..moveTo(100, 100) ..quadraticBezierTo(50, 250, 100, 400) ..lineTo(350, 400) ..cubicTo(400, 300, 300, 200, 350, 100) ..close(); builder.pushClipPath(path); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); // Add a translucent rect that has the same size of PlatformView. final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( const Rect.fromLTWH(0, 0, 500, 500), Paint()..color = const Color(0x22FF0000), ); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); finishBuilder(builder); } } /// Two platform views, both have clip rects class TwoPlatformViewClipRect extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. TwoPlatformViewClipRect( super.view, { required this.firstId, required this.secondId, }); /// The platform view identifier to use for the first platform view. final int firstId; /// The platform view identifier to use for the second platform view. final int secondId; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.pushOffset(0, 600); builder.pushClipRect(const Rect.fromLTRB(100, 100, 400, 400)); addPlatformView( firstId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 1', ); builder.pop(); builder.pop(); // Use a different rect to differentiate from the 1st clip rect. builder.pushClipRect(const Rect.fromLTRB(100, 100, 300, 300)); addPlatformView( secondId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 2', ); builder.pop(); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// Two platform views, both have clip rrects class TwoPlatformViewClipRRect extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. TwoPlatformViewClipRRect( super.view, { required this.firstId, required this.secondId, }); /// The platform view identifier to use for the first platform view. final int firstId; /// The platform view identifier to use for the second platform view. final int secondId; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.pushOffset(0, 600); builder.pushClipRRect( RRect.fromLTRBAndCorners( 0, 0, 500, 500, topLeft: const Radius.circular(15), topRight: const Radius.circular(50), bottomLeft: const Radius.circular(50), ), ); addPlatformView( firstId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 1', ); builder.pop(); builder.pop(); // Use a different rrect to differentiate from the 1st clip rrect. builder.pushClipRRect( RRect.fromLTRBAndCorners( 0, 0, 500, 500, topLeft: const Radius.circular(100), topRight: const Radius.circular(50), bottomLeft: const Radius.circular(50), ), ); addPlatformView( secondId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 2', ); builder.pop(); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// Two platform views, both have clip path class TwoPlatformViewClipPath extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. TwoPlatformViewClipPath( super.view, { required this.firstId, required this.secondId, }); /// The platform view identifier to use for the first platform view. final int firstId; /// The platform view identifier to use for the second platform view. final int secondId; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.pushOffset(0, 600); final Path path = Path() ..moveTo(100, 100) ..quadraticBezierTo(50, 250, 100, 400) ..lineTo(350, 400) ..cubicTo(400, 300, 300, 200, 350, 100) ..close(); builder.pushClipPath(path); addPlatformView( firstId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 1', ); builder.pop(); builder.pop(); // Use a different path to differentiate from the 1st clip path. final Path path2 = Path() ..moveTo(100, 100) ..quadraticBezierTo(100, 150, 100, 400) ..lineTo(350, 350) ..cubicTo(400, 300, 300, 200, 350, 200) ..close(); builder.pushClipPath(path2); addPlatformView( secondId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 2', ); builder.pop(); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// Platform view with transform. class PlatformViewTransformScenario extends PlatformViewScenario { /// Constructs a platform view with transform scenario. PlatformViewTransformScenario( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final Matrix4 matrix4 = Matrix4.identity() ..rotateZ(1) ..scale(0.5, 0.5, 1.0) ..translate(1000.0, 100.0); final SceneBuilder builder = SceneBuilder()..pushTransform(matrix4.storage); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder(builder); } } /// Platform view with opacity. class PlatformViewOpacityScenario extends PlatformViewScenario { /// Constructs a platform view with transform scenario. PlatformViewOpacityScenario( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder()..pushOpacity(150); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder(builder); } } /// A simple platform view for testing touch events from iOS. class PlatformViewForTouchIOSScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewForTouchIOSScenario( super.view, { this.id = 0, this.rejectUntilTouchesEnded = false, required this.accept, }) { _nextFrame = _firstFrame; } late void Function() _nextFrame; /// Whether gestures should be accepted or rejected. final bool accept; /// The platform view identifier. final int id; /// Whether touches should be rejected until the gesture ends. final bool rejectUntilTouchesEnded; @override void onBeginFrame(Duration duration) { _nextFrame(); } @override void onDrawFrame() { // Some iOS gesture recognizers bugs are introduced in the second frame (with a different platform view rect) after laying out the platform view. // So in this test, we load 2 frames to ensure that we cover those cases. // See https://github.com/flutter/flutter/issues/66044 if (_nextFrame == _firstFrame) { _nextFrame = _secondFrame; view.platformDispatcher.scheduleFrame(); } super.onDrawFrame(); } @override void onPointerDataPacket(PointerDataPacket packet) { if (packet.data.first.change == PointerChange.add) { String method = 'rejectGesture'; if (accept) { method = 'acceptGesture'; } const int valueString = 7; const int valueInt32 = 3; const int valueMap = 13; final Uint8List message = Uint8List.fromList(<int>[ valueString, ..._encodeString(method), valueMap, 1, valueString, ..._encodeString('id'), valueInt32, ..._to32(id), ]); view.platformDispatcher.sendPlatformMessage( 'flutter/platform_views', message.buffer.asByteData(), (ByteData? response) {}, ); } } void _firstFrame() { final SceneBuilder builder = SceneBuilder(); if (rejectUntilTouchesEnded) { addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, viewType: 'scenarios/textPlatformView_blockPolicyUntilTouchesEnded', ); } else { addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); } finishBuilder(builder); } void _secondFrame() { final SceneBuilder builder = SceneBuilder()..pushOffset(5, 5); if (rejectUntilTouchesEnded) { addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, viewType: 'scenarios/textPlatformView_blockPolicyUntilTouchesEnded', ); } else { addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); } finishBuilder(builder); } } /// Scenario for verifying overlapping platform views can accept touch gesture. /// See: https://github.com/flutter/flutter/issues/118366. /// /// Renders the first frame with a foreground platform view. /// Then renders the second frame with the foreground platform view covering /// a new background platform view. /// class PlatformViewForOverlappingPlatformViewsScenario extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformViewForOverlappingPlatformViewsScenario. PlatformViewForOverlappingPlatformViewsScenario( super.view, { required this.foregroundId, required this.backgroundId, }) { _nextFrame = _firstFrame; } /// The id for a foreground platform view that covers another background platform view. /// A good example is a dialog prompt in a real app. final int foregroundId; /// The id for a background platform view that is covered by a foreground platform view. final int backgroundId; late void Function() _nextFrame; @override void onBeginFrame(Duration duration) { _nextFrame(); } void _firstFrame() { final SceneBuilder builder = SceneBuilder(); builder.pushOffset(100, 100); addPlatformView( foregroundId, width: 100, height: 100, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'Foreground', ); builder.pop(); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } void _secondFrame() { final SceneBuilder builder = SceneBuilder(); builder.pushOffset(0, 0); addPlatformView( backgroundId, width: 300, height: 300, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'Background', ); builder.pop(); builder.pushOffset(100, 100); addPlatformView( foregroundId, width: 100, height: 100, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'Foreground', ); builder.pop(); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } int _frameCount = 0; @override void onDrawFrame() { _frameCount += 1; // TODO(hellohuanlin): Need further investigation - the first 2 frames are dropped for some reason. // Wait for 60 frames to ensure the first frame has actually been rendered // (Minimum required is 3 frames, but just to be safe) if (_nextFrame == _firstFrame && _frameCount == 60) { _nextFrame = _secondFrame; } view.platformDispatcher.scheduleFrame(); super.onDrawFrame(); } @override void onPointerDataPacket(PointerDataPacket packet) { final PointerData data = packet.data.first; final double x = data.physicalX; final double y = data.physicalY; if (data.change == PointerChange.up && 100 <= x && x < 200 && 100 <= y && y < 200) { const int valueString = 7; const int valueInt32 = 3; const int valueMap = 13; final Uint8List message = Uint8List.fromList(<int>[ valueString, ..._encodeString('acceptGesture'), valueMap, 1, valueString, ..._encodeString('id'), valueInt32, ..._to32(foregroundId), ]); view.platformDispatcher.sendPlatformMessage( 'flutter/platform_views', message.buffer.asByteData(), (ByteData? response) {}, ); } } } /// A simple platform view for testing platform view with a continuous texture layer. /// For example, it simulates a video being played. class PlatformViewWithContinuousTexture extends PlatformViewScenario { /// Constructs a platform view with continuous texture layer. PlatformViewWithContinuousTexture( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.addTexture(0, width: 300, height: 300, offset: const Offset(200, 200)); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); finishBuilder(builder); } } /// A simple platform view for testing backDropFilter with a platform view in the scene. /// /// The stack would look like: picture 1-> filter -> picture 2 -> pv -> picture 3. And picture 1 should be filtered. /// /// Note it is not testing applying backDropFilter on a platform view. /// See: https://github.com/flutter/flutter/issues/80766 class PlatformViewWithOtherBackDropFilter extends PlatformViewScenario { /// Constructs the scenario. PlatformViewWithOtherBackDropFilter( super.view, { super.id = 0, }); @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); // This is just a background picture to make the result more viewable. canvas.drawRect( const Rect.fromLTRB(0, 0, 500, 400), Paint()..color = const Color(0xFFFF0000), ); // This rect should look blur due to the backdrop filter. canvas.drawRect( const Rect.fromLTRB(0, 0, 300, 300), Paint()..color = const Color(0xFF00FF00), ); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); final ImageFilter filter = ImageFilter.blur(sigmaX: 8, sigmaY: 8); builder.pushBackdropFilter(filter); final PictureRecorder recorder2 = PictureRecorder(); final Canvas canvas2 = Canvas(recorder2); // This circle should not look blur. canvas2.drawCircle( const Offset(200, 100), 50, Paint()..color = const Color(0xFF0000EF), ); final Picture picture2 = recorder2.endRecording(); builder.addPicture(const Offset(100, 100), picture2); builder.pop(); builder.pushOffset(0, 600); addPlatformView( id, dispatcher: view.platformDispatcher, sceneBuilder: builder, ); builder.pop(); final PictureRecorder recorder3 = PictureRecorder(); final Canvas canvas3 = Canvas(recorder3); // Add another picture layer so an overlay UIView is created, which was // the root cause of the original issue. canvas3.drawCircle( const Offset(300, 200), 50, Paint()..color = const Color(0xFF0000EF), ); final Picture picture3 = recorder3.endRecording(); builder.addPicture(const Offset(100, 100), picture3); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// A simple platform view for testing backDropFilter with a platform view in the scene. /// /// The stack would look like: picture 1 -> pv1 -> picture 2 -> filter -> pv2 - > picture 3. class TwoPlatformViewsWithOtherBackDropFilter extends Scenario with _BasePlatformViewScenarioMixin { /// Constructs the scenario. TwoPlatformViewsWithOtherBackDropFilter( super.view, { required int firstId, required int secondId, }) : _firstId = firstId, _secondId = secondId; final int _firstId; final int _secondId; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); // This is just a background picture to make the result more viewable. canvas.drawRect( const Rect.fromLTRB(0, 0, 600, 1000), Paint()..color = const Color(0xFFFF0000), ); // This rect should look blur due to the backdrop filter. canvas.drawRect( const Rect.fromLTRB(0, 0, 300, 300), Paint()..color = const Color(0xFF00FF00), ); final Picture picture1 = recorder.endRecording(); builder.addPicture(Offset.zero, picture1); builder.pushOffset(0, 200); addPlatformView( _firstId, dispatcher: view.platformDispatcher, sceneBuilder: builder, width: 100, height: 100, text: 'platform view 1' ); final PictureRecorder recorder2 = PictureRecorder(); final Canvas canvas2 = Canvas(recorder2); // This circle should look blur due to the backdrop filter. canvas2.drawCircle( const Offset(200, 100), 50, Paint()..color = const Color(0xFF0000EF), ); final Picture picture2 = recorder2.endRecording(); builder.addPicture(const Offset(100, 100), picture2); final ImageFilter filter = ImageFilter.blur(sigmaX: 8, sigmaY: 8); builder.pushBackdropFilter(filter); builder.pushOffset(0, 600); addPlatformView( _secondId, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view 2', ); builder.pop(); builder.pop(); final PictureRecorder recorder3 = PictureRecorder(); final Canvas canvas3 = Canvas(recorder3); // Add another picture layer so an overlay UIView is created, which was // the root cause of the original issue. canvas3.drawCircle( const Offset(300, 200), 50, Paint()..color = const Color(0xFF0000EF), ); final Picture picture3 = recorder3.endRecording(); builder.addPicture(const Offset(100, 100), picture3); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// A simple platform view for testing backDropFilter with a platform view in the scene. /// /// The backdrop filter sigma value is negative, which tries to reproduce a crash, see: /// https://github.com/flutter/flutter/issues/127095 class PlatformViewWithNegativeBackDropFilter extends Scenario with _BasePlatformViewScenarioMixin { /// Constructs the scenario. PlatformViewWithNegativeBackDropFilter( super.view, { required int id, }) : _id = id; final int _id; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); // This is just a background picture to make the result more viewable. canvas.drawRect( const Rect.fromLTRB(0, 0, 600, 1000), Paint()..color = const Color(0xFFFF0000), ); canvas.drawRect( const Rect.fromLTRB(0, 0, 300, 300), Paint()..color = const Color(0xFF00FF00), ); final Picture picture1 = recorder.endRecording(); builder.addPicture(Offset.zero, picture1); builder.pushOffset(0, 200); addPlatformView( _id, dispatcher: view.platformDispatcher, sceneBuilder: builder, width: 100, height: 100, text: 'platform view 1' ); final PictureRecorder recorder2 = PictureRecorder(); final Canvas canvas2 = Canvas(recorder2); canvas2.drawCircle( const Offset(200, 100), 50, Paint()..color = const Color(0xFF0000EF), ); final Picture picture2 = recorder2.endRecording(); builder.addPicture(const Offset(100, 100), picture2); final ImageFilter filter = ImageFilter.blur(sigmaX: -8, sigmaY: 8); builder.pushBackdropFilter(filter); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// Builds a scenario where many platform views are scrolling and pass under a picture. class PlatformViewScrollingUnderWidget extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewScrollingUnderWidget( super.view, { required int firstPlatformViewId, required int lastPlatformViewId, }) : _firstPlatformViewId = firstPlatformViewId, _lastPlatformViewId = lastPlatformViewId; final int _firstPlatformViewId; final int _lastPlatformViewId; double _offset = 0; bool _movingUp = true; @override void onBeginFrame(Duration duration) { _buildOneFrame(_offset); } @override void onDrawFrame() { // Scroll up until -1000, then scroll down until -1. if (_offset < -1000) { _movingUp = false; } else if (_offset > -1) { _movingUp = true; } if (_movingUp) { _offset -= 100; } else { _offset += 100; } view.platformDispatcher.scheduleFrame(); super.onDrawFrame(); } Future<void> _buildOneFrame(double offset) async { const double cellWidth = 1000; double localOffset = offset; final SceneBuilder builder = SceneBuilder(); const double cellHeight = 300; for (int i = _firstPlatformViewId; i <= _lastPlatformViewId; i++) { // Build a list view with platform views. builder.pushOffset(0, localOffset); addPlatformView( i, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view $i', width: cellWidth, height: cellHeight, ); builder.pop(); localOffset += cellHeight; } // Add a "banner" that should display on top of the list view. final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( const Rect.fromLTRB(0, cellHeight, cellWidth, 100), Paint()..color = const Color(0xFFFF0000), ); final Picture picture = recorder.endRecording(); builder.addPicture(const Offset(0, 20), picture); final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } /// Builds a scenario where many platform views with clips scrolling. class PlatformViewsWithClipsScrolling extends Scenario with _BasePlatformViewScenarioMixin { /// Creates the PlatformView scenario. PlatformViewsWithClipsScrolling( super.view, { required int firstPlatformViewId, required int lastPlatformViewId, }) : _firstPlatformViewId = firstPlatformViewId, _lastPlatformViewId = lastPlatformViewId; final int _firstPlatformViewId; final int _lastPlatformViewId; double _offset = 0; bool _movingUp = true; @override void onBeginFrame(Duration duration) { _buildOneFrame(_offset); } @override void onDrawFrame() { // Scroll up until -1000, then scroll down until -1. if (_offset < -500) { _movingUp = false; } else if (_offset > -1) { _movingUp = true; } if (_movingUp) { _offset -= 100; } else { _offset += 100; } view.platformDispatcher.scheduleFrame(); super.onDrawFrame(); } Future<void> _buildOneFrame(double offset) async { const double cellWidth = 1000; double localOffset = offset; final SceneBuilder builder = SceneBuilder(); const double cellHeight = 300; for (int i = _firstPlatformViewId; i <= _lastPlatformViewId; i++) { // Build a list view with platform views. builder.pushOffset(0, localOffset); bool addedClipRRect = false; if (localOffset > -1) { addedClipRRect = true; builder.pushClipRRect( RRect.fromLTRBAndCorners( 100, 100, 400, 400, topLeft: const Radius.circular(15), topRight: const Radius.circular(50), bottomLeft: const Radius.circular(50), ), ); } addPlatformView( i, dispatcher: view.platformDispatcher, sceneBuilder: builder, text: 'platform view $i', width: cellWidth, height: cellHeight, ); if (addedClipRRect) { builder.pop(); } builder.pop(); localOffset += cellHeight; } final Scene scene = builder.build(); view.render(scene); scene.dispose(); } } final Map<String, int> _createdPlatformViews = <String, int> {}; final Map<String, bool> _calledToBeCreatedPlatformViews = <String, bool> {}; /// Adds the platform view to the scene. /// /// First, the platform view is created by calling the corresponding platform channel, /// then a new frame is scheduled, finally the platform view is added to the scene builder. void addPlatformView( int id, { required PlatformDispatcher dispatcher, required SceneBuilder sceneBuilder, String text = 'platform view', double width = 500, double height = 500, String viewType = 'scenarios/textPlatformView', }) { if (scenarioParams['view_type'] is String) { viewType = scenarioParams['view_type'] as String; } final String platformViewKey = '$viewType-$id'; if (_createdPlatformViews.containsKey(platformViewKey)) { addPlatformViewToSceneBuilder( id, sceneBuilder: sceneBuilder, textureId: _createdPlatformViews[platformViewKey]!, width: width, height: height, ); return; } if (_calledToBeCreatedPlatformViews.containsKey(platformViewKey)) { return; } _calledToBeCreatedPlatformViews[platformViewKey] = true; final bool usesAndroidHybridComposition = scenarioParams['use_android_view'] as bool? ?? false; final bool expectAndroidHybridCompositionFallback = scenarioParams['expect_android_view_fallback'] as bool? ?? false; const int valueTrue = 1; const int valueFalse = 2; const int valueInt32 = 3; const int valueFloat64 = 6; const int valueString = 7; const int valueUint8List = 8; const int valueMap = 13; final Uint8List message = Uint8List.fromList(<int>[ valueString, ..._encodeString('create'), valueMap, if (Platform.isIOS) 3, // 3 entries in map for iOS. if (Platform.isAndroid && !usesAndroidHybridComposition) 7, // 7 entries in map for texture on Android. if (Platform.isAndroid && usesAndroidHybridComposition) 5, // 5 entries in map for hybrid composition on Android. valueString, ..._encodeString('id'), valueInt32, ..._to32(id), valueString, ..._encodeString('viewType'), valueString, ..._encodeString(viewType), if (Platform.isAndroid && !usesAndroidHybridComposition) ...<int>[ valueString, ..._encodeString('width'), // This is missing the 64-bit boundary alignment, making the entire // message encoding fragile to changes before this point. Do not add new // variable-length values such as strings before this point. // TODO(stuartmorgan): Fix this to use the actual encoding logic, // including alignment: https://github.com/flutter/flutter/issues/111188 valueFloat64, ..._to64(width), valueString, ..._encodeString('height'), valueFloat64, ..._to64(height), valueString, ..._encodeString('direction'), valueInt32, ..._to32(0), // LTR valueString, ..._encodeString('hybridFallback'), if (expectAndroidHybridCompositionFallback) valueTrue else valueFalse, ], if (Platform.isAndroid && usesAndroidHybridComposition) ...<int>[ valueString, ..._encodeString('hybrid'), valueTrue, valueString, ..._encodeString('direction'), valueInt32, ..._to32(0), // LTR ], valueString, ..._encodeString('params'), valueUint8List, ..._encodeString(text), ]); dispatcher.sendPlatformMessage( 'flutter/platform_views', message.buffer.asByteData(), (ByteData? response) { late int textureId; if (response != null && Platform.isAndroid && !usesAndroidHybridComposition) { assert(response.getUint8(0) == 0, 'expected envelope'); final int type = response.getUint8(1); if (expectAndroidHybridCompositionFallback) { // Fallback is indicated with a null return. assert(type == 0, 'expected null'); textureId = -1; } else { // This is the texture ID. assert(type == 4, 'expected int64'); textureId = response.getInt64(2, Endian.host); } } else { // There no texture ID. textureId = -1; } _createdPlatformViews[platformViewKey] = textureId; dispatcher.scheduleFrame(); }, ); } /// Adds the platform view to the scene builder. Future<void> addPlatformViewToSceneBuilder( int id, { required SceneBuilder sceneBuilder, required int textureId, double width = 500, double height = 500, }) async { if (Platform.isIOS) { sceneBuilder.addPlatformView(id, width: width, height: height); } else if (Platform.isAndroid) { final bool expectAndroidHybridCompositionFallback = scenarioParams['expect_android_view_fallback'] as bool? ?? false; final bool usesAndroidHybridComposition = (scenarioParams['use_android_view'] as bool? ?? false) || expectAndroidHybridCompositionFallback; if (usesAndroidHybridComposition) { sceneBuilder.addPlatformView(id, width: width, height: height); } else if (textureId != -1) { sceneBuilder.addTexture(textureId, width: width, height: height); } else { throw UnsupportedError('Invalid texture id $textureId'); } } else { throw UnsupportedError( 'Platform ${Platform.operatingSystem} is not supported'); } } mixin _BasePlatformViewScenarioMixin on Scenario { // Add a picture and finishes the `sceneBuilder`. void finishBuilder( SceneBuilder sceneBuilder, { Offset? overlayOffset, }) { overlayOffset ??= const Offset(50, 50); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawCircle( overlayOffset, 50, Paint()..color = const Color(0xFFABCDEF), ); final Picture picture = recorder.endRecording(); sceneBuilder.addPicture(const Offset(300, 300), picture); final Scene scene = sceneBuilder.build(); view.render(scene); scene.dispose(); } }
engine/testing/scenario_app/lib/src/platform_view.dart/0
{ "file_path": "engine/testing/scenario_app/lib/src/platform_view.dart", "repo_id": "engine", "token_count": 19187 }
403
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io' as io; import 'dart:typed_data'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as p; import 'package:process_fakes/process_fakes.dart'; import 'package:skia_gold_client/skia_gold_client.dart'; void main() { /// A mock commit hash that is used to simulate a successful git call. const String mockCommitHash = '1234567890abcdef'; /// Simulating what a presubmit environment would look like. const Map<String, String> presubmitEnv = <String, String>{ 'GOLDCTL': 'python tools/goldctl.py', 'GOLD_TRYJOB': 'flutter/engine/1234567890', 'LOGDOG_STREAM_PREFIX': 'buildbucket/cr-buildbucket.appspot.com/1234567890/+/logdog', 'LUCI_CONTEXT': '{}', }; /// Simulating what a postsubmit environment would look like. const Map<String, String> postsubmitEnv = <String, String>{ 'GOLDCTL': 'python tools/goldctl.py', 'LOGDOG_STREAM_PREFIX': 'buildbucket/cr-buildbucket.appspot.com/1234567890/+/logdog', 'LUCI_CONTEXT': '{}' }; /// Simulating what a local environment would look like. const Map<String, String> localEnv = <String, String>{}; /// Creates a [SkiaGoldClient] with the given [dimensions] and [verbose] flag. /// /// Optionally, the [onRun] function can be provided to handle the execution /// of the command-line tool. If not provided, it throws an /// [UnsupportedError] by default. /// /// Side-effects of the client can be observed through the test fixture. SkiaGoldClient createClient( _TestFixture fixture, { required Map<String, String> environment, Map<String, String>? dimensions, bool verbose = false, io.ProcessResult Function(List<String> command) onRun = _runUnhandled, }) { return SkiaGoldClient( fixture.workDirectory, dimensions: dimensions, httpClient: fixture.httpClient, processManager: FakeProcessManager( onRun: onRun, ), verbose: verbose, stderr: fixture.outputSink, environment: environment, ); } /// Creates a `temp/auth_opt.json` file in the working directory. /// /// This simulates what the goldctl tool does when it runs. void createAuthOptDotJson(String workDirectory) { final io.File authOptDotJson = io.File(p.join(workDirectory, 'temp', 'auth_opt.json')); authOptDotJson.createSync(recursive: true); authOptDotJson.writeAsStringSync('{"GSUtil": false}'); } test('fails if GOLDCTL is not set', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: localEnv, ); try { await client.auth(); fail('auth should fail if GOLDCTL is not set'); } on StateError catch (error) { expect('$error', contains('GOLDCTL is not set')); } } finally { fixture.dispose(); } }); test('auth executes successfully', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: presubmitEnv, onRun: (List<String> command) { expect(command, <String>[ 'python tools/goldctl.py', 'auth', '--work-dir', p.join(fixture.workDirectory.path, 'temp'), '--luci', ]); createAuthOptDotJson(fixture.workDirectory.path); return io.ProcessResult(0, 0, '', ''); }, ); await client.auth(); } finally { fixture.dispose(); } }); test('auth is only invoked once per instance', () async { final _TestFixture fixture = _TestFixture(); try { int callsToGoldctl = 0; final SkiaGoldClient client = createClient( fixture, environment: presubmitEnv, onRun: (List<String> command) { callsToGoldctl++; expect(command, <String>[ 'python tools/goldctl.py', 'auth', '--work-dir', p.join(fixture.workDirectory.path, 'temp'), '--luci', ]); createAuthOptDotJson(fixture.workDirectory.path); return io.ProcessResult(0, 0, '', ''); }, ); await client.auth(); await client.auth(); expect(callsToGoldctl, 1); } finally { fixture.dispose(); } }); test('auth executes successfully with verbose logging', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: presubmitEnv, verbose: true, onRun: (List<String> command) { expect(command, <String>[ 'python tools/goldctl.py', 'auth', '--verbose', '--work-dir', p.join(fixture.workDirectory.path, 'temp'), '--luci', ]); return io.ProcessResult(0, 0, 'stdout', 'stderr'); }, ); await client.auth(); expect(fixture.outputSink.toString(), contains('stdout:\nstdout')); expect(fixture.outputSink.toString(), contains('stderr:\nstderr')); } finally { fixture.dispose(); } }); test('auth fails', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: presubmitEnv, onRun: (List<String> command) { return io.ProcessResult(1, 0, 'stdout-text', 'stderr-text'); }, ); try { await client.auth(); } on SkiaGoldProcessError catch (error) { expect(error.command, contains('auth')); expect(error.stdout, 'stdout-text'); expect(error.stderr, 'stderr-text'); expect(error.message, contains('Skia Gold authorization failed')); } } finally { fixture.dispose(); } }); test('addImg [pre-submit] executes successfully', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: presubmitEnv, onRun: (List<String> command) { if (command case ['git', ...]) { return io.ProcessResult(0, 0, mockCommitHash, ''); } if (command case ['python tools/goldctl.py', 'imgtest', 'init', ...]) { return io.ProcessResult(0, 0, '', ''); } expect(command, <String>[ 'python tools/goldctl.py', 'imgtest', 'add', '--work-dir', p.join(fixture.workDirectory.path, 'temp'), '--test-name', 'test-name', '--png-file', p.join(fixture.workDirectory.path, 'temp', 'golden.png'), '--add-test-optional-key', 'image_matching_algorithm:fuzzy', '--add-test-optional-key', 'fuzzy_max_different_pixels:10', '--add-test-optional-key', 'fuzzy_pixel_delta_threshold:0', ]); return io.ProcessResult(0, 0, '', ''); }, ); await client.addImg( 'test-name.foo', io.File(p.join(fixture.workDirectory.path, 'temp', 'golden.png')), screenshotSize: 1000, ); } finally { fixture.dispose(); } }); test('addImg [pre-submit] executes successfully with verbose logging', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: presubmitEnv, verbose: true, onRun: (List<String> command) { if (command case ['git', ...]) { return io.ProcessResult(0, 0, mockCommitHash, ''); } if (command case ['python tools/goldctl.py', 'imgtest', 'init', ...]) { return io.ProcessResult(0, 0, '', ''); } expect(command, <String>[ 'python tools/goldctl.py', 'imgtest', 'add', '--verbose', '--work-dir', p.join(fixture.workDirectory.path, 'temp'), '--test-name', 'test-name', '--png-file', p.join(fixture.workDirectory.path, 'temp', 'golden.png'), '--add-test-optional-key', 'image_matching_algorithm:fuzzy', '--add-test-optional-key', 'fuzzy_max_different_pixels:10', '--add-test-optional-key', 'fuzzy_pixel_delta_threshold:0', ]); return io.ProcessResult(0, 0, 'stdout', 'stderr'); }, ); await client.addImg( 'test-name.foo', io.File(p.join(fixture.workDirectory.path, 'temp', 'golden.png')), screenshotSize: 1000, ); expect(fixture.outputSink.toString(), contains('stdout:\nstdout')); expect(fixture.outputSink.toString(), contains('stderr:\nstderr')); } finally { fixture.dispose(); } }); // A success case (exit code 0) with a message of "Untriaged" is OK. test('addImg [pre-submit] succeeds but has an untriaged image', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: presubmitEnv, onRun: (List<String> command) { if (command case ['git', ...]) { return io.ProcessResult(0, 0, mockCommitHash, ''); } if (command case ['python tools/goldctl.py', 'imgtest', 'init', ...]) { return io.ProcessResult(0, 0, '', ''); } expect(command, <String>[ 'python tools/goldctl.py', 'imgtest', 'add', '--work-dir', p.join(fixture.workDirectory.path, 'temp'), '--test-name', 'test-name', '--png-file', p.join(fixture.workDirectory.path, 'temp', 'golden.png'), '--add-test-optional-key', 'image_matching_algorithm:fuzzy', '--add-test-optional-key', 'fuzzy_max_different_pixels:10', '--add-test-optional-key', 'fuzzy_pixel_delta_threshold:0', ]); // Intentionally returning a non-zero exit code. return io.ProcessResult(0, 1, 'Untriaged', ''); }, ); await client.addImg( 'test-name.foo', io.File(p.join(fixture.workDirectory.path, 'temp', 'golden.png')), screenshotSize: 1000, ); // Expect a stderr log message. final String log = fixture.outputSink.toString(); expect(log, contains('Untriaged image detected')); } finally { fixture.dispose(); } }); test('addImg [pre-submit] fails due to an unexpected error', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: presubmitEnv, onRun: (List<String> command) { if (command case ['git', ...]) { return io.ProcessResult(0, 0, mockCommitHash, ''); } if (command case ['python tools/goldctl.py', 'imgtest', 'init', ...]) { return io.ProcessResult(0, 0, '', ''); } return io.ProcessResult(1, 0, 'stdout-text', 'stderr-text'); }, ); try { await client.addImg( 'test-name.foo', io.File(p.join(fixture.workDirectory.path, 'temp', 'golden.png')), screenshotSize: 1000, ); } on SkiaGoldProcessError catch (error) { expect(error.message, contains('Skia Gold image test failed.')); expect(error.stdout, 'stdout-text'); expect(error.stderr, 'stderr-text'); expect(error.command, contains('imgtest add')); } } finally { fixture.dispose(); } }); test('addImg [post-submit] executes successfully', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: postsubmitEnv, onRun: (List<String> command) { if (command case ['git', ...]) { return io.ProcessResult(0, 0, mockCommitHash, ''); } if (command case ['python tools/goldctl.py', 'imgtest', 'init', ...]) { return io.ProcessResult(0, 0, '', ''); } expect(command, <String>[ 'python tools/goldctl.py', 'imgtest', 'add', '--work-dir', p.join(fixture.workDirectory.path, 'temp'), '--test-name', 'test-name', '--png-file', p.join(fixture.workDirectory.path, 'temp', 'golden.png'), '--passfail', '--add-test-optional-key', 'image_matching_algorithm:fuzzy', '--add-test-optional-key', 'fuzzy_max_different_pixels:10', '--add-test-optional-key', 'fuzzy_pixel_delta_threshold:0', ]); return io.ProcessResult(0, 0, '', ''); }, ); await client.addImg( 'test-name.foo', io.File(p.join(fixture.workDirectory.path, 'temp', 'golden.png')), screenshotSize: 1000, ); } finally { fixture.dispose(); } }); test('addImg [post-submit] executes successfully with verbose logging', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: postsubmitEnv, verbose: true, onRun: (List<String> command) { if (command case ['git', ...]) { return io.ProcessResult(0, 0, mockCommitHash, ''); } if (command case ['python tools/goldctl.py', 'imgtest', 'init', ...]) { return io.ProcessResult(0, 0, '', ''); } expect(command, <String>[ 'python tools/goldctl.py', 'imgtest', 'add', '--verbose', '--work-dir', p.join(fixture.workDirectory.path, 'temp'), '--test-name', 'test-name', '--png-file', p.join(fixture.workDirectory.path, 'temp', 'golden.png'), '--passfail', '--add-test-optional-key', 'image_matching_algorithm:fuzzy', '--add-test-optional-key', 'fuzzy_max_different_pixels:10', '--add-test-optional-key', 'fuzzy_pixel_delta_threshold:0', ]); return io.ProcessResult(0, 0, 'stdout', 'stderr'); }, ); await client.addImg( 'test-name.foo', io.File(p.join(fixture.workDirectory.path, 'temp', 'golden.png')), screenshotSize: 1000, ); expect(fixture.outputSink.toString(), contains('stdout:\nstdout')); expect(fixture.outputSink.toString(), contains('stderr:\nstderr')); } finally { fixture.dispose(); } }); test('addImg [post-submit] fails due to an unapproved image', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: postsubmitEnv, onRun: (List<String> command) { if (command case ['git', ...]) { return io.ProcessResult(0, 0, mockCommitHash, ''); } if (command case ['python tools/goldctl.py', 'imgtest', 'init', ...]) { return io.ProcessResult(0, 0, '', ''); } return io.ProcessResult(1, 0, 'stdout-text', 'stderr-text'); }, ); try { await client.addImg( 'test-name.foo', io.File(p.join(fixture.workDirectory.path, 'temp', 'golden.png')), screenshotSize: 1000, ); } on SkiaGoldProcessError catch (error) { expect(error.message, contains('Skia Gold image test failed.')); expect(error.stdout, 'stdout-text'); expect(error.stderr, 'stderr-text'); expect(error.command, contains('imgtest add')); } } finally { fixture.dispose(); } }); test('getExpectationsForTest returns the latest positive digest', () async { final _TestFixture fixture = _TestFixture(); try { final SkiaGoldClient client = createClient( fixture, environment: presubmitEnv, onRun: (List<String> command) { expect(command, <String>[ 'python tools/goldctl.py', 'imgtest', 'get', '--work-dir', p.join(fixture.workDirectory.path, 'temp'), '--test-name', 'test-name', ]); return io.ProcessResult(0, 0, '{"digest":"digest"}', ''); }, ); final String hash = client.getTraceID('test-name'); fixture.httpClient.setJsonResponse( Uri.parse('https://flutter-engine-gold.skia.org/json/v2/latestpositivedigest/$hash'), <String, Object?>{ 'digest': 'digest', }, ); final String? digest = await client.getExpectationForTest('test-name'); expect(digest, 'digest'); } finally { fixture.dispose(); } }); } final class _TestFixture { _TestFixture(); final io.Directory workDirectory = io.Directory.systemTemp.createTempSync('skia_gold_client_test'); final _FakeHttpClient httpClient = _FakeHttpClient(); final StringSink outputSink = StringBuffer(); void dispose() { workDirectory.deleteSync(recursive: true); } } io.ProcessResult _runUnhandled(List<String> command) { throw UnimplementedError('Unhandled run: ${command.join(' ')}'); } /// An in-memory fake of [io.HttpClient] that allows [getUrl] to be mocked. /// /// This class is used to simulate a response from the server. /// /// Any other methods called on this class will throw a [NoSuchMethodError]. final class _FakeHttpClient implements io.HttpClient { final Map<Uri, Object?> _expectedResponses = <Uri, Object?>{}; /// Sets an expected response for the given [request] to [jsonEncodableValue]. /// /// This method is used to simulate a response from the server. void setJsonResponse(Uri request, Object? jsonEncodableValue) { _expectedResponses[request] = jsonEncodableValue; } @override Future<io.HttpClientRequest> getUrl(Uri url) async { final Object? response = _expectedResponses[url]; if (response == null) { throw StateError('No request expected for $url'); } return _FakeHttpClientRequest.withJsonResponse(response); } @override Object? noSuchMethod(Invocation invocation) { return super.noSuchMethod(invocation); } } final class _FakeHttpClientRequest implements io.HttpClientRequest { factory _FakeHttpClientRequest.withJsonResponse(Object? jsonResponse) { final Uint8List bytes = utf8.encoder.convert(jsonEncode(jsonResponse)); return _FakeHttpClientRequest._(_FakeHttpClientResponse(bytes)); } _FakeHttpClientRequest._(this._response); final io.HttpClientResponse _response; @override Future<io.HttpClientResponse> close() async { return _response; } @override Object? noSuchMethod(Invocation invocation) { return super.noSuchMethod(invocation); } } final class _FakeHttpClientResponse extends Stream<List<int>> implements io.HttpClientResponse { _FakeHttpClientResponse(this._bytes); final Uint8List _bytes; @override StreamSubscription<List<int>> listen( void Function(List<int> event)? onData, { Function? onError, void Function()? onDone, bool? cancelOnError, }) { return Stream<List<int>>.fromIterable(<List<int>>[_bytes]).listen( onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError, ); } @override int get statusCode => 200; @override Object? noSuchMethod(Invocation invocation) { return super.noSuchMethod(invocation); } }
engine/testing/skia_gold_client/test/skia_gold_client_test.dart/0
{ "file_path": "engine/testing/skia_gold_client/test/skia_gold_client_test.dart", "repo_id": "engine", "token_count": 8972 }
404
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_TESTING_TEST_VULKAN_CONTEXT_H_ #define FLUTTER_TESTING_TEST_VULKAN_CONTEXT_H_ #include "flutter/fml/macros.h" #include "flutter/fml/memory/ref_ptr.h" #include "flutter/testing/test_vulkan_image.h" #include "flutter/vulkan/procs/vulkan_proc_table.h" #include "flutter/vulkan/vulkan_application.h" #include "flutter/vulkan/vulkan_device.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { namespace testing { class TestVulkanContext : public fml::RefCountedThreadSafe<TestVulkanContext> { public: TestVulkanContext(); ~TestVulkanContext(); std::optional<TestVulkanImage> CreateImage(const SkISize& size) const; sk_sp<GrDirectContext> GetGrDirectContext() const; private: fml::RefPtr<vulkan::VulkanProcTable> vk_; std::unique_ptr<vulkan::VulkanApplication> application_; std::unique_ptr<vulkan::VulkanDevice> device_; sk_sp<GrDirectContext> context_; friend class EmbedderTestContextVulkan; friend class EmbedderConfigBuilder; FML_FRIEND_MAKE_REF_COUNTED(TestVulkanContext); FML_FRIEND_REF_COUNTED_THREAD_SAFE(TestVulkanContext); FML_DISALLOW_COPY_AND_ASSIGN(TestVulkanContext); }; } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_TEST_VULKAN_CONTEXT_H_
engine/testing/test_vulkan_context.h/0
{ "file_path": "engine/testing/test_vulkan_context.h", "repo_id": "engine", "token_count": 541 }
405
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/common/config.gni") import("//flutter/testing/testing.gni") config("accessibility_config") { visibility = [ "//flutter/shell/platform/common:common_cpp_accessibility", "//flutter/third_party/accessibility/*", ] if (is_win) { # TODO(cbracken): https://github.com/flutter/flutter/issues/92229 defines = [ "_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING" ] } include_dirs = [ "//flutter/third_party/accessibility" ] } source_set("accessibility") { defines = [] public_deps = [ "ax", "ax_build", "base", "gfx", ] public_configs = [ ":accessibility_config" ] if (is_mac) { frameworks = [ "AppKit.framework", "CoreFoundation.framework", "CoreGraphics.framework", "CoreText.framework", "IOSurface.framework", ] } } if (enable_unittests) { test_fixtures("accessibility_fixtures") { fixtures = [] } executable("accessibility_unittests") { testonly = true public_configs = [ ":accessibility_config" ] if (is_mac || is_win) { sources = [ "ax/ax_enum_util_unittest.cc", "ax/ax_event_generator_unittest.cc", "ax/ax_node_data_unittest.cc", "ax/ax_node_position_unittest.cc", "ax/ax_range_unittest.cc", "ax/ax_role_properties_unittest.cc", "ax/ax_table_info_unittest.cc", "ax/ax_tree_unittest.cc", "ax/test_ax_node_helper.cc", "ax/test_ax_node_helper.h", "ax/test_ax_tree_manager.cc", "ax/test_ax_tree_manager.h", ] sources += [ "ax/platform/ax_platform_node_base_unittest.cc", "ax/platform/ax_platform_node_unittest.cc", "ax/platform/ax_platform_node_unittest.h", "ax/platform/ax_unique_id_unittest.cc", "ax/platform/test_ax_node_wrapper.cc", "ax/platform/test_ax_node_wrapper.h", ] if (is_mac) { sources += [ "ax/platform/ax_platform_node_mac_unittest.mm" ] frameworks = [ "AppKit.framework", "CoreFoundation.framework", "CoreGraphics.framework", "CoreText.framework", "IOSurface.framework", ] cflags_objcc = flutter_cflags_objcc ldflags = [ "-ObjC" ] } if (is_win) { sources += [ "ax/platform/ax_fragment_root_win_unittest.cc", "ax/platform/ax_platform_node_textprovider_win_unittest.cc", "ax/platform/ax_platform_node_textrangeprovider_win_unittest.cc", "ax/platform/ax_platform_node_win_unittest.cc", "base/win/dispatch_stub.cc", "base/win/dispatch_stub.h", "base/win/display_unittest.cc", "base/win/scoped_bstr_unittest.cc", "base/win/scoped_safearray_unittest.cc", "base/win/scoped_variant_unittest.cc", ] } sources += [ "base/logging_unittests.cc", "base/string_utils_unittest.cc", "gfx/geometry/insets_unittest.cc", "gfx/geometry/point_unittest.cc", "gfx/geometry/rect_unittest.cc", "gfx/geometry/size_unittest.cc", "gfx/geometry/vector2d_unittest.cc", "gfx/range/range_unittest.cc", "gfx/test/gfx_util.cc", "gfx/test/gfx_util.h", ] deps = [ ":accessibility", ":accessibility_fixtures", "//flutter/testing", "//flutter/testing:dart", ] } } }
engine/third_party/accessibility/BUILD.gn/0
{ "file_path": "engine/third_party/accessibility/BUILD.gn", "repo_id": "engine", "token_count": 1761 }
406
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ax_enum_util.h" namespace ui { const char* ToString(ax::mojom::Event event) { switch (event) { case ax::mojom::Event::kNone: return "none"; case ax::mojom::Event::kActiveDescendantChanged: return "activedescendantchanged"; case ax::mojom::Event::kAlert: return "alert"; case ax::mojom::Event::kAriaAttributeChanged: return "ariaAttributeChanged"; case ax::mojom::Event::kAutocorrectionOccured: return "autocorrectionOccured"; case ax::mojom::Event::kBlur: return "blur"; case ax::mojom::Event::kCheckedStateChanged: return "checkedStateChanged"; case ax::mojom::Event::kChildrenChanged: return "childrenChanged"; case ax::mojom::Event::kClicked: return "clicked"; case ax::mojom::Event::kControlsChanged: return "controlsChanged"; case ax::mojom::Event::kDocumentSelectionChanged: return "documentSelectionChanged"; case ax::mojom::Event::kDocumentTitleChanged: return "documentTitleChanged"; case ax::mojom::Event::kEndOfTest: return "endOfTest"; case ax::mojom::Event::kExpandedChanged: return "expandedChanged"; case ax::mojom::Event::kFocus: return "focus"; case ax::mojom::Event::kFocusAfterMenuClose: return "focusAfterMenuClose"; case ax::mojom::Event::kFocusContext: return "focusContext"; case ax::mojom::Event::kHide: return "hide"; case ax::mojom::Event::kHitTestResult: return "hitTestResult"; case ax::mojom::Event::kHover: return "hover"; case ax::mojom::Event::kImageFrameUpdated: return "imageFrameUpdated"; case ax::mojom::Event::kInvalidStatusChanged: return "invalidStatusChanged"; case ax::mojom::Event::kLayoutComplete: return "layoutComplete"; case ax::mojom::Event::kLiveRegionCreated: return "liveRegionCreated"; case ax::mojom::Event::kLiveRegionChanged: return "liveRegionChanged"; case ax::mojom::Event::kLoadComplete: return "loadComplete"; case ax::mojom::Event::kLoadStart: return "loadStart"; case ax::mojom::Event::kLocationChanged: return "locationChanged"; case ax::mojom::Event::kMediaStartedPlaying: return "mediaStartedPlaying"; case ax::mojom::Event::kMediaStoppedPlaying: return "mediaStoppedPlaying"; case ax::mojom::Event::kMenuEnd: return "menuEnd"; case ax::mojom::Event::kMenuListItemSelected: return "menuListItemSelected"; case ax::mojom::Event::kMenuListValueChanged: return "menuListValueChanged"; case ax::mojom::Event::kMenuPopupEnd: return "menuPopupEnd"; case ax::mojom::Event::kMenuPopupStart: return "menuPopupStart"; case ax::mojom::Event::kMenuStart: return "menuStart"; case ax::mojom::Event::kMouseCanceled: return "mouseCanceled"; case ax::mojom::Event::kMouseDragged: return "mouseDragged"; case ax::mojom::Event::kMouseMoved: return "mouseMoved"; case ax::mojom::Event::kMousePressed: return "mousePressed"; case ax::mojom::Event::kMouseReleased: return "mouseReleased"; case ax::mojom::Event::kRowCollapsed: return "rowCollapsed"; case ax::mojom::Event::kRowCountChanged: return "rowCountChanged"; case ax::mojom::Event::kRowExpanded: return "rowExpanded"; case ax::mojom::Event::kScrollPositionChanged: return "scrollPositionChanged"; case ax::mojom::Event::kScrolledToAnchor: return "scrolledToAnchor"; case ax::mojom::Event::kSelectedChildrenChanged: return "selectedChildrenChanged"; case ax::mojom::Event::kSelection: return "selection"; case ax::mojom::Event::kSelectionAdd: return "selectionAdd"; case ax::mojom::Event::kSelectionRemove: return "selectionRemove"; case ax::mojom::Event::kShow: return "show"; case ax::mojom::Event::kStateChanged: return "stateChanged"; case ax::mojom::Event::kTextChanged: return "textChanged"; case ax::mojom::Event::kTextSelectionChanged: return "textSelectionChanged"; case ax::mojom::Event::kTooltipClosed: return "tooltipClosed"; case ax::mojom::Event::kTooltipOpened: return "tooltipOpened"; case ax::mojom::Event::kWindowActivated: return "windowActivated"; case ax::mojom::Event::kWindowDeactivated: return "windowDeactivated"; case ax::mojom::Event::kWindowVisibilityChanged: return "windowVisibilityChanged"; case ax::mojom::Event::kTreeChanged: return "treeChanged"; case ax::mojom::Event::kValueChanged: return "valueChanged"; } return ""; } ax::mojom::Event ParseEvent(const char* event) { if (0 == strcmp(event, "none")) return ax::mojom::Event::kNone; if (0 == strcmp(event, "activedescendantchanged")) return ax::mojom::Event::kActiveDescendantChanged; if (0 == strcmp(event, "alert")) return ax::mojom::Event::kAlert; if (0 == strcmp(event, "ariaAttributeChanged")) return ax::mojom::Event::kAriaAttributeChanged; if (0 == strcmp(event, "autocorrectionOccured")) return ax::mojom::Event::kAutocorrectionOccured; if (0 == strcmp(event, "blur")) return ax::mojom::Event::kBlur; if (0 == strcmp(event, "checkedStateChanged")) return ax::mojom::Event::kCheckedStateChanged; if (0 == strcmp(event, "childrenChanged")) return ax::mojom::Event::kChildrenChanged; if (0 == strcmp(event, "clicked")) return ax::mojom::Event::kClicked; if (0 == strcmp(event, "controlsChanged")) return ax::mojom::Event::kControlsChanged; if (0 == strcmp(event, "documentSelectionChanged")) return ax::mojom::Event::kDocumentSelectionChanged; if (0 == strcmp(event, "documentTitleChanged")) return ax::mojom::Event::kDocumentTitleChanged; if (0 == strcmp(event, "endOfTest")) return ax::mojom::Event::kEndOfTest; if (0 == strcmp(event, "expandedChanged")) return ax::mojom::Event::kExpandedChanged; if (0 == strcmp(event, "focus")) return ax::mojom::Event::kFocus; if (0 == strcmp(event, "focusAfterMenuClose")) return ax::mojom::Event::kFocusAfterMenuClose; if (0 == strcmp(event, "focusContext")) return ax::mojom::Event::kFocusContext; if (0 == strcmp(event, "hide")) return ax::mojom::Event::kHide; if (0 == strcmp(event, "hitTestResult")) return ax::mojom::Event::kHitTestResult; if (0 == strcmp(event, "hover")) return ax::mojom::Event::kHover; if (0 == strcmp(event, "imageFrameUpdated")) return ax::mojom::Event::kImageFrameUpdated; if (0 == strcmp(event, "invalidStatusChanged")) return ax::mojom::Event::kInvalidStatusChanged; if (0 == strcmp(event, "layoutComplete")) return ax::mojom::Event::kLayoutComplete; if (0 == strcmp(event, "liveRegionCreated")) return ax::mojom::Event::kLiveRegionCreated; if (0 == strcmp(event, "liveRegionChanged")) return ax::mojom::Event::kLiveRegionChanged; if (0 == strcmp(event, "loadComplete")) return ax::mojom::Event::kLoadComplete; if (0 == strcmp(event, "loadStart")) return ax::mojom::Event::kLoadStart; if (0 == strcmp(event, "locationChanged")) return ax::mojom::Event::kLocationChanged; if (0 == strcmp(event, "mediaStartedPlaying")) return ax::mojom::Event::kMediaStartedPlaying; if (0 == strcmp(event, "mediaStoppedPlaying")) return ax::mojom::Event::kMediaStoppedPlaying; if (0 == strcmp(event, "menuEnd")) return ax::mojom::Event::kMenuEnd; if (0 == strcmp(event, "menuListItemSelected")) return ax::mojom::Event::kMenuListItemSelected; if (0 == strcmp(event, "menuListValueChanged")) return ax::mojom::Event::kMenuListValueChanged; if (0 == strcmp(event, "menuPopupEnd")) return ax::mojom::Event::kMenuPopupEnd; if (0 == strcmp(event, "menuPopupStart")) return ax::mojom::Event::kMenuPopupStart; if (0 == strcmp(event, "menuStart")) return ax::mojom::Event::kMenuStart; if (0 == strcmp(event, "mouseCanceled")) return ax::mojom::Event::kMouseCanceled; if (0 == strcmp(event, "mouseDragged")) return ax::mojom::Event::kMouseDragged; if (0 == strcmp(event, "mouseMoved")) return ax::mojom::Event::kMouseMoved; if (0 == strcmp(event, "mousePressed")) return ax::mojom::Event::kMousePressed; if (0 == strcmp(event, "mouseReleased")) return ax::mojom::Event::kMouseReleased; if (0 == strcmp(event, "rowCollapsed")) return ax::mojom::Event::kRowCollapsed; if (0 == strcmp(event, "rowCountChanged")) return ax::mojom::Event::kRowCountChanged; if (0 == strcmp(event, "rowExpanded")) return ax::mojom::Event::kRowExpanded; if (0 == strcmp(event, "scrollPositionChanged")) return ax::mojom::Event::kScrollPositionChanged; if (0 == strcmp(event, "scrolledToAnchor")) return ax::mojom::Event::kScrolledToAnchor; if (0 == strcmp(event, "selectedChildrenChanged")) return ax::mojom::Event::kSelectedChildrenChanged; if (0 == strcmp(event, "selection")) return ax::mojom::Event::kSelection; if (0 == strcmp(event, "selectionAdd")) return ax::mojom::Event::kSelectionAdd; if (0 == strcmp(event, "selectionRemove")) return ax::mojom::Event::kSelectionRemove; if (0 == strcmp(event, "show")) return ax::mojom::Event::kShow; if (0 == strcmp(event, "stateChanged")) return ax::mojom::Event::kStateChanged; if (0 == strcmp(event, "textChanged")) return ax::mojom::Event::kTextChanged; if (0 == strcmp(event, "textSelectionChanged")) return ax::mojom::Event::kTextSelectionChanged; if (0 == strcmp(event, "tooltipClosed")) return ax::mojom::Event::kTooltipClosed; if (0 == strcmp(event, "tooltipOpened")) return ax::mojom::Event::kTooltipOpened; if (0 == strcmp(event, "windowActivated")) return ax::mojom::Event::kWindowActivated; if (0 == strcmp(event, "windowDeactivated")) return ax::mojom::Event::kWindowDeactivated; if (0 == strcmp(event, "windowVisibilityChanged")) return ax::mojom::Event::kWindowVisibilityChanged; if (0 == strcmp(event, "treeChanged")) return ax::mojom::Event::kTreeChanged; if (0 == strcmp(event, "valueChanged")) return ax::mojom::Event::kValueChanged; return ax::mojom::Event::kNone; } const char* ToString(ax::mojom::Role role) { switch (role) { case ax::mojom::Role::kNone: return "none"; case ax::mojom::Role::kAbbr: return "abbr"; case ax::mojom::Role::kAlertDialog: return "alertDialog"; case ax::mojom::Role::kAlert: return "alert"; case ax::mojom::Role::kAnchor: return "anchor"; case ax::mojom::Role::kApplication: return "application"; case ax::mojom::Role::kArticle: return "article"; case ax::mojom::Role::kAudio: return "audio"; case ax::mojom::Role::kBanner: return "banner"; case ax::mojom::Role::kBlockquote: return "blockquote"; case ax::mojom::Role::kButton: return "button"; case ax::mojom::Role::kCanvas: return "canvas"; case ax::mojom::Role::kCaption: return "caption"; case ax::mojom::Role::kCaret: return "caret"; case ax::mojom::Role::kCell: return "cell"; case ax::mojom::Role::kCheckBox: return "checkBox"; case ax::mojom::Role::kClient: return "client"; case ax::mojom::Role::kCode: return "code"; case ax::mojom::Role::kColorWell: return "colorWell"; case ax::mojom::Role::kColumnHeader: return "columnHeader"; case ax::mojom::Role::kColumn: return "column"; case ax::mojom::Role::kComboBoxGrouping: return "comboBoxGrouping"; case ax::mojom::Role::kComboBoxMenuButton: return "comboBoxMenuButton"; case ax::mojom::Role::kComment: return "comment"; case ax::mojom::Role::kComplementary: return "complementary"; case ax::mojom::Role::kContentDeletion: return "contentDeletion"; case ax::mojom::Role::kContentInsertion: return "contentInsertion"; case ax::mojom::Role::kContentInfo: return "contentInfo"; case ax::mojom::Role::kDate: return "date"; case ax::mojom::Role::kDateTime: return "dateTime"; case ax::mojom::Role::kDefinition: return "definition"; case ax::mojom::Role::kDescriptionListDetail: return "descriptionListDetail"; case ax::mojom::Role::kDescriptionList: return "descriptionList"; case ax::mojom::Role::kDescriptionListTerm: return "descriptionListTerm"; case ax::mojom::Role::kDesktop: return "desktop"; case ax::mojom::Role::kDetails: return "details"; case ax::mojom::Role::kDialog: return "dialog"; case ax::mojom::Role::kDirectory: return "directory"; case ax::mojom::Role::kDisclosureTriangle: return "disclosureTriangle"; case ax::mojom::Role::kDocAbstract: return "docAbstract"; case ax::mojom::Role::kDocAcknowledgments: return "docAcknowledgments"; case ax::mojom::Role::kDocAfterword: return "docAfterword"; case ax::mojom::Role::kDocAppendix: return "docAppendix"; case ax::mojom::Role::kDocBackLink: return "docBackLink"; case ax::mojom::Role::kDocBiblioEntry: return "docBiblioEntry"; case ax::mojom::Role::kDocBibliography: return "docBibliography"; case ax::mojom::Role::kDocBiblioRef: return "docBiblioRef"; case ax::mojom::Role::kDocChapter: return "docChapter"; case ax::mojom::Role::kDocColophon: return "docColophon"; case ax::mojom::Role::kDocConclusion: return "docConclusion"; case ax::mojom::Role::kDocCover: return "docCover"; case ax::mojom::Role::kDocCredit: return "docCredit"; case ax::mojom::Role::kDocCredits: return "docCredits"; case ax::mojom::Role::kDocDedication: return "docDedication"; case ax::mojom::Role::kDocEndnote: return "docEndnote"; case ax::mojom::Role::kDocEndnotes: return "docEndnotes"; case ax::mojom::Role::kDocEpigraph: return "docEpigraph"; case ax::mojom::Role::kDocEpilogue: return "docEpilogue"; case ax::mojom::Role::kDocErrata: return "docErrata"; case ax::mojom::Role::kDocExample: return "docExample"; case ax::mojom::Role::kDocFootnote: return "docFootnote"; case ax::mojom::Role::kDocForeword: return "docForeword"; case ax::mojom::Role::kDocGlossary: return "docGlossary"; case ax::mojom::Role::kDocGlossRef: return "docGlossref"; case ax::mojom::Role::kDocIndex: return "docIndex"; case ax::mojom::Role::kDocIntroduction: return "docIntroduction"; case ax::mojom::Role::kDocNoteRef: return "docNoteRef"; case ax::mojom::Role::kDocNotice: return "docNotice"; case ax::mojom::Role::kDocPageBreak: return "docPageBreak"; case ax::mojom::Role::kDocPageList: return "docPageList"; case ax::mojom::Role::kDocPart: return "docPart"; case ax::mojom::Role::kDocPreface: return "docPreface"; case ax::mojom::Role::kDocPrologue: return "docPrologue"; case ax::mojom::Role::kDocPullquote: return "docPullquote"; case ax::mojom::Role::kDocQna: return "docQna"; case ax::mojom::Role::kDocSubtitle: return "docSubtitle"; case ax::mojom::Role::kDocTip: return "docTip"; case ax::mojom::Role::kDocToc: return "docToc"; case ax::mojom::Role::kDocument: return "document"; case ax::mojom::Role::kEmbeddedObject: return "embeddedObject"; case ax::mojom::Role::kEmphasis: return "emphasis"; case ax::mojom::Role::kFeed: return "feed"; case ax::mojom::Role::kFigcaption: return "figcaption"; case ax::mojom::Role::kFigure: return "figure"; case ax::mojom::Role::kFooter: return "footer"; case ax::mojom::Role::kFooterAsNonLandmark: return "footerAsNonLandmark"; case ax::mojom::Role::kForm: return "form"; case ax::mojom::Role::kGenericContainer: return "genericContainer"; case ax::mojom::Role::kGraphicsDocument: return "graphicsDocument"; case ax::mojom::Role::kGraphicsObject: return "graphicsObject"; case ax::mojom::Role::kGraphicsSymbol: return "graphicsSymbol"; case ax::mojom::Role::kGrid: return "grid"; case ax::mojom::Role::kGroup: return "group"; case ax::mojom::Role::kHeader: return "header"; case ax::mojom::Role::kHeaderAsNonLandmark: return "headerAsNonLandmark"; case ax::mojom::Role::kHeading: return "heading"; case ax::mojom::Role::kIframe: return "iframe"; case ax::mojom::Role::kIframePresentational: return "iframePresentational"; case ax::mojom::Role::kIgnored: return "ignored"; case ax::mojom::Role::kImageMap: return "imageMap"; case ax::mojom::Role::kImage: return "image"; case ax::mojom::Role::kImeCandidate: return "imeCandidate"; case ax::mojom::Role::kInlineTextBox: return "inlineTextBox"; case ax::mojom::Role::kInputTime: return "inputTime"; case ax::mojom::Role::kKeyboard: return "keyboard"; case ax::mojom::Role::kLabelText: return "labelText"; case ax::mojom::Role::kLayoutTable: return "layoutTable"; case ax::mojom::Role::kLayoutTableCell: return "layoutTableCell"; case ax::mojom::Role::kLayoutTableRow: return "layoutTableRow"; case ax::mojom::Role::kLegend: return "legend"; case ax::mojom::Role::kLineBreak: return "lineBreak"; case ax::mojom::Role::kLink: return "link"; case ax::mojom::Role::kList: return "list"; case ax::mojom::Role::kListBoxOption: return "listBoxOption"; case ax::mojom::Role::kListBox: return "listBox"; case ax::mojom::Role::kListGrid: return "listGrid"; case ax::mojom::Role::kListItem: return "listItem"; case ax::mojom::Role::kListMarker: return "listMarker"; case ax::mojom::Role::kLog: return "log"; case ax::mojom::Role::kMain: return "main"; case ax::mojom::Role::kMark: return "mark"; case ax::mojom::Role::kMarquee: return "marquee"; case ax::mojom::Role::kMath: return "math"; case ax::mojom::Role::kMenu: return "menu"; case ax::mojom::Role::kMenuBar: return "menuBar"; case ax::mojom::Role::kMenuItem: return "menuItem"; case ax::mojom::Role::kMenuItemCheckBox: return "menuItemCheckBox"; case ax::mojom::Role::kMenuItemRadio: return "menuItemRadio"; case ax::mojom::Role::kMenuListOption: return "menuListOption"; case ax::mojom::Role::kMenuListPopup: return "menuListPopup"; case ax::mojom::Role::kMeter: return "meter"; case ax::mojom::Role::kNavigation: return "navigation"; case ax::mojom::Role::kNote: return "note"; case ax::mojom::Role::kPane: return "pane"; case ax::mojom::Role::kParagraph: return "paragraph"; case ax::mojom::Role::kPdfActionableHighlight: return "pdfActionableHighlight"; case ax::mojom::Role::kPluginObject: return "pluginObject"; case ax::mojom::Role::kPopUpButton: return "popUpButton"; case ax::mojom::Role::kPortal: return "portal"; case ax::mojom::Role::kPre: return "pre"; case ax::mojom::Role::kPresentational: return "presentational"; case ax::mojom::Role::kProgressIndicator: return "progressIndicator"; case ax::mojom::Role::kRadioButton: return "radioButton"; case ax::mojom::Role::kRadioGroup: return "radioGroup"; case ax::mojom::Role::kRegion: return "region"; case ax::mojom::Role::kRootWebArea: return "rootWebArea"; case ax::mojom::Role::kRow: return "row"; case ax::mojom::Role::kRowGroup: return "rowGroup"; case ax::mojom::Role::kRowHeader: return "rowHeader"; case ax::mojom::Role::kRuby: return "ruby"; case ax::mojom::Role::kRubyAnnotation: return "rubyAnnotation"; case ax::mojom::Role::kSection: return "section"; case ax::mojom::Role::kStrong: return "strong"; case ax::mojom::Role::kSuggestion: return "suggestion"; case ax::mojom::Role::kSvgRoot: return "svgRoot"; case ax::mojom::Role::kScrollBar: return "scrollBar"; case ax::mojom::Role::kScrollView: return "scrollView"; case ax::mojom::Role::kSearch: return "search"; case ax::mojom::Role::kSearchBox: return "searchBox"; case ax::mojom::Role::kSlider: return "slider"; case ax::mojom::Role::kSliderThumb: return "sliderThumb"; case ax::mojom::Role::kSpinButton: return "spinButton"; case ax::mojom::Role::kSplitter: return "splitter"; case ax::mojom::Role::kStaticText: return "staticText"; case ax::mojom::Role::kStatus: return "status"; case ax::mojom::Role::kSwitch: return "switch"; case ax::mojom::Role::kTabList: return "tabList"; case ax::mojom::Role::kTabPanel: return "tabPanel"; case ax::mojom::Role::kTab: return "tab"; case ax::mojom::Role::kTable: return "table"; case ax::mojom::Role::kTableHeaderContainer: return "tableHeaderContainer"; case ax::mojom::Role::kTerm: return "term"; case ax::mojom::Role::kTextField: return "textField"; case ax::mojom::Role::kTextFieldWithComboBox: return "textFieldWithComboBox"; case ax::mojom::Role::kTime: return "time"; case ax::mojom::Role::kTimer: return "timer"; case ax::mojom::Role::kTitleBar: return "titleBar"; case ax::mojom::Role::kToggleButton: return "toggleButton"; case ax::mojom::Role::kToolbar: return "toolbar"; case ax::mojom::Role::kTreeGrid: return "treeGrid"; case ax::mojom::Role::kTreeItem: return "treeItem"; case ax::mojom::Role::kTree: return "tree"; case ax::mojom::Role::kUnknown: return "unknown"; case ax::mojom::Role::kTooltip: return "tooltip"; case ax::mojom::Role::kVideo: return "video"; case ax::mojom::Role::kWebArea: return "webArea"; case ax::mojom::Role::kWebView: return "webView"; case ax::mojom::Role::kWindow: return "window"; } return ""; } ax::mojom::Role ParseRole(const char* role) { if (0 == strcmp(role, "none")) return ax::mojom::Role::kNone; if (0 == strcmp(role, "abbr")) return ax::mojom::Role::kAbbr; if (0 == strcmp(role, "alertDialog")) return ax::mojom::Role::kAlertDialog; if (0 == strcmp(role, "alert")) return ax::mojom::Role::kAlert; if (0 == strcmp(role, "anchor")) return ax::mojom::Role::kAnchor; if (0 == strcmp(role, "application")) return ax::mojom::Role::kApplication; if (0 == strcmp(role, "article")) return ax::mojom::Role::kArticle; if (0 == strcmp(role, "audio")) return ax::mojom::Role::kAudio; if (0 == strcmp(role, "banner")) return ax::mojom::Role::kBanner; if (0 == strcmp(role, "blockquote")) return ax::mojom::Role::kBlockquote; if (0 == strcmp(role, "button")) return ax::mojom::Role::kButton; if (0 == strcmp(role, "canvas")) return ax::mojom::Role::kCanvas; if (0 == strcmp(role, "caption")) return ax::mojom::Role::kCaption; if (0 == strcmp(role, "caret")) return ax::mojom::Role::kCaret; if (0 == strcmp(role, "cell")) return ax::mojom::Role::kCell; if (0 == strcmp(role, "checkBox")) return ax::mojom::Role::kCheckBox; if (0 == strcmp(role, "client")) return ax::mojom::Role::kClient; if (0 == strcmp(role, "code")) return ax::mojom::Role::kCode; if (0 == strcmp(role, "colorWell")) return ax::mojom::Role::kColorWell; if (0 == strcmp(role, "columnHeader")) return ax::mojom::Role::kColumnHeader; if (0 == strcmp(role, "column")) return ax::mojom::Role::kColumn; if (0 == strcmp(role, "comboBoxGrouping")) return ax::mojom::Role::kComboBoxGrouping; if (0 == strcmp(role, "comboBoxMenuButton")) return ax::mojom::Role::kComboBoxMenuButton; if (0 == strcmp(role, "comment")) return ax::mojom::Role::kComment; if (0 == strcmp(role, "complementary")) return ax::mojom::Role::kComplementary; if (0 == strcmp(role, "contentDeletion")) return ax::mojom::Role::kContentDeletion; if (0 == strcmp(role, "contentInsertion")) return ax::mojom::Role::kContentInsertion; if (0 == strcmp(role, "contentInfo")) return ax::mojom::Role::kContentInfo; if (0 == strcmp(role, "date")) return ax::mojom::Role::kDate; if (0 == strcmp(role, "dateTime")) return ax::mojom::Role::kDateTime; if (0 == strcmp(role, "definition")) return ax::mojom::Role::kDefinition; if (0 == strcmp(role, "descriptionListDetail")) return ax::mojom::Role::kDescriptionListDetail; if (0 == strcmp(role, "descriptionList")) return ax::mojom::Role::kDescriptionList; if (0 == strcmp(role, "descriptionListTerm")) return ax::mojom::Role::kDescriptionListTerm; if (0 == strcmp(role, "desktop")) return ax::mojom::Role::kDesktop; if (0 == strcmp(role, "details")) return ax::mojom::Role::kDetails; if (0 == strcmp(role, "dialog")) return ax::mojom::Role::kDialog; if (0 == strcmp(role, "directory")) return ax::mojom::Role::kDirectory; if (0 == strcmp(role, "disclosureTriangle")) return ax::mojom::Role::kDisclosureTriangle; if (0 == strcmp(role, "docAbstract")) return ax::mojom::Role::kDocAbstract; if (0 == strcmp(role, "docAcknowledgments")) return ax::mojom::Role::kDocAcknowledgments; if (0 == strcmp(role, "docAfterword")) return ax::mojom::Role::kDocAfterword; if (0 == strcmp(role, "docAppendix")) return ax::mojom::Role::kDocAppendix; if (0 == strcmp(role, "docBackLink")) return ax::mojom::Role::kDocBackLink; if (0 == strcmp(role, "docBiblioEntry")) return ax::mojom::Role::kDocBiblioEntry; if (0 == strcmp(role, "docBibliography")) return ax::mojom::Role::kDocBibliography; if (0 == strcmp(role, "docBiblioRef")) return ax::mojom::Role::kDocBiblioRef; if (0 == strcmp(role, "docChapter")) return ax::mojom::Role::kDocChapter; if (0 == strcmp(role, "docColophon")) return ax::mojom::Role::kDocColophon; if (0 == strcmp(role, "docConclusion")) return ax::mojom::Role::kDocConclusion; if (0 == strcmp(role, "docCover")) return ax::mojom::Role::kDocCover; if (0 == strcmp(role, "docCredit")) return ax::mojom::Role::kDocCredit; if (0 == strcmp(role, "docCredits")) return ax::mojom::Role::kDocCredits; if (0 == strcmp(role, "docDedication")) return ax::mojom::Role::kDocDedication; if (0 == strcmp(role, "docEndnote")) return ax::mojom::Role::kDocEndnote; if (0 == strcmp(role, "docEndnotes")) return ax::mojom::Role::kDocEndnotes; if (0 == strcmp(role, "docEpigraph")) return ax::mojom::Role::kDocEpigraph; if (0 == strcmp(role, "docEpilogue")) return ax::mojom::Role::kDocEpilogue; if (0 == strcmp(role, "docErrata")) return ax::mojom::Role::kDocErrata; if (0 == strcmp(role, "docExample")) return ax::mojom::Role::kDocExample; if (0 == strcmp(role, "docFootnote")) return ax::mojom::Role::kDocFootnote; if (0 == strcmp(role, "docForeword")) return ax::mojom::Role::kDocForeword; if (0 == strcmp(role, "docGlossary")) return ax::mojom::Role::kDocGlossary; if (0 == strcmp(role, "docGlossref")) return ax::mojom::Role::kDocGlossRef; if (0 == strcmp(role, "docIndex")) return ax::mojom::Role::kDocIndex; if (0 == strcmp(role, "docIntroduction")) return ax::mojom::Role::kDocIntroduction; if (0 == strcmp(role, "docNoteRef")) return ax::mojom::Role::kDocNoteRef; if (0 == strcmp(role, "docNotice")) return ax::mojom::Role::kDocNotice; if (0 == strcmp(role, "docPageBreak")) return ax::mojom::Role::kDocPageBreak; if (0 == strcmp(role, "docPageList")) return ax::mojom::Role::kDocPageList; if (0 == strcmp(role, "docPart")) return ax::mojom::Role::kDocPart; if (0 == strcmp(role, "docPreface")) return ax::mojom::Role::kDocPreface; if (0 == strcmp(role, "docPrologue")) return ax::mojom::Role::kDocPrologue; if (0 == strcmp(role, "docPullquote")) return ax::mojom::Role::kDocPullquote; if (0 == strcmp(role, "docQna")) return ax::mojom::Role::kDocQna; if (0 == strcmp(role, "docSubtitle")) return ax::mojom::Role::kDocSubtitle; if (0 == strcmp(role, "docTip")) return ax::mojom::Role::kDocTip; if (0 == strcmp(role, "docToc")) return ax::mojom::Role::kDocToc; if (0 == strcmp(role, "document")) return ax::mojom::Role::kDocument; if (0 == strcmp(role, "embeddedObject")) return ax::mojom::Role::kEmbeddedObject; if (0 == strcmp(role, "emphasis")) return ax::mojom::Role::kEmphasis; if (0 == strcmp(role, "feed")) return ax::mojom::Role::kFeed; if (0 == strcmp(role, "figcaption")) return ax::mojom::Role::kFigcaption; if (0 == strcmp(role, "figure")) return ax::mojom::Role::kFigure; if (0 == strcmp(role, "footer")) return ax::mojom::Role::kFooter; if (0 == strcmp(role, "footerAsNonLandmark")) return ax::mojom::Role::kFooterAsNonLandmark; if (0 == strcmp(role, "form")) return ax::mojom::Role::kForm; if (0 == strcmp(role, "genericContainer")) return ax::mojom::Role::kGenericContainer; if (0 == strcmp(role, "graphicsDocument")) return ax::mojom::Role::kGraphicsDocument; if (0 == strcmp(role, "graphicsObject")) return ax::mojom::Role::kGraphicsObject; if (0 == strcmp(role, "graphicsSymbol")) return ax::mojom::Role::kGraphicsSymbol; if (0 == strcmp(role, "grid")) return ax::mojom::Role::kGrid; if (0 == strcmp(role, "group")) return ax::mojom::Role::kGroup; if (0 == strcmp(role, "heading")) return ax::mojom::Role::kHeading; if (0 == strcmp(role, "header")) return ax::mojom::Role::kHeader; if (0 == strcmp(role, "headerAsNonLandmark")) return ax::mojom::Role::kHeaderAsNonLandmark; if (0 == strcmp(role, "pdfActionableHighlight")) return ax::mojom::Role::kPdfActionableHighlight; if (0 == strcmp(role, "iframe")) return ax::mojom::Role::kIframe; if (0 == strcmp(role, "iframePresentational")) return ax::mojom::Role::kIframePresentational; if (0 == strcmp(role, "ignored")) return ax::mojom::Role::kIgnored; if (0 == strcmp(role, "imageMap")) return ax::mojom::Role::kImageMap; if (0 == strcmp(role, "image")) return ax::mojom::Role::kImage; if (0 == strcmp(role, "imeCandidate")) return ax::mojom::Role::kImeCandidate; if (0 == strcmp(role, "inlineTextBox")) return ax::mojom::Role::kInlineTextBox; if (0 == strcmp(role, "inputTime")) return ax::mojom::Role::kInputTime; if (0 == strcmp(role, "keyboard")) return ax::mojom::Role::kKeyboard; if (0 == strcmp(role, "labelText")) return ax::mojom::Role::kLabelText; if (0 == strcmp(role, "layoutTable")) return ax::mojom::Role::kLayoutTable; if (0 == strcmp(role, "layoutTableCell")) return ax::mojom::Role::kLayoutTableCell; if (0 == strcmp(role, "layoutTableRow")) return ax::mojom::Role::kLayoutTableRow; if (0 == strcmp(role, "legend")) return ax::mojom::Role::kLegend; if (0 == strcmp(role, "lineBreak")) return ax::mojom::Role::kLineBreak; if (0 == strcmp(role, "link")) return ax::mojom::Role::kLink; if (0 == strcmp(role, "listBoxOption")) return ax::mojom::Role::kListBoxOption; if (0 == strcmp(role, "listBox")) return ax::mojom::Role::kListBox; if (0 == strcmp(role, "listGrid")) return ax::mojom::Role::kListGrid; if (0 == strcmp(role, "listItem")) return ax::mojom::Role::kListItem; if (0 == strcmp(role, "listMarker")) return ax::mojom::Role::kListMarker; if (0 == strcmp(role, "list")) return ax::mojom::Role::kList; if (0 == strcmp(role, "log")) return ax::mojom::Role::kLog; if (0 == strcmp(role, "main")) return ax::mojom::Role::kMain; if (0 == strcmp(role, "mark")) return ax::mojom::Role::kMark; if (0 == strcmp(role, "marquee")) return ax::mojom::Role::kMarquee; if (0 == strcmp(role, "math")) return ax::mojom::Role::kMath; if (0 == strcmp(role, "menu")) return ax::mojom::Role::kMenu; if (0 == strcmp(role, "menuBar")) return ax::mojom::Role::kMenuBar; if (0 == strcmp(role, "menuItem")) return ax::mojom::Role::kMenuItem; if (0 == strcmp(role, "menuItemCheckBox")) return ax::mojom::Role::kMenuItemCheckBox; if (0 == strcmp(role, "menuItemRadio")) return ax::mojom::Role::kMenuItemRadio; if (0 == strcmp(role, "menuListOption")) return ax::mojom::Role::kMenuListOption; if (0 == strcmp(role, "menuListPopup")) return ax::mojom::Role::kMenuListPopup; if (0 == strcmp(role, "meter")) return ax::mojom::Role::kMeter; if (0 == strcmp(role, "navigation")) return ax::mojom::Role::kNavigation; if (0 == strcmp(role, "note")) return ax::mojom::Role::kNote; if (0 == strcmp(role, "pane")) return ax::mojom::Role::kPane; if (0 == strcmp(role, "paragraph")) return ax::mojom::Role::kParagraph; if (0 == strcmp(role, "pluginObject")) return ax::mojom::Role::kPluginObject; if (0 == strcmp(role, "popUpButton")) return ax::mojom::Role::kPopUpButton; if (0 == strcmp(role, "portal")) return ax::mojom::Role::kPortal; if (0 == strcmp(role, "pre")) return ax::mojom::Role::kPre; if (0 == strcmp(role, "presentational")) return ax::mojom::Role::kPresentational; if (0 == strcmp(role, "progressIndicator")) return ax::mojom::Role::kProgressIndicator; if (0 == strcmp(role, "radioButton")) return ax::mojom::Role::kRadioButton; if (0 == strcmp(role, "radioGroup")) return ax::mojom::Role::kRadioGroup; if (0 == strcmp(role, "region")) return ax::mojom::Role::kRegion; if (0 == strcmp(role, "rootWebArea")) return ax::mojom::Role::kRootWebArea; if (0 == strcmp(role, "row")) return ax::mojom::Role::kRow; if (0 == strcmp(role, "rowGroup")) return ax::mojom::Role::kRowGroup; if (0 == strcmp(role, "rowHeader")) return ax::mojom::Role::kRowHeader; if (0 == strcmp(role, "ruby")) return ax::mojom::Role::kRuby; if (0 == strcmp(role, "rubyAnnotation")) return ax::mojom::Role::kRubyAnnotation; if (0 == strcmp(role, "section")) return ax::mojom::Role::kSection; if (0 == strcmp(role, "scrollBar")) return ax::mojom::Role::kScrollBar; if (0 == strcmp(role, "scrollView")) return ax::mojom::Role::kScrollView; if (0 == strcmp(role, "search")) return ax::mojom::Role::kSearch; if (0 == strcmp(role, "searchBox")) return ax::mojom::Role::kSearchBox; if (0 == strcmp(role, "slider")) return ax::mojom::Role::kSlider; if (0 == strcmp(role, "sliderThumb")) return ax::mojom::Role::kSliderThumb; if (0 == strcmp(role, "spinButton")) return ax::mojom::Role::kSpinButton; if (0 == strcmp(role, "splitter")) return ax::mojom::Role::kSplitter; if (0 == strcmp(role, "staticText")) return ax::mojom::Role::kStaticText; if (0 == strcmp(role, "status")) return ax::mojom::Role::kStatus; if (0 == strcmp(role, "suggestion")) return ax::mojom::Role::kSuggestion; if (0 == strcmp(role, "svgRoot")) return ax::mojom::Role::kSvgRoot; if (0 == strcmp(role, "switch")) return ax::mojom::Role::kSwitch; if (0 == strcmp(role, "strong")) return ax::mojom::Role::kStrong; if (0 == strcmp(role, "tabList")) return ax::mojom::Role::kTabList; if (0 == strcmp(role, "tabPanel")) return ax::mojom::Role::kTabPanel; if (0 == strcmp(role, "tab")) return ax::mojom::Role::kTab; if (0 == strcmp(role, "tableHeaderContainer")) return ax::mojom::Role::kTableHeaderContainer; if (0 == strcmp(role, "table")) return ax::mojom::Role::kTable; if (0 == strcmp(role, "term")) return ax::mojom::Role::kTerm; if (0 == strcmp(role, "textField")) return ax::mojom::Role::kTextField; if (0 == strcmp(role, "textFieldWithComboBox")) return ax::mojom::Role::kTextFieldWithComboBox; if (0 == strcmp(role, "time")) return ax::mojom::Role::kTime; if (0 == strcmp(role, "timer")) return ax::mojom::Role::kTimer; if (0 == strcmp(role, "titleBar")) return ax::mojom::Role::kTitleBar; if (0 == strcmp(role, "toggleButton")) return ax::mojom::Role::kToggleButton; if (0 == strcmp(role, "toolbar")) return ax::mojom::Role::kToolbar; if (0 == strcmp(role, "treeGrid")) return ax::mojom::Role::kTreeGrid; if (0 == strcmp(role, "treeItem")) return ax::mojom::Role::kTreeItem; if (0 == strcmp(role, "tree")) return ax::mojom::Role::kTree; if (0 == strcmp(role, "unknown")) return ax::mojom::Role::kUnknown; if (0 == strcmp(role, "tooltip")) return ax::mojom::Role::kTooltip; if (0 == strcmp(role, "video")) return ax::mojom::Role::kVideo; if (0 == strcmp(role, "webArea")) return ax::mojom::Role::kWebArea; if (0 == strcmp(role, "webView")) return ax::mojom::Role::kWebView; if (0 == strcmp(role, "window")) return ax::mojom::Role::kWindow; return ax::mojom::Role::kNone; } const char* ToString(ax::mojom::State state) { switch (state) { case ax::mojom::State::kNone: return "none"; case ax::mojom::State::kAutofillAvailable: return "autofillAvailable"; case ax::mojom::State::kCollapsed: return "collapsed"; case ax::mojom::State::kDefault: return "default"; case ax::mojom::State::kEditable: return "editable"; case ax::mojom::State::kExpanded: return "expanded"; case ax::mojom::State::kFocusable: return "focusable"; case ax::mojom::State::kHorizontal: return "horizontal"; case ax::mojom::State::kHovered: return "hovered"; case ax::mojom::State::kIgnored: return "ignored"; case ax::mojom::State::kInvisible: return "invisible"; case ax::mojom::State::kLinked: return "linked"; case ax::mojom::State::kMultiline: return "multiline"; case ax::mojom::State::kMultiselectable: return "multiselectable"; case ax::mojom::State::kProtected: return "protected"; case ax::mojom::State::kRequired: return "required"; case ax::mojom::State::kRichlyEditable: return "richlyEditable"; case ax::mojom::State::kVertical: return "vertical"; case ax::mojom::State::kVisited: return "visited"; } return ""; } ax::mojom::State ParseState(const char* state) { if (0 == strcmp(state, "none")) return ax::mojom::State::kNone; if (0 == strcmp(state, "autofillAvailable")) return ax::mojom::State::kAutofillAvailable; if (0 == strcmp(state, "collapsed")) return ax::mojom::State::kCollapsed; if (0 == strcmp(state, "default")) return ax::mojom::State::kDefault; if (0 == strcmp(state, "editable")) return ax::mojom::State::kEditable; if (0 == strcmp(state, "expanded")) return ax::mojom::State::kExpanded; if (0 == strcmp(state, "focusable")) return ax::mojom::State::kFocusable; if (0 == strcmp(state, "horizontal")) return ax::mojom::State::kHorizontal; if (0 == strcmp(state, "hovered")) return ax::mojom::State::kHovered; if (0 == strcmp(state, "ignored")) return ax::mojom::State::kIgnored; if (0 == strcmp(state, "invisible")) return ax::mojom::State::kInvisible; if (0 == strcmp(state, "linked")) return ax::mojom::State::kLinked; if (0 == strcmp(state, "multiline")) return ax::mojom::State::kMultiline; if (0 == strcmp(state, "multiselectable")) return ax::mojom::State::kMultiselectable; if (0 == strcmp(state, "protected")) return ax::mojom::State::kProtected; if (0 == strcmp(state, "required")) return ax::mojom::State::kRequired; if (0 == strcmp(state, "richlyEditable")) return ax::mojom::State::kRichlyEditable; if (0 == strcmp(state, "vertical")) return ax::mojom::State::kVertical; if (0 == strcmp(state, "visited")) return ax::mojom::State::kVisited; return ax::mojom::State::kNone; } const char* ToString(ax::mojom::Action action) { switch (action) { case ax::mojom::Action::kNone: return "none"; case ax::mojom::Action::kBlur: return "blur"; case ax::mojom::Action::kClearAccessibilityFocus: return "clearAccessibilityFocus"; case ax::mojom::Action::kCollapse: return "collapse"; case ax::mojom::Action::kCustomAction: return "customAction"; case ax::mojom::Action::kDecrement: return "decrement"; case ax::mojom::Action::kDoDefault: return "doDefault"; case ax::mojom::Action::kExpand: return "expand"; case ax::mojom::Action::kFocus: return "focus"; case ax::mojom::Action::kGetImageData: return "getImageData"; case ax::mojom::Action::kHitTest: return "hitTest"; case ax::mojom::Action::kIncrement: return "increment"; case ax::mojom::Action::kLoadInlineTextBoxes: return "loadInlineTextBoxes"; case ax::mojom::Action::kReplaceSelectedText: return "replaceSelectedText"; case ax::mojom::Action::kScrollBackward: return "scrollBackward"; case ax::mojom::Action::kScrollForward: return "scrollForward"; case ax::mojom::Action::kScrollUp: return "scrollUp"; case ax::mojom::Action::kScrollDown: return "scrollDown"; case ax::mojom::Action::kScrollLeft: return "scrollLeft"; case ax::mojom::Action::kScrollRight: return "scrollRight"; case ax::mojom::Action::kScrollToMakeVisible: return "scrollToMakeVisible"; case ax::mojom::Action::kScrollToPoint: return "scrollToPoint"; case ax::mojom::Action::kSetAccessibilityFocus: return "setAccessibilityFocus"; case ax::mojom::Action::kSetScrollOffset: return "setScrollOffset"; case ax::mojom::Action::kSetSelection: return "setSelection"; case ax::mojom::Action::kSetSequentialFocusNavigationStartingPoint: return "setSequentialFocusNavigationStartingPoint"; case ax::mojom::Action::kSetValue: return "setValue"; case ax::mojom::Action::kShowContextMenu: return "showContextMenu"; case ax::mojom::Action::kGetTextLocation: return "getTextLocation"; case ax::mojom::Action::kAnnotatePageImages: return "annotatePageImages"; case ax::mojom::Action::kSignalEndOfTest: return "signalEndOfTest"; case ax::mojom::Action::kShowTooltip: return "showTooltip"; case ax::mojom::Action::kHideTooltip: return "hideTooltip"; case ax::mojom::Action::kInternalInvalidateTree: return "internalInvalidateTree"; } return ""; } ax::mojom::Action ParseAction(const char* action) { if (0 == strcmp(action, "none")) return ax::mojom::Action::kNone; if (0 == strcmp(action, "annotatePageImages")) return ax::mojom::Action::kAnnotatePageImages; if (0 == strcmp(action, "blur")) return ax::mojom::Action::kBlur; if (0 == strcmp(action, "clearAccessibilityFocus")) return ax::mojom::Action::kClearAccessibilityFocus; if (0 == strcmp(action, "collapse")) return ax::mojom::Action::kCollapse; if (0 == strcmp(action, "customAction")) return ax::mojom::Action::kCustomAction; if (0 == strcmp(action, "decrement")) return ax::mojom::Action::kDecrement; if (0 == strcmp(action, "doDefault")) return ax::mojom::Action::kDoDefault; if (0 == strcmp(action, "expand")) return ax::mojom::Action::kExpand; if (0 == strcmp(action, "focus")) return ax::mojom::Action::kFocus; if (0 == strcmp(action, "getImageData")) return ax::mojom::Action::kGetImageData; if (0 == strcmp(action, "getTextLocation")) return ax::mojom::Action::kGetTextLocation; if (0 == strcmp(action, "hitTest")) return ax::mojom::Action::kHitTest; if (0 == strcmp(action, "increment")) return ax::mojom::Action::kIncrement; if (0 == strcmp(action, "loadInlineTextBoxes")) return ax::mojom::Action::kLoadInlineTextBoxes; if (0 == strcmp(action, "replaceSelectedText")) return ax::mojom::Action::kReplaceSelectedText; if (0 == strcmp(action, "scrollBackward")) return ax::mojom::Action::kScrollBackward; if (0 == strcmp(action, "scrollForward")) return ax::mojom::Action::kScrollForward; if (0 == strcmp(action, "scrollUp")) return ax::mojom::Action::kScrollUp; if (0 == strcmp(action, "scrollDown")) return ax::mojom::Action::kScrollDown; if (0 == strcmp(action, "scrollLeft")) return ax::mojom::Action::kScrollLeft; if (0 == strcmp(action, "scrollRight")) return ax::mojom::Action::kScrollRight; if (0 == strcmp(action, "scrollToMakeVisible")) return ax::mojom::Action::kScrollToMakeVisible; if (0 == strcmp(action, "scrollToPoint")) return ax::mojom::Action::kScrollToPoint; if (0 == strcmp(action, "setAccessibilityFocus")) return ax::mojom::Action::kSetAccessibilityFocus; if (0 == strcmp(action, "setScrollOffset")) return ax::mojom::Action::kSetScrollOffset; if (0 == strcmp(action, "setSelection")) return ax::mojom::Action::kSetSelection; if (0 == strcmp(action, "setSequentialFocusNavigationStartingPoint")) return ax::mojom::Action::kSetSequentialFocusNavigationStartingPoint; if (0 == strcmp(action, "setValue")) return ax::mojom::Action::kSetValue; if (0 == strcmp(action, "showContextMenu")) return ax::mojom::Action::kShowContextMenu; if (0 == strcmp(action, "signalEndOfTest")) return ax::mojom::Action::kSignalEndOfTest; if (0 == strcmp(action, "showTooltip")) return ax::mojom::Action::kShowTooltip; if (0 == strcmp(action, "hideTooltip")) return ax::mojom::Action::kHideTooltip; if (0 == strcmp(action, "internalInvalidateTree")) return ax::mojom::Action::kInternalInvalidateTree; return ax::mojom::Action::kNone; } const char* ToString(ax::mojom::ActionFlags action_flags) { switch (action_flags) { case ax::mojom::ActionFlags::kNone: return "none"; case ax::mojom::ActionFlags::kRequestImages: return "requestImages"; case ax::mojom::ActionFlags::kRequestInlineTextBoxes: return "requestInlineTextBoxes"; } return ""; } ax::mojom::ActionFlags ParseActionFlags(const char* action_flags) { if (0 == strcmp(action_flags, "none")) return ax::mojom::ActionFlags::kNone; if (0 == strcmp(action_flags, "requestImages")) return ax::mojom::ActionFlags::kRequestImages; if (0 == strcmp(action_flags, "requestInlineTextBoxes")) return ax::mojom::ActionFlags::kRequestInlineTextBoxes; return ax::mojom::ActionFlags::kNone; } const char* ToString(ax::mojom::ScrollAlignment scroll_alignment) { switch (scroll_alignment) { case ax::mojom::ScrollAlignment::kNone: return "none"; case ax::mojom::ScrollAlignment::kScrollAlignmentCenter: return "scrollAlignmentCenter"; case ax::mojom::ScrollAlignment::kScrollAlignmentTop: return "scrollAlignmentTop"; case ax::mojom::ScrollAlignment::kScrollAlignmentBottom: return "scrollAlignmentBottom"; case ax::mojom::ScrollAlignment::kScrollAlignmentLeft: return "scrollAlignmentLeft"; case ax::mojom::ScrollAlignment::kScrollAlignmentRight: return "scrollAlignmentRight"; case ax::mojom::ScrollAlignment::kScrollAlignmentClosestEdge: return "scrollAlignmentClosestEdge"; } } ax::mojom::ScrollAlignment ParseScrollAlignment(const char* scroll_alignment) { if (0 == strcmp(scroll_alignment, "none")) return ax::mojom::ScrollAlignment::kNone; if (0 == strcmp(scroll_alignment, "scrollAlignmentCenter")) return ax::mojom::ScrollAlignment::kScrollAlignmentCenter; if (0 == strcmp(scroll_alignment, "scrollAlignmentTop")) return ax::mojom::ScrollAlignment::kScrollAlignmentTop; if (0 == strcmp(scroll_alignment, "scrollAlignmentBottom")) return ax::mojom::ScrollAlignment::kScrollAlignmentBottom; if (0 == strcmp(scroll_alignment, "scrollAlignmentLeft")) return ax::mojom::ScrollAlignment::kScrollAlignmentLeft; if (0 == strcmp(scroll_alignment, "scrollAlignmentRight")) return ax::mojom::ScrollAlignment::kScrollAlignmentRight; if (0 == strcmp(scroll_alignment, "scrollAlignmentClosestEdge")) return ax::mojom::ScrollAlignment::kScrollAlignmentClosestEdge; return ax::mojom::ScrollAlignment::kNone; } const char* ToString(ax::mojom::DefaultActionVerb default_action_verb) { switch (default_action_verb) { case ax::mojom::DefaultActionVerb::kNone: return "none"; case ax::mojom::DefaultActionVerb::kActivate: return "activate"; case ax::mojom::DefaultActionVerb::kCheck: return "check"; case ax::mojom::DefaultActionVerb::kClick: return "click"; case ax::mojom::DefaultActionVerb::kClickAncestor: // Some screen readers, such as Jaws, expect the following spelling of // this verb. return "click-ancestor"; case ax::mojom::DefaultActionVerb::kJump: return "jump"; case ax::mojom::DefaultActionVerb::kOpen: return "open"; case ax::mojom::DefaultActionVerb::kPress: return "press"; case ax::mojom::DefaultActionVerb::kSelect: return "select"; case ax::mojom::DefaultActionVerb::kUncheck: return "uncheck"; } return ""; } ax::mojom::DefaultActionVerb ParseDefaultActionVerb( const char* default_action_verb) { if (0 == strcmp(default_action_verb, "none")) return ax::mojom::DefaultActionVerb::kNone; if (0 == strcmp(default_action_verb, "activate")) return ax::mojom::DefaultActionVerb::kActivate; if (0 == strcmp(default_action_verb, "check")) return ax::mojom::DefaultActionVerb::kCheck; if (0 == strcmp(default_action_verb, "click")) return ax::mojom::DefaultActionVerb::kClick; // Some screen readers, such as Jaws, expect the following spelling of this // verb. if (0 == strcmp(default_action_verb, "click-ancestor")) return ax::mojom::DefaultActionVerb::kClickAncestor; if (0 == strcmp(default_action_verb, "jump")) return ax::mojom::DefaultActionVerb::kJump; if (0 == strcmp(default_action_verb, "open")) return ax::mojom::DefaultActionVerb::kOpen; if (0 == strcmp(default_action_verb, "press")) return ax::mojom::DefaultActionVerb::kPress; if (0 == strcmp(default_action_verb, "select")) return ax::mojom::DefaultActionVerb::kSelect; if (0 == strcmp(default_action_verb, "uncheck")) return ax::mojom::DefaultActionVerb::kUncheck; return ax::mojom::DefaultActionVerb::kNone; } const char* ToString(ax::mojom::Mutation mutation) { switch (mutation) { case ax::mojom::Mutation::kNone: return "none"; case ax::mojom::Mutation::kNodeCreated: return "nodeCreated"; case ax::mojom::Mutation::kSubtreeCreated: return "subtreeCreated"; case ax::mojom::Mutation::kNodeChanged: return "nodeChanged"; case ax::mojom::Mutation::kNodeRemoved: return "nodeRemoved"; } return ""; } ax::mojom::Mutation ParseMutation(const char* mutation) { if (0 == strcmp(mutation, "none")) return ax::mojom::Mutation::kNone; if (0 == strcmp(mutation, "nodeCreated")) return ax::mojom::Mutation::kNodeCreated; if (0 == strcmp(mutation, "subtreeCreated")) return ax::mojom::Mutation::kSubtreeCreated; if (0 == strcmp(mutation, "nodeChanged")) return ax::mojom::Mutation::kNodeChanged; if (0 == strcmp(mutation, "nodeRemoved")) return ax::mojom::Mutation::kNodeRemoved; return ax::mojom::Mutation::kNone; } const char* ToString(ax::mojom::StringAttribute string_attribute) { switch (string_attribute) { case ax::mojom::StringAttribute::kNone: return "none"; case ax::mojom::StringAttribute::kAccessKey: return "accessKey"; case ax::mojom::StringAttribute::kAriaInvalidValue: return "ariaInvalidValue"; case ax::mojom::StringAttribute::kAutoComplete: return "autoComplete"; case ax::mojom::StringAttribute::kChildTreeId: return "childTreeId"; case ax::mojom::StringAttribute::kClassName: return "className"; case ax::mojom::StringAttribute::kContainerLiveRelevant: return "containerLiveRelevant"; case ax::mojom::StringAttribute::kContainerLiveStatus: return "containerLiveStatus"; case ax::mojom::StringAttribute::kDescription: return "description"; case ax::mojom::StringAttribute::kDisplay: return "display"; case ax::mojom::StringAttribute::kFontFamily: return "fontFamily"; case ax::mojom::StringAttribute::kHtmlTag: return "htmlTag"; case ax::mojom::StringAttribute::kImageAnnotation: return "imageAnnotation"; case ax::mojom::StringAttribute::kImageDataUrl: return "imageDataUrl"; case ax::mojom::StringAttribute::kInnerHtml: return "innerHtml"; case ax::mojom::StringAttribute::kInputType: return "inputType"; case ax::mojom::StringAttribute::kKeyShortcuts: return "keyShortcuts"; case ax::mojom::StringAttribute::kLanguage: return "language"; case ax::mojom::StringAttribute::kName: return "name"; case ax::mojom::StringAttribute::kLiveRelevant: return "liveRelevant"; case ax::mojom::StringAttribute::kLiveStatus: return "liveStatus"; case ax::mojom::StringAttribute::kPlaceholder: return "placeholder"; case ax::mojom::StringAttribute::kRole: return "role"; case ax::mojom::StringAttribute::kRoleDescription: return "roleDescription"; case ax::mojom::StringAttribute::kTooltip: return "tooltip"; case ax::mojom::StringAttribute::kUrl: return "url"; case ax::mojom::StringAttribute::kValue: return "value"; } return ""; } ax::mojom::StringAttribute ParseStringAttribute(const char* string_attribute) { if (0 == strcmp(string_attribute, "none")) return ax::mojom::StringAttribute::kNone; if (0 == strcmp(string_attribute, "accessKey")) return ax::mojom::StringAttribute::kAccessKey; if (0 == strcmp(string_attribute, "ariaInvalidValue")) return ax::mojom::StringAttribute::kAriaInvalidValue; if (0 == strcmp(string_attribute, "autoComplete")) return ax::mojom::StringAttribute::kAutoComplete; if (0 == strcmp(string_attribute, "childTreeId")) return ax::mojom::StringAttribute::kChildTreeId; if (0 == strcmp(string_attribute, "className")) return ax::mojom::StringAttribute::kClassName; if (0 == strcmp(string_attribute, "containerLiveRelevant")) return ax::mojom::StringAttribute::kContainerLiveRelevant; if (0 == strcmp(string_attribute, "containerLiveStatus")) return ax::mojom::StringAttribute::kContainerLiveStatus; if (0 == strcmp(string_attribute, "description")) return ax::mojom::StringAttribute::kDescription; if (0 == strcmp(string_attribute, "display")) return ax::mojom::StringAttribute::kDisplay; if (0 == strcmp(string_attribute, "fontFamily")) return ax::mojom::StringAttribute::kFontFamily; if (0 == strcmp(string_attribute, "htmlTag")) return ax::mojom::StringAttribute::kHtmlTag; if (0 == strcmp(string_attribute, "imageAnnotation")) return ax::mojom::StringAttribute::kImageAnnotation; if (0 == strcmp(string_attribute, "imageDataUrl")) return ax::mojom::StringAttribute::kImageDataUrl; if (0 == strcmp(string_attribute, "innerHtml")) return ax::mojom::StringAttribute::kInnerHtml; if (0 == strcmp(string_attribute, "inputType")) return ax::mojom::StringAttribute::kInputType; if (0 == strcmp(string_attribute, "keyShortcuts")) return ax::mojom::StringAttribute::kKeyShortcuts; if (0 == strcmp(string_attribute, "language")) return ax::mojom::StringAttribute::kLanguage; if (0 == strcmp(string_attribute, "name")) return ax::mojom::StringAttribute::kName; if (0 == strcmp(string_attribute, "liveRelevant")) return ax::mojom::StringAttribute::kLiveRelevant; if (0 == strcmp(string_attribute, "liveStatus")) return ax::mojom::StringAttribute::kLiveStatus; if (0 == strcmp(string_attribute, "placeholder")) return ax::mojom::StringAttribute::kPlaceholder; if (0 == strcmp(string_attribute, "role")) return ax::mojom::StringAttribute::kRole; if (0 == strcmp(string_attribute, "roleDescription")) return ax::mojom::StringAttribute::kRoleDescription; if (0 == strcmp(string_attribute, "tooltip")) return ax::mojom::StringAttribute::kTooltip; if (0 == strcmp(string_attribute, "url")) return ax::mojom::StringAttribute::kUrl; if (0 == strcmp(string_attribute, "value")) return ax::mojom::StringAttribute::kValue; return ax::mojom::StringAttribute::kNone; } const char* ToString(ax::mojom::IntAttribute int_attribute) { switch (int_attribute) { case ax::mojom::IntAttribute::kNone: return "none"; case ax::mojom::IntAttribute::kDefaultActionVerb: return "defaultActionVerb"; case ax::mojom::IntAttribute::kDropeffect: return "dropeffect"; case ax::mojom::IntAttribute::kScrollX: return "scrollX"; case ax::mojom::IntAttribute::kScrollXMin: return "scrollXMin"; case ax::mojom::IntAttribute::kScrollXMax: return "scrollXMax"; case ax::mojom::IntAttribute::kScrollY: return "scrollY"; case ax::mojom::IntAttribute::kScrollYMin: return "scrollYMin"; case ax::mojom::IntAttribute::kScrollYMax: return "scrollYMax"; case ax::mojom::IntAttribute::kTextSelStart: return "textSelStart"; case ax::mojom::IntAttribute::kTextSelEnd: return "textSelEnd"; case ax::mojom::IntAttribute::kAriaColumnCount: return "ariaColumnCount"; case ax::mojom::IntAttribute::kAriaCellColumnIndex: return "ariaCellColumnIndex"; case ax::mojom::IntAttribute::kAriaCellColumnSpan: return "ariaCellColumnSpan"; case ax::mojom::IntAttribute::kAriaRowCount: return "ariaRowCount"; case ax::mojom::IntAttribute::kAriaCellRowIndex: return "ariaCellRowIndex"; case ax::mojom::IntAttribute::kAriaCellRowSpan: return "ariaCellRowSpan"; case ax::mojom::IntAttribute::kTableRowCount: return "tableRowCount"; case ax::mojom::IntAttribute::kTableColumnCount: return "tableColumnCount"; case ax::mojom::IntAttribute::kTableHeaderId: return "tableHeaderId"; case ax::mojom::IntAttribute::kTableRowIndex: return "tableRowIndex"; case ax::mojom::IntAttribute::kTableRowHeaderId: return "tableRowHeaderId"; case ax::mojom::IntAttribute::kTableColumnIndex: return "tableColumnIndex"; case ax::mojom::IntAttribute::kTableColumnHeaderId: return "tableColumnHeaderId"; case ax::mojom::IntAttribute::kTableCellColumnIndex: return "tableCellColumnIndex"; case ax::mojom::IntAttribute::kTableCellColumnSpan: return "tableCellColumnSpan"; case ax::mojom::IntAttribute::kTableCellRowIndex: return "tableCellRowIndex"; case ax::mojom::IntAttribute::kTableCellRowSpan: return "tableCellRowSpan"; case ax::mojom::IntAttribute::kSortDirection: return "sortDirection"; case ax::mojom::IntAttribute::kHierarchicalLevel: return "hierarchicalLevel"; case ax::mojom::IntAttribute::kNameFrom: return "nameFrom"; case ax::mojom::IntAttribute::kDescriptionFrom: return "descriptionFrom"; case ax::mojom::IntAttribute::kActivedescendantId: return "activedescendantId"; case ax::mojom::IntAttribute::kErrormessageId: return "errormessageId"; case ax::mojom::IntAttribute::kInPageLinkTargetId: return "inPageLinkTargetId"; case ax::mojom::IntAttribute::kMemberOfId: return "memberOfId"; case ax::mojom::IntAttribute::kNextOnLineId: return "nextOnLineId"; case ax::mojom::IntAttribute::kPopupForId: return "popupForId"; case ax::mojom::IntAttribute::kPreviousOnLineId: return "previousOnLineId"; case ax::mojom::IntAttribute::kRestriction: return "restriction"; case ax::mojom::IntAttribute::kSetSize: return "setSize"; case ax::mojom::IntAttribute::kPosInSet: return "posInSet"; case ax::mojom::IntAttribute::kColorValue: return "colorValue"; case ax::mojom::IntAttribute::kAriaCurrentState: return "ariaCurrentState"; case ax::mojom::IntAttribute::kBackgroundColor: return "backgroundColor"; case ax::mojom::IntAttribute::kColor: return "color"; case ax::mojom::IntAttribute::kHasPopup: return "haspopup"; case ax::mojom::IntAttribute::kInvalidState: return "invalidState"; case ax::mojom::IntAttribute::kCheckedState: return "checkedState"; case ax::mojom::IntAttribute::kListStyle: return "listStyle"; case ax::mojom::IntAttribute::kTextAlign: return "text-align"; case ax::mojom::IntAttribute::kTextDirection: return "textDirection"; case ax::mojom::IntAttribute::kTextPosition: return "textPosition"; case ax::mojom::IntAttribute::kTextStyle: return "textStyle"; case ax::mojom::IntAttribute::kTextOverlineStyle: return "textOverlineStyle"; case ax::mojom::IntAttribute::kTextStrikethroughStyle: return "textStrikethroughStyle"; case ax::mojom::IntAttribute::kTextUnderlineStyle: return "textUnderlineStyle"; case ax::mojom::IntAttribute::kPreviousFocusId: return "previousFocusId"; case ax::mojom::IntAttribute::kNextFocusId: return "nextFocusId"; case ax::mojom::IntAttribute::kImageAnnotationStatus: return "imageAnnotationStatus"; case ax::mojom::IntAttribute::kDOMNodeId: return "domNodeId"; } return ""; } ax::mojom::IntAttribute ParseIntAttribute(const char* int_attribute) { if (0 == strcmp(int_attribute, "none")) return ax::mojom::IntAttribute::kNone; if (0 == strcmp(int_attribute, "defaultActionVerb")) return ax::mojom::IntAttribute::kDefaultActionVerb; if (0 == strcmp(int_attribute, "dropeffect")) return ax::mojom::IntAttribute::kDropeffect; if (0 == strcmp(int_attribute, "scrollX")) return ax::mojom::IntAttribute::kScrollX; if (0 == strcmp(int_attribute, "scrollXMin")) return ax::mojom::IntAttribute::kScrollXMin; if (0 == strcmp(int_attribute, "scrollXMax")) return ax::mojom::IntAttribute::kScrollXMax; if (0 == strcmp(int_attribute, "scrollY")) return ax::mojom::IntAttribute::kScrollY; if (0 == strcmp(int_attribute, "scrollYMin")) return ax::mojom::IntAttribute::kScrollYMin; if (0 == strcmp(int_attribute, "scrollYMax")) return ax::mojom::IntAttribute::kScrollYMax; if (0 == strcmp(int_attribute, "textSelStart")) return ax::mojom::IntAttribute::kTextSelStart; if (0 == strcmp(int_attribute, "textSelEnd")) return ax::mojom::IntAttribute::kTextSelEnd; if (0 == strcmp(int_attribute, "ariaColumnCount")) return ax::mojom::IntAttribute::kAriaColumnCount; if (0 == strcmp(int_attribute, "ariaCellColumnIndex")) return ax::mojom::IntAttribute::kAriaCellColumnIndex; if (0 == strcmp(int_attribute, "ariaCellColumnSpan")) return ax::mojom::IntAttribute::kAriaCellColumnSpan; if (0 == strcmp(int_attribute, "ariaRowCount")) return ax::mojom::IntAttribute::kAriaRowCount; if (0 == strcmp(int_attribute, "ariaCellRowIndex")) return ax::mojom::IntAttribute::kAriaCellRowIndex; if (0 == strcmp(int_attribute, "ariaCellRowSpan")) return ax::mojom::IntAttribute::kAriaCellRowSpan; if (0 == strcmp(int_attribute, "tableRowCount")) return ax::mojom::IntAttribute::kTableRowCount; if (0 == strcmp(int_attribute, "tableColumnCount")) return ax::mojom::IntAttribute::kTableColumnCount; if (0 == strcmp(int_attribute, "tableHeaderId")) return ax::mojom::IntAttribute::kTableHeaderId; if (0 == strcmp(int_attribute, "tableRowIndex")) return ax::mojom::IntAttribute::kTableRowIndex; if (0 == strcmp(int_attribute, "tableRowHeaderId")) return ax::mojom::IntAttribute::kTableRowHeaderId; if (0 == strcmp(int_attribute, "tableColumnIndex")) return ax::mojom::IntAttribute::kTableColumnIndex; if (0 == strcmp(int_attribute, "tableColumnHeaderId")) return ax::mojom::IntAttribute::kTableColumnHeaderId; if (0 == strcmp(int_attribute, "tableCellColumnIndex")) return ax::mojom::IntAttribute::kTableCellColumnIndex; if (0 == strcmp(int_attribute, "tableCellColumnSpan")) return ax::mojom::IntAttribute::kTableCellColumnSpan; if (0 == strcmp(int_attribute, "tableCellRowIndex")) return ax::mojom::IntAttribute::kTableCellRowIndex; if (0 == strcmp(int_attribute, "tableCellRowSpan")) return ax::mojom::IntAttribute::kTableCellRowSpan; if (0 == strcmp(int_attribute, "sortDirection")) return ax::mojom::IntAttribute::kSortDirection; if (0 == strcmp(int_attribute, "hierarchicalLevel")) return ax::mojom::IntAttribute::kHierarchicalLevel; if (0 == strcmp(int_attribute, "nameFrom")) return ax::mojom::IntAttribute::kNameFrom; if (0 == strcmp(int_attribute, "descriptionFrom")) return ax::mojom::IntAttribute::kDescriptionFrom; if (0 == strcmp(int_attribute, "activedescendantId")) return ax::mojom::IntAttribute::kActivedescendantId; if (0 == strcmp(int_attribute, "errormessageId")) return ax::mojom::IntAttribute::kErrormessageId; if (0 == strcmp(int_attribute, "inPageLinkTargetId")) return ax::mojom::IntAttribute::kInPageLinkTargetId; if (0 == strcmp(int_attribute, "memberOfId")) return ax::mojom::IntAttribute::kMemberOfId; if (0 == strcmp(int_attribute, "nextOnLineId")) return ax::mojom::IntAttribute::kNextOnLineId; if (0 == strcmp(int_attribute, "popupForId")) return ax::mojom::IntAttribute::kPopupForId; if (0 == strcmp(int_attribute, "previousOnLineId")) return ax::mojom::IntAttribute::kPreviousOnLineId; if (0 == strcmp(int_attribute, "restriction")) return ax::mojom::IntAttribute::kRestriction; if (0 == strcmp(int_attribute, "setSize")) return ax::mojom::IntAttribute::kSetSize; if (0 == strcmp(int_attribute, "posInSet")) return ax::mojom::IntAttribute::kPosInSet; if (0 == strcmp(int_attribute, "colorValue")) return ax::mojom::IntAttribute::kColorValue; if (0 == strcmp(int_attribute, "ariaCurrentState")) return ax::mojom::IntAttribute::kAriaCurrentState; if (0 == strcmp(int_attribute, "backgroundColor")) return ax::mojom::IntAttribute::kBackgroundColor; if (0 == strcmp(int_attribute, "color")) return ax::mojom::IntAttribute::kColor; if (0 == strcmp(int_attribute, "haspopup")) return ax::mojom::IntAttribute::kHasPopup; if (0 == strcmp(int_attribute, "invalidState")) return ax::mojom::IntAttribute::kInvalidState; if (0 == strcmp(int_attribute, "checkedState")) return ax::mojom::IntAttribute::kCheckedState; if (0 == strcmp(int_attribute, "listStyle")) return ax::mojom::IntAttribute::kListStyle; if (0 == strcmp(int_attribute, "text-align")) return ax::mojom::IntAttribute::kTextAlign; if (0 == strcmp(int_attribute, "textDirection")) return ax::mojom::IntAttribute::kTextDirection; if (0 == strcmp(int_attribute, "textPosition")) return ax::mojom::IntAttribute::kTextPosition; if (0 == strcmp(int_attribute, "textStyle")) return ax::mojom::IntAttribute::kTextStyle; if (0 == strcmp(int_attribute, "textOverlineStyle")) return ax::mojom::IntAttribute::kTextOverlineStyle; if (0 == strcmp(int_attribute, "textStrikethroughStyle")) return ax::mojom::IntAttribute::kTextStrikethroughStyle; if (0 == strcmp(int_attribute, "textUnderlineStyle")) return ax::mojom::IntAttribute::kTextUnderlineStyle; if (0 == strcmp(int_attribute, "previousFocusId")) return ax::mojom::IntAttribute::kPreviousFocusId; if (0 == strcmp(int_attribute, "nextFocusId")) return ax::mojom::IntAttribute::kNextFocusId; if (0 == strcmp(int_attribute, "imageAnnotationStatus")) return ax::mojom::IntAttribute::kImageAnnotationStatus; if (0 == strcmp(int_attribute, "domNodeId")) return ax::mojom::IntAttribute::kDOMNodeId; return ax::mojom::IntAttribute::kNone; } const char* ToString(ax::mojom::FloatAttribute float_attribute) { switch (float_attribute) { case ax::mojom::FloatAttribute::kNone: return "none"; case ax::mojom::FloatAttribute::kValueForRange: return "valueForRange"; case ax::mojom::FloatAttribute::kMinValueForRange: return "minValueForRange"; case ax::mojom::FloatAttribute::kMaxValueForRange: return "maxValueForRange"; case ax::mojom::FloatAttribute::kStepValueForRange: return "stepValueForRange"; case ax::mojom::FloatAttribute::kFontSize: return "fontSize"; case ax::mojom::FloatAttribute::kFontWeight: return "fontWeight"; case ax::mojom::FloatAttribute::kTextIndent: return "textIndent"; } return ""; } ax::mojom::FloatAttribute ParseFloatAttribute(const char* float_attribute) { if (0 == strcmp(float_attribute, "none")) return ax::mojom::FloatAttribute::kNone; if (0 == strcmp(float_attribute, "valueForRange")) return ax::mojom::FloatAttribute::kValueForRange; if (0 == strcmp(float_attribute, "minValueForRange")) return ax::mojom::FloatAttribute::kMinValueForRange; if (0 == strcmp(float_attribute, "maxValueForRange")) return ax::mojom::FloatAttribute::kMaxValueForRange; if (0 == strcmp(float_attribute, "stepValueForRange")) return ax::mojom::FloatAttribute::kStepValueForRange; if (0 == strcmp(float_attribute, "fontSize")) return ax::mojom::FloatAttribute::kFontSize; if (0 == strcmp(float_attribute, "fontWeight")) return ax::mojom::FloatAttribute::kFontWeight; if (0 == strcmp(float_attribute, "textIndent")) return ax::mojom::FloatAttribute::kTextIndent; return ax::mojom::FloatAttribute::kNone; } const char* ToString(ax::mojom::BoolAttribute bool_attribute) { switch (bool_attribute) { case ax::mojom::BoolAttribute::kNone: return "none"; case ax::mojom::BoolAttribute::kBusy: return "busy"; case ax::mojom::BoolAttribute::kEditableRoot: return "editableRoot"; case ax::mojom::BoolAttribute::kContainerLiveAtomic: return "containerLiveAtomic"; case ax::mojom::BoolAttribute::kContainerLiveBusy: return "containerLiveBusy"; case ax::mojom::BoolAttribute::kGrabbed: return "grabbed"; case ax::mojom::BoolAttribute::kLiveAtomic: return "liveAtomic"; case ax::mojom::BoolAttribute::kModal: return "modal"; case ax::mojom::BoolAttribute::kUpdateLocationOnly: return "updateLocationOnly"; case ax::mojom::BoolAttribute::kCanvasHasFallback: return "canvasHasFallback"; case ax::mojom::BoolAttribute::kScrollable: return "scrollable"; case ax::mojom::BoolAttribute::kClickable: return "clickable"; case ax::mojom::BoolAttribute::kClipsChildren: return "clipsChildren"; case ax::mojom::BoolAttribute::kNotUserSelectableStyle: return "notUserSelectableStyle"; case ax::mojom::BoolAttribute::kSelected: return "selected"; case ax::mojom::BoolAttribute::kSelectedFromFocus: return "selectedFromFocus"; case ax::mojom::BoolAttribute::kSupportsTextLocation: return "supportsTextLocation"; case ax::mojom::BoolAttribute::kIsLineBreakingObject: return "isLineBreakingObject"; case ax::mojom::BoolAttribute::kIsPageBreakingObject: return "isPageBreakingObject"; case ax::mojom::BoolAttribute::kHasAriaAttribute: return "hasAriaAttribute"; } return ""; } ax::mojom::BoolAttribute ParseBoolAttribute(const char* bool_attribute) { if (0 == strcmp(bool_attribute, "none")) return ax::mojom::BoolAttribute::kNone; if (0 == strcmp(bool_attribute, "busy")) return ax::mojom::BoolAttribute::kBusy; if (0 == strcmp(bool_attribute, "editableRoot")) return ax::mojom::BoolAttribute::kEditableRoot; if (0 == strcmp(bool_attribute, "containerLiveAtomic")) return ax::mojom::BoolAttribute::kContainerLiveAtomic; if (0 == strcmp(bool_attribute, "containerLiveBusy")) return ax::mojom::BoolAttribute::kContainerLiveBusy; if (0 == strcmp(bool_attribute, "grabbed")) return ax::mojom::BoolAttribute::kGrabbed; if (0 == strcmp(bool_attribute, "liveAtomic")) return ax::mojom::BoolAttribute::kLiveAtomic; if (0 == strcmp(bool_attribute, "modal")) return ax::mojom::BoolAttribute::kModal; if (0 == strcmp(bool_attribute, "updateLocationOnly")) return ax::mojom::BoolAttribute::kUpdateLocationOnly; if (0 == strcmp(bool_attribute, "canvasHasFallback")) return ax::mojom::BoolAttribute::kCanvasHasFallback; if (0 == strcmp(bool_attribute, "scrollable")) return ax::mojom::BoolAttribute::kScrollable; if (0 == strcmp(bool_attribute, "clickable")) return ax::mojom::BoolAttribute::kClickable; if (0 == strcmp(bool_attribute, "clipsChildren")) return ax::mojom::BoolAttribute::kClipsChildren; if (0 == strcmp(bool_attribute, "notUserSelectableStyle")) return ax::mojom::BoolAttribute::kNotUserSelectableStyle; if (0 == strcmp(bool_attribute, "selected")) return ax::mojom::BoolAttribute::kSelected; if (0 == strcmp(bool_attribute, "selectedFromFocus")) return ax::mojom::BoolAttribute::kSelectedFromFocus; if (0 == strcmp(bool_attribute, "supportsTextLocation")) return ax::mojom::BoolAttribute::kSupportsTextLocation; if (0 == strcmp(bool_attribute, "isLineBreakingObject")) return ax::mojom::BoolAttribute::kIsLineBreakingObject; if (0 == strcmp(bool_attribute, "isPageBreakingObject")) return ax::mojom::BoolAttribute::kIsPageBreakingObject; if (0 == strcmp(bool_attribute, "hasAriaAttribute")) return ax::mojom::BoolAttribute::kHasAriaAttribute; return ax::mojom::BoolAttribute::kNone; } const char* ToString(ax::mojom::IntListAttribute int_list_attribute) { switch (int_list_attribute) { case ax::mojom::IntListAttribute::kNone: return "none"; case ax::mojom::IntListAttribute::kIndirectChildIds: return "indirectChildIds"; case ax::mojom::IntListAttribute::kControlsIds: return "controlsIds"; case ax::mojom::IntListAttribute::kDetailsIds: return "detailsIds"; case ax::mojom::IntListAttribute::kDescribedbyIds: return "describedbyIds"; case ax::mojom::IntListAttribute::kFlowtoIds: return "flowtoIds"; case ax::mojom::IntListAttribute::kLabelledbyIds: return "labelledbyIds"; case ax::mojom::IntListAttribute::kRadioGroupIds: return "radioGroupIds"; case ax::mojom::IntListAttribute::kMarkerTypes: return "markerTypes"; case ax::mojom::IntListAttribute::kMarkerStarts: return "markerStarts"; case ax::mojom::IntListAttribute::kMarkerEnds: return "markerEnds"; case ax::mojom::IntListAttribute::kCharacterOffsets: return "characterOffsets"; case ax::mojom::IntListAttribute::kCachedLineStarts: return "cachedLineStarts"; case ax::mojom::IntListAttribute::kWordStarts: return "wordStarts"; case ax::mojom::IntListAttribute::kWordEnds: return "wordEnds"; case ax::mojom::IntListAttribute::kCustomActionIds: return "customActionIds"; } return ""; } ax::mojom::IntListAttribute ParseIntListAttribute( const char* int_list_attribute) { if (0 == strcmp(int_list_attribute, "none")) return ax::mojom::IntListAttribute::kNone; if (0 == strcmp(int_list_attribute, "indirectChildIds")) return ax::mojom::IntListAttribute::kIndirectChildIds; if (0 == strcmp(int_list_attribute, "controlsIds")) return ax::mojom::IntListAttribute::kControlsIds; if (0 == strcmp(int_list_attribute, "detailsIds")) return ax::mojom::IntListAttribute::kDetailsIds; if (0 == strcmp(int_list_attribute, "describedbyIds")) return ax::mojom::IntListAttribute::kDescribedbyIds; if (0 == strcmp(int_list_attribute, "flowtoIds")) return ax::mojom::IntListAttribute::kFlowtoIds; if (0 == strcmp(int_list_attribute, "labelledbyIds")) return ax::mojom::IntListAttribute::kLabelledbyIds; if (0 == strcmp(int_list_attribute, "radioGroupIds")) return ax::mojom::IntListAttribute::kRadioGroupIds; if (0 == strcmp(int_list_attribute, "markerTypes")) return ax::mojom::IntListAttribute::kMarkerTypes; if (0 == strcmp(int_list_attribute, "markerStarts")) return ax::mojom::IntListAttribute::kMarkerStarts; if (0 == strcmp(int_list_attribute, "markerEnds")) return ax::mojom::IntListAttribute::kMarkerEnds; if (0 == strcmp(int_list_attribute, "characterOffsets")) return ax::mojom::IntListAttribute::kCharacterOffsets; if (0 == strcmp(int_list_attribute, "cachedLineStarts")) return ax::mojom::IntListAttribute::kCachedLineStarts; if (0 == strcmp(int_list_attribute, "wordStarts")) return ax::mojom::IntListAttribute::kWordStarts; if (0 == strcmp(int_list_attribute, "wordEnds")) return ax::mojom::IntListAttribute::kWordEnds; if (0 == strcmp(int_list_attribute, "customActionIds")) return ax::mojom::IntListAttribute::kCustomActionIds; return ax::mojom::IntListAttribute::kNone; } const char* ToString(ax::mojom::StringListAttribute string_list_attribute) { switch (string_list_attribute) { case ax::mojom::StringListAttribute::kNone: return "none"; case ax::mojom::StringListAttribute::kCustomActionDescriptions: return "customActionDescriptions"; } return ""; } ax::mojom::StringListAttribute ParseStringListAttribute( const char* string_list_attribute) { if (0 == strcmp(string_list_attribute, "none")) return ax::mojom::StringListAttribute::kNone; if (0 == strcmp(string_list_attribute, "customActionDescriptions")) return ax::mojom::StringListAttribute::kCustomActionDescriptions; return ax::mojom::StringListAttribute::kNone; } const char* ToString(ax::mojom::ListStyle list_style) { switch (list_style) { case ax::mojom::ListStyle::kNone: return "none"; case ax::mojom::ListStyle::kCircle: return "circle"; case ax::mojom::ListStyle::kDisc: return "disc"; case ax::mojom::ListStyle::kImage: return "image"; case ax::mojom::ListStyle::kNumeric: return "numeric"; case ax::mojom::ListStyle::kOther: return "other"; case ax::mojom::ListStyle::kSquare: return "square"; } return ""; } ax::mojom::ListStyle ParseListStyle(const char* list_style) { if (0 == strcmp(list_style, "none")) return ax::mojom::ListStyle::kNone; if (0 == strcmp(list_style, "circle")) return ax::mojom::ListStyle::kCircle; if (0 == strcmp(list_style, "disc")) return ax::mojom::ListStyle::kDisc; if (0 == strcmp(list_style, "image")) return ax::mojom::ListStyle::kImage; if (0 == strcmp(list_style, "numeric")) return ax::mojom::ListStyle::kNumeric; if (0 == strcmp(list_style, "other")) return ax::mojom::ListStyle::kOther; if (0 == strcmp(list_style, "square")) return ax::mojom::ListStyle::kSquare; return ax::mojom::ListStyle::kNone; } const char* ToString(ax::mojom::MarkerType marker_type) { switch (marker_type) { case ax::mojom::MarkerType::kNone: return "none"; case ax::mojom::MarkerType::kSpelling: return "spelling"; case ax::mojom::MarkerType::kGrammar: return "grammar"; case ax::mojom::MarkerType::kTextMatch: return "textMatch"; case ax::mojom::MarkerType::kActiveSuggestion: return "activeSuggestion"; case ax::mojom::MarkerType::kSuggestion: return "suggestion"; } return ""; } ax::mojom::MarkerType ParseMarkerType(const char* marker_type) { if (0 == strcmp(marker_type, "none")) return ax::mojom::MarkerType::kNone; if (0 == strcmp(marker_type, "spelling")) return ax::mojom::MarkerType::kSpelling; if (0 == strcmp(marker_type, "grammar")) return ax::mojom::MarkerType::kGrammar; if (0 == strcmp(marker_type, "textMatch")) return ax::mojom::MarkerType::kTextMatch; if (0 == strcmp(marker_type, "activeSuggestion")) return ax::mojom::MarkerType::kActiveSuggestion; if (0 == strcmp(marker_type, "suggestion")) return ax::mojom::MarkerType::kSuggestion; return ax::mojom::MarkerType::kNone; } const char* ToString(ax::mojom::MoveDirection move_direction) { switch (move_direction) { case ax::mojom::MoveDirection::kForward: return "forward"; case ax::mojom::MoveDirection::kBackward: return "backward"; } return ""; } ax::mojom::MoveDirection ParseMoveDirection(const char* move_direction) { if (0 == strcmp(move_direction, "forward")) return ax::mojom::MoveDirection::kForward; if (0 == strcmp(move_direction, "backward")) return ax::mojom::MoveDirection::kBackward; return ax::mojom::MoveDirection::kForward; } const char* ToString(ax::mojom::Command command) { switch (command) { case ax::mojom::Command::kClearSelection: return "clearSelection"; case ax::mojom::Command::kCut: return "cut"; case ax::mojom::Command::kDelete: return "delete"; case ax::mojom::Command::kDictate: return "dictate"; case ax::mojom::Command::kExtendSelection: return "extendSelection"; case ax::mojom::Command::kFormat: return "format"; case ax::mojom::Command::kInsert: return "insert"; case ax::mojom::Command::kMarker: return "marker"; case ax::mojom::Command::kMoveSelection: return "moveSelection"; case ax::mojom::Command::kPaste: return "paste"; case ax::mojom::Command::kReplace: return "replace"; case ax::mojom::Command::kSetSelection: return "setSelection"; case ax::mojom::Command::kType: return "type"; } return ""; } ax::mojom::Command ParseCommand(const char* command) { if (0 == strcmp(command, "clearSelection")) return ax::mojom::Command::kClearSelection; if (0 == strcmp(command, "cut")) return ax::mojom::Command::kCut; if (0 == strcmp(command, "delete")) return ax::mojom::Command::kDelete; if (0 == strcmp(command, "dictate")) return ax::mojom::Command::kDictate; if (0 == strcmp(command, "extendSelection")) return ax::mojom::Command::kExtendSelection; if (0 == strcmp(command, "format")) return ax::mojom::Command::kFormat; if (0 == strcmp(command, "insert")) return ax::mojom::Command::kInsert; if (0 == strcmp(command, "marker")) return ax::mojom::Command::kMarker; if (0 == strcmp(command, "moveSelection")) return ax::mojom::Command::kMoveSelection; if (0 == strcmp(command, "paste")) return ax::mojom::Command::kPaste; if (0 == strcmp(command, "replace")) return ax::mojom::Command::kReplace; if (0 == strcmp(command, "setSelection")) return ax::mojom::Command::kSetSelection; if (0 == strcmp(command, "type")) return ax::mojom::Command::kType; // Return the default command. return ax::mojom::Command::kType; } const char* ToString(ax::mojom::TextBoundary text_boundary) { switch (text_boundary) { case ax::mojom::TextBoundary::kCharacter: return "character"; case ax::mojom::TextBoundary::kFormat: return "format"; case ax::mojom::TextBoundary::kLineEnd: return "lineEnd"; case ax::mojom::TextBoundary::kLineStart: return "lineStart"; case ax::mojom::TextBoundary::kLineStartOrEnd: return "lineStartOrEnd"; case ax::mojom::TextBoundary::kObject: return "object"; case ax::mojom::TextBoundary::kPageEnd: return "pageEnd"; case ax::mojom::TextBoundary::kPageStart: return "pageStart"; case ax::mojom::TextBoundary::kPageStartOrEnd: return "pageStartOrEnd"; case ax::mojom::TextBoundary::kParagraphEnd: return "paragraphEnd"; case ax::mojom::TextBoundary::kParagraphStart: return "paragraphStart"; case ax::mojom::TextBoundary::kParagraphStartOrEnd: return "paragraphStartOrEnd"; case ax::mojom::TextBoundary::kSentenceEnd: return "sentenceEnd"; case ax::mojom::TextBoundary::kSentenceStart: return "sentenceStart"; case ax::mojom::TextBoundary::kSentenceStartOrEnd: return "sentenceStartOrEnd"; case ax::mojom::TextBoundary::kWebPage: return "webPage"; case ax::mojom::TextBoundary::kWordEnd: return "wordEnd"; case ax::mojom::TextBoundary::kWordStart: return "wordStart"; case ax::mojom::TextBoundary::kWordStartOrEnd: return "wordStartOrEnd"; } return ""; } ax::mojom::TextBoundary ParseTextBoundary(const char* text_boundary) { if (0 == strcmp(text_boundary, "object")) return ax::mojom::TextBoundary::kObject; if (0 == strcmp(text_boundary, "character")) return ax::mojom::TextBoundary::kCharacter; if (0 == strcmp(text_boundary, "format")) return ax::mojom::TextBoundary::kFormat; if (0 == strcmp(text_boundary, "lineEnd")) return ax::mojom::TextBoundary::kLineEnd; if (0 == strcmp(text_boundary, "lineStart")) return ax::mojom::TextBoundary::kLineStart; if (0 == strcmp(text_boundary, "lineStartOrEnd")) return ax::mojom::TextBoundary::kLineStartOrEnd; if (0 == strcmp(text_boundary, "pageEnd")) return ax::mojom::TextBoundary::kPageEnd; if (0 == strcmp(text_boundary, "pageStart")) return ax::mojom::TextBoundary::kPageStart; if (0 == strcmp(text_boundary, "pageStartOrEnd")) return ax::mojom::TextBoundary::kPageStartOrEnd; if (0 == strcmp(text_boundary, "paragraphEnd")) return ax::mojom::TextBoundary::kParagraphEnd; if (0 == strcmp(text_boundary, "paragraphStart")) return ax::mojom::TextBoundary::kParagraphStart; if (0 == strcmp(text_boundary, "paragraphStartOrEnd")) return ax::mojom::TextBoundary::kParagraphStartOrEnd; if (0 == strcmp(text_boundary, "sentenceEnd")) return ax::mojom::TextBoundary::kSentenceEnd; if (0 == strcmp(text_boundary, "sentenceStart")) return ax::mojom::TextBoundary::kSentenceStart; if (0 == strcmp(text_boundary, "sentenceStartOrEnd")) return ax::mojom::TextBoundary::kSentenceStartOrEnd; if (0 == strcmp(text_boundary, "webPage")) return ax::mojom::TextBoundary::kWebPage; if (0 == strcmp(text_boundary, "wordEnd")) return ax::mojom::TextBoundary::kWordEnd; if (0 == strcmp(text_boundary, "wordStart")) return ax::mojom::TextBoundary::kWordStart; if (0 == strcmp(text_boundary, "wordStartOrEnd")) return ax::mojom::TextBoundary::kWordStartOrEnd; return ax::mojom::TextBoundary::kObject; } const char* ToString(ax::mojom::TextDecorationStyle text_decoration_style) { switch (text_decoration_style) { case ax::mojom::TextDecorationStyle::kNone: return "none"; case ax::mojom::TextDecorationStyle::kSolid: return "solid"; case ax::mojom::TextDecorationStyle::kDashed: return "dashed"; case ax::mojom::TextDecorationStyle::kDotted: return "dotted"; case ax::mojom::TextDecorationStyle::kDouble: return "double"; case ax::mojom::TextDecorationStyle::kWavy: return "wavy"; } return ""; } ax::mojom::TextDecorationStyle ParseTextDecorationStyle( const char* text_decoration_style) { if (0 == strcmp(text_decoration_style, "none")) return ax::mojom::TextDecorationStyle::kNone; if (0 == strcmp(text_decoration_style, "solid")) return ax::mojom::TextDecorationStyle::kSolid; if (0 == strcmp(text_decoration_style, "dashed")) return ax::mojom::TextDecorationStyle::kDashed; if (0 == strcmp(text_decoration_style, "dotted")) return ax::mojom::TextDecorationStyle::kDotted; if (0 == strcmp(text_decoration_style, "double")) return ax::mojom::TextDecorationStyle::kDouble; if (0 == strcmp(text_decoration_style, "wavy")) return ax::mojom::TextDecorationStyle::kWavy; return ax::mojom::TextDecorationStyle::kNone; } const char* ToString(ax::mojom::TextAlign text_align) { switch (text_align) { case ax::mojom::TextAlign::kNone: return "none"; case ax::mojom::TextAlign::kLeft: return "left"; case ax::mojom::TextAlign::kRight: return "right"; case ax::mojom::TextAlign::kCenter: return "center"; case ax::mojom::TextAlign::kJustify: return "justify"; } return ""; } ax::mojom::TextAlign ParseTextAlign(const char* text_align) { if (0 == strcmp(text_align, "none")) return ax::mojom::TextAlign::kNone; if (0 == strcmp(text_align, "left")) return ax::mojom::TextAlign::kLeft; if (0 == strcmp(text_align, "right")) return ax::mojom::TextAlign::kRight; if (0 == strcmp(text_align, "center")) return ax::mojom::TextAlign::kCenter; if (0 == strcmp(text_align, "justify")) return ax::mojom::TextAlign::kJustify; return ax::mojom::TextAlign::kNone; } const char* ToString(ax::mojom::WritingDirection text_direction) { switch (text_direction) { case ax::mojom::WritingDirection::kNone: return "none"; case ax::mojom::WritingDirection::kLtr: return "ltr"; case ax::mojom::WritingDirection::kRtl: return "rtl"; case ax::mojom::WritingDirection::kTtb: return "ttb"; case ax::mojom::WritingDirection::kBtt: return "btt"; } return ""; } ax::mojom::WritingDirection ParseTextDirection(const char* text_direction) { if (0 == strcmp(text_direction, "none")) return ax::mojom::WritingDirection::kNone; if (0 == strcmp(text_direction, "ltr")) return ax::mojom::WritingDirection::kLtr; if (0 == strcmp(text_direction, "rtl")) return ax::mojom::WritingDirection::kRtl; if (0 == strcmp(text_direction, "ttb")) return ax::mojom::WritingDirection::kTtb; if (0 == strcmp(text_direction, "btt")) return ax::mojom::WritingDirection::kBtt; return ax::mojom::WritingDirection::kNone; } const char* ToString(ax::mojom::TextPosition text_position) { switch (text_position) { case ax::mojom::TextPosition::kNone: return "none"; case ax::mojom::TextPosition::kSubscript: return "subscript"; case ax::mojom::TextPosition::kSuperscript: return "superscript"; } return ""; } ax::mojom::TextPosition ParseTextPosition(const char* text_position) { if (0 == strcmp(text_position, "none")) return ax::mojom::TextPosition::kNone; if (0 == strcmp(text_position, "subscript")) return ax::mojom::TextPosition::kSubscript; if (0 == strcmp(text_position, "superscript")) return ax::mojom::TextPosition::kSuperscript; return ax::mojom::TextPosition::kNone; } const char* ToString(ax::mojom::TextStyle text_style) { switch (text_style) { case ax::mojom::TextStyle::kNone: return "none"; case ax::mojom::TextStyle::kBold: return "bold"; case ax::mojom::TextStyle::kItalic: return "italic"; case ax::mojom::TextStyle::kUnderline: return "underline"; case ax::mojom::TextStyle::kLineThrough: return "lineThrough"; case ax::mojom::TextStyle::kOverline: return "overline"; } return ""; } ax::mojom::TextStyle ParseTextStyle(const char* text_style) { if (0 == strcmp(text_style, "none")) return ax::mojom::TextStyle::kNone; if (0 == strcmp(text_style, "bold")) return ax::mojom::TextStyle::kBold; if (0 == strcmp(text_style, "italic")) return ax::mojom::TextStyle::kItalic; if (0 == strcmp(text_style, "underline")) return ax::mojom::TextStyle::kUnderline; if (0 == strcmp(text_style, "lineThrough")) return ax::mojom::TextStyle::kLineThrough; if (0 == strcmp(text_style, "overline")) return ax::mojom::TextStyle::kOverline; return ax::mojom::TextStyle::kNone; } const char* ToString(ax::mojom::AriaCurrentState aria_current_state) { switch (aria_current_state) { case ax::mojom::AriaCurrentState::kNone: return "none"; case ax::mojom::AriaCurrentState::kFalse: return "false"; case ax::mojom::AriaCurrentState::kTrue: return "true"; case ax::mojom::AriaCurrentState::kPage: return "page"; case ax::mojom::AriaCurrentState::kStep: return "step"; case ax::mojom::AriaCurrentState::kLocation: return "location"; case ax::mojom::AriaCurrentState::kUnclippedLocation: return "unclippedLocation"; case ax::mojom::AriaCurrentState::kDate: return "date"; case ax::mojom::AriaCurrentState::kTime: return "time"; } return ""; } ax::mojom::AriaCurrentState ParseAriaCurrentState( const char* aria_current_state) { if (0 == strcmp(aria_current_state, "none")) return ax::mojom::AriaCurrentState::kNone; if (0 == strcmp(aria_current_state, "false")) return ax::mojom::AriaCurrentState::kFalse; if (0 == strcmp(aria_current_state, "true")) return ax::mojom::AriaCurrentState::kTrue; if (0 == strcmp(aria_current_state, "page")) return ax::mojom::AriaCurrentState::kPage; if (0 == strcmp(aria_current_state, "step")) return ax::mojom::AriaCurrentState::kStep; if (0 == strcmp(aria_current_state, "location")) return ax::mojom::AriaCurrentState::kLocation; if (0 == strcmp(aria_current_state, "unclippedLocation")) return ax::mojom::AriaCurrentState::kUnclippedLocation; if (0 == strcmp(aria_current_state, "date")) return ax::mojom::AriaCurrentState::kDate; if (0 == strcmp(aria_current_state, "time")) return ax::mojom::AriaCurrentState::kTime; return ax::mojom::AriaCurrentState::kNone; } const char* ToString(ax::mojom::HasPopup has_popup) { switch (has_popup) { case ax::mojom::HasPopup::kFalse: return ""; case ax::mojom::HasPopup::kTrue: return "true"; case ax::mojom::HasPopup::kMenu: return "menu"; case ax::mojom::HasPopup::kListbox: return "listbox"; case ax::mojom::HasPopup::kTree: return "tree"; case ax::mojom::HasPopup::kGrid: return "grid"; case ax::mojom::HasPopup::kDialog: return "dialog"; } return ""; } ax::mojom::HasPopup ParseHasPopup(const char* has_popup) { if (0 == strcmp(has_popup, "true")) return ax::mojom::HasPopup::kTrue; if (0 == strcmp(has_popup, "menu")) return ax::mojom::HasPopup::kMenu; if (0 == strcmp(has_popup, "listbox")) return ax::mojom::HasPopup::kListbox; if (0 == strcmp(has_popup, "tree")) return ax::mojom::HasPopup::kTree; if (0 == strcmp(has_popup, "grid")) return ax::mojom::HasPopup::kGrid; if (0 == strcmp(has_popup, "dialog")) return ax::mojom::HasPopup::kDialog; return ax::mojom::HasPopup::kFalse; } const char* ToString(ax::mojom::InvalidState invalid_state) { switch (invalid_state) { case ax::mojom::InvalidState::kNone: return "none"; case ax::mojom::InvalidState::kFalse: return "false"; case ax::mojom::InvalidState::kTrue: return "true"; case ax::mojom::InvalidState::kOther: return "other"; } return ""; } ax::mojom::InvalidState ParseInvalidState(const char* invalid_state) { if (0 == strcmp(invalid_state, "none")) return ax::mojom::InvalidState::kNone; if (0 == strcmp(invalid_state, "false")) return ax::mojom::InvalidState::kFalse; if (0 == strcmp(invalid_state, "true")) return ax::mojom::InvalidState::kTrue; if (0 == strcmp(invalid_state, "other")) return ax::mojom::InvalidState::kOther; return ax::mojom::InvalidState::kNone; } const char* ToString(ax::mojom::Restriction restriction) { switch (restriction) { case ax::mojom::Restriction::kNone: return "none"; case ax::mojom::Restriction::kReadOnly: return "readOnly"; case ax::mojom::Restriction::kDisabled: return "disabled"; } return ""; } ax::mojom::Restriction ParseRestriction(const char* restriction) { if (0 == strcmp(restriction, "none")) return ax::mojom::Restriction::kNone; if (0 == strcmp(restriction, "readOnly")) return ax::mojom::Restriction::kReadOnly; if (0 == strcmp(restriction, "disabled")) return ax::mojom::Restriction::kDisabled; return ax::mojom::Restriction::kNone; } const char* ToString(ax::mojom::CheckedState checked_state) { switch (checked_state) { case ax::mojom::CheckedState::kNone: return "none"; case ax::mojom::CheckedState::kFalse: return "false"; case ax::mojom::CheckedState::kTrue: return "true"; case ax::mojom::CheckedState::kMixed: return "mixed"; } return ""; } ax::mojom::CheckedState ParseCheckedState(const char* checked_state) { if (0 == strcmp(checked_state, "none")) return ax::mojom::CheckedState::kNone; if (0 == strcmp(checked_state, "false")) return ax::mojom::CheckedState::kFalse; if (0 == strcmp(checked_state, "true")) return ax::mojom::CheckedState::kTrue; if (0 == strcmp(checked_state, "mixed")) return ax::mojom::CheckedState::kMixed; return ax::mojom::CheckedState::kNone; } const char* ToString(ax::mojom::SortDirection sort_direction) { switch (sort_direction) { case ax::mojom::SortDirection::kNone: return "none"; case ax::mojom::SortDirection::kUnsorted: return "unsorted"; case ax::mojom::SortDirection::kAscending: return "ascending"; case ax::mojom::SortDirection::kDescending: return "descending"; case ax::mojom::SortDirection::kOther: return "other"; } return ""; } ax::mojom::SortDirection ParseSortDirection(const char* sort_direction) { if (0 == strcmp(sort_direction, "none")) return ax::mojom::SortDirection::kNone; if (0 == strcmp(sort_direction, "unsorted")) return ax::mojom::SortDirection::kUnsorted; if (0 == strcmp(sort_direction, "ascending")) return ax::mojom::SortDirection::kAscending; if (0 == strcmp(sort_direction, "descending")) return ax::mojom::SortDirection::kDescending; if (0 == strcmp(sort_direction, "other")) return ax::mojom::SortDirection::kOther; return ax::mojom::SortDirection::kNone; } const char* ToString(ax::mojom::NameFrom name_from) { switch (name_from) { case ax::mojom::NameFrom::kNone: return "none"; case ax::mojom::NameFrom::kUninitialized: return "uninitialized"; case ax::mojom::NameFrom::kAttribute: return "attribute"; case ax::mojom::NameFrom::kAttributeExplicitlyEmpty: return "attributeExplicitlyEmpty"; case ax::mojom::NameFrom::kCaption: return "caption"; case ax::mojom::NameFrom::kContents: return "contents"; case ax::mojom::NameFrom::kPlaceholder: return "placeholder"; case ax::mojom::NameFrom::kRelatedElement: return "relatedElement"; case ax::mojom::NameFrom::kTitle: return "title"; case ax::mojom::NameFrom::kValue: return "value"; } return ""; } ax::mojom::NameFrom ParseNameFrom(const char* name_from) { if (0 == strcmp(name_from, "none")) return ax::mojom::NameFrom::kNone; if (0 == strcmp(name_from, "uninitialized")) return ax::mojom::NameFrom::kUninitialized; if (0 == strcmp(name_from, "attribute")) return ax::mojom::NameFrom::kAttribute; if (0 == strcmp(name_from, "attributeExplicitlyEmpty")) return ax::mojom::NameFrom::kAttributeExplicitlyEmpty; if (0 == strcmp(name_from, "caption")) return ax::mojom::NameFrom::kCaption; if (0 == strcmp(name_from, "contents")) return ax::mojom::NameFrom::kContents; if (0 == strcmp(name_from, "placeholder")) return ax::mojom::NameFrom::kPlaceholder; if (0 == strcmp(name_from, "relatedElement")) return ax::mojom::NameFrom::kRelatedElement; if (0 == strcmp(name_from, "title")) return ax::mojom::NameFrom::kTitle; if (0 == strcmp(name_from, "value")) return ax::mojom::NameFrom::kValue; return ax::mojom::NameFrom::kNone; } const char* ToString(ax::mojom::DescriptionFrom description_from) { switch (description_from) { case ax::mojom::DescriptionFrom::kNone: return "none"; case ax::mojom::DescriptionFrom::kUninitialized: return "uninitialized"; case ax::mojom::DescriptionFrom::kAttribute: return "attribute"; case ax::mojom::DescriptionFrom::kContents: return "contents"; case ax::mojom::DescriptionFrom::kRelatedElement: return "relatedElement"; case ax::mojom::DescriptionFrom::kTitle: return "title"; } return ""; } ax::mojom::DescriptionFrom ParseDescriptionFrom(const char* description_from) { if (0 == strcmp(description_from, "none")) return ax::mojom::DescriptionFrom::kNone; if (0 == strcmp(description_from, "uninitialized")) return ax::mojom::DescriptionFrom::kUninitialized; if (0 == strcmp(description_from, "attribute")) return ax::mojom::DescriptionFrom::kAttribute; if (0 == strcmp(description_from, "contents")) return ax::mojom::DescriptionFrom::kContents; if (0 == strcmp(description_from, "relatedElement")) return ax::mojom::DescriptionFrom::kRelatedElement; if (0 == strcmp(description_from, "title")) return ax::mojom::DescriptionFrom::kTitle; return ax::mojom::DescriptionFrom::kNone; } const char* ToString(ax::mojom::EventFrom event_from) { switch (event_from) { case ax::mojom::EventFrom::kNone: return "none"; case ax::mojom::EventFrom::kUser: return "user"; case ax::mojom::EventFrom::kPage: return "page"; case ax::mojom::EventFrom::kAction: return "action"; } return ""; } ax::mojom::EventFrom ParseEventFrom(const char* event_from) { if (0 == strcmp(event_from, "none")) return ax::mojom::EventFrom::kNone; if (0 == strcmp(event_from, "user")) return ax::mojom::EventFrom::kUser; if (0 == strcmp(event_from, "page")) return ax::mojom::EventFrom::kPage; if (0 == strcmp(event_from, "action")) return ax::mojom::EventFrom::kAction; return ax::mojom::EventFrom::kNone; } const char* ToString(ax::mojom::Gesture gesture) { switch (gesture) { case ax::mojom::Gesture::kNone: return "none"; case ax::mojom::Gesture::kClick: return "click"; case ax::mojom::Gesture::kSwipeLeft1: return "swipeLeft1"; case ax::mojom::Gesture::kSwipeUp1: return "swipeUp1"; case ax::mojom::Gesture::kSwipeRight1: return "swipeRight1"; case ax::mojom::Gesture::kSwipeDown1: return "swipeDown1"; case ax::mojom::Gesture::kSwipeLeft2: return "swipeLeft2"; case ax::mojom::Gesture::kSwipeUp2: return "swipeUp2"; case ax::mojom::Gesture::kSwipeRight2: return "swipeRight2"; case ax::mojom::Gesture::kSwipeDown2: return "swipeDown2"; case ax::mojom::Gesture::kSwipeLeft3: return "swipeLeft3"; case ax::mojom::Gesture::kSwipeUp3: return "swipeUp3"; case ax::mojom::Gesture::kSwipeRight3: return "swipeRight3"; case ax::mojom::Gesture::kSwipeDown3: return "swipeDown3"; case ax::mojom::Gesture::kSwipeLeft4: return "swipeLeft4"; case ax::mojom::Gesture::kSwipeUp4: return "swipeUp4"; case ax::mojom::Gesture::kSwipeRight4: return "swipeRight4"; case ax::mojom::Gesture::kSwipeDown4: return "swipeDown4"; case ax::mojom::Gesture::kTap2: return "tap2"; case ax::mojom::Gesture::kTap3: return "tap3"; case ax::mojom::Gesture::kTap4: return "tap4"; case ax::mojom::Gesture::kTouchExplore: return "touchExplore"; } return ""; } ax::mojom::Gesture ParseGesture(const char* gesture) { if (0 == strcmp(gesture, "none")) return ax::mojom::Gesture::kNone; if (0 == strcmp(gesture, "click")) return ax::mojom::Gesture::kClick; if (0 == strcmp(gesture, "swipeLeft1")) return ax::mojom::Gesture::kSwipeLeft1; if (0 == strcmp(gesture, "swipeUp1")) return ax::mojom::Gesture::kSwipeUp1; if (0 == strcmp(gesture, "swipeRight1")) return ax::mojom::Gesture::kSwipeRight1; if (0 == strcmp(gesture, "swipeDown1")) return ax::mojom::Gesture::kSwipeDown1; if (0 == strcmp(gesture, "swipeLeft2")) return ax::mojom::Gesture::kSwipeLeft2; if (0 == strcmp(gesture, "swipeUp2")) return ax::mojom::Gesture::kSwipeUp2; if (0 == strcmp(gesture, "swipeRight2")) return ax::mojom::Gesture::kSwipeRight2; if (0 == strcmp(gesture, "swipeDown2")) return ax::mojom::Gesture::kSwipeDown2; if (0 == strcmp(gesture, "swipeLeft3")) return ax::mojom::Gesture::kSwipeLeft3; if (0 == strcmp(gesture, "swipeUp3")) return ax::mojom::Gesture::kSwipeUp3; if (0 == strcmp(gesture, "swipeRight3")) return ax::mojom::Gesture::kSwipeRight3; if (0 == strcmp(gesture, "swipeDown3")) return ax::mojom::Gesture::kSwipeDown3; if (0 == strcmp(gesture, "swipeLeft4")) return ax::mojom::Gesture::kSwipeLeft4; if (0 == strcmp(gesture, "swipeUp4")) return ax::mojom::Gesture::kSwipeUp4; if (0 == strcmp(gesture, "swipeRight4")) return ax::mojom::Gesture::kSwipeRight4; if (0 == strcmp(gesture, "swipeDown4")) return ax::mojom::Gesture::kSwipeDown4; if (0 == strcmp(gesture, "tap2")) return ax::mojom::Gesture::kTap2; if (0 == strcmp(gesture, "tap3")) return ax::mojom::Gesture::kTap3; if (0 == strcmp(gesture, "tap4")) return ax::mojom::Gesture::kTap4; if (0 == strcmp(gesture, "touchExplore")) return ax::mojom::Gesture::kTouchExplore; return ax::mojom::Gesture::kNone; } const char* ToString(ax::mojom::TextAffinity text_affinity) { switch (text_affinity) { case ax::mojom::TextAffinity::kNone: return "none"; case ax::mojom::TextAffinity::kDownstream: return "downstream"; case ax::mojom::TextAffinity::kUpstream: return "upstream"; } return ""; } ax::mojom::TextAffinity ParseTextAffinity(const char* text_affinity) { if (0 == strcmp(text_affinity, "none")) return ax::mojom::TextAffinity::kNone; if (0 == strcmp(text_affinity, "downstream")) return ax::mojom::TextAffinity::kDownstream; if (0 == strcmp(text_affinity, "upstream")) return ax::mojom::TextAffinity::kUpstream; return ax::mojom::TextAffinity::kNone; } const char* ToString(ax::mojom::TreeOrder tree_order) { switch (tree_order) { case ax::mojom::TreeOrder::kNone: return "none"; case ax::mojom::TreeOrder::kUndefined: return "undefined"; case ax::mojom::TreeOrder::kBefore: return "before"; case ax::mojom::TreeOrder::kEqual: return "equal"; case ax::mojom::TreeOrder::kAfter: return "after"; } return ""; } ax::mojom::TreeOrder ParseTreeOrder(const char* tree_order) { if (0 == strcmp(tree_order, "none")) return ax::mojom::TreeOrder::kNone; if (0 == strcmp(tree_order, "undefined")) return ax::mojom::TreeOrder::kUndefined; if (0 == strcmp(tree_order, "before")) return ax::mojom::TreeOrder::kBefore; if (0 == strcmp(tree_order, "equal")) return ax::mojom::TreeOrder::kEqual; if (0 == strcmp(tree_order, "after")) return ax::mojom::TreeOrder::kAfter; return ax::mojom::TreeOrder::kNone; } const char* ToString(ax::mojom::ImageAnnotationStatus status) { switch (status) { case ax::mojom::ImageAnnotationStatus::kNone: return "none"; case ax::mojom::ImageAnnotationStatus::kWillNotAnnotateDueToScheme: return "kWillNotAnnotateDueToScheme"; case ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation: return "ineligibleForAnnotation"; case ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation: return "eligibleForAnnotation"; case ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation: return "silentlyEligibleForAnnotation"; case ax::mojom::ImageAnnotationStatus::kAnnotationPending: return "annotationPending"; case ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded: return "annotationSucceeded"; case ax::mojom::ImageAnnotationStatus::kAnnotationEmpty: return "annotationEmpty"; case ax::mojom::ImageAnnotationStatus::kAnnotationAdult: return "annotationAdult"; case ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed: return "annotationProcessFailed"; } return ""; } ax::mojom::ImageAnnotationStatus ParseImageAnnotationStatus( const char* status) { if (0 == strcmp(status, "none")) return ax::mojom::ImageAnnotationStatus::kNone; if (0 == strcmp(status, "kWillNotAnnotateDueToScheme")) return ax::mojom::ImageAnnotationStatus::kWillNotAnnotateDueToScheme; if (0 == strcmp(status, "ineligibleForAnnotation")) return ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation; if (0 == strcmp(status, "eligibleForAnnotation")) return ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation; if (0 == strcmp(status, "silentlyEligibleForAnnotation")) return ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation; if (0 == strcmp(status, "annotationPending")) return ax::mojom::ImageAnnotationStatus::kAnnotationPending; if (0 == strcmp(status, "annotationSucceeded")) return ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded; if (0 == strcmp(status, "annotationEmpty")) return ax::mojom::ImageAnnotationStatus::kAnnotationEmpty; if (0 == strcmp(status, "annotationAdult")) return ax::mojom::ImageAnnotationStatus::kAnnotationAdult; if (0 == strcmp(status, "annotationProcessFailed")) return ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed; return ax::mojom::ImageAnnotationStatus::kNone; } const char* ToString(ax::mojom::Dropeffect dropeffect) { switch (dropeffect) { case ax::mojom::Dropeffect::kCopy: return "copy"; case ax::mojom::Dropeffect::kExecute: return "execute"; case ax::mojom::Dropeffect::kLink: return "link"; case ax::mojom::Dropeffect::kMove: return "move"; case ax::mojom::Dropeffect::kPopup: return "popup"; case ax::mojom::Dropeffect::kNone: return "none"; } return ""; } ax::mojom::Dropeffect ParseDropeffect(const char* dropeffect) { if (0 == strcmp(dropeffect, "copy")) return ax::mojom::Dropeffect::kCopy; if (0 == strcmp(dropeffect, "execute")) return ax::mojom::Dropeffect::kExecute; if (0 == strcmp(dropeffect, "link")) return ax::mojom::Dropeffect::kLink; if (0 == strcmp(dropeffect, "move")) return ax::mojom::Dropeffect::kMove; if (0 == strcmp(dropeffect, "popup")) return ax::mojom::Dropeffect::kPopup; return ax::mojom::Dropeffect::kNone; } } // namespace ui
engine/third_party/accessibility/ax/ax_enum_util.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_enum_util.cc", "repo_id": "engine", "token_count": 44020 }
407
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_ACCESSIBILITY_AX_NODE_DATA_H_ #define UI_ACCESSIBILITY_AX_NODE_DATA_H_ #include <cstdint> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "ax_base_export.h" #include "ax_enums.h" #include "ax_node_text_styles.h" #include "ax_relative_bounds.h" namespace ui { // Return true if |attr| should be interpreted as the id of another node // in the same tree. AX_BASE_EXPORT bool IsNodeIdIntAttribute(ax::mojom::IntAttribute attr); // Return true if |attr| should be interpreted as a list of ids of // nodes in the same tree. AX_BASE_EXPORT bool IsNodeIdIntListAttribute(ax::mojom::IntListAttribute attr); // A compact representation of the accessibility information for a // single accessible object, in a form that can be serialized and sent from // one process to another. struct AX_BASE_EXPORT AXNodeData { // Defines the type used for AXNode IDs. using AXID = int32_t; AXNodeData(); virtual ~AXNodeData(); AXNodeData(const AXNodeData& other); AXNodeData(AXNodeData&& other); AXNodeData& operator=(AXNodeData other); // Accessing accessibility attributes: // // There are dozens of possible attributes for an accessibility node, // but only a few tend to apply to any one object, so we store them // in sparse arrays of <attribute id, attribute value> pairs, organized // by type (bool, int, float, string, int list). // // There are three accessors for each type of attribute: one that returns // true if the attribute is present and false if not, one that takes a // pointer argument and returns true if the attribute is present (if you // need to distinguish between the default value and a missing attribute), // and another that returns the default value for that type if the // attribute is not present. In addition, strings can be returned as // either std::string or std::u16string, for convenience. bool HasBoolAttribute(ax::mojom::BoolAttribute attribute) const; bool GetBoolAttribute(ax::mojom::BoolAttribute attribute) const; bool GetBoolAttribute(ax::mojom::BoolAttribute attribute, bool* value) const; bool HasFloatAttribute(ax::mojom::FloatAttribute attribute) const; float GetFloatAttribute(ax::mojom::FloatAttribute attribute) const; bool GetFloatAttribute(ax::mojom::FloatAttribute attribute, float* value) const; bool HasIntAttribute(ax::mojom::IntAttribute attribute) const; int GetIntAttribute(ax::mojom::IntAttribute attribute) const; bool GetIntAttribute(ax::mojom::IntAttribute attribute, int* value) const; bool HasStringAttribute(ax::mojom::StringAttribute attribute) const; const std::string& GetStringAttribute( ax::mojom::StringAttribute attribute) const; bool GetStringAttribute(ax::mojom::StringAttribute attribute, std::string* value) const; bool GetString16Attribute(ax::mojom::StringAttribute attribute, std::u16string* value) const; std::u16string GetString16Attribute( ax::mojom::StringAttribute attribute) const; bool HasIntListAttribute(ax::mojom::IntListAttribute attribute) const; const std::vector<int32_t>& GetIntListAttribute( ax::mojom::IntListAttribute attribute) const; bool GetIntListAttribute(ax::mojom::IntListAttribute attribute, std::vector<int32_t>* value) const; bool HasStringListAttribute(ax::mojom::StringListAttribute attribute) const; const std::vector<std::string>& GetStringListAttribute( ax::mojom::StringListAttribute attribute) const; bool GetStringListAttribute(ax::mojom::StringListAttribute attribute, std::vector<std::string>* value) const; bool GetHtmlAttribute(const char* attribute, std::u16string* value) const; bool GetHtmlAttribute(const char* attribute, std::string* value) const; // // Setting accessibility attributes. // // Replaces an attribute if present. This is safer than crashing via a // BASE_DCHECK or doing nothing, because most likely replacing is what the // caller would have wanted or what existing code already assumes. // void AddStringAttribute(ax::mojom::StringAttribute attribute, const std::string& value); void AddIntAttribute(ax::mojom::IntAttribute attribute, int32_t value); void AddFloatAttribute(ax::mojom::FloatAttribute attribute, float value); void AddBoolAttribute(ax::mojom::BoolAttribute attribute, bool value); void AddIntListAttribute(ax::mojom::IntListAttribute attribute, const std::vector<int32_t>& value); void AddStringListAttribute(ax::mojom::StringListAttribute attribute, const std::vector<std::string>& value); // // Removing accessibility attributes. // void RemoveStringAttribute(ax::mojom::StringAttribute attribute); void RemoveIntAttribute(ax::mojom::IntAttribute attribute); void RemoveFloatAttribute(ax::mojom::FloatAttribute attribute); void RemoveBoolAttribute(ax::mojom::BoolAttribute attribute); void RemoveIntListAttribute(ax::mojom::IntListAttribute attribute); void RemoveStringListAttribute(ax::mojom::StringListAttribute attribute); // // Text styles. // AXNodeTextStyles GetTextStyles() const; // // Convenience functions. // // Adds the name attribute or replaces it if already present. Also sets the // NameFrom attribute if not already set. void SetName(const std::string& name); void SetName(const std::u16string& name); // Allows nameless objects to pass accessibility checks. void SetNameExplicitlyEmpty(); // Adds the description attribute or replaces it if already present. void SetDescription(const std::string& description); void SetDescription(const std::u16string& description); // Adds the value attribute or replaces it if already present. void SetValue(const std::string& value); void SetValue(const std::u16string& value); // Adds the tooltip attribute or replaces it if already present. void SetTooltip(const std::string& value); void SetTooltip(const std::u16string& value); // Returns true if the given enum bit is 1. bool HasState(ax::mojom::State state) const; bool HasAction(ax::mojom::Action action) const; bool HasTextStyle(ax::mojom::TextStyle text_style) const; // aria-dropeffect is deprecated in WAI-ARIA 1.1. bool HasDropeffect(ax::mojom::Dropeffect dropeffect) const; // Set or remove bits in the given enum's corresponding bitfield. void AddState(ax::mojom::State state); void RemoveState(ax::mojom::State state); void AddAction(ax::mojom::Action action); void AddTextStyle(ax::mojom::TextStyle text_style); // aria-dropeffect is deprecated in WAI-ARIA 1.1. void AddDropeffect(ax::mojom::Dropeffect dropeffect); // Helper functions to get or set some common int attributes with some // specific enum types. To remove an attribute, set it to None. // // Please keep in alphabetic order. ax::mojom::CheckedState GetCheckedState() const; void SetCheckedState(ax::mojom::CheckedState checked_state); bool HasCheckedState() const; ax::mojom::DefaultActionVerb GetDefaultActionVerb() const; void SetDefaultActionVerb(ax::mojom::DefaultActionVerb default_action_verb); ax::mojom::HasPopup GetHasPopup() const; void SetHasPopup(ax::mojom::HasPopup has_popup); ax::mojom::InvalidState GetInvalidState() const; void SetInvalidState(ax::mojom::InvalidState invalid_state); ax::mojom::NameFrom GetNameFrom() const; void SetNameFrom(ax::mojom::NameFrom name_from); ax::mojom::DescriptionFrom GetDescriptionFrom() const; void SetDescriptionFrom(ax::mojom::DescriptionFrom description_from); ax::mojom::TextPosition GetTextPosition() const; void SetTextPosition(ax::mojom::TextPosition text_position); ax::mojom::Restriction GetRestriction() const; void SetRestriction(ax::mojom::Restriction restriction); ax::mojom::ListStyle GetListStyle() const; void SetListStyle(ax::mojom::ListStyle list_style); ax::mojom::TextAlign GetTextAlign() const; void SetTextAlign(ax::mojom::TextAlign text_align); ax::mojom::WritingDirection GetTextDirection() const; void SetTextDirection(ax::mojom::WritingDirection text_direction); ax::mojom::ImageAnnotationStatus GetImageAnnotationStatus() const; void SetImageAnnotationStatus(ax::mojom::ImageAnnotationStatus status); // Helper to determine if the data belongs to a node that gains focus when // clicked, such as a text field or a native HTML list box. bool IsActivatable() const; // Helper to determine if the data belongs to a node that is a native button // or ARIA role="button" in a pressed state. bool IsButtonPressed() const; // Helper to determine if the data belongs to a node that can respond to // clicks. bool IsClickable() const; // Helper to determine if the object is selectable. bool IsSelectable() const; // Helper to determine if the data has the ignored state or ignored role. bool IsIgnored() const; // Helper to determine if the data has the invisible state. bool IsInvisible() const; // Helper to determine if the data has the ignored state, the invisible state // or the ignored role. bool IsInvisibleOrIgnored() const; // Helper to determine if the data belongs to a node that is invocable. bool IsInvocable() const; // Helper to determine if the data belongs to a node that is a menu button. bool IsMenuButton() const; // This data belongs to a text field. This is any widget in which the user // should be able to enter and edit text. // // Examples include <input type="text">, <input type="password">, <textarea>, // <div contenteditable="true">, <div role="textbox">, <div role="searchbox"> // and <div role="combobox">. Note that when an ARIA role that indicates that // the widget is editable is used, such as "role=textbox", the element doesn't // need to be contenteditable for this method to return true, as in theory // JavaScript could be used to implement editing functionality. In practice, // this situation should be rare. bool IsTextField() const; // This data belongs to a text field that is used for entering passwords. bool IsPasswordField() const; // This data belongs to a text field that doesn't accept rich text content, // such as text with special formatting or styling. bool IsPlainTextField() const; // This data belongs to a text field that accepts rich text content, such as // text with special formatting or styling. bool IsRichTextField() const; // Helper to determine if |GetRestriction| is either ReadOnly or Disabled. // By default, all nodes that can't be edited are readonly. bool IsReadOnlyOrDisabled() const; // Helper to determine if the data belongs to a node that supports // range-based value. bool IsRangeValueSupported() const; // Helper to determine if the data belongs to a node that supports // expand/collapse. bool SupportsExpandCollapse() const; // Return a string representation of this data, for debugging. virtual std::string ToString() const; // Return a string representation of |aria-dropeffect| values, for testing // and debugging. // aria-dropeffect is deprecated in WAI-ARIA 1.1. std::string DropeffectBitfieldToString() const; // As much as possible this should behave as a simple, serializable, // copyable struct. int32_t id = -1; ax::mojom::Role role; uint32_t state; uint64_t actions; std::vector<std::pair<ax::mojom::StringAttribute, std::string>> string_attributes; std::vector<std::pair<ax::mojom::IntAttribute, int32_t>> int_attributes; std::vector<std::pair<ax::mojom::FloatAttribute, float>> float_attributes; std::vector<std::pair<ax::mojom::BoolAttribute, bool>> bool_attributes; std::vector<std::pair<ax::mojom::IntListAttribute, std::vector<int32_t>>> intlist_attributes; std::vector< std::pair<ax::mojom::StringListAttribute, std::vector<std::string>>> stringlist_attributes; std::vector<std::pair<std::string, std::string>> html_attributes; std::vector<int32_t> child_ids; AXRelativeBounds relative_bounds; }; } // namespace ui #endif // UI_ACCESSIBILITY_AX_NODE_DATA_H_
engine/third_party/accessibility/ax/ax_node_data.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_node_data.h", "repo_id": "engine", "token_count": 3825 }
408
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ax_table_info.h" #include <cstddef> #include "ax_constants.h" #include "ax_enums.h" #include "ax_node.h" #include "ax_role_properties.h" #include "ax_tree.h" #include "ax_tree_observer.h" #include "base/logging.h" using ax::mojom::IntAttribute; namespace ui { namespace { // Given a node representing a table row, search its children // recursively to find any cells or table headers, and append // them to |cells|. // // We recursively check generic containers like <div> and any // nodes that are ignored, but we don't search any other roles // in-between a table row and its cells. void FindCellsInRow(AXNode* node, std::vector<AXNode*>* cell_nodes) { for (AXNode* child : node->children()) { if (child->IsIgnored() || child->data().role == ax::mojom::Role::kGenericContainer) FindCellsInRow(child, cell_nodes); else if (IsCellOrTableHeader(child->data().role)) cell_nodes->push_back(child); } } // Given a node representing a table/grid, search its children // recursively to find any rows and append them to |row_node_list|, then // for each row find its cells and add them to |cell_nodes_per_row| as a // 2-dimensional array. // // We only recursively check for the following roles in between a table and // its rows: generic containers like <div>, any nodes that are ignored, and // table sections (which have Role::kRowGroup). void FindRowsAndThenCells(AXNode* node, std::vector<AXNode*>* row_node_list, std::vector<std::vector<AXNode*>>* cell_nodes_per_row, int32_t& caption_node_id) { for (AXNode* child : node->children()) { if (child->IsIgnored() || child->data().role == ax::mojom::Role::kGenericContainer || child->data().role == ax::mojom::Role::kGroup || child->data().role == ax::mojom::Role::kRowGroup) { FindRowsAndThenCells(child, row_node_list, cell_nodes_per_row, caption_node_id); } else if (IsTableRow(child->data().role)) { row_node_list->push_back(child); cell_nodes_per_row->push_back(std::vector<AXNode*>()); FindCellsInRow(child, &cell_nodes_per_row->back()); } else if (child->data().role == ax::mojom::Role::kCaption) caption_node_id = child->id(); } } size_t GetSizeTAttribute(const AXNode& node, IntAttribute attribute) { return base::saturated_cast<size_t>(node.GetIntAttribute(attribute)); } } // namespace // static AXTableInfo* AXTableInfo::Create(AXTree* tree, AXNode* table_node) { BASE_DCHECK(tree); BASE_DCHECK(table_node); #ifndef NDEBUG // Sanity check, make sure the node is in the tree. AXNode* node = table_node; while (node && node != tree->root()) node = node->parent(); BASE_DCHECK(node == tree->root()); #endif if (!IsTableLike(table_node->data().role)) return nullptr; AXTableInfo* info = new AXTableInfo(tree, table_node); bool success = info->Update(); BASE_DCHECK(success); return info; } bool AXTableInfo::Update() { if (!table_node_->IsTable()) return false; ClearVectors(); std::vector<std::vector<AXNode*>> cell_nodes_per_row; caption_id = 0; FindRowsAndThenCells(table_node_, &row_nodes, &cell_nodes_per_row, caption_id); BASE_DCHECK(cell_nodes_per_row.size() == row_nodes.size()); // Get the optional row and column count from the table. If we encounter // a cell with an index or span larger than this, we'll update the // table row and column count to be large enough to fit all cells. row_count = GetSizeTAttribute(*table_node_, IntAttribute::kTableRowCount); col_count = GetSizeTAttribute(*table_node_, IntAttribute::kTableColumnCount); // Note - GetIntAttribute returns 0 if no value has been specified for the // attribute. aria_row_count = static_cast<int>( table_node_->GetIntAttribute(IntAttribute::kAriaRowCount)); aria_col_count = static_cast<int>( table_node_->GetIntAttribute(IntAttribute::kAriaColumnCount)); // Iterate over the cells and build up an array of CellData // entries, one for each cell. Compute the actual row and column BuildCellDataVectorFromRowAndCellNodes(row_nodes, cell_nodes_per_row); // At this point we have computed valid row and column indices for // every cell in the table, and an accurate row and column count for the // whole table that fits every cell and its spans. The final step is to // fill in a 2-dimensional array that lets us look up an individual cell // by its (row, column) coordinates, plus arrays to hold row and column // headers. BuildCellAndHeaderVectorsFromCellData(); // On Mac, we add a few extra nodes to the table - see comment // at the top of UpdateExtraMacNodes for details. if (tree_->enable_extra_mac_nodes()) UpdateExtraMacNodes(); // The table metadata is now valid, any table queries will now be // fast. Any time a node in the table is updated, we'll have to // recompute all of this. valid_ = true; return true; } void AXTableInfo::Invalidate() { valid_ = false; } void AXTableInfo::ClearVectors() { col_headers.clear(); row_headers.clear(); all_headers.clear(); cell_ids.clear(); unique_cell_ids.clear(); cell_data_vector.clear(); row_nodes.clear(); cell_id_to_index.clear(); row_id_to_index.clear(); incremental_row_col_map_.clear(); } void AXTableInfo::BuildCellDataVectorFromRowAndCellNodes( const std::vector<AXNode*>& row_node_list, const std::vector<std::vector<AXNode*>>& cell_nodes_per_row) { // Iterate over the cells and build up an array of CellData // entries, one for each cell. Compute the actual row and column // indices for each cell by taking the specified row and column // index in the accessibility tree if legal, but replacing it with // valid table coordinates otherwise. size_t cell_index = 0; size_t current_aria_row_index = 1; size_t next_row_index = 0; for (size_t i = 0; i < cell_nodes_per_row.size(); i++) { auto& cell_nodes_in_this_row = cell_nodes_per_row[i]; AXNode* row_node = row_node_list[i]; bool is_first_cell_in_row = true; size_t current_col_index = 0; size_t current_aria_col_index = 1; // Make sure the row index is always at least as high as the one reported by // the source tree. row_id_to_index[row_node->id()] = std::max(next_row_index, GetSizeTAttribute(*row_node, IntAttribute::kTableRowIndex)); size_t* current_row_index = &row_id_to_index[row_node->id()]; size_t spanned_col_index = 0; for (AXNode* cell : cell_nodes_in_this_row) { // Fill in basic info in CellData. CellData cell_data; unique_cell_ids.push_back(cell->id()); cell_id_to_index[cell->id()] = cell_index++; cell_data.cell = cell; // Get table cell accessibility attributes - note that these may // be missing or invalid, we'll correct them next. cell_data.row_index = GetSizeTAttribute(*cell, IntAttribute::kTableCellRowIndex); cell_data.row_span = GetSizeTAttribute(*cell, IntAttribute::kTableCellRowSpan); cell_data.aria_row_index = GetSizeTAttribute(*cell, IntAttribute::kAriaCellRowIndex); cell_data.col_index = GetSizeTAttribute(*cell, IntAttribute::kTableCellColumnIndex); cell_data.aria_col_index = GetSizeTAttribute(*cell, IntAttribute::kAriaCellColumnIndex); cell_data.col_span = GetSizeTAttribute(*cell, IntAttribute::kTableCellColumnSpan); // The col span and row span must be at least 1. cell_data.row_span = std::max(size_t{1}, cell_data.row_span); cell_data.col_span = std::max(size_t{1}, cell_data.col_span); // Ensure the column index must always be incrementing. cell_data.col_index = std::max(cell_data.col_index, current_col_index); // And update the spanned column index. spanned_col_index = std::max(spanned_col_index, cell_data.col_index); if (is_first_cell_in_row) { is_first_cell_in_row = false; // If it's the first cell in the row, ensure the row index is // incrementing. The rest of the cells in this row are forced to have // the same row index. if (cell_data.row_index > *current_row_index) { *current_row_index = cell_data.row_index; } else { cell_data.row_index = *current_row_index; } // The starting ARIA row and column index might be specified in // the row node, we should check there. if (!cell_data.aria_row_index) { cell_data.aria_row_index = GetSizeTAttribute(*row_node, IntAttribute::kAriaCellRowIndex); } if (!cell_data.aria_col_index) { cell_data.aria_col_index = GetSizeTAttribute(*row_node, IntAttribute::kAriaCellColumnIndex); } cell_data.aria_row_index = std::max(cell_data.aria_row_index, current_aria_row_index); current_aria_row_index = cell_data.aria_row_index; } else { // Don't allow the row index to change after the beginning // of a row. cell_data.row_index = *current_row_index; cell_data.aria_row_index = current_aria_row_index; } // Adjust the spanned col index by looking at the incremental row col map. // This map contains already filled in values, accounting for spans, of // all row, col indices. The map should have filled in all values we need // (upper left triangle of cells of the table). while (true) { const auto& row_it = incremental_row_col_map_.find(*current_row_index); if (row_it == incremental_row_col_map_.end()) { break; } else { const auto& col_it = row_it->second.find(spanned_col_index); if (col_it == row_it->second.end()) { break; } else { // A pre-existing cell resides in our desired position. Make a // best-fit to the right of the existing span. const CellData& spanned_cell_data = col_it->second; spanned_col_index = spanned_cell_data.col_index + spanned_cell_data.col_span; // Adjust the actual col index to be the best fit with the existing // spanned cell data. cell_data.col_index = spanned_col_index; } } } // Memoize the cell data using our incremental row col map. for (size_t r = cell_data.row_index; r < (cell_data.row_index + cell_data.row_span); r++) { for (size_t c = cell_data.col_index; c < (cell_data.col_index + cell_data.col_span); c++) { incremental_row_col_map_[r][c] = cell_data; } } // Ensure the ARIA col index is incrementing. cell_data.aria_col_index = std::max(cell_data.aria_col_index, current_aria_col_index); current_aria_col_index = cell_data.aria_col_index; // Update the row count and col count for the whole table to make // sure they're large enough to fit this cell, including its spans. // The -1 in the ARIA calculations is because ARIA indices are 1-based, // whereas all other indices are zero-based. row_count = std::max(row_count, cell_data.row_index + cell_data.row_span); col_count = std::max(col_count, cell_data.col_index + cell_data.col_span); if (aria_row_count != ax::mojom::kUnknownAriaColumnOrRowCount) { aria_row_count = std::max( (aria_row_count), static_cast<int>(current_aria_row_index + cell_data.row_span - 1)); } if (aria_col_count != ax::mojom::kUnknownAriaColumnOrRowCount) { aria_col_count = std::max( (aria_col_count), static_cast<int>(current_aria_col_index + cell_data.col_span - 1)); } // Update |current_col_index| to reflect the next available index after // this cell including its colspan. The next column index in this row // must be at least this large. Same for the current ARIA col index. current_col_index = cell_data.col_index + cell_data.col_span; current_aria_col_index = cell_data.aria_col_index + cell_data.col_span; spanned_col_index = current_col_index; // Add this cell to our vector. cell_data_vector.push_back(cell_data); } // At the end of each row, increment |current_aria_row_index| to reflect the // next available index after this row. The next row index must be at least // this large. Also update |next_row_index|. current_aria_row_index++; next_row_index = *current_row_index + 1; } } void AXTableInfo::BuildCellAndHeaderVectorsFromCellData() { // Allocate space for the 2-D array of cell IDs and 1-D // arrays of row headers and column headers. row_headers.resize(row_count); col_headers.resize(col_count); // Fill in the arrays. // // At this point we have computed valid row and column indices for // every cell in the table, and an accurate row and column count for the // whole table that fits every cell and its spans. The final step is to // fill in a 2-dimensional array that lets us look up an individual cell // by its (row, column) coordinates, plus arrays to hold row and column // headers. // For cells. cell_ids.resize(row_count); for (size_t r = 0; r < row_count; r++) { cell_ids[r].resize(col_count); for (size_t c = 0; c < col_count; c++) { const auto& row_it = incremental_row_col_map_.find(r); if (row_it != incremental_row_col_map_.end()) { const auto& col_it = row_it->second.find(c); if (col_it != row_it->second.end()) cell_ids[r][c] = col_it->second.cell->id(); } } } // No longer need this. incremental_row_col_map_.clear(); // For relations. for (auto& cell_data : cell_data_vector) { for (size_t r = cell_data.row_index; r < cell_data.row_index + cell_data.row_span; r++) { BASE_DCHECK(r < row_count); for (size_t c = cell_data.col_index; c < cell_data.col_index + cell_data.col_span; c++) { BASE_DCHECK(c < col_count); AXNode* cell = cell_data.cell; if (cell->data().role == ax::mojom::Role::kColumnHeader) { col_headers[c].push_back(cell->id()); all_headers.push_back(cell->id()); } else if (cell->data().role == ax::mojom::Role::kRowHeader) { row_headers[r].push_back(cell->id()); all_headers.push_back(cell->id()); } } } } } void AXTableInfo::UpdateExtraMacNodes() { // On macOS, maintain additional AXNodes: one column node for each // column of the table, and one table header container. // // The nodes all set the table as the parent node, that way the Mac-specific // platform code can treat these nodes as additional children of the table // node. // // The columns have id -1, -2, -3, ... - this won't conflict with ids from // the source tree, which are all positive. // // Each column has the kColumnIndex attribute set, and then each of the cells // in that column gets added as an indirect ID. That exposes them as children // via Mac APIs but ensures we don't explore those nodes multiple times when // walking the tree. The column also has the ID of the first column header // set. // // The table header container is just a node with all of the headers in the // table as indirect children. if (!extra_mac_nodes.empty()) { // Delete old extra nodes. ClearExtraMacNodes(); } // One node for each column, and one more for the table header container. size_t extra_node_count = col_count + 1; // Resize. extra_mac_nodes.resize(extra_node_count); std::vector<AXTreeObserver::Change> changes; changes.reserve(extra_node_count + 1); // Room for extra nodes + table itself. // Create column nodes. for (size_t i = 0; i < col_count; i++) { extra_mac_nodes[i] = CreateExtraMacColumnNode(i); changes.push_back(AXTreeObserver::Change( extra_mac_nodes[i], AXTreeObserver::ChangeType::NODE_CREATED)); } // Create table header container node. extra_mac_nodes[col_count] = CreateExtraMacTableHeaderNode(); changes.push_back(AXTreeObserver::Change( extra_mac_nodes[col_count], AXTreeObserver::ChangeType::NODE_CREATED)); // Update the columns to reflect current state of the table. for (size_t i = 0; i < col_count; i++) UpdateExtraMacColumnNodeAttributes(i); // Update the table header container to contain all headers. ui::AXNodeData data = extra_mac_nodes[col_count]->data(); data.intlist_attributes.clear(); data.AddIntListAttribute(ax::mojom::IntListAttribute::kIndirectChildIds, all_headers); extra_mac_nodes[col_count]->SetData(data); changes.push_back(AXTreeObserver::Change( table_node_, AXTreeObserver::ChangeType::NODE_CHANGED)); for (AXTreeObserver* observer : tree_->observers()) { observer->OnAtomicUpdateFinished(tree_, false, changes); } } AXNode* AXTableInfo::CreateExtraMacColumnNode(size_t col_index) { int32_t id = tree_->GetNextNegativeInternalNodeId(); size_t index_in_parent = col_index + table_node_->children().size(); int32_t unignored_index_in_parent = col_index + table_node_->GetUnignoredChildCount(); AXNode* node = new AXNode(tree_, table_node_, id, index_in_parent, unignored_index_in_parent); AXNodeData data; data.id = id; data.role = ax::mojom::Role::kColumn; node->SetData(data); for (AXTreeObserver* observer : tree_->observers()) observer->OnNodeCreated(tree_, node); return node; } AXNode* AXTableInfo::CreateExtraMacTableHeaderNode() { int32_t id = tree_->GetNextNegativeInternalNodeId(); size_t index_in_parent = col_count + table_node_->children().size(); int32_t unignored_index_in_parent = col_count + table_node_->GetUnignoredChildCount(); AXNode* node = new AXNode(tree_, table_node_, id, index_in_parent, unignored_index_in_parent); AXNodeData data; data.id = id; data.role = ax::mojom::Role::kTableHeaderContainer; node->SetData(data); for (AXTreeObserver* observer : tree_->observers()) observer->OnNodeCreated(tree_, node); return node; } void AXTableInfo::UpdateExtraMacColumnNodeAttributes(size_t col_index) { ui::AXNodeData data = extra_mac_nodes[col_index]->data(); data.int_attributes.clear(); // Update the column index. data.AddIntAttribute(IntAttribute::kTableColumnIndex, static_cast<int32_t>(col_index)); // Update the column header. if (!col_headers[col_index].empty()) { data.AddIntAttribute(IntAttribute::kTableColumnHeaderId, col_headers[col_index][0]); } // Update the list of cells in the column. data.intlist_attributes.clear(); std::vector<int32_t> col_nodes; int32_t last = 0; for (size_t row_index = 0; row_index < row_count; row_index++) { int32_t cell_id = cell_ids[row_index][col_index]; if (cell_id != 0 && cell_id != last) col_nodes.push_back(cell_id); last = cell_id; } data.AddIntListAttribute(ax::mojom::IntListAttribute::kIndirectChildIds, col_nodes); extra_mac_nodes[col_index]->SetData(data); } void AXTableInfo::ClearExtraMacNodes() { for (AXNode* extra_mac_node : extra_mac_nodes) { for (AXTreeObserver* observer : tree_->observers()) observer->OnNodeWillBeDeleted(tree_, extra_mac_node); AXNode::AXID deleted_id = extra_mac_node->id(); delete extra_mac_node; for (AXTreeObserver* observer : tree_->observers()) observer->OnNodeDeleted(tree_, deleted_id); } extra_mac_nodes.clear(); } std::string AXTableInfo::ToString() const { // First, scan through to get the length of the largest id. int padding = 0; for (size_t r = 0; r < row_count; r++) { for (size_t c = 0; c < col_count; c++) { // Extract the length of the id for padding purposes. padding = std::max(padding, static_cast<int>(log10(cell_ids[r][c]))); } } std::string result; for (size_t r = 0; r < row_count; r++) { result += "|"; for (size_t c = 0; c < col_count; c++) { int cell_id = cell_ids[r][c]; result += base::NumberToString(cell_id); int cell_padding = padding; if (cell_id != 0) cell_padding = padding - static_cast<int>(log10(cell_id)); result += std::string(cell_padding, ' ') + '|'; } result += "\n"; } return result; } AXTableInfo::AXTableInfo(AXTree* tree, AXNode* table_node) : tree_(tree), table_node_(table_node) {} AXTableInfo::~AXTableInfo() { if (!extra_mac_nodes.empty()) { ClearExtraMacNodes(); for (AXTreeObserver* observer : tree_->observers()) { observer->OnAtomicUpdateFinished( tree_, false, {{table_node_, AXTreeObserver::ChangeType::NODE_CHANGED}}); } } } } // namespace ui
engine/third_party/accessibility/ax/ax_table_info.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_table_info.cc", "repo_id": "engine", "token_count": 8192 }
409
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ax_tree.h" #include <cstddef> #include <cstdint> #include <memory> #include "ax_enum_util.h" #include "ax_node.h" #include "ax_node_position.h" #include "ax_tree_data.h" #include "ax_tree_id.h" #include "ax_tree_observer.h" #include "base/string_utils.h" #include "gtest/gtest.h" #include "test_ax_tree_manager.h" // Helper macro for testing selection values and maintain // correct stack tracing and failure causality. #define TEST_SELECTION(tree_update, tree, input, expected) \ { \ tree_update.has_tree_data = true; \ tree_update.tree_data.sel_anchor_object_id = input.anchor_id; \ tree_update.tree_data.sel_anchor_offset = input.anchor_offset; \ tree_update.tree_data.sel_focus_object_id = input.focus_id; \ tree_update.tree_data.sel_focus_offset = input.focus_offset; \ EXPECT_TRUE(tree->Unserialize(tree_update)); \ AXTree::Selection actual = tree->GetUnignoredSelection(); \ EXPECT_EQ(expected.anchor_id, actual.anchor_object_id); \ EXPECT_EQ(expected.anchor_offset, actual.anchor_offset); \ EXPECT_EQ(expected.focus_id, actual.focus_object_id); \ EXPECT_EQ(expected.focus_offset, actual.focus_offset); \ } namespace ui { namespace { std::string IntVectorToString(const std::vector<int>& items) { std::string str; for (size_t i = 0; i < items.size(); ++i) { if (i > 0) str += ","; str += base::NumberToString(items[i]); } return str; } std::string GetBoundsAsString(const AXTree& tree, int32_t id) { AXNode* node = tree.GetFromId(id); gfx::RectF bounds = tree.GetTreeBounds(node); return base::StringPrintf("(%.0f, %.0f) size (%.0f x %.0f)", bounds.x(), bounds.y(), bounds.width(), bounds.height()); } std::string GetUnclippedBoundsAsString(const AXTree& tree, int32_t id) { AXNode* node = tree.GetFromId(id); gfx::RectF bounds = tree.GetTreeBounds(node, nullptr, false); return base::StringPrintf("(%.0f, %.0f) size (%.0f x %.0f)", bounds.x(), bounds.y(), bounds.width(), bounds.height()); } bool IsNodeOffscreen(const AXTree& tree, int32_t id) { AXNode* node = tree.GetFromId(id); bool result = false; tree.GetTreeBounds(node, &result); return result; } class TestAXTreeObserver : public AXTreeObserver { public: TestAXTreeObserver(AXTree* tree) : tree_(tree), tree_data_changed_(false), root_changed_(false) { tree_->AddObserver(this); } ~TestAXTreeObserver() { tree_->RemoveObserver(this); } void OnNodeDataWillChange(AXTree* tree, const AXNodeData& old_node_data, const AXNodeData& new_node_data) override {} void OnNodeDataChanged(AXTree* tree, const AXNodeData& old_node_data, const AXNodeData& new_node_data) override {} void OnTreeDataChanged(AXTree* tree, const ui::AXTreeData& old_data, const ui::AXTreeData& new_data) override { tree_data_changed_ = true; } std::optional<AXNode::AXID> unignored_parent_id_before_node_deleted; void OnNodeWillBeDeleted(AXTree* tree, AXNode* node) override { // When this observer function is called in an update, the actual node // deletion has not happened yet. Verify that node still exists in the tree. ASSERT_NE(nullptr, tree->GetFromId(node->id())); node_will_be_deleted_ids_.push_back(node->id()); if (unignored_parent_id_before_node_deleted) { ASSERT_NE(nullptr, node->GetUnignoredParent()); ASSERT_EQ(*unignored_parent_id_before_node_deleted, node->GetUnignoredParent()->id()); } } void OnSubtreeWillBeDeleted(AXTree* tree, AXNode* node) override { subtree_deleted_ids_.push_back(node->id()); } void OnNodeWillBeReparented(AXTree* tree, AXNode* node) override { node_will_be_reparented_ids_.push_back(node->id()); } void OnSubtreeWillBeReparented(AXTree* tree, AXNode* node) override { subtree_will_be_reparented_ids_.push_back(node->id()); } void OnNodeCreated(AXTree* tree, AXNode* node) override { created_ids_.push_back(node->id()); } void OnNodeDeleted(AXTree* tree, int32_t node_id) override { // When this observer function is called in an update, node has already been // deleted from the tree. Verify that the node is absent from the tree. ASSERT_EQ(nullptr, tree->GetFromId(node_id)); deleted_ids_.push_back(node_id); } void OnNodeReparented(AXTree* tree, AXNode* node) override { node_reparented_ids_.push_back(node->id()); } void OnNodeChanged(AXTree* tree, AXNode* node) override { changed_ids_.push_back(node->id()); } void OnAtomicUpdateFinished(AXTree* tree, bool root_changed, const std::vector<Change>& changes) override { root_changed_ = root_changed; for (size_t i = 0; i < changes.size(); ++i) { int id = changes[i].node->id(); switch (changes[i].type) { case NODE_CREATED: node_creation_finished_ids_.push_back(id); break; case SUBTREE_CREATED: subtree_creation_finished_ids_.push_back(id); break; case NODE_REPARENTED: node_reparented_finished_ids_.push_back(id); break; case SUBTREE_REPARENTED: subtree_reparented_finished_ids_.push_back(id); break; case NODE_CHANGED: change_finished_ids_.push_back(id); break; } } } void OnRoleChanged(AXTree* tree, AXNode* node, ax::mojom::Role old_role, ax::mojom::Role new_role) override { attribute_change_log_.push_back(base::StringPrintf( "Role changed from %s to %s", ToString(old_role), ToString(new_role))); } void OnStateChanged(AXTree* tree, AXNode* node, ax::mojom::State state, bool new_value) override { attribute_change_log_.push_back(base::StringPrintf( "%s changed to %s", ToString(state), new_value ? "true" : "false")); } void OnStringAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::StringAttribute attr, const std::string& old_value, const std::string& new_value) override { attribute_change_log_.push_back( base::StringPrintf("%s changed from %s to %s", ToString(attr), old_value.c_str(), new_value.c_str())); } void OnIntAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::IntAttribute attr, int32_t old_value, int32_t new_value) override { attribute_change_log_.push_back(base::StringPrintf( "%s changed from %d to %d", ToString(attr), old_value, new_value)); } void OnFloatAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::FloatAttribute attr, float old_value, float new_value) override { attribute_change_log_.push_back(base::StringPrintf( "%s changed from %.1f to %.1f", ToString(attr), old_value, new_value)); } void OnBoolAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::BoolAttribute attr, bool new_value) override { attribute_change_log_.push_back(base::StringPrintf( "%s changed to %s", ToString(attr), new_value ? "true" : "false")); } void OnIntListAttributeChanged( AXTree* tree, AXNode* node, ax::mojom::IntListAttribute attr, const std::vector<int32_t>& old_value, const std::vector<int32_t>& new_value) override { attribute_change_log_.push_back( base::StringPrintf("%s changed from %s to %s", ToString(attr), IntVectorToString(old_value).c_str(), IntVectorToString(new_value).c_str())); } bool tree_data_changed() const { return tree_data_changed_; } bool root_changed() const { return root_changed_; } const std::vector<int32_t>& deleted_ids() { return deleted_ids_; } const std::vector<int32_t>& subtree_deleted_ids() { return subtree_deleted_ids_; } const std::vector<int32_t>& created_ids() { return created_ids_; } const std::vector<int32_t>& node_creation_finished_ids() { return node_creation_finished_ids_; } const std::vector<int32_t>& subtree_creation_finished_ids() { return subtree_creation_finished_ids_; } const std::vector<int32_t>& node_reparented_finished_ids() { return node_reparented_finished_ids_; } const std::vector<int32_t>& subtree_will_be_reparented_ids() { return subtree_will_be_reparented_ids_; } const std::vector<int32_t>& node_will_be_reparented_ids() { return node_will_be_reparented_ids_; } const std::vector<int32_t>& node_will_be_deleted_ids() { return node_will_be_deleted_ids_; } const std::vector<int32_t>& node_reparented_ids() { return node_reparented_ids_; } const std::vector<int32_t>& subtree_reparented_finished_ids() { return subtree_reparented_finished_ids_; } const std::vector<int32_t>& change_finished_ids() { return change_finished_ids_; } const std::vector<std::string>& attribute_change_log() { return attribute_change_log_; } private: AXTree* tree_; bool tree_data_changed_; bool root_changed_; std::vector<int32_t> deleted_ids_; std::vector<int32_t> subtree_deleted_ids_; std::vector<int32_t> created_ids_; std::vector<int32_t> changed_ids_; std::vector<int32_t> subtree_will_be_reparented_ids_; std::vector<int32_t> node_will_be_reparented_ids_; std::vector<int32_t> node_will_be_deleted_ids_; std::vector<int32_t> node_creation_finished_ids_; std::vector<int32_t> subtree_creation_finished_ids_; std::vector<int32_t> node_reparented_ids_; std::vector<int32_t> node_reparented_finished_ids_; std::vector<int32_t> subtree_reparented_finished_ids_; std::vector<int32_t> change_finished_ids_; std::vector<std::string> attribute_change_log_; }; } // namespace // A macro for testing that a std::optional has both a value and that its value // is set to a particular expectation. #define EXPECT_OPTIONAL_EQ(expected, actual) \ EXPECT_TRUE(actual.has_value()); \ if (actual) { \ EXPECT_EQ(expected, actual.value()); \ } TEST(AXTreeTest, SerializeAXTreeUpdate) { AXNodeData list; list.id = 3; list.role = ax::mojom::Role::kList; list.child_ids.push_back(4); list.child_ids.push_back(5); list.child_ids.push_back(6); AXNodeData list_item_2; list_item_2.id = 5; list_item_2.role = ax::mojom::Role::kListItem; AXNodeData list_item_3; list_item_3.id = 6; list_item_3.role = ax::mojom::Role::kListItem; AXNodeData button; button.id = 7; button.role = ax::mojom::Role::kButton; AXTreeUpdate update; update.root_id = 3; update.nodes.push_back(list); update.nodes.push_back(list_item_2); update.nodes.push_back(list_item_3); update.nodes.push_back(button); EXPECT_EQ( "AXTreeUpdate: root id 3\n" "id=3 list (0, 0)-(0, 0) child_ids=4,5,6\n" " id=5 listItem (0, 0)-(0, 0)\n" " id=6 listItem (0, 0)-(0, 0)\n" "id=7 button (0, 0)-(0, 0)\n", update.ToString()); } TEST(AXTreeTest, LeaveOrphanedDeletedSubtreeFails) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[0].child_ids.push_back(3); initial_state.nodes[1].id = 2; initial_state.nodes[2].id = 3; AXTree tree(initial_state); // This should fail because we delete a subtree rooted at id=2 // but never update it. AXTreeUpdate update; update.node_id_to_clear = 2; update.nodes.resize(1); update.nodes[0].id = 3; EXPECT_FALSE(tree.Unserialize(update)); ASSERT_EQ("Nodes left pending by the update: 2", tree.error()); } TEST(AXTreeTest, LeaveOrphanedNewChildFails) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; AXTree tree(initial_state); // This should fail because we add a new child to the root node // but never update it. AXTreeUpdate update; update.nodes.resize(1); update.nodes[0].id = 1; update.nodes[0].child_ids.push_back(2); EXPECT_FALSE(tree.Unserialize(update)); ASSERT_EQ("Nodes left pending by the update: 2", tree.error()); } TEST(AXTreeTest, DuplicateChildIdFails) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; AXTree tree(initial_state); // This should fail because a child id appears twice. AXTreeUpdate update; update.nodes.resize(2); update.nodes[0].id = 1; update.nodes[0].child_ids.push_back(2); update.nodes[0].child_ids.push_back(2); update.nodes[1].id = 2; EXPECT_FALSE(tree.Unserialize(update)); ASSERT_EQ("Node 1 has duplicate child id 2", tree.error()); } TEST(AXTreeTest, InvalidReparentingFails) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[1].id = 2; initial_state.nodes[1].child_ids.push_back(3); initial_state.nodes[2].id = 3; AXTree tree(initial_state); // This should fail because node 3 is reparented from node 2 to node 1 // without deleting node 1's subtree first. AXTreeUpdate update; update.nodes.resize(3); update.nodes[0].id = 1; update.nodes[0].child_ids.push_back(3); update.nodes[0].child_ids.push_back(2); update.nodes[1].id = 2; update.nodes[2].id = 3; EXPECT_FALSE(tree.Unserialize(update)); ASSERT_EQ("Node 3 is not marked for destruction, would be reparented to 1", tree.error()); } TEST(AXTreeTest, NoReparentingOfRootIfNoNewRoot) { AXNodeData root; root.id = 1; AXNodeData child1; child1.id = 2; AXNodeData child2; child2.id = 3; root.child_ids = {child1.id}; child1.child_ids = {child2.id}; AXTreeUpdate initial_state; initial_state.root_id = root.id; initial_state.nodes = {root, child1, child2}; AXTree tree(initial_state); // Update the root but don't change it by reparenting |child2| to be a child // of the root. root.child_ids = {child1.id, child2.id}; child1.child_ids = {}; AXTreeUpdate update; update.root_id = root.id; update.node_id_to_clear = root.id; update.nodes = {root, child1, child2}; TestAXTreeObserver test_observer(&tree); ASSERT_TRUE(tree.Unserialize(update)); EXPECT_EQ(0U, test_observer.deleted_ids().size()); EXPECT_EQ(0U, test_observer.subtree_deleted_ids().size()); EXPECT_EQ(0U, test_observer.created_ids().size()); EXPECT_EQ(0U, test_observer.node_creation_finished_ids().size()); EXPECT_EQ(0U, test_observer.subtree_creation_finished_ids().size()); EXPECT_EQ(0U, test_observer.node_reparented_finished_ids().size()); ASSERT_EQ(2U, test_observer.subtree_reparented_finished_ids().size()); EXPECT_EQ(child1.id, test_observer.subtree_reparented_finished_ids()[0]); EXPECT_EQ(child2.id, test_observer.subtree_reparented_finished_ids()[1]); ASSERT_EQ(1U, test_observer.change_finished_ids().size()); EXPECT_EQ(root.id, test_observer.change_finished_ids()[0]); EXPECT_FALSE(test_observer.root_changed()); EXPECT_FALSE(test_observer.tree_data_changed()); } TEST(AXTreeTest, NoReparentingIfOnlyRemovedAndChangedNotReAdded) { AXNodeData root; root.id = 1; AXNodeData child1; child1.id = 2; AXNodeData child2; child2.id = 3; root.child_ids = {child1.id}; child1.child_ids = {child2.id}; AXTreeUpdate initial_state; initial_state.root_id = root.id; initial_state.nodes = {root, child1, child2}; AXTree tree(initial_state); // Change existing attributes. AXTreeUpdate update; update.nodes.resize(2); update.nodes[0].id = 2; update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kActivedescendantId, 3); update.nodes[1].id = 1; TestAXTreeObserver test_observer(&tree); EXPECT_TRUE(tree.Unserialize(update)) << tree.error(); EXPECT_EQ(2U, test_observer.deleted_ids().size()); EXPECT_EQ(2U, test_observer.subtree_deleted_ids().size()); EXPECT_EQ(0U, test_observer.created_ids().size()); EXPECT_EQ(0U, test_observer.node_creation_finished_ids().size()); EXPECT_EQ(0U, test_observer.subtree_creation_finished_ids().size()); EXPECT_EQ(0U, test_observer.node_will_be_reparented_ids().size()); EXPECT_EQ(2U, test_observer.node_will_be_deleted_ids().size()); EXPECT_EQ(0U, test_observer.subtree_will_be_reparented_ids().size()); EXPECT_EQ(0U, test_observer.node_reparented_ids().size()); EXPECT_EQ(0U, test_observer.node_reparented_finished_ids().size()); EXPECT_EQ(0U, test_observer.subtree_reparented_finished_ids().size()); EXPECT_FALSE(test_observer.root_changed()); EXPECT_FALSE(test_observer.tree_data_changed()); } // Tests a fringe scenario that may happen if multiple AXTreeUpdates are merged. // Make sure that when a node is reparented then removed from the tree // that it notifies OnNodeDeleted rather than OnNodeReparented. TEST(AXTreeTest, NoReparentingIfRemovedMultipleTimesAndNotInFinalTree) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(4); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids = {2, 4}; initial_state.nodes[1].id = 2; initial_state.nodes[1].child_ids = {3}; initial_state.nodes[2].id = 3; initial_state.nodes[3].id = 4; AXTree tree(initial_state); AXTreeUpdate update; update.nodes.resize(4); // Delete AXID 3 update.nodes[0].id = 2; // Reparent AXID 3 onto AXID 4 update.nodes[1].id = 4; update.nodes[1].child_ids = {3}; update.nodes[2].id = 3; // Delete AXID 3 update.nodes[3].id = 4; TestAXTreeObserver test_observer(&tree); ASSERT_TRUE(tree.Unserialize(update)) << tree.error(); EXPECT_EQ(1U, test_observer.deleted_ids().size()); EXPECT_EQ(1U, test_observer.subtree_deleted_ids().size()); EXPECT_EQ(0U, test_observer.created_ids().size()); EXPECT_EQ(0U, test_observer.node_creation_finished_ids().size()); EXPECT_EQ(0U, test_observer.subtree_creation_finished_ids().size()); EXPECT_EQ(0U, test_observer.node_will_be_reparented_ids().size()); EXPECT_EQ(1U, test_observer.node_will_be_deleted_ids().size()); EXPECT_EQ(0U, test_observer.subtree_will_be_reparented_ids().size()); EXPECT_EQ(0U, test_observer.node_reparented_ids().size()); EXPECT_EQ(0U, test_observer.node_reparented_finished_ids().size()); EXPECT_EQ(0U, test_observer.subtree_reparented_finished_ids().size()); EXPECT_FALSE(test_observer.root_changed()); EXPECT_FALSE(test_observer.tree_data_changed()); } // Tests a fringe scenario that may happen if multiple AXTreeUpdates are merged. // Make sure that when a node is reparented multiple times and exists in the // final tree that it notifies OnNodeReparented rather than OnNodeDeleted. TEST(AXTreeTest, ReparentIfRemovedMultipleTimesButExistsInFinalTree) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(4); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids = {2, 4}; initial_state.nodes[1].id = 2; initial_state.nodes[1].child_ids = {3}; initial_state.nodes[2].id = 3; initial_state.nodes[3].id = 4; AXTree tree(initial_state); AXTreeUpdate update; update.nodes.resize(6); // Delete AXID 3 update.nodes[0].id = 2; // Reparent AXID 3 onto AXID 4 update.nodes[1].id = 4; update.nodes[1].child_ids = {3}; update.nodes[2].id = 3; // Delete AXID 3 update.nodes[3].id = 4; // Reparent AXID 3 onto AXID 2 update.nodes[4].id = 2; update.nodes[4].child_ids = {3}; update.nodes[5].id = 3; TestAXTreeObserver test_observer(&tree); ASSERT_TRUE(tree.Unserialize(update)) << tree.error(); EXPECT_EQ(0U, test_observer.deleted_ids().size()); EXPECT_EQ(0U, test_observer.subtree_deleted_ids().size()); EXPECT_EQ(0U, test_observer.created_ids().size()); EXPECT_EQ(0U, test_observer.node_creation_finished_ids().size()); EXPECT_EQ(0U, test_observer.subtree_creation_finished_ids().size()); EXPECT_EQ(1U, test_observer.node_will_be_reparented_ids().size()); EXPECT_EQ(0U, test_observer.node_will_be_deleted_ids().size()); EXPECT_EQ(1U, test_observer.subtree_will_be_reparented_ids().size()); EXPECT_EQ(1U, test_observer.node_reparented_ids().size()); EXPECT_EQ(0U, test_observer.node_reparented_finished_ids().size()); EXPECT_EQ(1U, test_observer.subtree_reparented_finished_ids().size()); EXPECT_FALSE(test_observer.root_changed()); EXPECT_FALSE(test_observer.tree_data_changed()); } TEST(AXTreeTest, ReparentRootIfRootChanged) { AXNodeData root; root.id = 1; AXNodeData child1; child1.id = 2; AXNodeData child2; child2.id = 3; root.child_ids = {child1.id}; child1.child_ids = {child2.id}; AXTreeUpdate initial_state; initial_state.root_id = root.id; initial_state.nodes = {root, child1, child2}; AXTree tree(initial_state); // Create a new root and reparent |child2| to be a child of the new root. AXNodeData root2; root2.id = 4; root2.child_ids = {child1.id, child2.id}; child1.child_ids = {}; AXTreeUpdate update; update.root_id = root2.id; update.node_id_to_clear = root.id; update.nodes = {root2, child1, child2}; TestAXTreeObserver test_observer(&tree); ASSERT_TRUE(tree.Unserialize(update)); ASSERT_EQ(1U, test_observer.deleted_ids().size()); EXPECT_EQ(root.id, test_observer.deleted_ids()[0]); ASSERT_EQ(1U, test_observer.subtree_deleted_ids().size()); EXPECT_EQ(root.id, test_observer.subtree_deleted_ids()[0]); ASSERT_EQ(1U, test_observer.created_ids().size()); EXPECT_EQ(root2.id, test_observer.created_ids()[0]); EXPECT_EQ(0U, test_observer.node_creation_finished_ids().size()); ASSERT_EQ(1U, test_observer.subtree_creation_finished_ids().size()); EXPECT_EQ(root2.id, test_observer.subtree_creation_finished_ids()[0]); ASSERT_EQ(2U, test_observer.node_reparented_finished_ids().size()); EXPECT_EQ(child1.id, test_observer.node_reparented_finished_ids()[0]); EXPECT_EQ(child2.id, test_observer.node_reparented_finished_ids()[1]); EXPECT_EQ(0U, test_observer.subtree_reparented_finished_ids().size()); EXPECT_EQ(0U, test_observer.change_finished_ids().size()); EXPECT_TRUE(test_observer.root_changed()); EXPECT_FALSE(test_observer.tree_data_changed()); } TEST(AXTreeTest, ImplicitChildrenDelete) { // This test covers the case where an AXTreeUpdate includes a node without // mentioning that node's children, this should cause a delete of those child // nodes. // Setup initial tree state // Tree: // 1 // 2 3 AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.resize(2); initial_state.nodes[0].child_ids[0] = 2; initial_state.nodes[0].child_ids[1] = 3; initial_state.nodes[1].id = 2; initial_state.nodes[2].id = 3; AXTree tree(initial_state); EXPECT_NE(tree.GetFromId(1), nullptr); EXPECT_NE(tree.GetFromId(2), nullptr); EXPECT_NE(tree.GetFromId(3), nullptr); // Perform a no-op update of node 1 but omit any mention of its children. This // should delete all of the node's children. AXTreeUpdate update; update.nodes.resize(1); update.nodes[0].id = 1; ASSERT_TRUE(tree.Unserialize(update)); // Check that nodes 2 and 3 have been deleted. EXPECT_NE(tree.GetFromId(1), nullptr); EXPECT_EQ(tree.GetFromId(2), nullptr); EXPECT_EQ(tree.GetFromId(3), nullptr); } TEST(AXTreeTest, IndexInParentAfterReorder) { // This test covers the case where an AXTreeUpdate includes // reordered children. The unignored index in parent // values should be updated. // Setup initial tree state. // Tree: // 1 // 2 3 4 AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(4); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.resize(3); initial_state.nodes[0].child_ids[0] = 2; initial_state.nodes[0].child_ids[1] = 3; initial_state.nodes[0].child_ids[2] = 4; initial_state.nodes[1].id = 2; initial_state.nodes[2].id = 3; initial_state.nodes[3].id = 4; AXTree tree(initial_state); // Index in parent correct. EXPECT_EQ(0U, tree.GetFromId(2)->GetUnignoredIndexInParent()); EXPECT_EQ(1U, tree.GetFromId(3)->GetUnignoredIndexInParent()); EXPECT_EQ(2U, tree.GetFromId(4)->GetUnignoredIndexInParent()); // Perform an update where we reorder children to [ 4 3 2 ] AXTreeUpdate update; update.nodes.resize(4); update.root_id = 1; update.nodes[0].id = 1; update.nodes[0].child_ids.resize(3); update.nodes[0].child_ids[0] = 4; update.nodes[0].child_ids[1] = 3; update.nodes[0].child_ids[2] = 2; update.nodes[1].id = 2; update.nodes[2].id = 3; update.nodes[3].id = 4; ASSERT_TRUE(tree.Unserialize(update)); // Index in parent should have changed as well. EXPECT_EQ(0U, tree.GetFromId(4)->GetUnignoredIndexInParent()); EXPECT_EQ(1U, tree.GetFromId(3)->GetUnignoredIndexInParent()); EXPECT_EQ(2U, tree.GetFromId(2)->GetUnignoredIndexInParent()); } TEST(AXTreeTest, IndexInParentAfterReorderIgnoredNode) { // This test covers another case where an AXTreeUpdate includes // reordered children. If one of the reordered nodes is ignored, its // children's unignored index in parent should also be updated. // Setup initial tree state. // Tree: // 1 // 2 3i 4 // 5 6 AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(6); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.resize(3); initial_state.nodes[0].child_ids[0] = 2; initial_state.nodes[0].child_ids[1] = 3; initial_state.nodes[0].child_ids[2] = 4; initial_state.nodes[1].id = 2; initial_state.nodes[2].id = 3; initial_state.nodes[2].AddState(ax::mojom::State::kIgnored); initial_state.nodes[2].child_ids.resize(2); initial_state.nodes[2].child_ids[0] = 5; initial_state.nodes[2].child_ids[1] = 6; initial_state.nodes[3].id = 4; initial_state.nodes[4].id = 5; initial_state.nodes[5].id = 6; AXTree tree(initial_state); // Index in parent correct. EXPECT_EQ(0U, tree.GetFromId(2)->GetUnignoredIndexInParent()); EXPECT_EQ(1U, tree.GetFromId(5)->GetUnignoredIndexInParent()); EXPECT_EQ(2U, tree.GetFromId(6)->GetUnignoredIndexInParent()); EXPECT_EQ(3U, tree.GetFromId(4)->GetUnignoredIndexInParent()); // Perform an update where we reorder children to [ 3i 2 4 ]. The // unignored index in parent for the children of the ignored node (3) should // be updated. AXTreeUpdate update; update.root_id = 1; update.nodes.resize(6); update.nodes[0].id = 1; update.nodes[0].child_ids.resize(3); update.nodes[0].child_ids[0] = 3; update.nodes[0].child_ids[1] = 2; update.nodes[0].child_ids[2] = 4; update.nodes[1].id = 2; update.nodes[2].id = 3; update.nodes[2].AddState(ax::mojom::State::kIgnored); update.nodes[2].child_ids.resize(2); update.nodes[2].child_ids[0] = 5; update.nodes[2].child_ids[1] = 6; update.nodes[3].id = 4; update.nodes[4].id = 5; update.nodes[5].id = 6; ASSERT_TRUE(tree.Unserialize(update)); EXPECT_EQ(2U, tree.GetFromId(2)->GetUnignoredIndexInParent()); EXPECT_EQ(0U, tree.GetFromId(5)->GetUnignoredIndexInParent()); EXPECT_EQ(1U, tree.GetFromId(6)->GetUnignoredIndexInParent()); EXPECT_EQ(3U, tree.GetFromId(4)->GetUnignoredIndexInParent()); } TEST(AXTreeTest, ImplicitAttributeDelete) { // This test covers the case where an AXTreeUpdate includes a node without // mentioning one of that node's attributes, this should cause a delete of any // unmentioned attribute that was previously set on the node. AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; initial_state.nodes[0].SetName("Node 1 name"); AXTree tree(initial_state); EXPECT_NE(tree.GetFromId(1), nullptr); EXPECT_EQ( tree.GetFromId(1)->GetStringAttribute(ax::mojom::StringAttribute::kName), "Node 1 name"); // Perform a no-op update of node 1 but omit any mention of the name // attribute. This should delete the name attribute. AXTreeUpdate update; update.nodes.resize(1); update.nodes[0].id = 1; ASSERT_TRUE(tree.Unserialize(update)); // Check that the name attribute is no longer present. EXPECT_NE(tree.GetFromId(1), nullptr); EXPECT_FALSE( tree.GetFromId(1)->HasStringAttribute(ax::mojom::StringAttribute::kName)); } TEST(AXTreeTest, TreeObserverIsCalled) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(2); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[1].id = 2; AXTree tree(initial_state); AXTreeUpdate update; update.root_id = 3; update.node_id_to_clear = 1; update.nodes.resize(2); update.nodes[0].id = 3; update.nodes[0].child_ids.push_back(4); update.nodes[1].id = 4; TestAXTreeObserver test_observer(&tree); ASSERT_TRUE(tree.Unserialize(update)); ASSERT_EQ(2U, test_observer.deleted_ids().size()); EXPECT_EQ(1, test_observer.deleted_ids()[0]); EXPECT_EQ(2, test_observer.deleted_ids()[1]); ASSERT_EQ(1U, test_observer.subtree_deleted_ids().size()); EXPECT_EQ(1, test_observer.subtree_deleted_ids()[0]); ASSERT_EQ(2U, test_observer.created_ids().size()); EXPECT_EQ(3, test_observer.created_ids()[0]); EXPECT_EQ(4, test_observer.created_ids()[1]); ASSERT_EQ(1U, test_observer.subtree_creation_finished_ids().size()); EXPECT_EQ(3, test_observer.subtree_creation_finished_ids()[0]); ASSERT_EQ(1U, test_observer.node_creation_finished_ids().size()); EXPECT_EQ(4, test_observer.node_creation_finished_ids()[0]); ASSERT_TRUE(test_observer.root_changed()); } TEST(AXTreeTest, TreeObserverIsCalledForTreeDataChanges) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; initial_state.has_tree_data = true; initial_state.tree_data.title = "Initial"; AXTree tree(initial_state); TestAXTreeObserver test_observer(&tree); // An empty update shouldn't change tree data. AXTreeUpdate empty_update; EXPECT_TRUE(tree.Unserialize(empty_update)); EXPECT_FALSE(test_observer.tree_data_changed()); EXPECT_EQ("Initial", tree.data().title); // An update with tree data shouldn't change tree data if // |has_tree_data| isn't set. AXTreeUpdate ignored_tree_data_update; ignored_tree_data_update.tree_data.title = "Ignore Me"; EXPECT_TRUE(tree.Unserialize(ignored_tree_data_update)); EXPECT_FALSE(test_observer.tree_data_changed()); EXPECT_EQ("Initial", tree.data().title); // An update with |has_tree_data| set should update the tree data. AXTreeUpdate tree_data_update; tree_data_update.has_tree_data = true; tree_data_update.tree_data.title = "New Title"; EXPECT_TRUE(tree.Unserialize(tree_data_update)); EXPECT_TRUE(test_observer.tree_data_changed()); EXPECT_EQ("New Title", tree.data().title); } TEST(AXTreeTest, ReparentingDoesNotTriggerNodeCreated) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[1].id = 2; initial_state.nodes[1].child_ids.push_back(3); initial_state.nodes[2].id = 3; AXTree tree(initial_state); TestAXTreeObserver test_observer(&tree); AXTreeUpdate update; update.nodes.resize(2); update.node_id_to_clear = 2; update.root_id = 1; update.nodes[0].id = 1; update.nodes[0].child_ids.push_back(3); update.nodes[1].id = 3; EXPECT_TRUE(tree.Unserialize(update)) << tree.error(); std::vector<int> created = test_observer.node_creation_finished_ids(); std::vector<int> subtree_reparented = test_observer.subtree_reparented_finished_ids(); std::vector<int> node_reparented = test_observer.node_reparented_finished_ids(); ASSERT_FALSE(base::Contains(created, 3)); ASSERT_TRUE(base::Contains(subtree_reparented, 3)); ASSERT_FALSE(base::Contains(node_reparented, 3)); } TEST(AXTreeTest, MultipleIgnoredChangesDoesNotBreakCache) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[1].id = 2; initial_state.nodes[1].AddState(ax::mojom::State::kIgnored); initial_state.nodes[1].child_ids.push_back(3); initial_state.nodes[2].id = 3; AXTree tree(initial_state); TestAXTreeObserver test_observer(&tree); EXPECT_EQ(1u, tree.GetFromId(2)->GetUnignoredChildCount()); AXTreeUpdate update; update.nodes.resize(2); update.nodes[0].id = 3; update.nodes[0].AddState(ax::mojom::State::kIgnored); update.nodes[1].id = 2; update.nodes[1].child_ids.push_back(3); EXPECT_TRUE(tree.Unserialize(update)) << tree.error(); EXPECT_EQ(0u, tree.GetFromId(2)->GetUnignoredChildCount()); EXPECT_FALSE(tree.GetFromId(2)->data().HasState(ax::mojom::State::kIgnored)); EXPECT_TRUE(tree.GetFromId(3)->data().HasState(ax::mojom::State::kIgnored)); } TEST(AXTreeTest, NodeToClearUpdatesParentUnignoredCount) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(4); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[1].id = 2; initial_state.nodes[1].AddState(ax::mojom::State::kIgnored); initial_state.nodes[1].child_ids.push_back(3); initial_state.nodes[1].child_ids.push_back(4); initial_state.nodes[2].id = 3; initial_state.nodes[3].id = 4; AXTree tree(initial_state); EXPECT_EQ(2u, tree.GetFromId(1)->GetUnignoredChildCount()); EXPECT_EQ(2u, tree.GetFromId(2)->GetUnignoredChildCount()); AXTreeUpdate update; update.nodes.resize(1); update.node_id_to_clear = 2; update.root_id = 1; update.nodes[0] = initial_state.nodes[1]; update.nodes[0].state = 0; update.nodes[0].child_ids.resize(0); EXPECT_TRUE(tree.Unserialize(update)) << tree.error(); EXPECT_EQ(1u, tree.GetFromId(1)->GetUnignoredChildCount()); } TEST(AXTreeTest, TreeObserverIsNotCalledForReparenting) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(2); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[1].id = 2; AXTree tree(initial_state); AXTreeUpdate update; update.node_id_to_clear = 1; update.root_id = 2; update.nodes.resize(2); update.nodes[0].id = 2; update.nodes[0].child_ids.push_back(4); update.nodes[1].id = 4; TestAXTreeObserver test_observer(&tree); EXPECT_TRUE(tree.Unserialize(update)); ASSERT_EQ(1U, test_observer.deleted_ids().size()); EXPECT_EQ(1, test_observer.deleted_ids()[0]); ASSERT_EQ(1U, test_observer.subtree_deleted_ids().size()); EXPECT_EQ(1, test_observer.subtree_deleted_ids()[0]); ASSERT_EQ(1U, test_observer.created_ids().size()); EXPECT_EQ(4, test_observer.created_ids()[0]); ASSERT_EQ(1U, test_observer.subtree_creation_finished_ids().size()); EXPECT_EQ(4, test_observer.subtree_creation_finished_ids()[0]); ASSERT_EQ(1U, test_observer.subtree_reparented_finished_ids().size()); EXPECT_EQ(2, test_observer.subtree_reparented_finished_ids()[0]); EXPECT_EQ(0U, test_observer.node_creation_finished_ids().size()); EXPECT_EQ(0U, test_observer.node_reparented_finished_ids().size()); ASSERT_TRUE(test_observer.root_changed()); } // UAF caught by ax_tree_fuzzer TEST(AXTreeTest, BogusAXTree) { AXTreeUpdate initial_state; AXNodeData node; node.id = 0; initial_state.nodes.push_back(node); initial_state.nodes.push_back(node); ui::AXTree tree; tree.Unserialize(initial_state); } // UAF caught by ax_tree_fuzzer TEST(AXTreeTest, BogusAXTree2) { AXTreeUpdate initial_state; AXNodeData node; node.id = 0; initial_state.nodes.push_back(node); AXNodeData node2; node2.id = 0; node2.child_ids.push_back(0); node2.child_ids.push_back(0); initial_state.nodes.push_back(node2); ui::AXTree tree; tree.Unserialize(initial_state); } // UAF caught by ax_tree_fuzzer TEST(AXTreeTest, BogusAXTree3) { AXTreeUpdate initial_state; AXNodeData node; node.id = 0; node.child_ids.push_back(1); initial_state.nodes.push_back(node); AXNodeData node2; node2.id = 1; node2.child_ids.push_back(1); node2.child_ids.push_back(1); initial_state.nodes.push_back(node2); ui::AXTree tree; tree.Unserialize(initial_state); } TEST(AXTreeTest, RoleAndStateChangeCallbacks) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kButton; initial_state.nodes[0].SetCheckedState(ax::mojom::CheckedState::kTrue); initial_state.nodes[0].AddState(ax::mojom::State::kFocusable); AXTree tree(initial_state); TestAXTreeObserver test_observer(&tree); // Change the role and state. AXTreeUpdate update; update.root_id = 1; update.nodes.resize(1); update.nodes[0].id = 1; update.nodes[0].role = ax::mojom::Role::kCheckBox; update.nodes[0].SetCheckedState(ax::mojom::CheckedState::kFalse); update.nodes[0].AddState(ax::mojom::State::kFocusable); update.nodes[0].AddState(ax::mojom::State::kVisited); EXPECT_TRUE(tree.Unserialize(update)); const std::vector<std::string>& change_log = test_observer.attribute_change_log(); ASSERT_EQ(3U, change_log.size()); EXPECT_EQ("Role changed from button to checkBox", change_log[0]); EXPECT_EQ("visited changed to true", change_log[1]); EXPECT_EQ("checkedState changed from 2 to 1", change_log[2]); } TEST(AXTreeTest, AttributeChangeCallbacks) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; initial_state.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kName, "N1"); initial_state.nodes[0].AddStringAttribute( ax::mojom::StringAttribute::kDescription, "D1"); initial_state.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kLiveAtomic, true); initial_state.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kBusy, false); initial_state.nodes[0].AddFloatAttribute( ax::mojom::FloatAttribute::kMinValueForRange, 1.0); initial_state.nodes[0].AddFloatAttribute( ax::mojom::FloatAttribute::kMaxValueForRange, 10.0); initial_state.nodes[0].AddFloatAttribute( ax::mojom::FloatAttribute::kStepValueForRange, 3.0); initial_state.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollX, 5); initial_state.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollXMin, 1); AXTree tree(initial_state); TestAXTreeObserver test_observer(&tree); // Change existing attributes. AXTreeUpdate update0; update0.root_id = 1; update0.nodes.resize(1); update0.nodes[0].id = 1; update0.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kName, "N2"); update0.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kDescription, "D2"); update0.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kLiveAtomic, false); update0.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kBusy, true); update0.nodes[0].AddFloatAttribute( ax::mojom::FloatAttribute::kMinValueForRange, 2.0); update0.nodes[0].AddFloatAttribute( ax::mojom::FloatAttribute::kMaxValueForRange, 9.0); update0.nodes[0].AddFloatAttribute( ax::mojom::FloatAttribute::kStepValueForRange, 0.5); update0.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollX, 6); update0.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollXMin, 2); EXPECT_TRUE(tree.Unserialize(update0)); const std::vector<std::string>& change_log = test_observer.attribute_change_log(); ASSERT_EQ(9U, change_log.size()); EXPECT_EQ("name changed from N1 to N2", change_log[0]); EXPECT_EQ("description changed from D1 to D2", change_log[1]); EXPECT_EQ("liveAtomic changed to false", change_log[2]); EXPECT_EQ("busy changed to true", change_log[3]); EXPECT_EQ("minValueForRange changed from 1.0 to 2.0", change_log[4]); EXPECT_EQ("maxValueForRange changed from 10.0 to 9.0", change_log[5]); EXPECT_EQ("stepValueForRange changed from 3.0 to 0.5", change_log[6]); EXPECT_EQ("scrollX changed from 5 to 6", change_log[7]); EXPECT_EQ("scrollXMin changed from 1 to 2", change_log[8]); TestAXTreeObserver test_observer2(&tree); // Add and remove attributes. AXTreeUpdate update1; update1.root_id = 1; update1.nodes.resize(1); update1.nodes[0].id = 1; update1.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kDescription, "D3"); update1.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kValue, "V3"); update1.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kModal, true); update1.nodes[0].AddFloatAttribute(ax::mojom::FloatAttribute::kValueForRange, 5.0); update1.nodes[0].AddFloatAttribute( ax::mojom::FloatAttribute::kMaxValueForRange, 9.0); update1.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollX, 7); update1.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollXMax, 10); EXPECT_TRUE(tree.Unserialize(update1)); const std::vector<std::string>& change_log2 = test_observer2.attribute_change_log(); ASSERT_EQ(11U, change_log2.size()); EXPECT_EQ("name changed from N2 to ", change_log2[0]); EXPECT_EQ("description changed from D2 to D3", change_log2[1]); EXPECT_EQ("value changed from to V3", change_log2[2]); EXPECT_EQ("busy changed to false", change_log2[3]); EXPECT_EQ("modal changed to true", change_log2[4]); EXPECT_EQ("minValueForRange changed from 2.0 to 0.0", change_log2[5]); EXPECT_EQ("stepValueForRange changed from 3.0 to 0.5", change_log[6]); EXPECT_EQ("valueForRange changed from 0.0 to 5.0", change_log2[7]); EXPECT_EQ("scrollXMin changed from 2 to 0", change_log2[8]); EXPECT_EQ("scrollX changed from 6 to 7", change_log2[9]); EXPECT_EQ("scrollXMax changed from 0 to 10", change_log2[10]); } TEST(AXTreeTest, IntListChangeCallbacks) { std::vector<int32_t> one; one.push_back(1); std::vector<int32_t> two; two.push_back(2); two.push_back(2); std::vector<int32_t> three; three.push_back(3); AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; initial_state.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kControlsIds, one); initial_state.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kRadioGroupIds, two); AXTree tree(initial_state); TestAXTreeObserver test_observer(&tree); // Change existing attributes. AXTreeUpdate update0; update0.root_id = 1; update0.nodes.resize(1); update0.nodes[0].id = 1; update0.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kControlsIds, two); update0.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kRadioGroupIds, three); EXPECT_TRUE(tree.Unserialize(update0)); const std::vector<std::string>& change_log = test_observer.attribute_change_log(); ASSERT_EQ(2U, change_log.size()); EXPECT_EQ("controlsIds changed from 1 to 2,2", change_log[0]); EXPECT_EQ("radioGroupIds changed from 2,2 to 3", change_log[1]); TestAXTreeObserver test_observer2(&tree); // Add and remove attributes. AXTreeUpdate update1; update1.root_id = 1; update1.nodes.resize(1); update1.nodes[0].id = 1; update1.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kRadioGroupIds, two); update1.nodes[0].AddIntListAttribute(ax::mojom::IntListAttribute::kFlowtoIds, three); EXPECT_TRUE(tree.Unserialize(update1)); const std::vector<std::string>& change_log2 = test_observer2.attribute_change_log(); ASSERT_EQ(3U, change_log2.size()); EXPECT_EQ("controlsIds changed from 2,2 to ", change_log2[0]); EXPECT_EQ("radioGroupIds changed from 3 to 2,2", change_log2[1]); EXPECT_EQ("flowtoIds changed from to 3", change_log2[2]); } // Create a very simple tree and make sure that we can get the bounds of // any node. TEST(AXTreeTest, GetBoundsBasic) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(2); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(100, 10, 400, 300); AXTree tree(tree_update); EXPECT_EQ("(0, 0) size (800 x 600)", GetBoundsAsString(tree, 1)); EXPECT_EQ("(100, 10) size (400 x 300)", GetBoundsAsString(tree, 2)); } // If a node doesn't specify its location but at least one child does have // a location, its computed bounds should be the union of all child bounds. TEST(AXTreeTest, EmptyNodeBoundsIsUnionOfChildren) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(); // Deliberately empty. tree_update.nodes[1].child_ids.push_back(3); tree_update.nodes[1].child_ids.push_back(4); tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(100, 10, 400, 20); tree_update.nodes[3].id = 4; tree_update.nodes[3].relative_bounds.bounds = gfx::RectF(200, 30, 400, 20); AXTree tree(tree_update); EXPECT_EQ("(100, 10) size (500 x 40)", GetBoundsAsString(tree, 2)); } // If a node doesn't specify its location but at least one child does have // a location, it will be offscreen if all of its children are offscreen. TEST(AXTreeTest, EmptyNodeNotOffscreenEvenIfAllChildrenOffscreen) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].role = ax::mojom::Role::kRootWebArea; tree_update.nodes[0].AddBoolAttribute( ax::mojom::BoolAttribute::kClipsChildren, true); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(); // Deliberately empty. tree_update.nodes[1].child_ids.push_back(3); tree_update.nodes[1].child_ids.push_back(4); // Both children are offscreen tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(900, 10, 400, 20); tree_update.nodes[3].id = 4; tree_update.nodes[3].relative_bounds.bounds = gfx::RectF(1000, 30, 400, 20); AXTree tree(tree_update); EXPECT_FALSE(IsNodeOffscreen(tree, 2)); EXPECT_TRUE(IsNodeOffscreen(tree, 3)); EXPECT_TRUE(IsNodeOffscreen(tree, 4)); } // Test that getting the bounds of a node works when there's a transform. TEST(AXTreeTest, GetBoundsWithTransform) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(3); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 400, 300); tree_update.nodes[0].relative_bounds.transform = std::make_unique<gfx::Transform>(); tree_update.nodes[0].relative_bounds.transform->Scale(2.0, 2.0); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[0].child_ids.push_back(3); tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(20, 10, 50, 5); tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(20, 30, 50, 5); tree_update.nodes[2].relative_bounds.transform = std::make_unique<gfx::Transform>(); tree_update.nodes[2].relative_bounds.transform->Scale(2.0, 2.0); AXTree tree(tree_update); EXPECT_EQ("(0, 0) size (800 x 600)", GetBoundsAsString(tree, 1)); EXPECT_EQ("(40, 20) size (100 x 10)", GetBoundsAsString(tree, 2)); EXPECT_EQ("(80, 120) size (200 x 20)", GetBoundsAsString(tree, 3)); } // Test that getting the bounds of a node that's inside a container // works correctly. TEST(AXTreeTest, GetBoundsWithContainerId) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(100, 50, 600, 500); tree_update.nodes[1].child_ids.push_back(3); tree_update.nodes[1].child_ids.push_back(4); tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.offset_container_id = 2; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(20, 30, 50, 5); tree_update.nodes[3].id = 4; tree_update.nodes[3].relative_bounds.bounds = gfx::RectF(20, 30, 50, 5); AXTree tree(tree_update); EXPECT_EQ("(120, 80) size (50 x 5)", GetBoundsAsString(tree, 3)); EXPECT_EQ("(20, 30) size (50 x 5)", GetBoundsAsString(tree, 4)); } // Test that getting the bounds of a node that's inside a scrolling container // works correctly. TEST(AXTreeTest, GetBoundsWithScrolling) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(3); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(100, 50, 600, 500); tree_update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kScrollX, 5); tree_update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kScrollY, 10); tree_update.nodes[1].child_ids.push_back(3); tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.offset_container_id = 2; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(20, 30, 50, 5); AXTree tree(tree_update); EXPECT_EQ("(115, 70) size (50 x 5)", GetBoundsAsString(tree, 3)); } // When a node has zero size, we try to get the bounds from an ancestor. TEST(AXTreeTest, GetBoundsOfNodeWithZeroSize) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(5); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].child_ids = {2}; tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(100, 100, 300, 200); tree_update.nodes[1].child_ids = {3, 4, 5}; // This child has relative coordinates and no offset and no size. tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.offset_container_id = 2; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(0, 0, 0, 0); // This child has relative coordinates and an offset, but no size. tree_update.nodes[3].id = 4; tree_update.nodes[3].relative_bounds.offset_container_id = 2; tree_update.nodes[3].relative_bounds.bounds = gfx::RectF(20, 20, 0, 0); // This child has absolute coordinates, an offset, and no size. tree_update.nodes[4].id = 5; tree_update.nodes[4].relative_bounds.bounds = gfx::RectF(120, 120, 0, 0); AXTree tree(tree_update); EXPECT_EQ("(100, 100) size (300 x 200)", GetBoundsAsString(tree, 3)); EXPECT_EQ("(120, 120) size (280 x 180)", GetBoundsAsString(tree, 4)); EXPECT_EQ("(120, 120) size (280 x 180)", GetBoundsAsString(tree, 5)); } TEST(AXTreeTest, GetBoundsEmptyBoundsInheritsFromParent) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(3); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[1].AddBoolAttribute( ax::mojom::BoolAttribute::kClipsChildren, true); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(300, 200, 100, 100); tree_update.nodes[1].child_ids.push_back(3); tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(); AXTree tree(tree_update); EXPECT_EQ("(0, 0) size (800 x 600)", GetBoundsAsString(tree, 1)); EXPECT_EQ("(300, 200) size (100 x 100)", GetBoundsAsString(tree, 2)); EXPECT_EQ("(300, 200) size (100 x 100)", GetBoundsAsString(tree, 3)); EXPECT_EQ("(0, 0) size (800 x 600)", GetUnclippedBoundsAsString(tree, 1)); EXPECT_EQ("(300, 200) size (100 x 100)", GetUnclippedBoundsAsString(tree, 2)); EXPECT_EQ("(300, 200) size (100 x 100)", GetUnclippedBoundsAsString(tree, 3)); EXPECT_FALSE(IsNodeOffscreen(tree, 1)); EXPECT_FALSE(IsNodeOffscreen(tree, 2)); EXPECT_TRUE(IsNodeOffscreen(tree, 3)); } TEST(AXTreeTest, GetBoundsCropsChildToRoot) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(5); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].AddBoolAttribute( ax::mojom::BoolAttribute::kClipsChildren, true); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[0].child_ids.push_back(3); tree_update.nodes[0].child_ids.push_back(4); tree_update.nodes[0].child_ids.push_back(5); // Cropped in the top left tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(-100, -100, 150, 150); // Cropped in the bottom right tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(700, 500, 150, 150); // Offscreen on the top tree_update.nodes[3].id = 4; tree_update.nodes[3].relative_bounds.bounds = gfx::RectF(50, -200, 150, 150); // Offscreen on the bottom tree_update.nodes[4].id = 5; tree_update.nodes[4].relative_bounds.bounds = gfx::RectF(50, 700, 150, 150); AXTree tree(tree_update); EXPECT_EQ("(0, 0) size (50 x 50)", GetBoundsAsString(tree, 2)); EXPECT_EQ("(700, 500) size (100 x 100)", GetBoundsAsString(tree, 3)); EXPECT_EQ("(50, 0) size (150 x 1)", GetBoundsAsString(tree, 4)); EXPECT_EQ("(50, 599) size (150 x 1)", GetBoundsAsString(tree, 5)); // Check the unclipped bounds are as expected. EXPECT_EQ("(-100, -100) size (150 x 150)", GetUnclippedBoundsAsString(tree, 2)); EXPECT_EQ("(700, 500) size (150 x 150)", GetUnclippedBoundsAsString(tree, 3)); EXPECT_EQ("(50, -200) size (150 x 150)", GetUnclippedBoundsAsString(tree, 4)); EXPECT_EQ("(50, 700) size (150 x 150)", GetUnclippedBoundsAsString(tree, 5)); } TEST(AXTreeTest, GetBoundsSetsOffscreenIfClipsChildren) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(5); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].AddBoolAttribute( ax::mojom::BoolAttribute::kClipsChildren, true); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[0].child_ids.push_back(3); tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); tree_update.nodes[1].AddBoolAttribute( ax::mojom::BoolAttribute::kClipsChildren, true); tree_update.nodes[1].child_ids.push_back(4); tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); tree_update.nodes[2].child_ids.push_back(5); // Clipped by its parent tree_update.nodes[3].id = 4; tree_update.nodes[3].relative_bounds.bounds = gfx::RectF(250, 250, 100, 100); tree_update.nodes[3].relative_bounds.offset_container_id = 2; // Outside of its parent, but its parent does not clip children, // so it should not be offscreen. tree_update.nodes[4].id = 5; tree_update.nodes[4].relative_bounds.bounds = gfx::RectF(250, 250, 100, 100); tree_update.nodes[4].relative_bounds.offset_container_id = 3; AXTree tree(tree_update); EXPECT_TRUE(IsNodeOffscreen(tree, 4)); EXPECT_FALSE(IsNodeOffscreen(tree, 5)); } TEST(AXTreeTest, GetBoundsUpdatesOffscreen) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(5); tree_update.nodes[0].id = 1; tree_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].role = ax::mojom::Role::kRootWebArea; tree_update.nodes[0].AddBoolAttribute( ax::mojom::BoolAttribute::kClipsChildren, true); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[0].child_ids.push_back(3); tree_update.nodes[0].child_ids.push_back(4); tree_update.nodes[0].child_ids.push_back(5); // Fully onscreen tree_update.nodes[1].id = 2; tree_update.nodes[1].relative_bounds.bounds = gfx::RectF(10, 10, 150, 150); // Cropped in the bottom right tree_update.nodes[2].id = 3; tree_update.nodes[2].relative_bounds.bounds = gfx::RectF(700, 500, 150, 150); // Offscreen on the top tree_update.nodes[3].id = 4; tree_update.nodes[3].relative_bounds.bounds = gfx::RectF(50, -200, 150, 150); // Offscreen on the bottom tree_update.nodes[4].id = 5; tree_update.nodes[4].relative_bounds.bounds = gfx::RectF(50, 700, 150, 150); AXTree tree(tree_update); EXPECT_FALSE(IsNodeOffscreen(tree, 2)); EXPECT_FALSE(IsNodeOffscreen(tree, 3)); EXPECT_TRUE(IsNodeOffscreen(tree, 4)); EXPECT_TRUE(IsNodeOffscreen(tree, 5)); } TEST(AXTreeTest, IntReverseRelations) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(4); initial_state.nodes[0].id = 1; initial_state.nodes[0].AddIntAttribute( ax::mojom::IntAttribute::kActivedescendantId, 2); initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[0].child_ids.push_back(3); initial_state.nodes[0].child_ids.push_back(4); initial_state.nodes[1].id = 2; initial_state.nodes[2].id = 3; initial_state.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kMemberOfId, 1); initial_state.nodes[3].id = 4; initial_state.nodes[3].AddIntAttribute(ax::mojom::IntAttribute::kMemberOfId, 1); AXTree tree(initial_state); auto reverse_active_descendant = tree.GetReverseRelations(ax::mojom::IntAttribute::kActivedescendantId, 2); ASSERT_EQ(1U, reverse_active_descendant.size()); EXPECT_TRUE(base::Contains(reverse_active_descendant, 1)); reverse_active_descendant = tree.GetReverseRelations(ax::mojom::IntAttribute::kActivedescendantId, 1); ASSERT_EQ(0U, reverse_active_descendant.size()); auto reverse_errormessage = tree.GetReverseRelations(ax::mojom::IntAttribute::kErrormessageId, 1); ASSERT_EQ(0U, reverse_errormessage.size()); auto reverse_member_of = tree.GetReverseRelations(ax::mojom::IntAttribute::kMemberOfId, 1); ASSERT_EQ(2U, reverse_member_of.size()); EXPECT_TRUE(base::Contains(reverse_member_of, 3)); EXPECT_TRUE(base::Contains(reverse_member_of, 4)); AXTreeUpdate update = initial_state; update.nodes.resize(5); update.nodes[0].int_attributes.clear(); update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kActivedescendantId, 5); update.nodes[0].child_ids.push_back(5); update.nodes[2].int_attributes.clear(); update.nodes[4].id = 5; update.nodes[4].AddIntAttribute(ax::mojom::IntAttribute::kMemberOfId, 1); EXPECT_TRUE(tree.Unserialize(update)); reverse_active_descendant = tree.GetReverseRelations(ax::mojom::IntAttribute::kActivedescendantId, 2); ASSERT_EQ(0U, reverse_active_descendant.size()); reverse_active_descendant = tree.GetReverseRelations(ax::mojom::IntAttribute::kActivedescendantId, 5); ASSERT_EQ(1U, reverse_active_descendant.size()); EXPECT_TRUE(base::Contains(reverse_active_descendant, 1)); reverse_member_of = tree.GetReverseRelations(ax::mojom::IntAttribute::kMemberOfId, 1); ASSERT_EQ(2U, reverse_member_of.size()); EXPECT_TRUE(base::Contains(reverse_member_of, 4)); EXPECT_TRUE(base::Contains(reverse_member_of, 5)); } TEST(AXTreeTest, IntListReverseRelations) { std::vector<int32_t> node_two; node_two.push_back(2); std::vector<int32_t> nodes_two_three; nodes_two_three.push_back(2); nodes_two_three.push_back(3); AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kLabelledbyIds, node_two); initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[0].child_ids.push_back(3); initial_state.nodes[1].id = 2; initial_state.nodes[2].id = 3; AXTree tree(initial_state); auto reverse_labelled_by = tree.GetReverseRelations(ax::mojom::IntListAttribute::kLabelledbyIds, 2); ASSERT_EQ(1U, reverse_labelled_by.size()); EXPECT_TRUE(base::Contains(reverse_labelled_by, 1)); reverse_labelled_by = tree.GetReverseRelations(ax::mojom::IntListAttribute::kLabelledbyIds, 3); ASSERT_EQ(0U, reverse_labelled_by.size()); // Change existing attributes. AXTreeUpdate update = initial_state; update.nodes[0].intlist_attributes.clear(); update.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kLabelledbyIds, nodes_two_three); EXPECT_TRUE(tree.Unserialize(update)); reverse_labelled_by = tree.GetReverseRelations(ax::mojom::IntListAttribute::kLabelledbyIds, 3); ASSERT_EQ(1U, reverse_labelled_by.size()); EXPECT_TRUE(base::Contains(reverse_labelled_by, 1)); } TEST(AXTreeTest, DeletingNodeUpdatesReverseRelations) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids = {2, 3}; initial_state.nodes[1].id = 2; initial_state.nodes[2].id = 3; initial_state.nodes[2].AddIntAttribute( ax::mojom::IntAttribute::kActivedescendantId, 2); AXTree tree(initial_state); auto reverse_active_descendant = tree.GetReverseRelations(ax::mojom::IntAttribute::kActivedescendantId, 2); ASSERT_EQ(1U, reverse_active_descendant.size()); EXPECT_TRUE(base::Contains(reverse_active_descendant, 3)); AXTreeUpdate update; update.root_id = 1; update.nodes.resize(1); update.nodes[0].id = 1; update.nodes[0].child_ids = {2}; EXPECT_TRUE(tree.Unserialize(update)); reverse_active_descendant = tree.GetReverseRelations(ax::mojom::IntAttribute::kActivedescendantId, 2); ASSERT_EQ(0U, reverse_active_descendant.size()); } TEST(AXTreeTest, ReverseRelationsDoNotKeepGrowing) { // The number of total entries in int_reverse_relations and // intlist_reverse_relations should not keep growing as the tree // changes. AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(2); initial_state.nodes[0].id = 1; initial_state.nodes[0].AddIntAttribute( ax::mojom::IntAttribute::kActivedescendantId, 2); initial_state.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kLabelledbyIds, {2}); initial_state.nodes[0].child_ids.push_back(2); initial_state.nodes[1].id = 2; AXTree tree(initial_state); for (int i = 0; i < 1000; ++i) { AXTreeUpdate update; update.root_id = 1; update.nodes.resize(2); update.nodes[0].id = 1; update.nodes[1].id = i + 3; update.nodes[0].AddIntAttribute( ax::mojom::IntAttribute::kActivedescendantId, update.nodes[1].id); update.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kLabelledbyIds, {update.nodes[1].id}); update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kMemberOfId, 1); update.nodes[0].child_ids.push_back(update.nodes[1].id); EXPECT_TRUE(tree.Unserialize(update)); } size_t map_key_count = 0; size_t set_entry_count = 0; for (auto& iter : tree.int_reverse_relations()) { map_key_count += iter.second.size() + 1; for (auto it2 = iter.second.begin(); it2 != iter.second.end(); ++it2) { set_entry_count += it2->second.size(); } } // Note: 10 is arbitrary, the idea here is just that we mutated the tree // 1000 times, so if we have fewer than 10 entries in the maps / sets then // the map isn't growing / leaking. Same below. EXPECT_LT(map_key_count, 10U); EXPECT_LT(set_entry_count, 10U); map_key_count = 0; set_entry_count = 0; for (auto& iter : tree.intlist_reverse_relations()) { map_key_count += iter.second.size() + 1; for (auto it2 = iter.second.begin(); it2 != iter.second.end(); ++it2) { set_entry_count += it2->second.size(); } } EXPECT_LT(map_key_count, 10U); EXPECT_LT(set_entry_count, 10U); } TEST(AXTreeTest, SkipIgnoredNodes) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(5); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[1].child_ids = {4, 5}; tree_update.nodes[2].id = 3; tree_update.nodes[3].id = 4; tree_update.nodes[4].id = 5; AXTree tree(tree_update); AXNode* root = tree.root(); ASSERT_EQ(2u, root->children().size()); ASSERT_EQ(2, root->children()[0]->id()); ASSERT_EQ(3, root->children()[1]->id()); EXPECT_EQ(3u, root->GetUnignoredChildCount()); EXPECT_EQ(4, root->GetUnignoredChildAtIndex(0)->id()); EXPECT_EQ(5, root->GetUnignoredChildAtIndex(1)->id()); EXPECT_EQ(3, root->GetUnignoredChildAtIndex(2)->id()); EXPECT_EQ(0u, root->GetUnignoredChildAtIndex(0)->GetUnignoredIndexInParent()); EXPECT_EQ(1u, root->GetUnignoredChildAtIndex(1)->GetUnignoredIndexInParent()); EXPECT_EQ(2u, root->GetUnignoredChildAtIndex(2)->GetUnignoredIndexInParent()); EXPECT_EQ(1, root->GetUnignoredChildAtIndex(0)->GetUnignoredParent()->id()); } TEST(AXTreeTest, CachedUnignoredValues) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(5); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids = {2, 3}; initial_state.nodes[1].id = 2; initial_state.nodes[1].AddState(ax::mojom::State::kIgnored); initial_state.nodes[1].child_ids = {4, 5}; initial_state.nodes[2].id = 3; initial_state.nodes[3].id = 4; initial_state.nodes[4].id = 5; AXTree tree(initial_state); AXNode* root = tree.root(); ASSERT_EQ(2u, root->children().size()); ASSERT_EQ(2, root->children()[0]->id()); ASSERT_EQ(3, root->children()[1]->id()); EXPECT_EQ(3u, root->GetUnignoredChildCount()); EXPECT_EQ(4, root->GetUnignoredChildAtIndex(0)->id()); EXPECT_EQ(5, root->GetUnignoredChildAtIndex(1)->id()); EXPECT_EQ(3, root->GetUnignoredChildAtIndex(2)->id()); EXPECT_EQ(0u, root->GetUnignoredChildAtIndex(0)->GetUnignoredIndexInParent()); EXPECT_EQ(1u, root->GetUnignoredChildAtIndex(1)->GetUnignoredIndexInParent()); EXPECT_EQ(2u, root->GetUnignoredChildAtIndex(2)->GetUnignoredIndexInParent()); EXPECT_EQ(1, root->GetUnignoredChildAtIndex(0)->GetUnignoredParent()->id()); // Ensure when a node goes from ignored to unignored, its children have their // unignored_index_in_parent updated. AXTreeUpdate update = initial_state; update.nodes[1].RemoveState(ax::mojom::State::kIgnored); EXPECT_TRUE(tree.Unserialize(update)); root = tree.root(); EXPECT_EQ(2u, root->GetUnignoredChildCount()); EXPECT_EQ(2, root->GetUnignoredChildAtIndex(0)->id()); EXPECT_EQ(2u, tree.GetFromId(2)->GetUnignoredChildCount()); EXPECT_EQ(0u, tree.GetFromId(4)->GetUnignoredIndexInParent()); EXPECT_EQ(1u, tree.GetFromId(5)->GetUnignoredIndexInParent()); // Ensure when a node goes from unignored to unignored, siblings are correctly // updated. AXTreeUpdate update2 = update; update2.nodes[3].AddState(ax::mojom::State::kIgnored); EXPECT_TRUE(tree.Unserialize(update2)); EXPECT_EQ(1u, tree.GetFromId(2)->GetUnignoredChildCount()); EXPECT_EQ(0u, tree.GetFromId(5)->GetUnignoredIndexInParent()); // Ensure siblings of a deleted node are updated. AXTreeUpdate update3 = update2; update3.nodes.resize(1); update3.nodes[0].id = 1; update3.nodes[0].child_ids = {3}; EXPECT_TRUE(tree.Unserialize(update3)); EXPECT_EQ(1u, tree.GetFromId(1)->GetUnignoredChildCount()); EXPECT_EQ(0u, tree.GetFromId(3)->GetUnignoredIndexInParent()); // Ensure new nodes are correctly updated. AXTreeUpdate update4 = update3; update4.nodes.resize(3); update4.nodes[0].id = 1; update4.nodes[0].child_ids = {3, 6}; update4.nodes[1].id = 6; update4.nodes[1].child_ids = {7}; update4.nodes[2].id = 7; EXPECT_TRUE(tree.Unserialize(update4)); EXPECT_EQ(2u, tree.GetFromId(1)->GetUnignoredChildCount()); EXPECT_EQ(0u, tree.GetFromId(3)->GetUnignoredIndexInParent()); EXPECT_EQ(1u, tree.GetFromId(6)->GetUnignoredIndexInParent()); EXPECT_EQ(0u, tree.GetFromId(7)->GetUnignoredIndexInParent()); // Ensure reparented nodes are correctly updated. AXTreeUpdate update5 = update4; update5.nodes.resize(2); update5.node_id_to_clear = 6; update5.nodes[0].id = 1; update5.nodes[0].child_ids = {3, 7}; update5.nodes[1].id = 7; update5.nodes[1].child_ids = {}; EXPECT_TRUE(tree.Unserialize(update5)); EXPECT_EQ(2u, tree.GetFromId(1)->GetUnignoredChildCount()); EXPECT_EQ(0u, tree.GetFromId(3)->GetUnignoredIndexInParent()); EXPECT_EQ(1u, tree.GetFromId(7)->GetUnignoredIndexInParent()); AXTreeUpdate update6; update6.nodes.resize(1); update6.nodes[0].id = 7; update6.nodes[0].AddState(ax::mojom::State::kIgnored); EXPECT_TRUE(tree.Unserialize(update6)); EXPECT_EQ(1u, tree.GetFromId(1)->GetUnignoredChildCount()); EXPECT_EQ(0u, tree.GetFromId(3)->GetUnignoredIndexInParent()); AXTreeUpdate update7 = update6; update7.nodes.resize(2); update7.nodes[0].id = 7; update7.nodes[0].child_ids = {8}; update7.nodes[1].id = 8; EXPECT_TRUE(tree.Unserialize(update7)); EXPECT_EQ(2u, tree.GetFromId(1)->GetUnignoredChildCount()); EXPECT_EQ(0u, tree.GetFromId(3)->GetUnignoredIndexInParent()); } TEST(AXTreeTest, TestRecursionUnignoredChildCount) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(5); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[1].child_ids = {4}; tree_update.nodes[2].id = 3; tree_update.nodes[2].AddState(ax::mojom::State::kIgnored); tree_update.nodes[3].id = 4; tree_update.nodes[3].child_ids = {5}; tree_update.nodes[3].AddState(ax::mojom::State::kIgnored); tree_update.nodes[4].id = 5; AXTree tree(tree_update); AXNode* root = tree.root(); EXPECT_EQ(2u, root->children().size()); EXPECT_EQ(1u, root->GetUnignoredChildCount()); EXPECT_EQ(5, root->GetUnignoredChildAtIndex(0)->id()); AXNode* unignored = tree.GetFromId(5); EXPECT_EQ(0u, unignored->GetUnignoredChildCount()); } TEST(AXTreeTest, NullUnignoredChildren) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(3); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[2].id = 3; tree_update.nodes[2].AddState(ax::mojom::State::kIgnored); AXTree tree(tree_update); AXNode* root = tree.root(); EXPECT_EQ(2u, root->children().size()); EXPECT_EQ(0u, root->GetUnignoredChildCount()); EXPECT_EQ(nullptr, root->GetUnignoredChildAtIndex(0)); EXPECT_EQ(nullptr, root->GetUnignoredChildAtIndex(1)); } TEST(AXTreeTest, UnignoredChildIteratorIncrementDecrementPastEnd) { AXTreeUpdate tree_update; // RootWebArea #1 // ++StaticText "text1" #2 tree_update.root_id = 1; tree_update.nodes.resize(2); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kWebArea; tree_update.nodes[0].child_ids = {2}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kStaticText; tree_update.nodes[1].SetName("text1"); AXTree tree(tree_update); AXNode* root = tree.root(); { { AXNode::UnignoredChildIterator root_unignored_iter = root->UnignoredChildrenBegin(); EXPECT_EQ(2, root_unignored_iter->id()); EXPECT_EQ("text1", root_unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); // Call unignored child iterator on root and increment, we should reach // the end since there is only one iterator element. EXPECT_EQ(root->UnignoredChildrenEnd(), ++root_unignored_iter); // We increment past the end, and we should still stay at the end. EXPECT_EQ(root->UnignoredChildrenEnd(), ++root_unignored_iter); // When we decrement from the end, we should get the last iterator element // "text1". --root_unignored_iter; EXPECT_EQ(2, root_unignored_iter->id()); EXPECT_EQ("text1", root_unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); } { AXNode::UnignoredChildIterator root_unignored_iter = root->UnignoredChildrenBegin(); EXPECT_EQ(2, root_unignored_iter->id()); EXPECT_EQ("text1", root_unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); // Call unignored child iterator on root and decrement from the beginning, // we should stay at the beginning. --root_unignored_iter; EXPECT_EQ(2, root_unignored_iter->id()); EXPECT_EQ("text1", root_unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); // When we decrement past the beginning, we should still stay at the // beginning. --root_unignored_iter; EXPECT_EQ(2, root_unignored_iter->id()); EXPECT_EQ("text1", root_unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); // We increment past the end, and we should still reach the end. EXPECT_EQ(root->UnignoredChildrenEnd(), ++root_unignored_iter); } } } TEST(AXTreeTest, UnignoredChildIteratorIgnoredContainerSiblings) { AXTreeUpdate tree_update; // RootWebArea #1 // ++genericContainer IGNORED #2 // ++++StaticText "text1" #3 // ++genericContainer IGNORED #4 // ++++StaticText "text2" #5 // ++genericContainer IGNORED #6 // ++++StaticText "text3" #7 tree_update.root_id = 1; tree_update.nodes.resize(7); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kWebArea; tree_update.nodes[0].child_ids = {2, 4, 6}; tree_update.nodes[1].id = 2; tree_update.nodes[1].child_ids = {3}; tree_update.nodes[1].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kStaticText; tree_update.nodes[2].SetName("text1"); tree_update.nodes[3].id = 4; tree_update.nodes[3].child_ids = {5}; tree_update.nodes[3].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[3].AddState(ax::mojom::State::kIgnored); tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kStaticText; tree_update.nodes[4].SetName("text2"); tree_update.nodes[5].id = 6; tree_update.nodes[5].child_ids = {7}; tree_update.nodes[5].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[5].AddState(ax::mojom::State::kIgnored); tree_update.nodes[6].id = 7; tree_update.nodes[6].role = ax::mojom::Role::kStaticText; tree_update.nodes[6].SetName("text3"); AXTree tree(tree_update); { // Call unignored child iterator on root and iterate till the end, we should // get "text1", "text2", "text3" respectively because the sibling text nodes // share the same parent (i.e. root) as |unignored_iter|. AXNode* root = tree.root(); AXNode::UnignoredChildIterator root_unignored_iter = root->UnignoredChildrenBegin(); EXPECT_EQ(3, root_unignored_iter->id()); EXPECT_EQ("text1", root_unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); EXPECT_EQ(5, (++root_unignored_iter)->id()); EXPECT_EQ("text2", (*root_unignored_iter) .GetStringAttribute(ax::mojom::StringAttribute::kName)); EXPECT_EQ(7, (++root_unignored_iter)->id()); EXPECT_EQ("text3", root_unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); EXPECT_EQ(root->UnignoredChildrenEnd(), ++root_unignored_iter); } { // Call unignored child iterator on the ignored generic container of "text1" // (id=2), When we iterate to the next of "text1", we should // reach the end because the sibling text node "text2" does not share the // same parent as |unignored_iter| of "text1". AXNode* text1_ignored_container = tree.GetFromId(2); AXNode::UnignoredChildIterator unignored_iter = text1_ignored_container->UnignoredChildrenBegin(); EXPECT_EQ(3, unignored_iter->id()); EXPECT_EQ("text1", unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); // The next child of "text1" should be the end. EXPECT_EQ(text1_ignored_container->UnignoredChildrenEnd(), ++unignored_iter); // Call unignored child iterator on the ignored generic container of "text2" // (id=4), When we iterate to the previous of "text2", we should // reach the end because the sibling text node "text1" does not share the // same parent as |unignored_iter| of "text2". AXNode* text2_ignored_container = tree.GetFromId(4); unignored_iter = text2_ignored_container->UnignoredChildrenBegin(); EXPECT_EQ(5, unignored_iter->id()); EXPECT_EQ("text2", unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); // Decrement the iterator of "text2" should still remain on "text2" since // the beginning of iterator is "text2." --unignored_iter; EXPECT_EQ(5, unignored_iter->id()); EXPECT_EQ("text2", unignored_iter->GetStringAttribute( ax::mojom::StringAttribute::kName)); } } TEST(AXTreeTest, UnignoredChildIterator) { AXTreeUpdate tree_update; // (i) => node is ignored // 1 // |__________ // | | | // 2(i) 3 4 // |_______________________ // | | | | // 5 6 7(i) 8(i) // | | |________ // | | | | // 9 10(i) 11(i) 12 // | |____ // | | | // 13(i) 14 15 tree_update.root_id = 1; tree_update.nodes.resize(15); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].child_ids = {5, 6, 7, 8}; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[2].id = 3; tree_update.nodes[3].id = 4; tree_update.nodes[4].id = 5; tree_update.nodes[4].child_ids = {9}; tree_update.nodes[5].id = 6; tree_update.nodes[5].child_ids = {10}; tree_update.nodes[6].id = 7; tree_update.nodes[6].child_ids = {11, 12}; tree_update.nodes[6].AddState(ax::mojom::State::kIgnored); tree_update.nodes[7].id = 8; tree_update.nodes[7].AddState(ax::mojom::State::kIgnored); tree_update.nodes[8].id = 9; tree_update.nodes[9].id = 10; tree_update.nodes[9].child_ids = {13}; tree_update.nodes[9].AddState(ax::mojom::State::kIgnored); tree_update.nodes[10].id = 11; tree_update.nodes[10].child_ids = {14, 15}; tree_update.nodes[10].AddState(ax::mojom::State::kIgnored); tree_update.nodes[11].id = 12; tree_update.nodes[12].id = 13; tree_update.nodes[12].AddState(ax::mojom::State::kIgnored); tree_update.nodes[13].id = 14; tree_update.nodes[14].id = 15; AXTree tree(tree_update); AXNode* root = tree.root(); // Test traversal // UnignoredChildren(root) = {5, 6, 14, 15, 12, 3, 4} AXNode::UnignoredChildIterator unignored_iterator = root->UnignoredChildrenBegin(); EXPECT_EQ(5, unignored_iterator->id()); EXPECT_EQ(6, (++unignored_iterator)->id()); EXPECT_EQ(14, (++unignored_iterator)->id()); EXPECT_EQ(15, (++unignored_iterator)->id()); EXPECT_EQ(14, (--unignored_iterator)->id()); EXPECT_EQ(6, (--unignored_iterator)->id()); EXPECT_EQ(14, (++unignored_iterator)->id()); EXPECT_EQ(15, (++unignored_iterator)->id()); EXPECT_EQ(12, (++unignored_iterator)->id()); EXPECT_EQ(3, (++unignored_iterator)->id()); EXPECT_EQ(4, (++unignored_iterator)->id()); EXPECT_EQ(root->UnignoredChildrenEnd(), ++unignored_iterator); // test empty list // UnignoredChildren(3) = {} AXNode* node3 = tree.GetFromId(3); unignored_iterator = node3->UnignoredChildrenBegin(); EXPECT_EQ(node3->UnignoredChildrenEnd(), unignored_iterator); // empty list from ignored node with no children // UnignoredChildren(8) = {} AXNode* node8 = tree.GetFromId(8); unignored_iterator = node8->UnignoredChildrenBegin(); EXPECT_EQ(node8->UnignoredChildrenEnd(), unignored_iterator); // empty list from ignored node with unignored children // UnignoredChildren(11) = {} AXNode* node11 = tree.GetFromId(11); unignored_iterator = node11->UnignoredChildrenBegin(); EXPECT_EQ(14, unignored_iterator->id()); // Two UnignoredChildIterators from the same parent at the same position // should be equivalent, even in end position. unignored_iterator = root->UnignoredChildrenBegin(); AXNode::UnignoredChildIterator unignored_iterator2 = root->UnignoredChildrenBegin(); auto end = root->UnignoredChildrenEnd(); while (unignored_iterator != end) { ASSERT_EQ(unignored_iterator, unignored_iterator2); ++unignored_iterator; ++unignored_iterator2; } ASSERT_EQ(unignored_iterator, unignored_iterator2); } TEST(AXTreeTest, UnignoredAccessors) { AXTreeUpdate tree_update; // (i) => node is ignored // 1 // |__________ // | | | // 2(i) 3 4 // |_______________________ // | | | | // 5 6 7(i) 8(i) // | | |________ // | | | | // 9 10(i) 11(i) 12 // | |____ // | | | // 13(i) 14 15 // | | // 16 17(i) tree_update.root_id = 1; tree_update.nodes.resize(17); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].child_ids = {5, 6, 7, 8}; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[2].id = 3; tree_update.nodes[3].id = 4; tree_update.nodes[4].id = 5; tree_update.nodes[4].child_ids = {9}; tree_update.nodes[5].id = 6; tree_update.nodes[5].child_ids = {10}; tree_update.nodes[6].id = 7; tree_update.nodes[6].child_ids = {11, 12}; tree_update.nodes[6].AddState(ax::mojom::State::kIgnored); tree_update.nodes[7].id = 8; tree_update.nodes[7].AddState(ax::mojom::State::kIgnored); tree_update.nodes[8].id = 9; tree_update.nodes[9].id = 10; tree_update.nodes[9].child_ids = {13}; tree_update.nodes[9].AddState(ax::mojom::State::kIgnored); tree_update.nodes[10].id = 11; tree_update.nodes[10].child_ids = {14, 15}; tree_update.nodes[10].AddState(ax::mojom::State::kIgnored); tree_update.nodes[11].id = 12; tree_update.nodes[12].id = 13; tree_update.nodes[12].child_ids = {16}; tree_update.nodes[12].AddState(ax::mojom::State::kIgnored); tree_update.nodes[13].id = 14; tree_update.nodes[13].child_ids = {17}; tree_update.nodes[14].id = 15; tree_update.nodes[15].id = 16; tree_update.nodes[16].id = 17; tree_update.nodes[16].AddState(ax::mojom::State::kIgnored); AXTree tree(tree_update); EXPECT_EQ(4, tree.GetFromId(1)->GetLastUnignoredChild()->id()); EXPECT_EQ(12, tree.GetFromId(2)->GetLastUnignoredChild()->id()); EXPECT_EQ(nullptr, tree.GetFromId(3)->GetLastUnignoredChild()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetLastUnignoredChild()); EXPECT_EQ(9, tree.GetFromId(5)->GetLastUnignoredChild()->id()); EXPECT_EQ(16, tree.GetFromId(6)->GetLastUnignoredChild()->id()); EXPECT_EQ(12, tree.GetFromId(7)->GetLastUnignoredChild()->id()); EXPECT_EQ(nullptr, tree.GetFromId(8)->GetLastUnignoredChild()); EXPECT_EQ(nullptr, tree.GetFromId(9)->GetLastUnignoredChild()); EXPECT_EQ(16, tree.GetFromId(10)->GetLastUnignoredChild()->id()); EXPECT_EQ(15, tree.GetFromId(11)->GetLastUnignoredChild()->id()); EXPECT_EQ(nullptr, tree.GetFromId(12)->GetLastUnignoredChild()); EXPECT_EQ(16, tree.GetFromId(13)->GetLastUnignoredChild()->id()); EXPECT_EQ(nullptr, tree.GetFromId(14)->GetLastUnignoredChild()); EXPECT_EQ(nullptr, tree.GetFromId(15)->GetLastUnignoredChild()); EXPECT_EQ(nullptr, tree.GetFromId(16)->GetLastUnignoredChild()); EXPECT_EQ(nullptr, tree.GetFromId(17)->GetLastUnignoredChild()); } TEST(AXTreeTest, UnignoredNextPreviousChild) { AXTreeUpdate tree_update; // (i) => node is ignored // 1 // |__________ // | | | // 2(i) 3 4 // |_______________________ // | | | | // 5 6 7(i) 8(i) // | | |________ // | | | | // 9 10(i) 11(i) 12 // | |____ // | | | // 13(i) 14 15 // | // 16 tree_update.root_id = 1; tree_update.nodes.resize(16); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].child_ids = {5, 6, 7, 8}; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[2].id = 3; tree_update.nodes[3].id = 4; tree_update.nodes[4].id = 5; tree_update.nodes[4].child_ids = {9}; tree_update.nodes[5].id = 6; tree_update.nodes[5].child_ids = {10}; tree_update.nodes[6].id = 7; tree_update.nodes[6].child_ids = {11, 12}; tree_update.nodes[6].AddState(ax::mojom::State::kIgnored); tree_update.nodes[7].id = 8; tree_update.nodes[7].AddState(ax::mojom::State::kIgnored); tree_update.nodes[8].id = 9; tree_update.nodes[9].id = 10; tree_update.nodes[9].child_ids = {13}; tree_update.nodes[9].AddState(ax::mojom::State::kIgnored); tree_update.nodes[10].id = 11; tree_update.nodes[10].child_ids = {14, 15}; tree_update.nodes[10].AddState(ax::mojom::State::kIgnored); tree_update.nodes[11].id = 12; tree_update.nodes[12].id = 13; tree_update.nodes[12].child_ids = {16}; tree_update.nodes[12].AddState(ax::mojom::State::kIgnored); tree_update.nodes[13].id = 14; tree_update.nodes[14].id = 15; tree_update.nodes[15].id = 16; AXTree tree(tree_update); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(2)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(4), tree.GetFromId(3)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(12), tree.GetFromId(3)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(4)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(6), tree.GetFromId(5)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(5)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(14), tree.GetFromId(6)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(5), tree.GetFromId(6)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(7)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(6), tree.GetFromId(7)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(8)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(12), tree.GetFromId(8)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(9)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(9)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(10)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(10)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(12), tree.GetFromId(11)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(6), tree.GetFromId(11)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(12)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(15), tree.GetFromId(12)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(13)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(13)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(15), tree.GetFromId(14)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(6), tree.GetFromId(14)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(12), tree.GetFromId(15)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(14), tree.GetFromId(15)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(16)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(16)->GetPreviousUnignoredSibling()); } TEST(AXTreeTest, GetSiblingsNoIgnored) { // Since this tree base::contains no ignored nodes, PreviousSibling and // NextSibling are equivalent to their unignored counterparts. // // 1 // ├── 2 // │ └── 4 // └── 3 AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[1].child_ids = {4}; tree_update.nodes[2].id = 3; tree_update.nodes[3].id = 4; AXTree tree(tree_update); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetNextSibling()); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(2)->GetNextSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(2)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(2), tree.GetFromId(3)->GetPreviousSibling()); EXPECT_EQ(tree.GetFromId(2), tree.GetFromId(3)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(3)->GetNextSibling()); EXPECT_EQ(nullptr, tree.GetFromId(3)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetNextSibling()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetNextUnignoredSibling()); } TEST(AXTreeTest, GetUnignoredSiblingsChildrenPromoted) { // An ignored node has its' children considered as though they were promoted // to their parents place. // // (i) => node is ignored. // // 1 // ├── 2(i) // │ ├── 4 // │ └── 5 // └── 3 AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(5); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[1].child_ids = {4, 5}; tree_update.nodes[2].id = 3; tree_update.nodes[3].id = 4; tree_update.nodes[4].id = 5; AXTree tree(tree_update); // Root node has no siblings. EXPECT_EQ(nullptr, tree.GetFromId(1)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousUnignoredSibling()); // Node 2's view of siblings: // literal tree: null <-- [2(i)] --> 3 // unignored tree: null <-- [2(i)] --> 3 EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(2)->GetNextSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(2)->GetNextUnignoredSibling()); // Node 3's view of siblings: // literal tree: 2(i) <-- [3] --> null // unignored tree: 5 <-- [4] --> null EXPECT_EQ(tree.GetFromId(2), tree.GetFromId(3)->GetPreviousSibling()); EXPECT_EQ(tree.GetFromId(5), tree.GetFromId(3)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(3)->GetNextSibling()); EXPECT_EQ(nullptr, tree.GetFromId(3)->GetNextUnignoredSibling()); // Node 4's view of siblings: // literal tree: null <-- [4] --> 5 // unignored tree: null <-- [4] --> 5 EXPECT_EQ(nullptr, tree.GetFromId(4)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(5), tree.GetFromId(4)->GetNextSibling()); EXPECT_EQ(tree.GetFromId(5), tree.GetFromId(4)->GetNextUnignoredSibling()); // Node 5's view of siblings: // literal tree: 4 <-- [5] --> null // unignored tree: 4 <-- [5] --> 3 EXPECT_EQ(tree.GetFromId(4), tree.GetFromId(5)->GetPreviousSibling()); EXPECT_EQ(tree.GetFromId(4), tree.GetFromId(5)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(5)->GetNextSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(5)->GetNextUnignoredSibling()); } TEST(AXTreeTest, GetUnignoredSiblingsIgnoredChildSkipped) { // Ignored children of ignored parents are skipped over. // // (i) => node is ignored. // // 1 // ├── 2(i) // │ ├── 4 // │ └── 5(i) // └── 3 AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(5); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[1].child_ids = {4, 5}; tree_update.nodes[2].id = 3; tree_update.nodes[3].id = 4; tree_update.nodes[4].id = 5; tree_update.nodes[4].AddState(ax::mojom::State::kIgnored); AXTree tree(tree_update); // Root node has no siblings. EXPECT_EQ(nullptr, tree.GetFromId(1)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetNextUnignoredSibling()); // Node 2's view of siblings: // literal tree: null <-- [2(i)] --> 3 // unignored tree: null <-- [2(i)] --> 3 EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(2)->GetNextSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(2)->GetNextUnignoredSibling()); // Node 3's view of siblings: // literal tree: 2(i) <-- [3] --> null // unignored tree: 4 <-- [3] --> null EXPECT_EQ(tree.GetFromId(2), tree.GetFromId(3)->GetPreviousSibling()); EXPECT_EQ(tree.GetFromId(4), tree.GetFromId(3)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(3)->GetNextSibling()); EXPECT_EQ(nullptr, tree.GetFromId(3)->GetNextUnignoredSibling()); // Node 4's view of siblings: // literal tree: null <-- [4] --> 5(i) // unignored tree: null <-- [4] --> 3 EXPECT_EQ(nullptr, tree.GetFromId(4)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetPreviousUnignoredSibling()); EXPECT_EQ(tree.GetFromId(5), tree.GetFromId(4)->GetNextSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(4)->GetNextUnignoredSibling()); // Node 5's view of siblings: // literal tree: 4 <-- [5(i)] --> null // unignored tree: 4 <-- [5(i)] --> 3 EXPECT_EQ(tree.GetFromId(4), tree.GetFromId(5)->GetPreviousSibling()); EXPECT_EQ(tree.GetFromId(4), tree.GetFromId(5)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(5)->GetNextSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(5)->GetNextUnignoredSibling()); } TEST(AXTreeTest, GetUnignoredSiblingIgnoredParentIrrelevant) { // An ignored parent is not relevant unless the search would need to continue // up through it. // // (i) => node is ignored. // // 1(i) // ├── 2 // └── 3 AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(3); tree_update.nodes[0].id = 1; tree_update.nodes[0].AddState(ax::mojom::State::kIgnored); tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[2].id = 3; AXTree tree(tree_update); // Node 2 and 3 are each other's unignored siblings, the parent's ignored // status is not relevant for this search. EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(2)->GetNextUnignoredSibling()); EXPECT_EQ(tree.GetFromId(2), tree.GetFromId(3)->GetPreviousUnignoredSibling()); } TEST(AXTreeTest, GetUnignoredSiblingsAllIgnored) { // Test termination when all nodes, including the root node, are ignored. // // (i) => node is ignored. // // 1(i) // └── 2(i) AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(2); tree_update.nodes[0].id = 1; tree_update.nodes[0].AddState(ax::mojom::State::kIgnored); tree_update.nodes[0].child_ids = {2}; tree_update.nodes[1].id = 2; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); AXTree tree(tree_update); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetNextUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, tree.GetFromId(2)->GetNextUnignoredSibling()); } TEST(AXTreeTest, GetUnignoredSiblingsNestedIgnored) { // Test promotion of children through multiple layers of ignored parents. // (i) => node is ignored. // // 1 // ├── 2 // ├── 3(i) // │ └── 5(i) // │ └── 6 // └── 4 AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(6); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[2].id = 3; tree_update.nodes[2].AddState(ax::mojom::State::kIgnored); tree_update.nodes[2].child_ids = {5}; tree_update.nodes[3].id = 4; tree_update.nodes[4].id = 5; tree_update.nodes[4].AddState(ax::mojom::State::kIgnored); tree_update.nodes[4].child_ids = {6}; tree_update.nodes[5].id = 6; AXTree tree(tree_update); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetPreviousUnignoredSibling()); const AXNode* node2 = tree.GetFromId(2); const AXNode* node3 = tree.GetFromId(3); const AXNode* node4 = tree.GetFromId(4); const AXNode* node5 = tree.GetFromId(5); const AXNode* node6 = tree.GetFromId(6); ASSERT_NE(nullptr, node2); ASSERT_NE(nullptr, node3); ASSERT_NE(nullptr, node4); ASSERT_NE(nullptr, node5); ASSERT_NE(nullptr, node6); // Node 2's view of siblings: // literal tree: null <-- [2] --> 3 // unignored tree: null <-- [2] --> 6 EXPECT_EQ(nullptr, node2->GetPreviousSibling()); EXPECT_EQ(nullptr, node2->GetPreviousUnignoredSibling()); EXPECT_EQ(node3, node2->GetNextSibling()); EXPECT_EQ(node6, node2->GetNextUnignoredSibling()); // Node 3's view of siblings: // literal tree: 2 <-- [3(i)] --> 4 // unignored tree: 2 <-- [3(i)] --> 4 EXPECT_EQ(node2, node3->GetPreviousSibling()); EXPECT_EQ(node2, node3->GetPreviousUnignoredSibling()); EXPECT_EQ(node4, node3->GetNextSibling()); EXPECT_EQ(node4, node3->GetNextUnignoredSibling()); // Node 4's view of siblings: // literal tree: 3 <-- [4] --> null // unignored tree: 6 <-- [4] --> null EXPECT_EQ(node3, node4->GetPreviousSibling()); EXPECT_EQ(node6, node4->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, node4->GetNextSibling()); EXPECT_EQ(nullptr, node4->GetNextUnignoredSibling()); // Node 5's view of siblings: // literal tree: null <-- [5(i)] --> null // unignored tree: 2 <-- [5(i)] --> 4 EXPECT_EQ(nullptr, node5->GetPreviousSibling()); EXPECT_EQ(node2, node5->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, node5->GetNextSibling()); EXPECT_EQ(node4, node5->GetNextUnignoredSibling()); // Node 6's view of siblings: // literal tree: null <-- [6] --> null // unignored tree: 2 <-- [6] --> 4 EXPECT_EQ(nullptr, node6->GetPreviousSibling()); EXPECT_EQ(node2, node6->GetPreviousUnignoredSibling()); EXPECT_EQ(nullptr, node6->GetNextSibling()); EXPECT_EQ(node4, node6->GetNextUnignoredSibling()); } TEST(AXTreeTest, UnignoredSelection) { AXTreeUpdate tree_update; // (i) => node is ignored // 1 // |__________ // | | | // 2(i) 3 4 // |_______________________ // | | | | // 5 6 7(i) 8(i) // | | |________ // | | | | // 9 10(i) 11(i) 12 // | |____ // | | | // 13(i) 14 15 // | // 16 // Unignored Tree (conceptual) // 1 // |______________________ // | | | | | | | // 5 6 14 15 12 3 4 // | | // 9 16 tree_update.has_tree_data = true; tree_update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); tree_update.root_id = 1; tree_update.nodes.resize(16); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].child_ids = {5, 6, 7, 8}; tree_update.nodes[1].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[1].AddState(ax::mojom::State::kIgnored); tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kStaticText; tree_update.nodes[2].SetName("text"); tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kStaticText; tree_update.nodes[3].SetName("text"); tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[4].child_ids = {9}; tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[5].child_ids = {10}; tree_update.nodes[6].id = 7; tree_update.nodes[6].child_ids = {11, 12}; tree_update.nodes[6].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[6].AddState(ax::mojom::State::kIgnored); tree_update.nodes[7].id = 8; tree_update.nodes[7].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[7].AddState(ax::mojom::State::kIgnored); tree_update.nodes[8].id = 9; tree_update.nodes[8].role = ax::mojom::Role::kStaticText; tree_update.nodes[8].SetName("text"); tree_update.nodes[9].id = 10; tree_update.nodes[9].child_ids = {13}; tree_update.nodes[9].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[9].AddState(ax::mojom::State::kIgnored); tree_update.nodes[10].id = 11; tree_update.nodes[10].child_ids = {14, 15}; tree_update.nodes[10].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[10].AddState(ax::mojom::State::kIgnored); tree_update.nodes[11].id = 12; tree_update.nodes[11].role = ax::mojom::Role::kStaticText; tree_update.nodes[11].SetName("text"); tree_update.nodes[12].id = 13; tree_update.nodes[12].child_ids = {16}; tree_update.nodes[12].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[12].AddState(ax::mojom::State::kIgnored); tree_update.nodes[13].id = 14; tree_update.nodes[13].role = ax::mojom::Role::kStaticText; tree_update.nodes[13].SetName("text"); tree_update.nodes[14].id = 15; tree_update.nodes[14].role = ax::mojom::Role::kStaticText; tree_update.nodes[14].SetName("text"); tree_update.nodes[15].id = 16; tree_update.nodes[15].role = ax::mojom::Role::kStaticText; tree_update.nodes[15].SetName("text"); TestAXTreeManager test_ax_tree_manager(std::make_unique<AXTree>(tree_update)); AXTree::Selection unignored_selection = test_ax_tree_manager.GetTree()->GetUnignoredSelection(); EXPECT_EQ(AXNode::kInvalidAXID, unignored_selection.anchor_object_id); EXPECT_EQ(-1, unignored_selection.anchor_offset); EXPECT_EQ(AXNode::kInvalidAXID, unignored_selection.focus_object_id); EXPECT_EQ(-1, unignored_selection.focus_offset); struct SelectionData { int32_t anchor_id; int32_t anchor_offset; int32_t focus_id; int32_t focus_offset; }; SelectionData input = {1, 0, 1, 0}; SelectionData expected = {9, 0, 9, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {1, 0, 2, 2}; expected = {9, 0, 14, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {2, 1, 5, 0}; expected = {16, 0, 5, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {5, 0, 9, 0}; expected = {5, 0, 9, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {9, 0, 6, 0}; expected = {9, 0, 16, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {6, 0, 10, 0}; expected = {16, 0, 16, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {10, 0, 13, 0}; expected = {16, 0, 16, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {13, 0, 16, 0}; expected = {16, 0, 16, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {16, 0, 7, 0}; expected = {16, 0, 14, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {7, 0, 11, 0}; expected = {14, 0, 14, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {11, 1, 14, 2}; expected = {15, 0, 14, 2}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {14, 2, 15, 3}; expected = {14, 2, 15, 3}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {15, 0, 12, 0}; expected = {15, 0, 12, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {12, 0, 8, 0}; expected = {12, 0, 3, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {8, 0, 3, 0}; expected = {12, 4, 3, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {3, 0, 4, 0}; expected = {3, 0, 4, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); input = {4, 0, 4, 0}; expected = {4, 0, 4, 0}; TEST_SELECTION(tree_update, test_ax_tree_manager.GetTree(), input, expected); } TEST(AXTreeTest, GetChildrenOrSiblings) { // 1 // ├── 2 // │ └── 5 // ├── 3 // └── 4 AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(5); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].child_ids = {5}; tree_update.nodes[2].id = 3; tree_update.nodes[3].id = 4; tree_update.nodes[4].id = 5; AXTree tree(tree_update); EXPECT_EQ(tree.GetFromId(2), tree.GetFromId(1)->GetFirstChild()); EXPECT_EQ(tree.GetFromId(5), tree.GetFromId(2)->GetFirstChild()); EXPECT_EQ(nullptr, tree.GetFromId(3)->GetFirstChild()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetFirstChild()); EXPECT_EQ(nullptr, tree.GetFromId(5)->GetFirstChild()); EXPECT_EQ(tree.GetFromId(4), tree.GetFromId(1)->GetLastChild()); EXPECT_EQ(tree.GetFromId(5), tree.GetFromId(2)->GetLastChild()); EXPECT_EQ(nullptr, tree.GetFromId(3)->GetLastChild()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetLastChild()); EXPECT_EQ(nullptr, tree.GetFromId(5)->GetLastChild()); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(2)->GetPreviousSibling()); EXPECT_EQ(tree.GetFromId(2), tree.GetFromId(3)->GetPreviousSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(4)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(5)->GetPreviousSibling()); EXPECT_EQ(nullptr, tree.GetFromId(1)->GetNextSibling()); EXPECT_EQ(tree.GetFromId(3), tree.GetFromId(2)->GetNextSibling()); EXPECT_EQ(tree.GetFromId(4), tree.GetFromId(3)->GetNextSibling()); EXPECT_EQ(nullptr, tree.GetFromId(4)->GetNextSibling()); EXPECT_EQ(nullptr, tree.GetFromId(5)->GetNextSibling()); } // Tests GetPosInSet and GetSetSize return the assigned int attribute values. TEST(AXTreeTest, SetSizePosInSetAssigned) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; tree_update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 2); tree_update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 12); tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; tree_update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 5); tree_update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 12); tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListItem; tree_update.nodes[3].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 9); tree_update.nodes[3].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 12); AXTree tree(tree_update); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(2, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(12, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(5, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(12, item2->GetSetSize()); AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(9, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(12, item3->GetSetSize()); } // Tests that PosInSet and SetSize can be calculated if not assigned. TEST(AXTreeTest, SetSizePosInSetUnassigned) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListItem; AXTree tree(tree_update); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item2->GetSetSize()); AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(3, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item3->GetSetSize()); } // Tests PosInSet can be calculated if unassigned, and SetSize can be // assigned on the outerlying ordered set. TEST(AXTreeTest, SetSizeAssignedOnContainer) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 7); tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListItem; AXTree tree(tree_update); // Items should inherit SetSize from ordered set if not specified. AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(7, item1->GetSetSize()); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(7, item2->GetSetSize()); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(7, item3->GetSetSize()); EXPECT_OPTIONAL_EQ(3, item3->GetPosInSet()); } // Tests GetPosInSet and GetSetSize on a list containing various roles. // Roles for items and associated ordered set should match up. TEST(AXTreeTest, SetSizePosInSetDiverseList) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(6); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kMenu; tree_update.nodes[0].child_ids = {2, 3, 4, 5, 6}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kMenuItem; // 1 of 4 tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kMenuItemCheckBox; // 2 of 4 tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kMenuItemRadio; // 3 of 4 tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kMenuItem; // 4 of 4 tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kTab; // 0 of 0 AXTree tree(tree_update); // kMenu is allowed to contain: kMenuItem, kMenuItemCheckbox, // and kMenuItemRadio. For PosInSet and SetSize purposes, these items // are treated as the same role. AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, item1->GetSetSize()); AXNode* checkbox = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, checkbox->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, checkbox->GetSetSize()); AXNode* radio = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(3, radio->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, radio->GetSetSize()); AXNode* item3 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(4, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, item3->GetSetSize()); AXNode* tab = tree.GetFromId(6); EXPECT_FALSE(tab->GetPosInSet()); EXPECT_FALSE(tab->GetSetSize()); } // Tests GetPosInSet and GetSetSize on a nested list. TEST(AXTreeTest, SetSizePosInSetNestedList) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(7); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 4, 7}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kList; tree_update.nodes[3].child_ids = {5, 6}; tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kListItem; tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kListItem; tree_update.nodes[6].id = 7; tree_update.nodes[6].role = ax::mojom::Role::kListItem; AXTree tree(tree_update); AXNode* outer_item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, outer_item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, outer_item1->GetSetSize()); AXNode* outer_item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, outer_item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, outer_item2->GetSetSize()); AXNode* inner_item1 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(1, inner_item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, inner_item1->GetSetSize()); AXNode* inner_item2 = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(2, inner_item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, inner_item2->GetSetSize()); AXNode* outer_item3 = tree.GetFromId(7); EXPECT_OPTIONAL_EQ(3, outer_item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, outer_item3->GetSetSize()); } // Tests PosInSet can be calculated if one item specifies PosInSet, but // other assignments are missing. TEST(AXTreeTest, PosInSetMissing) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 20); tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; tree_update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 13); tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListItem; AXTree tree(tree_update); // Item1 should have pos of 12, since item2 is assigned a pos of 13. AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(20, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(13, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(20, item2->GetSetSize()); // Item2 should have pos of 14, since item2 is assigned a pos of 13. AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(14, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(20, item3->GetSetSize()); } // A more difficult test that involves missing PosInSet and SetSize values. TEST(AXTreeTest, SetSizePosInSetMissingDifficult) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(6); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 4, 5, 6}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; // 1 of 11 tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; tree_update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 5); // 5 of 11 tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListItem; // 6 of 11 tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kListItem; tree_update.nodes[4].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 10); // 10 of 11 tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kListItem; // 11 of 11 AXTree tree(tree_update); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(11, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(5, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(11, item2->GetSetSize()); AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(6, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(11, item3->GetSetSize()); AXNode* item4 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(10, item4->GetPosInSet()); EXPECT_OPTIONAL_EQ(11, item4->GetSetSize()); AXNode* item5 = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(11, item5->GetPosInSet()); EXPECT_OPTIONAL_EQ(11, item5->GetSetSize()); } // Tests that code overwrites decreasing SetSize assignments to largest of // assigned values. TEST(AXTreeTest, SetSizeDecreasing) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; // 1 of 5 tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; // 2 of 5 tree_update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 5); tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListItem; // 3 of 5 tree_update.nodes[3].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 4); AXTree tree(tree_update); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(5, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(5, item2->GetSetSize()); AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(3, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(5, item3->GetSetSize()); } // Tests that code overwrites decreasing PosInSet values. TEST(AXTreeTest, PosInSetDecreasing) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; // 1 of 8 tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; // 7 of 8 tree_update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 7); tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListItem; // 8 of 8 tree_update.nodes[3].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 3); AXTree tree(tree_update); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(8, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(7, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(8, item2->GetSetSize()); AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(8, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(8, item3->GetSetSize()); } // Tests that code overwrites duplicate PosInSet values. Note this case is // tricky; an update to the second element causes an update to the third // element. TEST(AXTreeTest, PosInSetDuplicates) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; // 6 of 8 tree_update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 6); tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; // 7 of 8 tree_update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 6); tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListItem; // 8 of 8 tree_update.nodes[3].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 7); AXTree tree(tree_update); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(6, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(8, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(7, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(8, item2->GetSetSize()); AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(8, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(8, item3->GetSetSize()); } // Tests GetPosInSet and GetSetSize when some list items are nested in a generic // container. TEST(AXTreeTest, SetSizePosInSetNestedContainer) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(7); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3, 7}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; // 1 of 4 tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[2].child_ids = {4, 5}; tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListItem; // 2 of 4 tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kIgnored; tree_update.nodes[4].child_ids = {6}; tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kListItem; // 3 of 4 tree_update.nodes[6].id = 7; tree_update.nodes[6].role = ax::mojom::Role::kListItem; // 4 of 4 AXTree tree(tree_update); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, item1->GetSetSize()); AXNode* g_container = tree.GetFromId(3); EXPECT_FALSE(g_container->GetPosInSet()); EXPECT_FALSE(g_container->GetSetSize()); AXNode* item2 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, item2->GetSetSize()); AXNode* ignored = tree.GetFromId(5); EXPECT_FALSE(ignored->GetPosInSet()); EXPECT_FALSE(ignored->GetSetSize()); AXNode* item3 = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(3, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, item3->GetSetSize()); AXNode* item4 = tree.GetFromId(7); EXPECT_OPTIONAL_EQ(4, item4->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, item4->GetSetSize()); } // Tests GetSetSize and GetPosInSet are correct, even when list items change. // Tests that previously calculated values are not used after tree is updated. TEST(AXTreeTest, SetSizePosInSetDeleteItem) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(4); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kList; initial_state.nodes[0].child_ids = {2, 3, 4}; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kListItem; // 1 of 3 initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kListItem; // 2 of 3 initial_state.nodes[3].id = 4; initial_state.nodes[3].role = ax::mojom::Role::kListItem; // 3 of 3 AXTree tree(initial_state); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item2->GetSetSize()); AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(3, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item3->GetSetSize()); // TreeUpdates only need to describe what changed in tree. AXTreeUpdate update = initial_state; update.nodes.resize(1); update.nodes[0].child_ids = {2, 4}; // Delete item 2 of 3 from list. ASSERT_TRUE(tree.Unserialize(update)); AXNode* new_item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, new_item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, new_item1->GetSetSize()); AXNode* new_item2 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(2, new_item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, new_item2->GetSetSize()); } // Tests GetSetSize and GetPosInSet are correct, even when list items change. // This test adds an item to the front of a list, which invalidates previously // calculated PosInSet and SetSize values. Tests that old values are not // used after tree is updated. TEST(AXTreeTest, SetSizePosInSetAddItem) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(4); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kList; initial_state.nodes[0].child_ids = {2, 3, 4}; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kListItem; // 1 of 3 initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kListItem; // 2 of 3 initial_state.nodes[3].id = 4; initial_state.nodes[3].role = ax::mojom::Role::kListItem; // 3 of 3 AXTree tree(initial_state); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item2->GetSetSize()); AXNode* item3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(3, item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item3->GetSetSize()); // Insert an item at the beginning of the list. AXTreeUpdate update = initial_state; update.nodes.resize(2); update.nodes[0].id = 1; update.nodes[0].child_ids = {5, 2, 3, 4}; update.nodes[1].id = 5; update.nodes[1].role = ax::mojom::Role::kListItem; ASSERT_TRUE(tree.Unserialize(update)); AXNode* new_item1 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(1, new_item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, new_item1->GetSetSize()); AXNode* new_item2 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(2, new_item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, new_item2->GetSetSize()); AXNode* new_item3 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(3, new_item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, new_item3->GetSetSize()); AXNode* new_item4 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(4, new_item4->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, new_item4->GetSetSize()); } // Tests that the outerlying ordered set reports a SetSize. Ordered sets // should not report a PosInSet value other than 0, since they are not // considered to be items within a set (even when nested). TEST(AXTreeTest, OrderedSetReportsSetSize) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(12); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; // SetSize = 3 tree_update.nodes[0].child_ids = {2, 3, 4, 7, 8, 9, 12}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; // 1 of 3 tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; // 2 of 3 tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kList; // SetSize = 2 tree_update.nodes[3].child_ids = {5, 6}; tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kListItem; // 1 of 2 tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kListItem; // 2 of 2 tree_update.nodes[6].id = 7; tree_update.nodes[6].role = ax::mojom::Role::kListItem; // 3 of 3 tree_update.nodes[7].id = 8; tree_update.nodes[7].role = ax::mojom::Role::kList; // SetSize = 0 tree_update.nodes[8].id = 9; tree_update.nodes[8].role = ax::mojom::Role::kList; // SetSize = 1 because only 1 // item whose role matches tree_update.nodes[8].child_ids = {10, 11}; tree_update.nodes[9].id = 10; tree_update.nodes[9].role = ax::mojom::Role::kArticle; tree_update.nodes[10].id = 11; tree_update.nodes[10].role = ax::mojom::Role::kListItem; tree_update.nodes[11].id = 12; tree_update.nodes[11].role = ax::mojom::Role::kList; tree_update.nodes[11].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 5); AXTree tree(tree_update); AXNode* outer_list = tree.GetFromId(1); EXPECT_FALSE(outer_list->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, outer_list->GetSetSize()); AXNode* outer_list_item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, outer_list_item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, outer_list_item1->GetSetSize()); AXNode* outer_list_item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, outer_list_item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, outer_list_item2->GetSetSize()); AXNode* outer_list_item3 = tree.GetFromId(7); EXPECT_OPTIONAL_EQ(3, outer_list_item3->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, outer_list_item3->GetSetSize()); AXNode* inner_list1 = tree.GetFromId(4); EXPECT_FALSE(inner_list1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, inner_list1->GetSetSize()); AXNode* inner_list1_item1 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(1, inner_list1_item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, inner_list1_item1->GetSetSize()); AXNode* inner_list1_item2 = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(2, inner_list1_item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, inner_list1_item2->GetSetSize()); AXNode* inner_list2 = tree.GetFromId(8); // Empty list EXPECT_FALSE(inner_list2->GetPosInSet()); EXPECT_OPTIONAL_EQ(0, inner_list2->GetSetSize()); AXNode* inner_list3 = tree.GetFromId(9); EXPECT_FALSE(inner_list3->GetPosInSet()); // Only 1 item whose role matches. EXPECT_OPTIONAL_EQ(1, inner_list3->GetSetSize()); AXNode* inner_list3_article1 = tree.GetFromId(10); EXPECT_FALSE(inner_list3_article1->GetPosInSet()); EXPECT_FALSE(inner_list3_article1->GetSetSize()); AXNode* inner_list3_item1 = tree.GetFromId(11); EXPECT_OPTIONAL_EQ(1, inner_list3_item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(1, inner_list3_item1->GetSetSize()); AXNode* inner_list4 = tree.GetFromId(12); EXPECT_FALSE(inner_list4->GetPosInSet()); // Even though list is empty, kSetSize attribute was set, so it takes // precedence EXPECT_OPTIONAL_EQ(5, inner_list4->GetSetSize()); } // Tests GetPosInSet and GetSetSize code on invalid input. TEST(AXTreeTest, SetSizePosInSetInvalid) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(3); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kListItem; // 0 of 0 tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; tree_update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 4); // 0 of 0 tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; AXTree tree(tree_update); AXNode* item1 = tree.GetFromId(1); EXPECT_FALSE(item1->GetPosInSet()); EXPECT_FALSE(item1->GetSetSize()); AXNode* item2 = tree.GetFromId(2); EXPECT_FALSE(item2->GetPosInSet()); EXPECT_FALSE(item2->GetSetSize()); AXNode* item3 = tree.GetFromId(3); EXPECT_FALSE(item3->GetPosInSet()); EXPECT_FALSE(item3->GetSetSize()); } // Tests GetPosInSet and GetSetSize code on kRadioButtons. Radio buttons // behave differently than other item-like elements; most notably, they do not // need to be contained within an ordered set to report a PosInSet or SetSize. TEST(AXTreeTest, SetSizePosInSetRadioButtons) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(13); tree_update.nodes[0].id = 1; tree_update.nodes[0].child_ids = {2, 3, 4, 10, 13}; // This test passes because the root node is a kRadioGroup. tree_update.nodes[0].role = ax::mojom::Role::kRadioGroup; // Setsize = 5; // Radio buttons are not required to be contained within an ordered set. tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kRadioButton; // 1 of 5 tree_update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName, "sports"); tree_update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 1); tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kRadioButton; // 2 of 5 tree_update.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName, "books"); tree_update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 2); tree_update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 5); // Radio group with nested generic container. tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kRadioGroup; // setsize = 4 tree_update.nodes[3].child_ids = {5, 6, 7}; tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kRadioButton; tree_update.nodes[4].AddStringAttribute(ax::mojom::StringAttribute::kName, "recipes"); // 1 of 4 tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kRadioButton; tree_update.nodes[5].AddStringAttribute(ax::mojom::StringAttribute::kName, "recipes"); // 2 of 4 tree_update.nodes[6].id = 7; tree_update.nodes[6].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[6].child_ids = {8, 9}; tree_update.nodes[7].id = 8; tree_update.nodes[7].role = ax::mojom::Role::kRadioButton; tree_update.nodes[7].AddStringAttribute(ax::mojom::StringAttribute::kName, "recipes"); // 3 of 4 tree_update.nodes[8].id = 9; tree_update.nodes[8].role = ax::mojom::Role::kRadioButton; tree_update.nodes[8].AddStringAttribute(ax::mojom::StringAttribute::kName, "recipes"); // 4 of 4 // Radio buttons are allowed to be contained within forms. tree_update.nodes[9].id = 10; tree_update.nodes[9].role = ax::mojom::Role::kForm; tree_update.nodes[9].child_ids = {11, 12}; tree_update.nodes[10].id = 11; tree_update.nodes[10].role = ax::mojom::Role::kRadioButton; tree_update.nodes[10].AddStringAttribute(ax::mojom::StringAttribute::kName, "cities"); // 1 of 2 tree_update.nodes[11].id = 12; tree_update.nodes[11].role = ax::mojom::Role::kRadioButton; tree_update.nodes[11].AddStringAttribute(ax::mojom::StringAttribute::kName, "cities"); // 2 of 2 tree_update.nodes[12].id = 13; tree_update.nodes[12].role = ax::mojom::Role::kRadioButton; // 4 of 5 tree_update.nodes[12].AddStringAttribute(ax::mojom::StringAttribute::kName, "sports"); tree_update.nodes[12].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 4); AXTree tree(tree_update); AXNode* sports_button1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, sports_button1->GetPosInSet()); EXPECT_OPTIONAL_EQ(5, sports_button1->GetSetSize()); AXNode* books_button = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, books_button->GetPosInSet()); EXPECT_OPTIONAL_EQ(5, books_button->GetSetSize()); AXNode* radiogroup1 = tree.GetFromId(4); EXPECT_FALSE(radiogroup1->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, radiogroup1->GetSetSize()); AXNode* recipes_button1 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(1, recipes_button1->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, recipes_button1->GetSetSize()); AXNode* recipes_button2 = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(2, recipes_button2->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, recipes_button2->GetSetSize()); AXNode* generic_container = tree.GetFromId(7); EXPECT_FALSE(generic_container->GetPosInSet()); EXPECT_FALSE(generic_container->GetSetSize()); AXNode* recipes_button3 = tree.GetFromId(8); EXPECT_OPTIONAL_EQ(3, recipes_button3->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, recipes_button3->GetSetSize()); AXNode* recipes_button4 = tree.GetFromId(9); EXPECT_OPTIONAL_EQ(4, recipes_button4->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, recipes_button4->GetSetSize()); // Elements with role kForm shouldn't report posinset or setsize AXNode* form = tree.GetFromId(10); EXPECT_FALSE(form->GetPosInSet()); EXPECT_FALSE(form->GetSetSize()); AXNode* cities_button1 = tree.GetFromId(11); EXPECT_OPTIONAL_EQ(1, cities_button1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, cities_button1->GetSetSize()); AXNode* cities_button2 = tree.GetFromId(12); EXPECT_OPTIONAL_EQ(2, cities_button2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, cities_button2->GetSetSize()); AXNode* sports_button2 = tree.GetFromId(13); EXPECT_OPTIONAL_EQ(4, sports_button2->GetPosInSet()); EXPECT_OPTIONAL_EQ(5, sports_button2->GetSetSize()); } // Tests GetPosInSet and GetSetSize on a list that includes radio buttons. // Note that radio buttons do not contribute to the SetSize of the outerlying // list. TEST(AXTreeTest, SetSizePosInSetRadioButtonsInList) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(6); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; // SetSize = 2, since only base::contains 2 // ListItems tree_update.nodes[0].child_ids = {2, 3, 4, 5, 6}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kRadioButton; // 1 of 3 tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListItem; // 1 of 2 tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kRadioButton; // 2 of 3 tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kListItem; // 2 of 2 tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kRadioButton; // 3 of 3 AXTree tree(tree_update); AXNode* list = tree.GetFromId(1); EXPECT_FALSE(list->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, list->GetSetSize()); AXNode* radiobutton1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, radiobutton1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, radiobutton1->GetSetSize()); AXNode* item1 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item1->GetSetSize()); AXNode* radiobutton2 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(2, radiobutton2->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, radiobutton2->GetSetSize()); AXNode* item2 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item2->GetSetSize()); AXNode* radiobutton3 = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(3, radiobutton3->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, radiobutton3->GetSetSize()); // Ensure that the setsize of list was not modified after calling GetPosInSet // and GetSetSize on kRadioButtons. EXPECT_FALSE(list->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, list->GetSetSize()); } // Tests GetPosInSet and GetSetSize on a flat tree representation. According // to the tree representation, the three elements are siblings. However, // due to the presence of the kHierarchicalLevel attribute, they all belong // to different sets. TEST(AXTreeTest, SetSizePosInSetFlatTree) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(4); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kTree; tree_update.nodes[0].child_ids = {2, 3, 4}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kTreeItem; // 1 of 1 tree_update.nodes[1].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 1); tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kTreeItem; // 1 of 1 tree_update.nodes[2].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 2); tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kTreeItem; // 1 of 1 tree_update.nodes[3].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 3); AXTree tree(tree_update); AXNode* item1_level1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1_level1->GetPosInSet()); EXPECT_OPTIONAL_EQ(1, item1_level1->GetSetSize()); AXNode* item1_level2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(1, item1_level2->GetPosInSet()); EXPECT_OPTIONAL_EQ(1, item1_level2->GetSetSize()); AXNode* item1_level3 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(1, item1_level3->GetPosInSet()); EXPECT_OPTIONAL_EQ(1, item1_level3->GetSetSize()); } // Tests GetPosInSet and GetSetSize on a flat tree representation, where only // the level is specified. TEST(AXTreeTest, SetSizePosInSetFlatTreeLevelsOnly) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(9); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kTree; tree_update.nodes[0].child_ids = {2, 3, 4, 5, 6, 7, 8, 9}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kTreeItem; // 1 of 3 tree_update.nodes[1].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 1); tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kTreeItem; // 1 of 2 tree_update.nodes[2].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 2); tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kTreeItem; // 2 of 2 tree_update.nodes[3].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 2); tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kTreeItem; // 2 of 3 tree_update.nodes[4].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 1); tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kTreeItem; // 1 of 3 tree_update.nodes[5].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 2); tree_update.nodes[6].id = 7; tree_update.nodes[6].role = ax::mojom::Role::kTreeItem; // 2 of 3 tree_update.nodes[6].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 2); tree_update.nodes[7].id = 8; tree_update.nodes[7].role = ax::mojom::Role::kTreeItem; // 3 of 3 tree_update.nodes[7].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 2); tree_update.nodes[8].id = 9; tree_update.nodes[8].role = ax::mojom::Role::kTreeItem; // 3 of 3 tree_update.nodes[8].AddIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel, 1); AXTree tree(tree_update); // The order in which we query the nodes should not matter. AXNode* item3_level1 = tree.GetFromId(9); EXPECT_OPTIONAL_EQ(3, item3_level1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item3_level1->GetSetSize()); AXNode* item3_level2a = tree.GetFromId(8); EXPECT_OPTIONAL_EQ(3, item3_level2a->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item3_level2a->GetSetSize()); AXNode* item2_level2a = tree.GetFromId(7); EXPECT_OPTIONAL_EQ(2, item2_level2a->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item2_level2a->GetSetSize()); AXNode* item1_level2a = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(1, item1_level2a->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item1_level2a->GetSetSize()); AXNode* item2_level1 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(2, item2_level1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item2_level1->GetSetSize()); AXNode* item2_level2 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(2, item2_level2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item2_level2->GetSetSize()); AXNode* item1_level2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(1, item1_level2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item1_level2->GetSetSize()); AXNode* item1_level1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1_level1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item1_level1->GetSetSize()); AXNode* ordered_set = tree.GetFromId(1); EXPECT_OPTIONAL_EQ(3, ordered_set->GetSetSize()); } // Tests that GetPosInSet and GetSetSize work while a tree is being // unserialized. TEST(AXTreeTest, SetSizePosInSetSubtreeDeleted) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kTree; initial_state.nodes[0].child_ids = {2, 3}; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kTreeItem; initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kTreeItem; AXTree tree(initial_state); AXNode* tree_node = tree.GetFromId(1); AXNode* item = tree.GetFromId(3); // This should work normally. EXPECT_OPTIONAL_EQ(2, item->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item->GetSetSize()); // Remove item from tree. AXTreeUpdate tree_update = initial_state; tree_update.nodes.resize(1); tree_update.nodes[0].child_ids = {2}; ASSERT_TRUE(tree.Unserialize(tree_update)); // These values are lazily created, so to test that they fail when // called in the middle of a tree update, fake the update state. tree.SetTreeUpdateInProgressState(true); ASSERT_FALSE(tree_node->GetPosInSet()); ASSERT_FALSE(tree_node->GetSetSize()); // Then reset the state to make sure we have the expected values // after |Unserialize|. tree.SetTreeUpdateInProgressState(false); ASSERT_FALSE(tree_node->GetPosInSet()); EXPECT_OPTIONAL_EQ(1, tree_node->GetSetSize()); } // Tests that GetPosInSet and GetSetSize work when there are ignored nodes. TEST(AXTreeTest, SetSizePosInSetIgnoredItem) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kTree; initial_state.nodes[0].child_ids = {2, 3}; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kTreeItem; initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kTreeItem; AXTree tree(initial_state); AXNode* tree_node = tree.GetFromId(1); AXNode* item1 = tree.GetFromId(2); AXNode* item2 = tree.GetFromId(3); // This should work normally. ASSERT_FALSE(tree_node->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, tree_node->GetSetSize()); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item1->GetSetSize()); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item2->GetSetSize()); // Remove item from tree. AXTreeUpdate tree_update; tree_update.nodes.resize(1); tree_update.nodes[0] = initial_state.nodes[1]; tree_update.nodes[0].AddState(ax::mojom::State::kIgnored); ASSERT_TRUE(tree.Unserialize(tree_update)); ASSERT_FALSE(tree_node->GetPosInSet()); EXPECT_OPTIONAL_EQ(1, tree_node->GetSetSize()); // Ignored nodes are not part of ordered sets. EXPECT_FALSE(item1->GetPosInSet()); EXPECT_FALSE(item1->GetSetSize()); EXPECT_OPTIONAL_EQ(1, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(1, item2->GetSetSize()); } // Tests that kPopUpButtons are assigned the SetSize of the wrapped // kMenuListPopup, if one is present. TEST(AXTreeTest, SetSizePosInSetPopUpButton) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(6); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids = {2, 3}; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kPopUpButton; initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kPopUpButton; initial_state.nodes[2].child_ids = {4}; initial_state.nodes[3].id = 4; initial_state.nodes[3].role = ax::mojom::Role::kMenuListPopup; initial_state.nodes[3].child_ids = {5, 6}; initial_state.nodes[4].id = 5; initial_state.nodes[4].role = ax::mojom::Role::kMenuListOption; initial_state.nodes[5].id = 6; initial_state.nodes[5].role = ax::mojom::Role::kMenuListOption; AXTree tree(initial_state); // The first popupbutton should have SetSize of 0. AXNode* popup_button_1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(0, popup_button_1->GetSetSize()); // The second popupbutton should have SetSize of 2, since the menulistpopup // that it wraps has a SetSize of 2. AXNode* popup_button_2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, popup_button_2->GetSetSize()); } // Tests that PosInSet and SetSize are still correctly calculated when there // are nodes with role of kUnknown layered between items and ordered set. TEST(AXTreeTest, SetSizePosInSetUnkown) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(5); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids = {2}; initial_state.nodes[0].role = ax::mojom::Role::kMenu; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kUnknown; initial_state.nodes[1].child_ids = {3}; initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kUnknown; initial_state.nodes[2].child_ids = {4, 5}; initial_state.nodes[3].id = 4; initial_state.nodes[3].role = ax::mojom::Role::kMenuItem; initial_state.nodes[4].id = 5; initial_state.nodes[4].role = ax::mojom::Role::kMenuItem; AXTree tree(initial_state); AXNode* menu = tree.GetFromId(1); EXPECT_OPTIONAL_EQ(2, menu->GetSetSize()); AXNode* item1 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item2->GetSetSize()); } TEST(AXTreeTest, SetSizePosInSetMenuItemValidChildOfMenuListPopup) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids = {2, 3}; initial_state.nodes[0].role = ax::mojom::Role::kMenuListPopup; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kMenuItem; initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kMenuListOption; AXTree tree(initial_state); AXNode* menu = tree.GetFromId(1); EXPECT_OPTIONAL_EQ(2, menu->GetSetSize()); AXNode* item1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item1->GetSetSize()); AXNode* item2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, item2->GetSetSize()); } TEST(AXTreeTest, SetSizePostInSetListBoxOptionWithGroup) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(7); initial_state.nodes[0].id = 1; initial_state.nodes[0].child_ids = {2, 3}; initial_state.nodes[0].role = ax::mojom::Role::kListBox; initial_state.nodes[1].id = 2; initial_state.nodes[1].child_ids = {4, 5}; initial_state.nodes[1].role = ax::mojom::Role::kGroup; initial_state.nodes[2].id = 3; initial_state.nodes[2].child_ids = {6, 7}; initial_state.nodes[2].role = ax::mojom::Role::kGroup; initial_state.nodes[3].id = 4; initial_state.nodes[3].role = ax::mojom::Role::kListBoxOption; initial_state.nodes[4].id = 5; initial_state.nodes[4].role = ax::mojom::Role::kListBoxOption; initial_state.nodes[5].id = 6; initial_state.nodes[5].role = ax::mojom::Role::kListBoxOption; initial_state.nodes[6].id = 7; initial_state.nodes[6].role = ax::mojom::Role::kListBoxOption; AXTree tree(initial_state); AXNode* listbox_option1 = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(1, listbox_option1->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, listbox_option1->GetSetSize()); AXNode* listbox_option2 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(2, listbox_option2->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, listbox_option2->GetSetSize()); AXNode* listbox_option3 = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(3, listbox_option3->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, listbox_option3->GetSetSize()); AXNode* listbox_option4 = tree.GetFromId(7); EXPECT_OPTIONAL_EQ(4, listbox_option4->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, listbox_option4->GetSetSize()); } TEST(AXTreeTest, SetSizePosInSetGroup) { // The behavior of a group changes depending on the context it appears in // i.e. if it appears alone vs. if it is contained within another set-like // element. The below example shows a group standing alone: // // <ul role="group"> <!-- SetSize = 3 --> // <li role="menuitemradio" aria-checked="true">Small</li> // <li role="menuitemradio" aria-checked="false">Medium</li> // <li role="menuitemradio" aria-checked="false">Large</li> // </ul> // // However, when it is contained within another set-like element, like a // listbox, it should simply act like a generic container: // // <div role="listbox"> <!-- SetSize = 3 --> // <div role="option">Red</div> <!-- 1 of 3 --> // <div role="option">Yellow</div> <!-- 2 of 3 --> // <div role="group"> <!-- SetSize = 0 --> // <div role="option">Blue</div> <!-- 3 of 3 --> // </div> // </div> // // Please note: the GetPosInSet and GetSetSize functions take slightly // different code paths when initially run on items vs. the container. // Exercise both code paths in this test. AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(6); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kMenu; // SetSize = 4 tree_update.nodes[0].child_ids = {2, 6}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kGroup; // SetSize = 0 tree_update.nodes[1].child_ids = {3, 4, 5}; tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kMenuItemRadio; // 1 of 4 tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kMenuItemRadio; // 2 of 4 tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kMenuItemRadio; // 3 of 4 tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kMenuItemRadio; // 4 of 4 AXTree tree(tree_update); // Get data on kMenu first. AXNode* menu = tree.GetFromId(1); EXPECT_OPTIONAL_EQ(4, menu->GetSetSize()); AXNode* group = tree.GetFromId(2); EXPECT_FALSE(group->GetSetSize()); // The below values should have already been computed and cached. AXNode* item1 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(1, item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, item1->GetSetSize()); AXNode* item4 = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(4, item4->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, item4->GetSetSize()); AXTreeUpdate next_tree_update; next_tree_update.root_id = 1; next_tree_update.nodes.resize(6); next_tree_update.nodes[0].id = 1; next_tree_update.nodes[0].role = ax::mojom::Role::kListBox; // SetSize = 4 next_tree_update.nodes[0].child_ids = {2, 6}; next_tree_update.nodes[1].id = 2; next_tree_update.nodes[1].role = ax::mojom::Role::kGroup; // SetSize = 0 next_tree_update.nodes[1].child_ids = {3, 4, 5}; next_tree_update.nodes[2].id = 3; next_tree_update.nodes[2].role = ax::mojom::Role::kListBoxOption; // 1 of 4 next_tree_update.nodes[3].id = 4; next_tree_update.nodes[3].role = ax::mojom::Role::kListBoxOption; // 2 of 4 next_tree_update.nodes[4].id = 5; next_tree_update.nodes[4].role = ax::mojom::Role::kListBoxOption; // 3 of 4 next_tree_update.nodes[5].id = 6; next_tree_update.nodes[5].role = ax::mojom::Role::kListBoxOption; // 4 of 4 AXTree next_tree(next_tree_update); // Get data on kListBoxOption first. AXNode* option1 = next_tree.GetFromId(3); EXPECT_OPTIONAL_EQ(1, option1->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, option1->GetSetSize()); AXNode* option2 = next_tree.GetFromId(4); EXPECT_OPTIONAL_EQ(2, option2->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, option2->GetSetSize()); AXNode* option3 = next_tree.GetFromId(5); EXPECT_OPTIONAL_EQ(3, option3->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, option3->GetSetSize()); AXNode* option4 = next_tree.GetFromId(6); EXPECT_OPTIONAL_EQ(4, option4->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, option4->GetSetSize()); AXNode* next_group = next_tree.GetFromId(2); EXPECT_FALSE(next_group->GetSetSize()); // The below value should have already been computed and cached. AXNode* listbox = next_tree.GetFromId(1); EXPECT_OPTIONAL_EQ(4, listbox->GetSetSize()); // Standalone groups are allowed. AXTreeUpdate third_tree_update; third_tree_update.root_id = 1; third_tree_update.nodes.resize(3); third_tree_update.nodes[0].id = 1; third_tree_update.nodes[0].role = ax::mojom::Role::kGroup; third_tree_update.nodes[0].child_ids = {2, 3}; third_tree_update.nodes[1].id = 2; third_tree_update.nodes[1].role = ax::mojom::Role::kListItem; third_tree_update.nodes[2].id = 3; third_tree_update.nodes[2].role = ax::mojom::Role::kListItem; AXTree third_tree(third_tree_update); // Ensure that groups can't also stand alone. AXNode* last_group = third_tree.GetFromId(1); EXPECT_OPTIONAL_EQ(2, last_group->GetSetSize()); AXNode* list_item1 = third_tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, list_item1->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, list_item1->GetSetSize()); AXNode* list_item2 = third_tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, list_item2->GetPosInSet()); EXPECT_OPTIONAL_EQ(2, list_item2->GetSetSize()); // Test nested groups. AXTreeUpdate last_tree_update; last_tree_update.root_id = 1; last_tree_update.nodes.resize(6); last_tree_update.nodes[0].id = 1; last_tree_update.nodes[0].role = ax::mojom::Role::kMenuBar; last_tree_update.nodes[0].child_ids = {2}; last_tree_update.nodes[1].id = 2; last_tree_update.nodes[1].role = ax::mojom::Role::kGroup; last_tree_update.nodes[1].child_ids = {3, 4}; last_tree_update.nodes[2].id = 3; last_tree_update.nodes[2].role = ax::mojom::Role::kMenuItemCheckBox; last_tree_update.nodes[3].id = 4; last_tree_update.nodes[3].role = ax::mojom::Role::kGroup; last_tree_update.nodes[3].child_ids = {5, 6}; last_tree_update.nodes[4].id = 5; last_tree_update.nodes[4].role = ax::mojom::Role::kMenuItemCheckBox; last_tree_update.nodes[5].id = 6; last_tree_update.nodes[5].role = ax::mojom::Role::kMenuItemCheckBox; AXTree last_tree(last_tree_update); AXNode* checkbox1 = last_tree.GetFromId(3); EXPECT_OPTIONAL_EQ(1, checkbox1->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, checkbox1->GetSetSize()); AXNode* checkbox2 = last_tree.GetFromId(5); EXPECT_OPTIONAL_EQ(2, checkbox2->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, checkbox2->GetSetSize()); AXNode* checkbox3 = last_tree.GetFromId(6); EXPECT_OPTIONAL_EQ(3, checkbox3->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, checkbox3->GetSetSize()); AXNode* menu_bar = last_tree.GetFromId(1); EXPECT_OPTIONAL_EQ(3, menu_bar->GetSetSize()); AXNode* outer_group = last_tree.GetFromId(2); EXPECT_FALSE(outer_group->GetSetSize()); AXNode* inner_group = last_tree.GetFromId(4); EXPECT_FALSE(inner_group->GetSetSize()); } TEST(AXTreeTest, SetSizePosInSetHidden) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(6); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kListBox; // SetSize = 4 tree_update.nodes[0].child_ids = {2, 3, 4, 5, 6}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListBoxOption; // 1 of 4 tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kListBoxOption; // 2 of 4 tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListBoxOption; // Hidden tree_update.nodes[3].AddState(ax::mojom::State::kInvisible); tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kListBoxOption; // 3 of 4 tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kListBoxOption; // 4 of 4 AXTree tree(tree_update); AXNode* list_box = tree.GetFromId(1); EXPECT_OPTIONAL_EQ(4, list_box->GetSetSize()); AXNode* option1 = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(1, option1->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, option1->GetSetSize()); AXNode* option2 = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(2, option2->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, option2->GetSetSize()); AXNode* option_hidden = tree.GetFromId(4); EXPECT_FALSE(option_hidden->GetPosInSet()); EXPECT_FALSE(option_hidden->GetSetSize()); AXNode* option3 = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(3, option3->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, option3->GetSetSize()); AXNode* option4 = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(4, option4->GetPosInSet()); EXPECT_OPTIONAL_EQ(4, option4->GetSetSize()); } // Tests that we get the correct PosInSet and SetSize values when using an // aria-controls relationship. TEST(AXTreeTest, SetSizePosInSetControls) { std::vector<int32_t> three; three.push_back(3); std::vector<int32_t> hundred; hundred.push_back(100); std::vector<int32_t> eight; eight.push_back(8); AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(8); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[0].child_ids = {2, 3, 7, 8}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kPopUpButton; // SetSize = 3 tree_update.nodes[1].AddIntListAttribute( ax::mojom::IntListAttribute::kControlsIds, three); tree_update.nodes[1].SetHasPopup(ax::mojom::HasPopup::kMenu); tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kMenu; // SetSize = 3 tree_update.nodes[2].child_ids = {4, 5, 6}; tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kMenuItem; // 1 of 3 tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kMenuItem; // 2 of 3 tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kMenuItem; // 3 of 3 tree_update.nodes[6].id = 7; tree_update.nodes[6].role = ax::mojom::Role::kPopUpButton; // Test an invalid controls id. tree_update.nodes[6].AddIntListAttribute( ax::mojom::IntListAttribute::kControlsIds, hundred); // GetSetSize should handle self-references e.g. if a popup button controls // itself. tree_update.nodes[7].id = 8; tree_update.nodes[7].role = ax::mojom::Role::kPopUpButton; tree_update.nodes[7].AddIntListAttribute( ax::mojom::IntListAttribute::kControlsIds, eight); AXTree tree(tree_update); AXNode* button = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(3, button->GetSetSize()); EXPECT_FALSE(button->GetPosInSet()); AXNode* menu = tree.GetFromId(3); EXPECT_OPTIONAL_EQ(3, menu->GetSetSize()); AXNode* item = tree.GetFromId(4); EXPECT_OPTIONAL_EQ(1, item->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item->GetSetSize()); item = tree.GetFromId(5); EXPECT_OPTIONAL_EQ(2, item->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item->GetSetSize()); item = tree.GetFromId(6); EXPECT_OPTIONAL_EQ(3, item->GetPosInSet()); EXPECT_OPTIONAL_EQ(3, item->GetSetSize()); button = tree.GetFromId(7); EXPECT_OPTIONAL_EQ(0, button->GetSetSize()); button = tree.GetFromId(8); EXPECT_OPTIONAL_EQ(0, button->GetSetSize()); } // Tests GetPosInSet and GetSetSize return the assigned int attribute values // when a pop-up button is a leaf node. TEST(AXTreeTest, SetSizePosInSetLeafPopUpButton) { AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(2); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[0].child_ids = {2}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kPopUpButton; tree_update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 3); tree_update.nodes[1].AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 77); AXTree tree(tree_update); AXNode* pop_up_button = tree.GetFromId(2); EXPECT_OPTIONAL_EQ(3, pop_up_button->GetPosInSet()); EXPECT_OPTIONAL_EQ(77, pop_up_button->GetSetSize()); } TEST(AXTreeTest, OnNodeWillBeDeletedHasValidUnignoredParent) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea; initial_state.nodes[0].child_ids = {2}; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kGenericContainer; initial_state.nodes[1].child_ids = {3}; initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kGenericContainer; AXTree tree(initial_state); AXTreeUpdate tree_update; tree_update.nodes.resize(1); // Remove child from node:2, and add State::kIgnored tree_update.nodes[0] = initial_state.nodes[1]; tree_update.nodes[0].AddState(ax::mojom::State::kIgnored); tree_update.nodes[0].child_ids.clear(); // Before node:3 is deleted, the unignored parent is node:2. // Assert that this is the case in |OnNodeWillBeDeleted|. TestAXTreeObserver test_observer(&tree); test_observer.unignored_parent_id_before_node_deleted = 2; ASSERT_TRUE(tree.Unserialize(tree_update)); } TEST(AXTreeTest, OnNodeHasBeenDeleted) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(6); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea; initial_state.nodes[0].child_ids = {2}; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kButton; initial_state.nodes[1].child_ids = {3, 4}; initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kCheckBox; initial_state.nodes[3].id = 4; initial_state.nodes[3].role = ax::mojom::Role::kStaticText; initial_state.nodes[3].child_ids = {5, 6}; initial_state.nodes[4].id = 5; initial_state.nodes[4].role = ax::mojom::Role::kInlineTextBox; initial_state.nodes[5].id = 6; initial_state.nodes[5].role = ax::mojom::Role::kInlineTextBox; AXTree tree(initial_state); AXTreeUpdate update; update.nodes.resize(2); update.nodes[0] = initial_state.nodes[1]; update.nodes[0].child_ids = {4}; update.nodes[1] = initial_state.nodes[3]; update.nodes[1].child_ids = {}; TestAXTreeObserver test_observer(&tree); ASSERT_TRUE(tree.Unserialize(update)); EXPECT_EQ(3U, test_observer.deleted_ids().size()); EXPECT_EQ(3, test_observer.deleted_ids()[0]); EXPECT_EQ(5, test_observer.deleted_ids()[1]); EXPECT_EQ(6, test_observer.deleted_ids()[2]); // Verify that the nodes we intend to delete in the update are actually // absent from the tree. for (auto id : test_observer.deleted_ids()) { SCOPED_TRACE(testing::Message() << "Node with id=" << id << ", should not exist in the tree"); EXPECT_EQ(nullptr, tree.GetFromId(id)); } } // Tests a fringe scenario that may happen if multiple AXTreeUpdates are merged. // Make sure that we correctly Unserialize if a newly created node is deleted, // and possibly recreated later. TEST(AXTreeTest, SingleUpdateDeletesNewlyCreatedChildNode) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea; AXTree tree(initial_state); AXTreeUpdate tree_update; tree_update.nodes.resize(6); // Add child node:2 tree_update.nodes[0] = initial_state.nodes[0]; tree_update.nodes[0].child_ids = {2}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kGenericContainer; // Remove child node:2 tree_update.nodes[2] = initial_state.nodes[0]; // Add child node:2 tree_update.nodes[3] = initial_state.nodes[0]; tree_update.nodes[3].child_ids = {2}; tree_update.nodes[4].id = 2; tree_update.nodes[4].role = ax::mojom::Role::kGenericContainer; // Remove child node:2 tree_update.nodes[5] = initial_state.nodes[0]; ASSERT_TRUE(tree.Unserialize(tree_update)) << tree.error(); ASSERT_EQ( "AXTree\n" "id=1 rootWebArea (0, 0)-(0, 0)\n", tree.ToString()); // Unserialize again, but with another add child. tree_update.nodes.resize(8); tree_update.nodes[6] = initial_state.nodes[0]; tree_update.nodes[6].child_ids = {2}; tree_update.nodes[7].id = 2; tree_update.nodes[7].role = ax::mojom::Role::kGenericContainer; ASSERT_TRUE(tree.Unserialize(tree_update)) << tree.error(); ASSERT_EQ( "AXTree\n" "id=1 rootWebArea (0, 0)-(0, 0) child_ids=2\n" " id=2 genericContainer (0, 0)-(0, 0)\n", tree.ToString()); } // Tests a fringe scenario that may happen if multiple AXTreeUpdates are merged. // Make sure that we correctly Unserialize if a node is reparented multiple // times. TEST(AXTreeTest, SingleUpdateReparentsNodeMultipleTimes) { // ++{kRootWebArea, 1} // ++++{kList, 2} // ++++++{kListItem, 4} // ++++{kList, 3} AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(4); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea; initial_state.nodes[0].child_ids = {2, 3}; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kList; initial_state.nodes[1].child_ids = {4}; initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kList; initial_state.nodes[3].id = 4; initial_state.nodes[3].role = ax::mojom::Role::kListItem; AXTree tree(initial_state); AXTreeUpdate tree_update; tree_update.nodes.resize(6); // Remove child node:4 tree_update.nodes[0].id = 2; tree_update.nodes[0].role = ax::mojom::Role::kList; // Reparent child node:4 onto node:3 tree_update.nodes[1].id = 3; tree_update.nodes[1].role = ax::mojom::Role::kList; tree_update.nodes[1].child_ids = {4}; tree_update.nodes[2].id = 4; tree_update.nodes[2].role = ax::mojom::Role::kListItem; // Remove child ndoe:4 tree_update.nodes[3].id = 3; tree_update.nodes[3].role = ax::mojom::Role::kList; // Reparent child node:4 onto node:2 tree_update.nodes[4].id = 2; tree_update.nodes[4].role = ax::mojom::Role::kList; tree_update.nodes[4].child_ids = {4}; tree_update.nodes[5].id = 4; tree_update.nodes[5].role = ax::mojom::Role::kListItem; ASSERT_TRUE(tree.Unserialize(tree_update)) << tree.error(); EXPECT_EQ( "AXTree\nid=1 rootWebArea (0, 0)-(0, 0) child_ids=2,3\n" " id=2 list (0, 0)-(0, 0) child_ids=4\n" " id=4 listItem (0, 0)-(0, 0)\n" " id=3 list (0, 0)-(0, 0)\n", tree.ToString()); // Unserialize again, but with another reparent. tree_update.nodes.resize(9); tree_update.nodes[6] = tree_update.nodes[0]; tree_update.nodes[7] = tree_update.nodes[1]; tree_update.nodes[8] = tree_update.nodes[2]; ASSERT_TRUE(tree.Unserialize(tree_update)) << tree.error(); EXPECT_EQ( "AXTree\nid=1 rootWebArea (0, 0)-(0, 0) child_ids=2,3\n" " id=2 list (0, 0)-(0, 0)\n" " id=3 list (0, 0)-(0, 0) child_ids=4\n" " id=4 listItem (0, 0)-(0, 0)\n", tree.ToString()); } // Tests a fringe scenario that may happen if multiple AXTreeUpdates are merged. // Make sure that we correctly Unserialize if a newly created node toggles its // ignored state. TEST(AXTreeTest, SingleUpdateIgnoresNewlyCreatedUnignoredChildNode) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea; AXTree tree(initial_state); AXTreeUpdate tree_update; tree_update.nodes.resize(3); // Add child node:2 tree_update.nodes[0] = initial_state.nodes[0]; tree_update.nodes[0].child_ids = {2}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kGenericContainer; // Add State::kIgnored to node:2 tree_update.nodes[2] = tree_update.nodes[1]; tree_update.nodes[2].AddState(ax::mojom::State::kIgnored); ASSERT_TRUE(tree.Unserialize(tree_update)) << tree.error(); ASSERT_EQ( "AXTree\n" "id=1 rootWebArea (0, 0)-(0, 0) child_ids=2\n" " id=2 genericContainer IGNORED (0, 0)-(0, 0)\n", tree.ToString()); } // Tests a fringe scenario that may happen if multiple AXTreeUpdates are merged. // Make sure that we correctly Unserialize if a newly created node toggles its // ignored state. TEST(AXTreeTest, SingleUpdateTogglesIgnoredStateAfterCreatingNode) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(1); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea; AXTree tree(initial_state); ASSERT_EQ( "AXTree\n" "id=1 rootWebArea (0, 0)-(0, 0)\n", tree.ToString()); AXTreeUpdate tree_update; tree_update.nodes.resize(5); // Add child node:2, node:3 tree_update.nodes[0] = initial_state.nodes[0]; tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[2].id = 3; tree_update.nodes[2].role = ax::mojom::Role::kGenericContainer; tree_update.nodes[2].AddState(ax::mojom::State::kIgnored); // Add State::kIgnored to node:2 tree_update.nodes[3] = tree_update.nodes[1]; tree_update.nodes[3].AddState(ax::mojom::State::kIgnored); // Remove State::kIgnored from node:3 tree_update.nodes[4] = tree_update.nodes[2]; tree_update.nodes[4].RemoveState(ax::mojom::State::kIgnored); ASSERT_TRUE(tree.Unserialize(tree_update)) << tree.error(); ASSERT_EQ( "AXTree\n" "id=1 rootWebArea (0, 0)-(0, 0) child_ids=2,3\n" " id=2 genericContainer IGNORED (0, 0)-(0, 0)\n" " id=3 genericContainer (0, 0)-(0, 0)\n", tree.ToString()); } // Tests a fringe scenario that may happen if multiple AXTreeUpdates are merged. // Make sure that we correctly Unserialize if a node toggles its ignored state // and is then removed from the tree. TEST(AXTreeTest, SingleUpdateTogglesIgnoredStateBeforeDestroyingNode) { AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes.resize(3); initial_state.nodes[0].id = 1; initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea; initial_state.nodes[0].child_ids = {2, 3}; initial_state.nodes[1].id = 2; initial_state.nodes[1].role = ax::mojom::Role::kGenericContainer; initial_state.nodes[2].id = 3; initial_state.nodes[2].role = ax::mojom::Role::kGenericContainer; initial_state.nodes[2].AddState(ax::mojom::State::kIgnored); AXTree tree(initial_state); ASSERT_EQ( "AXTree\n" "id=1 rootWebArea (0, 0)-(0, 0) child_ids=2,3\n" " id=2 genericContainer (0, 0)-(0, 0)\n" " id=3 genericContainer IGNORED (0, 0)-(0, 0)\n", tree.ToString()); AXTreeUpdate tree_update; tree_update.nodes.resize(3); // Add State::kIgnored to node:2 tree_update.nodes[0] = initial_state.nodes[1]; tree_update.nodes[0].AddState(ax::mojom::State::kIgnored); // Remove State::kIgnored from node:3 tree_update.nodes[1] = initial_state.nodes[2]; tree_update.nodes[1].RemoveState(ax::mojom::State::kIgnored); // Remove child node:2, node:3 tree_update.nodes[2] = initial_state.nodes[0]; tree_update.nodes[2].child_ids.clear(); ASSERT_TRUE(tree.Unserialize(tree_update)) << tree.error(); ASSERT_EQ( "AXTree\n" "id=1 rootWebArea (0, 0)-(0, 0)\n", tree.ToString()); } // Tests that the IsInListMarker() method returns true if the current node is a // list marker or if it's a descendant node of a list marker. TEST(AXTreeTest, TestIsInListMarker) { // This test uses the template of a list of one element: "1. List item" AXTreeUpdate tree_update; tree_update.root_id = 1; tree_update.nodes.resize(8); tree_update.nodes[0].id = 1; tree_update.nodes[0].role = ax::mojom::Role::kList; tree_update.nodes[0].child_ids = {2, 3}; tree_update.nodes[1].id = 2; tree_update.nodes[1].role = ax::mojom::Role::kListItem; tree_update.nodes[2].id = 3; tree_update.nodes[2].child_ids = {4, 7}; tree_update.nodes[3].id = 4; tree_update.nodes[3].role = ax::mojom::Role::kListMarker; tree_update.nodes[3].child_ids = {5}; tree_update.nodes[4].id = 5; tree_update.nodes[4].role = ax::mojom::Role::kStaticText; // "1. " tree_update.nodes[4].child_ids = {6}; tree_update.nodes[5].id = 6; tree_update.nodes[5].role = ax::mojom::Role::kInlineTextBox; // "1. " tree_update.nodes[6].id = 7; tree_update.nodes[6].role = ax::mojom::Role::kStaticText; // "List item" tree_update.nodes[6].child_ids = {8}; tree_update.nodes[7].id = 8; tree_update.nodes[7].role = ax::mojom::Role::kInlineTextBox; // "List item" AXTree tree(tree_update); AXNode* list_node = tree.GetFromId(1); ASSERT_EQ(false, list_node->IsInListMarker()); AXNode* list_item_node = tree.GetFromId(2); ASSERT_EQ(false, list_item_node->IsInListMarker()); AXNode* list_marker1 = tree.GetFromId(4); ASSERT_EQ(true, list_marker1->IsInListMarker()); AXNode* static_node1 = tree.GetFromId(5); ASSERT_EQ(true, static_node1->IsInListMarker()); AXNode* inline_node1 = tree.GetFromId(6); ASSERT_EQ(true, inline_node1->IsInListMarker()); AXNode* static_node2 = tree.GetFromId(7); ASSERT_EQ(false, static_node2->IsInListMarker()); AXNode* inline_node2 = tree.GetFromId(8); ASSERT_EQ(false, inline_node2->IsInListMarker()); } } // namespace ui
engine/third_party/accessibility/ax/ax_tree_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_tree_unittest.cc", "repo_id": "engine", "token_count": 75133 }
410
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_MAC_H_ #define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_MAC_H_ #import <Cocoa/Cocoa.h> #include "base/macros.h" #include "base/platform/darwin/scoped_nsobject.h" #include "ax/ax_export.h" #include "ax_platform_node_base.h" @class AXPlatformNodeCocoa; namespace ui { class AXPlatformNodeMac : public AXPlatformNodeBase { public: AXPlatformNodeMac(); // AXPlatformNode. gfx::NativeViewAccessible GetNativeViewAccessible() override; void NotifyAccessibilityEvent(ax::mojom::Event event_type) override; void AnnounceText(const std::u16string& text) override; // AXPlatformNodeBase. void Destroy() override; bool IsPlatformCheckable() const override; protected: void AddAttributeToList(const char* name, const char* value, PlatformAttributeList* attributes) override; private: ~AXPlatformNodeMac() override; base::scoped_nsobject<AXPlatformNodeCocoa> native_node_; BASE_DISALLOW_COPY_AND_ASSIGN(AXPlatformNodeMac); }; // Convenience function to determine whether an internal object role should // expose its accessible name in AXValue (as opposed to AXTitle/AXDescription). AX_EXPORT bool IsNameExposedInAXValueForRole(ax::mojom::Role role); } // namespace ui AX_EXPORT @interface AXPlatformNodeCocoa : NSAccessibilityElement <NSAccessibility> // Maps AX roles to native roles. Returns NSAccessibilityUnknownRole if not // found. + (NSString*)nativeRoleFromAXRole:(ax::mojom::Role)role; // Maps AX roles to native subroles. Returns nil if not found. + (NSString*)nativeSubroleFromAXRole:(ax::mojom::Role)role; // Maps AX events to native notifications. Returns nil if not found. + (NSString*)nativeNotificationFromAXEvent:(ax::mojom::Event)event; - (instancetype)initWithNode:(ui::AXPlatformNodeBase*)node; - (void)detach; @property(nonatomic, readonly) NSRect boundsInScreen; @property(nonatomic, readonly) ui::AXPlatformNodeBase* node; @end #endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_MAC_H_
engine/third_party/accessibility/ax/platform/ax_platform_node_mac.h/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_mac.h", "repo_id": "engine", "token_count": 764 }
411
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/accessibility/platform/ax_platform_relation_win.h" #include <wrl/client.h> #include <algorithm> #include <vector> #include "base/lazy_instance.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/win/enum_variant.h" #include "base/win/scoped_variant.h" #include "third_party/iaccessible2/ia2_api_all.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/ax_mode_observer.h" #include "ui/accessibility/ax_node_data.h" #include "ui/accessibility/ax_role_properties.h" #include "ui/accessibility/ax_text_utils.h" #include "ui/accessibility/ax_tree_data.h" #include "ui/accessibility/platform/ax_platform_node_base.h" #include "ui/accessibility/platform/ax_platform_node_delegate.h" #include "ui/accessibility/platform/ax_unique_id.h" #include "ui/base/win/atl_module.h" #include "ui/gfx/geometry/rect_conversions.h" namespace ui { AXPlatformRelationWin::AXPlatformRelationWin() { win::CreateATLModuleIfNeeded(); } AXPlatformRelationWin::~AXPlatformRelationWin() {} base::string16 GetIA2RelationFromIntAttr(ax::mojom::IntAttribute attribute) { switch (attribute) { case ax::mojom::IntAttribute::kMemberOfId: return IA2_RELATION_MEMBER_OF; case ax::mojom::IntAttribute::kErrormessageId: return IA2_RELATION_ERROR; case ax::mojom::IntAttribute::kPopupForId: // Map "popup for" to "controlled by". // Unlike ATK there is no special IA2 popup-for relationship, but it can // be exposed via the controlled by relation, which is also computed for // content as the reverse of the controls relationship. return IA2_RELATION_CONTROLLED_BY; default: break; } return base::string16(); } base::string16 GetIA2RelationFromIntListAttr( ax::mojom::IntListAttribute attribute) { switch (attribute) { case ax::mojom::IntListAttribute::kControlsIds: return IA2_RELATION_CONTROLLER_FOR; case ax::mojom::IntListAttribute::kDescribedbyIds: return IA2_RELATION_DESCRIBED_BY; case ax::mojom::IntListAttribute::kDetailsIds: return IA2_RELATION_DETAILS; case ax::mojom::IntListAttribute::kFlowtoIds: return IA2_RELATION_FLOWS_TO; case ax::mojom::IntListAttribute::kLabelledbyIds: return IA2_RELATION_LABELLED_BY; default: break; } return base::string16(); } base::string16 GetIA2ReverseRelationFromIntAttr( ax::mojom::IntAttribute attribute) { switch (attribute) { case ax::mojom::IntAttribute::kErrormessageId: return IA2_RELATION_ERROR_FOR; default: break; } return base::string16(); } base::string16 GetIA2ReverseRelationFromIntListAttr( ax::mojom::IntListAttribute attribute) { switch (attribute) { case ax::mojom::IntListAttribute::kControlsIds: return IA2_RELATION_CONTROLLED_BY; case ax::mojom::IntListAttribute::kDescribedbyIds: return IA2_RELATION_DESCRIPTION_FOR; case ax::mojom::IntListAttribute::kDetailsIds: return IA2_RELATION_DETAILS_FOR; case ax::mojom::IntListAttribute::kFlowtoIds: return IA2_RELATION_FLOWS_FROM; case ax::mojom::IntListAttribute::kLabelledbyIds: return IA2_RELATION_LABEL_FOR; default: break; } return base::string16(); } // static int AXPlatformRelationWin::EnumerateRelationships( AXPlatformNodeBase* node, int desired_index, const base::string16& desired_ia2_relation, base::string16* out_ia2_relation, std::set<AXPlatformNode*>* out_targets) { const AXNodeData& node_data = node->GetData(); AXPlatformNodeDelegate* delegate = node->GetDelegate(); // The first time this is called, populate vectors with all of the // int attributes and intlist attributes that have reverse relations // we care about on Windows. Computing these by calling // GetIA2ReverseRelationFrom{Int|IntList}Attr on every possible attribute // simplifies the work needed to support an additional relation // attribute in the future. static std::vector<ax::mojom::IntAttribute> int_attributes_with_reverse_relations; static std::vector<ax::mojom::IntListAttribute> intlist_attributes_with_reverse_relations; static bool first_time = true; if (first_time) { for (int32_t attr_index = static_cast<int32_t>(ax::mojom::IntAttribute::kNone); attr_index <= static_cast<int32_t>(ax::mojom::IntAttribute::kMaxValue); ++attr_index) { auto attr = static_cast<ax::mojom::IntAttribute>(attr_index); if (!GetIA2ReverseRelationFromIntAttr(attr).empty()) int_attributes_with_reverse_relations.push_back(attr); } for (int32_t attr_index = static_cast<int32_t>(ax::mojom::IntListAttribute::kNone); attr_index <= static_cast<int32_t>(ax::mojom::IntListAttribute::kMaxValue); ++attr_index) { auto attr = static_cast<ax::mojom::IntListAttribute>(attr_index); if (!GetIA2ReverseRelationFromIntListAttr(attr).empty()) intlist_attributes_with_reverse_relations.push_back(attr); } first_time = false; } // Enumerate all of the relations and reverse relations that // are exposed via IAccessible2 on Windows. We do this with a series // of loops. Every time we encounter one, we check if the caller // requested that particular relation by index, and return it. // Otherwise we build up and return the total number of relations found. int total_count = 0; // Iterate over all int attributes on this node to check the ones // that correspond to IAccessible2 relations. for (size_t i = 0; i < node_data.int_attributes.size(); ++i) { ax::mojom::IntAttribute int_attribute = node_data.int_attributes[i].first; base::string16 relation = GetIA2RelationFromIntAttr(int_attribute); if (!relation.empty() && (desired_ia2_relation.empty() || desired_ia2_relation == relation)) { // Skip reflexive relations if (node_data.int_attributes[i].second == node_data.id) continue; if (desired_index == total_count) { *out_ia2_relation = relation; out_targets->insert( delegate->GetFromNodeID(node_data.int_attributes[i].second)); return 1; } total_count++; } } // Iterate over all of the int attributes that have reverse relations // in IAccessible2, and query AXTree to see if the reverse relation exists. for (ax::mojom::IntAttribute int_attribute : int_attributes_with_reverse_relations) { base::string16 relation = GetIA2ReverseRelationFromIntAttr(int_attribute); std::set<AXPlatformNode*> targets = delegate->GetReverseRelations(int_attribute); // Erase reflexive relations. targets.erase(node); if (targets.size()) { if (!relation.empty() && (desired_ia2_relation.empty() || desired_ia2_relation == relation)) { if (desired_index == total_count) { *out_ia2_relation = relation; *out_targets = targets; return 1; } total_count++; } } } // Iterate over all intlist attributes on this node to check the ones // that correspond to IAccessible2 relations. for (size_t i = 0; i < node_data.intlist_attributes.size(); ++i) { ax::mojom::IntListAttribute intlist_attribute = node_data.intlist_attributes[i].first; base::string16 relation = GetIA2RelationFromIntListAttr(intlist_attribute); if (!relation.empty() && (desired_ia2_relation.empty() || desired_ia2_relation == relation)) { if (desired_index == total_count) { *out_ia2_relation = relation; for (int32_t target_id : node_data.intlist_attributes[i].second) { // Skip reflexive relations if (target_id == node_data.id) continue; out_targets->insert(delegate->GetFromNodeID(target_id)); } if (out_targets->size() == 0) continue; return 1; } total_count++; } } // Iterate over all of the intlist attributes that have reverse relations // in IAccessible2, and query AXTree to see if the reverse relation exists. for (ax::mojom::IntListAttribute intlist_attribute : intlist_attributes_with_reverse_relations) { base::string16 relation = GetIA2ReverseRelationFromIntListAttr(intlist_attribute); std::set<AXPlatformNode*> targets = delegate->GetReverseRelations(intlist_attribute); // Erase reflexive relations. targets.erase(node); if (targets.size()) { if (!relation.empty() && (desired_ia2_relation.empty() || desired_ia2_relation == relation)) { if (desired_index == total_count) { *out_ia2_relation = relation; *out_targets = targets; return 1; } total_count++; } } } return total_count; } void AXPlatformRelationWin::Initialize(const base::string16& type) { type_ = type; } void AXPlatformRelationWin::Invalidate() { targets_.clear(); } void AXPlatformRelationWin::AddTarget(AXPlatformNodeWin* target) { targets_.push_back(target); } IFACEMETHODIMP AXPlatformRelationWin::get_relationType(BSTR* relation_type) { if (!relation_type) return E_INVALIDARG; *relation_type = SysAllocString(type_.c_str()); DCHECK(*relation_type); return S_OK; } IFACEMETHODIMP AXPlatformRelationWin::get_nTargets(LONG* n_targets) { if (!n_targets) return E_INVALIDARG; *n_targets = static_cast<LONG>(targets_.size()); return S_OK; } IFACEMETHODIMP AXPlatformRelationWin::get_target(LONG target_index, IUnknown** target) { if (!target) return E_INVALIDARG; if (target_index < 0 || target_index >= static_cast<LONG>(targets_.size())) { return E_INVALIDARG; } *target = static_cast<IAccessible*>(targets_[target_index].Get()); (*target)->AddRef(); return S_OK; } IFACEMETHODIMP AXPlatformRelationWin::get_targets(LONG max_targets, IUnknown** targets, LONG* n_targets) { if (!targets || !n_targets) return E_INVALIDARG; LONG count = static_cast<LONG>(targets_.size()); if (count > max_targets) count = max_targets; *n_targets = count; if (count == 0) return S_FALSE; for (LONG i = 0; i < count; ++i) { HRESULT result = get_target(i, &targets[i]); if (result != S_OK) return result; } return S_OK; } IFACEMETHODIMP AXPlatformRelationWin::get_localizedRelationType(BSTR* relation_type) { return E_NOTIMPL; } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_platform_relation_win.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_relation_win.cc", "repo_id": "engine", "token_count": 4334 }
412
// 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_CHECKED_MATH_IMPL_H_ #define BASE_NUMERICS_CHECKED_MATH_IMPL_H_ #include <climits> #include <cmath> #include <cstddef> #include <cstdint> #include <cstdlib> #include <limits> #include <type_traits> #include "base/numerics/safe_conversions.h" #include "base/numerics/safe_math_shared_impl.h" namespace base { namespace internal { template <typename T> constexpr bool CheckedAddImpl(T x, T y, T* result) { static_assert(std::is_integral<T>::value, "Type must be integral"); // Since the value of x+y is undefined if we have a signed type, we compute // it using the unsigned type of the same size. using UnsignedDst = typename std::make_unsigned<T>::type; using SignedDst = typename std::make_signed<T>::type; UnsignedDst ux = static_cast<UnsignedDst>(x); UnsignedDst uy = static_cast<UnsignedDst>(y); UnsignedDst uresult = static_cast<UnsignedDst>(ux + uy); *result = static_cast<T>(uresult); // Addition is valid if the sign of (x + y) is equal to either that of x or // that of y. return (std::is_signed<T>::value) ? static_cast<SignedDst>((uresult ^ ux) & (uresult ^ uy)) >= 0 : uresult >= uy; // Unsigned is either valid or underflow. } template <typename T, typename U, class Enable = void> struct CheckedAddOp {}; template <typename T, typename U> struct CheckedAddOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = typename MaxExponentPromotion<T, U>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { // TODO(jschuh) Make this "constexpr if" once we're C++17. if (CheckedAddFastOp<T, U>::is_supported) return CheckedAddFastOp<T, U>::Do(x, y, result); // Double the underlying type up to a full machine word. using FastPromotion = typename FastIntegerArithmeticPromotion<T, U>::type; using Promotion = typename std::conditional<(IntegerBitsPlusSign<FastPromotion>::value > IntegerBitsPlusSign<intptr_t>::value), typename BigEnoughPromotion<T, U>::type, FastPromotion>::type; // Fail if either operand is out of range for the promoted type. // TODO(jschuh): This could be made to work for a broader range of values. if (BASE_NUMERICS_UNLIKELY(!IsValueInRangeForNumericType<Promotion>(x) || !IsValueInRangeForNumericType<Promotion>(y))) { return false; } Promotion presult = {}; bool is_valid = true; if (IsIntegerArithmeticSafe<Promotion, T, U>::value) { presult = static_cast<Promotion>(x) + static_cast<Promotion>(y); } else { is_valid = CheckedAddImpl(static_cast<Promotion>(x), static_cast<Promotion>(y), &presult); } *result = static_cast<V>(presult); return is_valid && IsValueInRangeForNumericType<V>(presult); } }; template <typename T> constexpr bool CheckedSubImpl(T x, T y, T* result) { static_assert(std::is_integral<T>::value, "Type must be integral"); // Since the value of x+y is undefined if we have a signed type, we compute // it using the unsigned type of the same size. using UnsignedDst = typename std::make_unsigned<T>::type; using SignedDst = typename std::make_signed<T>::type; UnsignedDst ux = static_cast<UnsignedDst>(x); UnsignedDst uy = static_cast<UnsignedDst>(y); UnsignedDst uresult = static_cast<UnsignedDst>(ux - uy); *result = static_cast<T>(uresult); // Subtraction is valid if either x and y have same sign, or (x-y) and x have // the same sign. return (std::is_signed<T>::value) ? static_cast<SignedDst>((uresult ^ ux) & (ux ^ uy)) >= 0 : x >= y; } template <typename T, typename U, class Enable = void> struct CheckedSubOp {}; template <typename T, typename U> struct CheckedSubOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = typename MaxExponentPromotion<T, U>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { // TODO(jschuh) Make this "constexpr if" once we're C++17. if (CheckedSubFastOp<T, U>::is_supported) return CheckedSubFastOp<T, U>::Do(x, y, result); // Double the underlying type up to a full machine word. using FastPromotion = typename FastIntegerArithmeticPromotion<T, U>::type; using Promotion = typename std::conditional<(IntegerBitsPlusSign<FastPromotion>::value > IntegerBitsPlusSign<intptr_t>::value), typename BigEnoughPromotion<T, U>::type, FastPromotion>::type; // Fail if either operand is out of range for the promoted type. // TODO(jschuh): This could be made to work for a broader range of values. if (BASE_NUMERICS_UNLIKELY(!IsValueInRangeForNumericType<Promotion>(x) || !IsValueInRangeForNumericType<Promotion>(y))) { return false; } Promotion presult = {}; bool is_valid = true; if (IsIntegerArithmeticSafe<Promotion, T, U>::value) { presult = static_cast<Promotion>(x) - static_cast<Promotion>(y); } else { is_valid = CheckedSubImpl(static_cast<Promotion>(x), static_cast<Promotion>(y), &presult); } *result = static_cast<V>(presult); return is_valid && IsValueInRangeForNumericType<V>(presult); } }; template <typename T> constexpr bool CheckedMulImpl(T x, T y, T* result) { static_assert(std::is_integral<T>::value, "Type must be integral"); // Since the value of x*y is potentially undefined if we have a signed type, // we compute it using the unsigned type of the same size. using UnsignedDst = typename std::make_unsigned<T>::type; using SignedDst = typename std::make_signed<T>::type; const UnsignedDst ux = SafeUnsignedAbs(x); const UnsignedDst uy = SafeUnsignedAbs(y); UnsignedDst uresult = static_cast<UnsignedDst>(ux * uy); const bool is_negative = std::is_signed<T>::value && static_cast<SignedDst>(x ^ y) < 0; *result = is_negative ? 0 - uresult : uresult; // We have a fast out for unsigned identity or zero on the second operand. // After that it's an unsigned overflow check on the absolute value, with // a +1 bound for a negative result. return uy <= UnsignedDst(!std::is_signed<T>::value || is_negative) || ux <= (std::numeric_limits<T>::max() + UnsignedDst(is_negative)) / uy; } template <typename T, typename U, class Enable = void> struct CheckedMulOp {}; template <typename T, typename U> struct CheckedMulOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = typename MaxExponentPromotion<T, U>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { // TODO(jschuh) Make this "constexpr if" once we're C++17. if (CheckedMulFastOp<T, U>::is_supported) return CheckedMulFastOp<T, U>::Do(x, y, result); using Promotion = typename FastIntegerArithmeticPromotion<T, U>::type; // Verify the destination type can hold the result (always true for 0). if (BASE_NUMERICS_UNLIKELY((!IsValueInRangeForNumericType<Promotion>(x) || !IsValueInRangeForNumericType<Promotion>(y)) && x && y)) { return false; } Promotion presult = {}; bool is_valid = true; if (CheckedMulFastOp<Promotion, Promotion>::is_supported) { // The fast op may be available with the promoted type. is_valid = CheckedMulFastOp<Promotion, Promotion>::Do(x, y, &presult); } else if (IsIntegerArithmeticSafe<Promotion, T, U>::value) { presult = static_cast<Promotion>(x) * static_cast<Promotion>(y); } else { is_valid = CheckedMulImpl(static_cast<Promotion>(x), static_cast<Promotion>(y), &presult); } *result = static_cast<V>(presult); return is_valid && IsValueInRangeForNumericType<V>(presult); } }; // Division just requires a check for a zero denominator or an invalid negation // on signed min/-1. template <typename T, typename U, class Enable = void> struct CheckedDivOp {}; template <typename T, typename U> struct CheckedDivOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = typename MaxExponentPromotion<T, U>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { if (BASE_NUMERICS_UNLIKELY(!y)) return false; // The overflow check can be compiled away if we don't have the exact // combination of types needed to trigger this case. using Promotion = typename BigEnoughPromotion<T, U>::type; if (BASE_NUMERICS_UNLIKELY( (std::is_signed<T>::value && std::is_signed<U>::value && IsTypeInRangeForNumericType<T, Promotion>::value && static_cast<Promotion>(x) == std::numeric_limits<Promotion>::lowest() && y == static_cast<U>(-1)))) { return false; } // This branch always compiles away if the above branch wasn't removed. if (BASE_NUMERICS_UNLIKELY((!IsValueInRangeForNumericType<Promotion>(x) || !IsValueInRangeForNumericType<Promotion>(y)) && x)) { return false; } Promotion presult = Promotion(x) / Promotion(y); *result = static_cast<V>(presult); return IsValueInRangeForNumericType<V>(presult); } }; template <typename T, typename U, class Enable = void> struct CheckedModOp {}; template <typename T, typename U> struct CheckedModOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = typename MaxExponentPromotion<T, U>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { if (BASE_NUMERICS_UNLIKELY(!y)) return false; using Promotion = typename BigEnoughPromotion<T, U>::type; if (BASE_NUMERICS_UNLIKELY( (std::is_signed<T>::value && std::is_signed<U>::value && IsTypeInRangeForNumericType<T, Promotion>::value && static_cast<Promotion>(x) == std::numeric_limits<Promotion>::lowest() && y == static_cast<U>(-1)))) { *result = 0; return true; } Promotion presult = static_cast<Promotion>(x) % static_cast<Promotion>(y); *result = static_cast<Promotion>(presult); return IsValueInRangeForNumericType<V>(presult); } }; template <typename T, typename U, class Enable = void> struct CheckedLshOp {}; // Left shift. Shifts less than 0 or greater than or equal to the number // of bits in the promoted type are undefined. Shifts of negative values // are undefined. Otherwise it is defined when the result fits. template <typename T, typename U> struct CheckedLshOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = T; template <typename V> static constexpr bool Do(T x, U shift, V* result) { // Disallow negative numbers and verify the shift is in bounds. if (BASE_NUMERICS_LIKELY(!IsValueNegative(x) && as_unsigned(shift) < as_unsigned(std::numeric_limits<T>::digits))) { // Shift as unsigned to avoid undefined behavior. *result = static_cast<V>(as_unsigned(x) << shift); // If the shift can be reversed, we know it was valid. return *result >> shift == x; } // Handle the legal corner-case of a full-width signed shift of zero. return std::is_signed<T>::value && !x && as_unsigned(shift) == as_unsigned(std::numeric_limits<T>::digits); } }; template <typename T, typename U, class Enable = void> struct CheckedRshOp {}; // Right shift. Shifts less than 0 or greater than or equal to the number // of bits in the promoted type are undefined. Otherwise, it is always defined, // but a right shift of a negative value is implementation-dependent. template <typename T, typename U> struct CheckedRshOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = T; template <typename V> static bool Do(T x, U shift, V* result) { // Use the type conversion push negative values out of range. if (BASE_NUMERICS_LIKELY(as_unsigned(shift) < IntegerBitsPlusSign<T>::value)) { T tmp = x >> shift; *result = static_cast<V>(tmp); return IsValueInRangeForNumericType<V>(tmp); } return false; } }; template <typename T, typename U, class Enable = void> struct CheckedAndOp {}; // For simplicity we support only unsigned integer results. template <typename T, typename U> struct CheckedAndOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = typename std::make_unsigned< typename MaxExponentPromotion<T, U>::type>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { result_type tmp = static_cast<result_type>(x) & static_cast<result_type>(y); *result = static_cast<V>(tmp); return IsValueInRangeForNumericType<V>(tmp); } }; template <typename T, typename U, class Enable = void> struct CheckedOrOp {}; // For simplicity we support only unsigned integers. template <typename T, typename U> struct CheckedOrOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = typename std::make_unsigned< typename MaxExponentPromotion<T, U>::type>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { result_type tmp = static_cast<result_type>(x) | static_cast<result_type>(y); *result = static_cast<V>(tmp); return IsValueInRangeForNumericType<V>(tmp); } }; template <typename T, typename U, class Enable = void> struct CheckedXorOp {}; // For simplicity we support only unsigned integers. template <typename T, typename U> struct CheckedXorOp<T, U, typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value>::type> { using result_type = typename std::make_unsigned< typename MaxExponentPromotion<T, U>::type>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { result_type tmp = static_cast<result_type>(x) ^ static_cast<result_type>(y); *result = static_cast<V>(tmp); return IsValueInRangeForNumericType<V>(tmp); } }; // Max doesn't really need to be implemented this way because it can't fail, // but it makes the code much cleaner to use the MathOp wrappers. template <typename T, typename U, class Enable = void> struct CheckedMaxOp {}; template <typename T, typename U> struct CheckedMaxOp< T, U, typename std::enable_if<std::is_arithmetic<T>::value && std::is_arithmetic<U>::value>::type> { using result_type = typename MaxExponentPromotion<T, U>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { result_type tmp = IsGreater<T, U>::Test(x, y) ? static_cast<result_type>(x) : static_cast<result_type>(y); *result = static_cast<V>(tmp); return IsValueInRangeForNumericType<V>(tmp); } }; // Min doesn't really need to be implemented this way because it can't fail, // but it makes the code much cleaner to use the MathOp wrappers. template <typename T, typename U, class Enable = void> struct CheckedMinOp {}; template <typename T, typename U> struct CheckedMinOp< T, U, typename std::enable_if<std::is_arithmetic<T>::value && std::is_arithmetic<U>::value>::type> { using result_type = typename LowestValuePromotion<T, U>::type; template <typename V> static constexpr bool Do(T x, U y, V* result) { result_type tmp = IsLess<T, U>::Test(x, y) ? static_cast<result_type>(x) : static_cast<result_type>(y); *result = static_cast<V>(tmp); return IsValueInRangeForNumericType<V>(tmp); } }; // This is just boilerplate that wraps the standard floating point arithmetic. // A macro isn't the nicest solution, but it beats rewriting these repeatedly. #define BASE_FLOAT_ARITHMETIC_OPS(NAME, OP) \ template <typename T, typename U> \ struct Checked##NAME##Op< \ T, U, \ typename std::enable_if<std::is_floating_point<T>::value || \ std::is_floating_point<U>::value>::type> { \ using result_type = typename MaxExponentPromotion<T, U>::type; \ template <typename V> \ static constexpr bool Do(T x, U y, V* result) { \ using Promotion = typename MaxExponentPromotion<T, U>::type; \ Promotion presult = x OP y; \ *result = static_cast<V>(presult); \ return IsValueInRangeForNumericType<V>(presult); \ } \ }; BASE_FLOAT_ARITHMETIC_OPS(Add, +) BASE_FLOAT_ARITHMETIC_OPS(Sub, -) BASE_FLOAT_ARITHMETIC_OPS(Mul, *) BASE_FLOAT_ARITHMETIC_OPS(Div, /) #undef BASE_FLOAT_ARITHMETIC_OPS // Floats carry around their validity state with them, but integers do not. So, // we wrap the underlying value in a specialization in order to hide that detail // and expose an interface via accessors. enum NumericRepresentation { NUMERIC_INTEGER, NUMERIC_FLOATING, NUMERIC_UNKNOWN }; template <typename NumericType> struct GetNumericRepresentation { static const NumericRepresentation value = std::is_integral<NumericType>::value ? NUMERIC_INTEGER : (std::is_floating_point<NumericType>::value ? NUMERIC_FLOATING : NUMERIC_UNKNOWN); }; template <typename T, NumericRepresentation type = GetNumericRepresentation<T>::value> class CheckedNumericState {}; // Integrals require quite a bit of additional housekeeping to manage state. template <typename T> class CheckedNumericState<T, NUMERIC_INTEGER> { private: // is_valid_ precedes value_ because member intializers in the constructors // are evaluated in field order, and is_valid_ must be read when initializing // value_. bool is_valid_; T value_; // Ensures that a type conversion does not trigger undefined behavior. template <typename Src> static constexpr T WellDefinedConversionOrZero(const Src value, const bool is_valid) { using SrcType = typename internal::UnderlyingType<Src>::type; return (std::is_integral<SrcType>::value || is_valid) ? static_cast<T>(value) : static_cast<T>(0); } public: template <typename Src, NumericRepresentation type> friend class CheckedNumericState; constexpr CheckedNumericState() : is_valid_(true), value_(0) {} template <typename Src> constexpr CheckedNumericState(Src value, bool is_valid) : is_valid_(is_valid && IsValueInRangeForNumericType<T>(value)), value_(WellDefinedConversionOrZero(value, is_valid_)) { static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric."); } // Copy constructor. template <typename Src> constexpr CheckedNumericState(const CheckedNumericState<Src>& rhs) : is_valid_(rhs.IsValid()), value_(WellDefinedConversionOrZero(rhs.value(), is_valid_)) {} template <typename Src> constexpr explicit CheckedNumericState(Src value) : is_valid_(IsValueInRangeForNumericType<T>(value)), value_(WellDefinedConversionOrZero(value, is_valid_)) {} constexpr bool is_valid() const { return is_valid_; } constexpr T value() const { return value_; } }; // Floating points maintain their own validity, but need translation wrappers. template <typename T> class CheckedNumericState<T, NUMERIC_FLOATING> { private: T value_; // Ensures that a type conversion does not trigger undefined behavior. template <typename Src> static constexpr T WellDefinedConversionOrNaN(const Src value, const bool is_valid) { using SrcType = typename internal::UnderlyingType<Src>::type; return (StaticDstRangeRelationToSrcRange<T, SrcType>::value == NUMERIC_RANGE_CONTAINED || is_valid) ? static_cast<T>(value) : std::numeric_limits<T>::quiet_NaN(); } public: template <typename Src, NumericRepresentation type> friend class CheckedNumericState; constexpr CheckedNumericState() : value_(0.0) {} template <typename Src> constexpr CheckedNumericState(Src value, bool is_valid) : value_(WellDefinedConversionOrNaN(value, is_valid)) {} template <typename Src> constexpr explicit CheckedNumericState(Src value) : value_(WellDefinedConversionOrNaN( value, IsValueInRangeForNumericType<T>(value))) {} // Copy constructor. template <typename Src> constexpr CheckedNumericState(const CheckedNumericState<Src>& rhs) : value_(WellDefinedConversionOrNaN( rhs.value(), rhs.is_valid() && IsValueInRangeForNumericType<T>(rhs.value()))) {} constexpr bool is_valid() const { // Written this way because std::isfinite is not reliably constexpr. return MustTreatAsConstexpr(value_) ? value_ <= std::numeric_limits<T>::max() && value_ >= std::numeric_limits<T>::lowest() : std::isfinite(value_); } constexpr T value() const { return value_; } }; } // namespace internal } // namespace base #endif // BASE_NUMERICS_CHECKED_MATH_IMPL_H_
engine/third_party/accessibility/base/numerics/checked_math_impl.h/0
{ "file_path": "engine/third_party/accessibility/base/numerics/checked_math_impl.h", "repo_id": "engine", "token_count": 10020 }
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 "string_utils.h" #include <array> #include <cctype> #include <codecvt> #include <locale> #include <regex> #include <sstream> #include "flutter/fml/string_conversion.h" #include "third_party/dart/third_party/double-conversion/src/double-conversion.h" #include "no_destructor.h" namespace base { using double_conversion::DoubleToStringConverter; using double_conversion::StringBuilder; namespace { constexpr char kExponentChar = 'e'; constexpr char kInfinitySymbol[] = "Infinity"; constexpr char kNaNSymbol[] = "NaN"; // The number of digits after the decimal we allow before switching to // exponential representation. constexpr int kDecimalInShortestLow = -6; // The number of digits before the decimal we allow before switching to // exponential representation. constexpr int kDecimalInShortestHigh = 12; constexpr int kConversionFlags = DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN; const DoubleToStringConverter& GetDoubleToStringConverter() { static DoubleToStringConverter converter( kConversionFlags, kInfinitySymbol, kNaNSymbol, kExponentChar, kDecimalInShortestLow, kDecimalInShortestHigh, 0, 0); return converter; } std::string NumberToStringImpl(double number, bool is_single_precision) { if (number == 0.0) { return "0"; } constexpr int kBufferSize = 128; std::array<char, kBufferSize> char_buffer; StringBuilder builder(char_buffer.data(), char_buffer.size()); if (is_single_precision) { GetDoubleToStringConverter().ToShortestSingle(static_cast<float>(number), &builder); } else { GetDoubleToStringConverter().ToShortest(number, &builder); } return std::string(char_buffer.data(), builder.position()); } } // namespace std::u16string ASCIIToUTF16(std::string src) { return std::u16string(src.begin(), src.end()); } std::u16string UTF8ToUTF16(std::string src) { return fml::Utf8ToUtf16(src); } std::string UTF16ToUTF8(std::u16string src) { return fml::Utf16ToUtf8(src); } std::u16string NumberToString16(float number) { return ASCIIToUTF16(NumberToString(number)); } std::u16string NumberToString16(int32_t number) { return ASCIIToUTF16(NumberToString(number)); } std::u16string NumberToString16(unsigned int number) { return ASCIIToUTF16(NumberToString(number)); } std::u16string NumberToString16(double number) { return ASCIIToUTF16(NumberToString(number)); } std::string NumberToString(int32_t number) { return std::to_string(number); } std::string NumberToString(unsigned int number) { return std::to_string(number); } std::string NumberToString(float number) { return NumberToStringImpl(number, true); } std::string NumberToString(double number) { return NumberToStringImpl(number, false); } std::string JoinString(std::vector<std::string> tokens, std::string delimiter) { std::ostringstream imploded; for (size_t i = 0; i < tokens.size(); i++) { if (i == tokens.size() - 1) { imploded << tokens[i]; } else { imploded << tokens[i] << delimiter; } } return imploded.str(); } std::u16string JoinString(std::vector<std::u16string> tokens, std::u16string delimiter) { std::u16string result; for (size_t i = 0; i < tokens.size(); i++) { if (i == tokens.size() - 1) { result.append(tokens[i]); } else { result.append(tokens[i]); result.append(delimiter); } } return result; } void ReplaceChars(std::string in, std::string from, std::string to, std::string* out) { size_t pos = in.find(from); while (pos != std::string::npos) { in.replace(pos, from.size(), to); pos = in.find(from, pos + to.size()); } *out = in; } void ReplaceChars(std::u16string in, std::u16string from, std::u16string to, std::u16string* out) { size_t pos = in.find(from); while (pos != std::u16string::npos) { in.replace(pos, from.size(), to); pos = in.find(from, pos + to.size()); } *out = in; } const std::string& EmptyString() { static const base::NoDestructor<std::string> s; return *s; } std::string ToUpperASCII(std::string str) { std::string ret; ret.reserve(str.size()); for (size_t i = 0; i < str.size(); i++) ret.push_back(std::toupper(str[i])); return ret; } std::string ToLowerASCII(std::string str) { std::string ret; ret.reserve(str.size()); for (size_t i = 0; i < str.size(); i++) ret.push_back(std::tolower(str[i])); return ret; } bool LowerCaseEqualsASCII(std::string a, std::string b) { std::string lower_a = ToLowerASCII(a); return lower_a.compare(ToLowerASCII(b)) == 0; } bool ContainsOnlyChars(std::u16string str, char16_t ch) { return std::find_if(str.begin(), str.end(), [ch](char16_t c) { return c != ch; }) == str.end(); } } // namespace base
engine/third_party/accessibility/base/string_utils.cc/0
{ "file_path": "engine/third_party/accessibility/base/string_utils.cc", "repo_id": "engine", "token_count": 1986 }
414
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/win/scoped_bstr.h" #include <cstddef> #include "gtest/gtest.h" namespace base { namespace win { namespace { constexpr wchar_t kTestString1[] = L"123"; constexpr wchar_t kTestString2[] = L"456789"; constexpr size_t test1_len = std::size(kTestString1) - 1; constexpr size_t test2_len = std::size(kTestString2) - 1; } // namespace TEST(ScopedBstrTest, Empty) { ScopedBstr b; EXPECT_EQ(nullptr, b.Get()); EXPECT_EQ(0u, b.Length()); EXPECT_EQ(0u, b.ByteLength()); b.Reset(nullptr); EXPECT_EQ(nullptr, b.Get()); EXPECT_EQ(nullptr, b.Release()); ScopedBstr b2; b.Swap(b2); EXPECT_EQ(nullptr, b.Get()); } TEST(ScopedBstrTest, Basic) { ScopedBstr b(kTestString1); EXPECT_EQ(test1_len, b.Length()); EXPECT_EQ(test1_len * sizeof(kTestString1[0]), b.ByteLength()); } namespace { void CreateTestString1(BSTR* ret) { *ret = SysAllocString(kTestString1); } } // namespace TEST(ScopedBstrTest, Swap) { ScopedBstr b1(kTestString1); ScopedBstr b2; b1.Swap(b2); EXPECT_EQ(test1_len, b2.Length()); EXPECT_EQ(0u, b1.Length()); EXPECT_STREQ(kTestString1, b2.Get()); BSTR tmp = b2.Release(); EXPECT_NE(nullptr, tmp); EXPECT_STREQ(kTestString1, tmp); EXPECT_EQ(nullptr, b2.Get()); SysFreeString(tmp); } TEST(ScopedBstrTest, OutParam) { ScopedBstr b; CreateTestString1(b.Receive()); EXPECT_STREQ(kTestString1, b.Get()); } TEST(ScopedBstrTest, AllocateBytesAndSetByteLen) { constexpr size_t num_bytes = 100; ScopedBstr b; EXPECT_NE(nullptr, b.AllocateBytes(num_bytes)); EXPECT_EQ(num_bytes, b.ByteLength()); EXPECT_EQ(num_bytes / sizeof(kTestString1[0]), b.Length()); lstrcpy(b.Get(), kTestString1); EXPECT_EQ(test1_len, static_cast<size_t>(lstrlen(b.Get()))); EXPECT_EQ(num_bytes / sizeof(kTestString1[0]), b.Length()); b.SetByteLen(lstrlen(b.Get()) * sizeof(kTestString2[0])); EXPECT_EQ(b.Length(), static_cast<size_t>(lstrlen(b.Get()))); } TEST(ScopedBstrTest, AllocateAndSetByteLen) { ScopedBstr b; EXPECT_NE(nullptr, b.Allocate(kTestString2)); EXPECT_EQ(test2_len, b.Length()); b.SetByteLen((test2_len - 1) * sizeof(kTestString2[0])); EXPECT_EQ(test2_len - 1, b.Length()); } } // namespace win } // namespace base
engine/third_party/accessibility/base/win/scoped_bstr_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/base/win/scoped_bstr_unittest.cc", "repo_id": "engine", "token_count": 1029 }
415
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "insets.h" #include "gtest/gtest.h" #include "insets_f.h" #include "rect.h" #include "size.h" #include "vector2d.h" TEST(InsetsTest, InsetsDefault) { gfx::Insets insets; EXPECT_EQ(0, insets.top()); EXPECT_EQ(0, insets.left()); EXPECT_EQ(0, insets.bottom()); EXPECT_EQ(0, insets.right()); EXPECT_EQ(0, insets.width()); EXPECT_EQ(0, insets.height()); EXPECT_TRUE(insets.IsEmpty()); } TEST(InsetsTest, Insets) { gfx::Insets insets(1, 2, 3, 4); EXPECT_EQ(1, insets.top()); EXPECT_EQ(2, insets.left()); EXPECT_EQ(3, insets.bottom()); EXPECT_EQ(4, insets.right()); EXPECT_EQ(6, insets.width()); // Left + right. EXPECT_EQ(4, insets.height()); // Top + bottom. EXPECT_FALSE(insets.IsEmpty()); } TEST(InsetsTest, SetTop) { gfx::Insets insets(1); insets.set_top(2); EXPECT_EQ(gfx::Insets(2, 1, 1, 1), insets); } TEST(InsetsTest, SetBottom) { gfx::Insets insets(1); insets.set_bottom(2); EXPECT_EQ(gfx::Insets(1, 1, 2, 1), insets); } TEST(InsetsTest, SetLeft) { gfx::Insets insets(1); insets.set_left(2); EXPECT_EQ(gfx::Insets(1, 2, 1, 1), insets); } TEST(InsetsTest, SetRight) { gfx::Insets insets(1); insets.set_right(2); EXPECT_EQ(gfx::Insets(1, 1, 1, 2), insets); } TEST(InsetsTest, Set) { gfx::Insets insets; insets.Set(1, 2, 3, 4); EXPECT_EQ(1, insets.top()); EXPECT_EQ(2, insets.left()); EXPECT_EQ(3, insets.bottom()); EXPECT_EQ(4, insets.right()); } TEST(InsetsTest, Operators) { gfx::Insets insets; insets.Set(1, 2, 3, 4); insets += gfx::Insets(5, 6, 7, 8); EXPECT_EQ(6, insets.top()); EXPECT_EQ(8, insets.left()); EXPECT_EQ(10, insets.bottom()); EXPECT_EQ(12, insets.right()); insets -= gfx::Insets(-1, 0, 1, 2); EXPECT_EQ(7, insets.top()); EXPECT_EQ(8, insets.left()); EXPECT_EQ(9, insets.bottom()); EXPECT_EQ(10, insets.right()); insets = gfx::Insets(10, 10, 10, 10) + gfx::Insets(5, 5, 0, -20); EXPECT_EQ(15, insets.top()); EXPECT_EQ(15, insets.left()); EXPECT_EQ(10, insets.bottom()); EXPECT_EQ(-10, insets.right()); insets = gfx::Insets(10, 10, 10, 10) - gfx::Insets(5, 5, 0, -20); EXPECT_EQ(5, insets.top()); EXPECT_EQ(5, insets.left()); EXPECT_EQ(10, insets.bottom()); EXPECT_EQ(30, insets.right()); } TEST(InsetsFTest, Operators) { gfx::InsetsF insets; insets.Set(1.f, 2.5f, 3.3f, 4.1f); insets += gfx::InsetsF(5.8f, 6.7f, 7.6f, 8.5f); EXPECT_FLOAT_EQ(6.8f, insets.top()); EXPECT_FLOAT_EQ(9.2f, insets.left()); EXPECT_FLOAT_EQ(10.9f, insets.bottom()); EXPECT_FLOAT_EQ(12.6f, insets.right()); insets -= gfx::InsetsF(-1.f, 0, 1.1f, 2.2f); EXPECT_FLOAT_EQ(7.8f, insets.top()); EXPECT_FLOAT_EQ(9.2f, insets.left()); EXPECT_FLOAT_EQ(9.8f, insets.bottom()); EXPECT_FLOAT_EQ(10.4f, insets.right()); insets = gfx::InsetsF(10, 10.1f, 10.01f, 10.001f) + gfx::InsetsF(5.5f, 5.f, 0, -20.2f); EXPECT_FLOAT_EQ(15.5f, insets.top()); EXPECT_FLOAT_EQ(15.1f, insets.left()); EXPECT_FLOAT_EQ(10.01f, insets.bottom()); EXPECT_FLOAT_EQ(-10.199f, insets.right()); insets = gfx::InsetsF(10, 10.1f, 10.01f, 10.001f) - gfx::InsetsF(5.5f, 5.f, 0, -20.2f); EXPECT_FLOAT_EQ(4.5f, insets.top()); EXPECT_FLOAT_EQ(5.1f, insets.left()); EXPECT_FLOAT_EQ(10.01f, insets.bottom()); EXPECT_FLOAT_EQ(30.201f, insets.right()); } TEST(InsetsTest, Equality) { gfx::Insets insets1; insets1.Set(1, 2, 3, 4); gfx::Insets insets2; // Test operator== and operator!=. EXPECT_FALSE(insets1 == insets2); EXPECT_TRUE(insets1 != insets2); insets2.Set(1, 2, 3, 4); EXPECT_TRUE(insets1 == insets2); EXPECT_FALSE(insets1 != insets2); } TEST(InsetsTest, ToString) { gfx::Insets insets(1, 2, 3, 4); EXPECT_EQ("1,2,3,4", insets.ToString()); } TEST(InsetsTest, Offset) { const gfx::Insets insets(1, 2, 3, 4); const gfx::Rect rect(5, 6, 7, 8); const gfx::Vector2d vector(9, 10); // Whether you inset then offset the rect, offset then inset the rect, or // offset the insets then apply to the rect, the outcome should be the same. gfx::Rect inset_first = rect; inset_first.Inset(insets); inset_first.Offset(vector); gfx::Rect offset_first = rect; offset_first.Offset(vector); offset_first.Inset(insets); gfx::Rect inset_by_offset = rect; inset_by_offset.Inset(insets.Offset(vector)); EXPECT_EQ(inset_first, offset_first); EXPECT_EQ(inset_by_offset, inset_first); } TEST(InsetsTest, Scale) { gfx::Insets test(10, 5); test = test.Scale(2.f, 3.f); EXPECT_EQ(gfx::Insets(30, 10), test); test = gfx::Insets(7, 3); test = test.Scale(-2.f, -3.f); EXPECT_EQ(gfx::Insets(-21, -6), test); } TEST(InsetsTest, IntegerOverflow) { constexpr int int_min = std::numeric_limits<int>::min(); constexpr int int_max = std::numeric_limits<int>::max(); gfx::Insets width_height_test(int_max); EXPECT_EQ(int_max, width_height_test.width()); EXPECT_EQ(int_max, width_height_test.height()); gfx::Insets plus_test(int_max); plus_test += gfx::Insets(int_max); EXPECT_EQ(gfx::Insets(int_max), plus_test); gfx::Insets negation_test = -gfx::Insets(int_min); EXPECT_EQ(gfx::Insets(int_max), negation_test); gfx::Insets scale_test(int_max); scale_test = scale_test.Scale(2.f, 2.f); EXPECT_EQ(gfx::Insets(int_max), scale_test); } TEST(InsetsTest, IntegerUnderflow) { constexpr int int_min = std::numeric_limits<int>::min(); constexpr int int_max = std::numeric_limits<int>::max(); gfx::Insets width_height_test = gfx::Insets(int_min); EXPECT_EQ(int_min, width_height_test.width()); EXPECT_EQ(int_min, width_height_test.height()); gfx::Insets minus_test(int_min); minus_test -= gfx::Insets(int_max); EXPECT_EQ(gfx::Insets(int_min), minus_test); gfx::Insets scale_test = gfx::Insets(int_min); scale_test = scale_test.Scale(2.f, 2.f); EXPECT_EQ(gfx::Insets(int_min), scale_test); } TEST(InsetsTest, IntegerOverflowSetVariants) { constexpr int int_max = std::numeric_limits<int>::max(); gfx::Insets set_test(20); set_test.set_top(int_max); EXPECT_EQ(int_max, set_test.top()); EXPECT_EQ(0, set_test.bottom()); set_test.set_left(int_max); EXPECT_EQ(int_max, set_test.left()); EXPECT_EQ(0, set_test.right()); set_test = gfx::Insets(30); set_test.set_bottom(int_max); EXPECT_EQ(int_max - 30, set_test.bottom()); EXPECT_EQ(30, set_test.top()); set_test.set_right(int_max); EXPECT_EQ(int_max - 30, set_test.right()); EXPECT_EQ(30, set_test.left()); } TEST(InsetsTest, IntegerUnderflowSetVariants) { constexpr int int_min = std::numeric_limits<int>::min(); gfx::Insets set_test(-20); set_test.set_top(int_min); EXPECT_EQ(int_min, set_test.top()); EXPECT_EQ(0, set_test.bottom()); set_test.set_left(int_min); EXPECT_EQ(int_min, set_test.left()); EXPECT_EQ(0, set_test.right()); set_test = gfx::Insets(-30); set_test.set_bottom(int_min); EXPECT_EQ(int_min + 30, set_test.bottom()); EXPECT_EQ(-30, set_test.top()); set_test.set_right(int_min); EXPECT_EQ(int_min + 30, set_test.right()); EXPECT_EQ(-30, set_test.left()); } TEST(InsetsTest, IntegerOverflowSet) { constexpr int int_max = std::numeric_limits<int>::max(); gfx::Insets set_all_test; set_all_test.Set(10, 20, int_max, int_max); EXPECT_EQ(gfx::Insets(10, 20, int_max - 10, int_max - 20), set_all_test); } TEST(InsetsTest, IntegerOverflowOffset) { constexpr int int_max = std::numeric_limits<int>::max(); const gfx::Vector2d max_vector(int_max, int_max); gfx::Insets insets(1, 2, 3, 4); gfx::Insets offset_test = insets.Offset(max_vector); EXPECT_EQ(gfx::Insets(int_max, int_max, 3 - int_max, 4 - int_max), offset_test); } TEST(InsetsTest, IntegerUnderflowOffset) { constexpr int int_min = std::numeric_limits<int>::min(); const gfx::Vector2d min_vector(int_min, int_min); gfx::Insets insets(-10); gfx::Insets offset_test = insets.Offset(min_vector); EXPECT_EQ(gfx::Insets(int_min, int_min, -10 - int_min, -10 - int_min), offset_test); } TEST(InsetsTest, Size) { gfx::Insets insets(1, 2, 3, 4); EXPECT_EQ(gfx::Size(6, 4), insets.size()); }
engine/third_party/accessibility/gfx/geometry/insets_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/insets_unittest.cc", "repo_id": "engine", "token_count": 3766 }
416
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_GEOMETRY_SIZE_H_ #define UI_GFX_GEOMETRY_SIZE_H_ #include <algorithm> #include <iosfwd> #include <string> #include "ax_build/build_config.h" #include "base/compiler_specific.h" #include "base/numerics/safe_math.h" #include "gfx/gfx_export.h" #if defined(OS_WIN) typedef struct tagSIZE SIZE; #elif defined(OS_APPLE) typedef struct CGSize CGSize; #endif namespace gfx { // A size has width and height values. class GFX_EXPORT Size { public: constexpr Size() : width_(0), height_(0) {} constexpr Size(int width, int height) : width_(std::max(0, width)), height_(std::max(0, height)) {} #if defined(OS_APPLE) explicit Size(const CGSize& s); #endif #if defined(OS_APPLE) Size& operator=(const CGSize& s); #endif void operator+=(const Size& size); void operator-=(const Size& size); #if defined(OS_WIN) SIZE ToSIZE() const; #elif defined(OS_APPLE) CGSize ToCGSize() const; #endif constexpr int width() const { return width_; } constexpr int height() const { return height_; } void set_width(int width) { width_ = std::max(0, width); } void set_height(int height) { height_ = std::max(0, height); } // This call will CHECK if the area of this size would overflow int. int GetArea() const; // Returns a checked numeric representation of the area. base::CheckedNumeric<int> GetCheckedArea() const; void SetSize(int width, int height) { set_width(width); set_height(height); } void Enlarge(int grow_width, int grow_height); void SetToMin(const Size& other); void SetToMax(const Size& other); bool IsEmpty() const { return !width() || !height(); } std::string ToString() const; private: int width_; int height_; }; inline bool operator==(const Size& lhs, const Size& rhs) { return lhs.width() == rhs.width() && lhs.height() == rhs.height(); } inline bool operator!=(const Size& lhs, const Size& rhs) { return !(lhs == rhs); } inline Size operator+(Size lhs, const Size& rhs) { lhs += rhs; return lhs; } inline Size operator-(Size lhs, const Size& rhs) { lhs -= rhs; return lhs; } // 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 Size& size, ::std::ostream* os); // Helper methods to scale a gfx::Size to a new gfx::Size. GFX_EXPORT Size ScaleToCeiledSize(const Size& size, float x_scale, float y_scale); GFX_EXPORT Size ScaleToCeiledSize(const Size& size, float scale); GFX_EXPORT Size ScaleToFlooredSize(const Size& size, float x_scale, float y_scale); GFX_EXPORT Size ScaleToFlooredSize(const Size& size, float scale); GFX_EXPORT Size ScaleToRoundedSize(const Size& size, float x_scale, float y_scale); GFX_EXPORT Size ScaleToRoundedSize(const Size& size, float scale); } // namespace gfx #endif // UI_GFX_GEOMETRY_SIZE_H_
engine/third_party/accessibility/gfx/geometry/size.h/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/size.h", "repo_id": "engine", "token_count": 1081 }
417
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ACCESSIBILITY_GFX_NATIVE_WIDGET_TYPES_H_ #define ACCESSIBILITY_GFX_NATIVE_WIDGET_TYPES_H_ #include <cstdint> #include "ax_build/build_config.h" #include "gfx/gfx_export.h" #if defined(OS_ANDROID) #include "base/android/scoped_java_ref.h" #elif defined(OS_APPLE) #include <objc/objc.h> #elif defined(OS_WIN) #include "base/win/windows_types.h" #endif // This file provides cross platform typedefs for native widget types. // NativeWindow: this is a handle to a native, top-level window // NativeView: this is a handle to a native UI element. It may be the // same type as a NativeWindow on some platforms. // NativeViewId: Often, in our cross process model, we need to pass around a // reference to a "window". This reference will, say, be echoed back from a // renderer to the browser when it wishes to query its size. On Windows we // use an HWND for this. // // As a rule of thumb - if you're in the renderer, you should be dealing // with NativeViewIds. This should remind you that you shouldn't be doing // direct operations on platform widgets from the renderer process. // // If you're in the browser, you're probably dealing with NativeViews, // unless you're in the IPC layer, which will be translating between // NativeViewIds from the renderer and NativeViews. // // The name 'View' here meshes with OS X where the UI elements are called // 'views' and with our Chrome UI code where the elements are also called // 'views'. #if defined(USE_AURA) namespace aura { class Window; } namespace ui { class Cursor; class Event; namespace mojom { enum class CursorType; } } // namespace ui #endif // defined(USE_AURA) #if defined(OS_WIN) typedef struct HFONT__* HFONT; struct IAccessible; #elif defined(OS_IOS) struct CGContext; #ifdef __OBJC__ @class UIEvent; @class UIFont; @class UIImage; @class UIView; @class UIWindow; @class UITextField; #else class UIEvent; class UIFont; class UIImage; class UIView; class UIWindow; class UITextField; #endif // __OBJC__ #elif defined(OS_MAC) struct CGContext; #ifdef __OBJC__ @class NSCursor; @class NSEvent; @class NSFont; @class NSImage; @class NSView; @class NSWindow; @class NSTextField; #else class NSCursor; class NSEvent; class NSFont; class NSImage; struct NSView; class NSWindow; class NSTextField; #endif // __OBJC__ #endif #if defined(OS_ANDROID) struct ANativeWindow; namespace ui { class WindowAndroid; class ViewAndroid; } // namespace ui #endif class SkBitmap; #if defined(OS_LINUX) && !defined(OS_CHROMEOS) extern "C" { struct _AtkObject; typedef struct _AtkObject AtkObject; } #endif namespace gfx { #if defined(USE_AURA) typedef ui::Cursor NativeCursor; typedef aura::Window* NativeView; typedef aura::Window* NativeWindow; typedef ui::Event* NativeEvent; constexpr NativeView kNullNativeView = nullptr; constexpr NativeWindow kNullNativeWindow = nullptr; #elif defined(OS_IOS) typedef void* NativeCursor; typedef UIView* NativeView; typedef UIWindow* NativeWindow; typedef UIEvent* NativeEvent; constexpr NativeView kNullNativeView = nullptr; constexpr NativeWindow kNullNativeWindow = nullptr; #elif defined(OS_MAC) typedef NSCursor* NativeCursor; typedef NSEvent* NativeEvent; // NativeViews and NativeWindows on macOS are not necessarily in the same // process as the NSViews and NSWindows that they represent. Require an // explicit function call (GetNativeNSView or GetNativeNSWindow) to retrieve // the underlying NSView or NSWindow. // https://crbug.com/893719 class GFX_EXPORT NativeView { public: constexpr NativeView() {} // TODO(ccameron): Make this constructor explicit. constexpr NativeView(NSView* ns_view) : ns_view_(ns_view) {} // This function name is verbose (that is, not just GetNSView) so that it // is easily grep-able. NSView* GetNativeNSView() const { return ns_view_; } operator bool() const { return ns_view_ != 0; } bool operator==(const NativeView& other) const { return ns_view_ == other.ns_view_; } bool operator!=(const NativeView& other) const { return ns_view_ != other.ns_view_; } bool operator<(const NativeView& other) const { return ns_view_ < other.ns_view_; } private: NSView* ns_view_ = nullptr; }; class GFX_EXPORT NativeWindow { public: constexpr NativeWindow() {} // TODO(ccameron): Make this constructor explicit. constexpr NativeWindow(NSWindow* ns_window) : ns_window_(ns_window) {} // This function name is verbose (that is, not just GetNSWindow) so that it // is easily grep-able. NSWindow* GetNativeNSWindow() const { return ns_window_; } operator bool() const { return ns_window_ != 0; } bool operator==(const NativeWindow& other) const { return ns_window_ == other.ns_window_; } bool operator!=(const NativeWindow& other) const { return ns_window_ != other.ns_window_; } bool operator<(const NativeWindow& other) const { return ns_window_ < other.ns_window_; } private: NSWindow* ns_window_ = nullptr; }; const NativeView kNullNativeView = NativeView(nullptr); const NativeWindow kNullNativeWindow = NativeWindow(nullptr); #elif defined(OS_ANDROID) typedef void* NativeCursor; typedef ui::ViewAndroid* NativeView; typedef ui::WindowAndroid* NativeWindow; typedef base::android::ScopedJavaGlobalRef<jobject> NativeEvent; constexpr NativeView kNullNativeView = nullptr; constexpr NativeWindow kNullNativeWindow = nullptr; #elif defined(OS_LINUX) // TODO(chunhtai): Figures out what is the correct type for Linux // https://github.com/flutter/flutter/issues/74270 typedef void* NativeCursor; #elif defined(OS_WIN) typedef void* NativeCursor; typedef void* NativeView; typedef void* NativeWindow; typedef void* NativeEvent; constexpr NativeView kNullNativeView = nullptr; constexpr NativeWindow kNullNativeWindow = nullptr; #else #error Unknown build environment. #endif #if defined(OS_WIN) typedef HFONT NativeFont; typedef IAccessible* NativeViewAccessible; #elif defined(OS_IOS) typedef UIFont* NativeFont; typedef id NativeViewAccessible; #elif defined(OS_MAC) typedef NSFont* NativeFont; typedef id NativeViewAccessible; #elif defined(OS_LINUX) && !defined(OS_CHROMEOS) // Linux doesn't have a native font type. typedef AtkObject* NativeViewAccessible; #else // Android, Chrome OS, etc. typedef struct _UnimplementedNativeViewAccessible UnimplementedNativeViewAccessible; typedef UnimplementedNativeViewAccessible* NativeViewAccessible; #endif // A constant value to indicate that gfx::NativeCursor refers to no cursor. #if defined(USE_AURA) const ui::mojom::CursorType kNullCursor = static_cast<ui::mojom::CursorType>(-1); #else const gfx::NativeCursor kNullCursor = static_cast<gfx::NativeCursor>(nullptr); #endif // Note: for test_shell we're packing a pointer into the NativeViewId. So, if // you make it a type which is smaller than a pointer, you have to fix // test_shell. // // See comment at the top of the file for usage. typedef intptr_t NativeViewId; // AcceleratedWidget provides a surface to compositors to paint pixels. #if defined(OS_WIN) typedef HWND AcceleratedWidget; constexpr AcceleratedWidget kNullAcceleratedWidget = nullptr; #elif defined(OS_IOS) typedef UIView* AcceleratedWidget; constexpr AcceleratedWidget kNullAcceleratedWidget = 0; #elif defined(OS_MAC) typedef uint64_t AcceleratedWidget; constexpr AcceleratedWidget kNullAcceleratedWidget = 0; #elif defined(OS_ANDROID) typedef ANativeWindow* AcceleratedWidget; constexpr AcceleratedWidget kNullAcceleratedWidget = 0; #elif defined(USE_OZONE) || defined(USE_X11) typedef uint32_t AcceleratedWidget; constexpr AcceleratedWidget kNullAcceleratedWidget = 0; #elif defined(OS_LINUX) // TODO(chunhtai): Figure out what the correct type is for the Linux. // https://github.com/flutter/flutter/issues/74270 typedef void* AcceleratedWidget; constexpr AcceleratedWidget kNullAcceleratedWidget = nullptr; #else #error unknown platform #endif } // namespace gfx #endif // ACCESSIBILITY_GFX_NATIVE_WIDGET_TYPES_H_
engine/third_party/accessibility/gfx/native_widget_types.h/0
{ "file_path": "engine/third_party/accessibility/gfx/native_widget_types.h", "repo_id": "engine", "token_count": 2711 }
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. #include <cmath> #import "flutter/third_party/spring_animation/spring_animation.h" #include "gtest/gtest.h" TEST(SpringAnimationTest, CanInitializeCorrectly) { SpringAnimation* animation = [[SpringAnimation alloc] initWithStiffness:1000 damping:500 mass:3 initialVelocity:0 fromValue:0 toValue:1000]; ASSERT_TRUE(animation.stiffness == 1000); ASSERT_TRUE(animation.damping == 500); ASSERT_TRUE(animation.mass == 3); ASSERT_TRUE(animation.initialVelocity == 0); ASSERT_TRUE(animation.fromValue == 0); ASSERT_TRUE(animation.toValue == 1000); } TEST(SpringAnimationTest, CurveFunctionCanWorkCorrectly) { // Here is the keyboard curve config on iOS platform. SpringAnimation* animation = [[SpringAnimation alloc] initWithStiffness:1000 damping:500 mass:3 initialVelocity:0 fromValue:0 toValue:1000]; const double accuracy = 1.0; const double startTime = 0; const double endTime = 0.6; const double startValue = [animation curveFunction:startTime]; ASSERT_TRUE(fabs(startValue - animation.fromValue) < accuracy); const double toValue = [animation curveFunction:endTime]; ASSERT_TRUE(fabs(toValue - animation.toValue) < accuracy); } TEST(SpringAnimationTest, CanUpdatePositionValuesAndCalculateCorrectly) { SpringAnimation* animation = [[SpringAnimation alloc] initWithStiffness:1000 damping:500 mass:3 initialVelocity:0 fromValue:0 toValue:1000]; const double startTime = 0; const double endTime = 0.6; const double startValue1 = [animation curveFunction:startTime]; const double toValue1 = [animation curveFunction:endTime]; animation.fromValue = 10; animation.toValue = 800; ASSERT_TRUE(animation.fromValue == 10); ASSERT_TRUE(animation.toValue == 800); const double startValue2 = [animation curveFunction:startTime]; const double toValue2 = [animation curveFunction:endTime]; ASSERT_TRUE(startValue2 > startValue1); ASSERT_TRUE(toValue2 < toValue1); }
engine/third_party/spring_animation/SpringAnimationTest.mm/0
{ "file_path": "engine/third_party/spring_animation/SpringAnimationTest.mm", "repo_id": "engine", "token_count": 1619 }
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. #ifndef LIB_CONVERTER_TONIC_DART_CONVERTER_H_ #define LIB_CONVERTER_TONIC_DART_CONVERTER_H_ #include <string> #include <type_traits> #include <vector> #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/common/macros.h" #include "tonic/logging/dart_error.h" namespace tonic { // DartConvert converts types back and forth from Sky to Dart. The template // parameter |T| determines what kind of type conversion to perform. template <typename T, typename Enable = void> struct DartConverter {}; // This is to work around the fact that typedefs do not create new types. If you // have a typedef, and want it to use a different converter, specialize this // template and override the types here. // Ex: // typedef int ColorType; // Want to use a different converter. // class ColorConverterType {}; // Dummy type. // template<> struct DartConvertType<ColorConverterType> { // using ConverterType = ColorConverterType; // using ValueType = ColorType; // }; template <typename T> struct DartConverterTypes { using ConverterType = T; using ValueType = T; }; template <> struct DartConverter<void> { using FfiType = void; static constexpr const char* kFfiRepresentation = "Void"; static constexpr const char* kDartRepresentation = "void"; static constexpr bool kAllowedInLeafCall = true; static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } }; //////////////////////////////////////////////////////////////////////////////// // Boolean template <> struct DartConverter<bool> { using NativeType = bool; using FfiType = bool; static constexpr const char* kFfiRepresentation = "Bool"; static constexpr const char* kDartRepresentation = "bool"; static constexpr bool kAllowedInLeafCall = true; static Dart_Handle ToDart(NativeType val) { return Dart_NewBoolean(val); } static void SetReturnValue(Dart_NativeArguments args, bool val) { Dart_SetBooleanReturnValue(args, val); } static NativeType FromDart(Dart_Handle handle) { bool result = 0; Dart_BooleanValue(handle, &result); return result; } static NativeType FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { bool result = false; Dart_GetNativeBooleanArgument(args, index, &result); return result; } static NativeType FromFfi(FfiType val) { return val; } static FfiType ToFfi(NativeType val) { return val; } static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } }; //////////////////////////////////////////////////////////////////////////////// // Numbers template <typename T> struct DartConverterInteger { using FfiType = T; static constexpr const char* kDartRepresentation = "int"; static constexpr bool kAllowedInLeafCall = true; static Dart_Handle ToDart(T val) { return Dart_NewInteger(val); } static void SetReturnValue(Dart_NativeArguments args, T val) { Dart_SetIntegerReturnValue(args, val); } static T FromDart(Dart_Handle handle) { int64_t result = 0; Dart_IntegerToInt64(handle, &result); return static_cast<T>(result); } static T FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { int64_t result = 0; Dart_GetNativeIntegerArgument(args, index, &result); return static_cast<T>(result); } static T FromFfi(FfiType val) { return val; } static FfiType ToFfi(T val) { return val; } static const char* GetDartRepresentation() { return kDartRepresentation; } // Note: Returns the correct bit-width for the host architecture. static const char* GetFfiRepresentation() { if (sizeof(T) == 4) { if (std::is_signed<T>()) { return "Int32"; } return "Uint32"; } TONIC_DCHECK(sizeof(T) == 8); if (std::is_signed<T>()) { return "Int64"; } return "Uint64"; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } }; template <> struct DartConverter<int> : public DartConverterInteger<int> {}; template <> struct DartConverter<long int> : public DartConverterInteger<long int> {}; template <> struct DartConverter<unsigned> : public DartConverterInteger<unsigned> {}; template <> struct DartConverter<long long> : public DartConverterInteger<long long> {}; template <> struct DartConverter<unsigned long> : public DartConverterInteger<unsigned long> {}; template <> struct DartConverter<unsigned long long> { using FfiType = unsigned long long; static constexpr const char* kFfiRepresentation = "Uint64"; static constexpr const char* kDartRepresentation = "int"; static constexpr bool kAllowedInLeafCall = true; // TODO(abarth): The Dart VM API doesn't yet have an entry-point for // an unsigned 64-bit type. We will need to add a Dart API for // constructing an integer from uint64_t. // // (In the meantime, we have asserts below to check that we're never // converting values that have the 64th bit set.) static Dart_Handle ToDart(unsigned long long val) { TONIC_DCHECK(val <= 0x7fffffffffffffffLL); return Dart_NewInteger(static_cast<int64_t>(val)); } static void SetReturnValue(Dart_NativeArguments args, unsigned long long val) { TONIC_DCHECK(val <= 0x7fffffffffffffffLL); Dart_SetIntegerReturnValue(args, val); } static unsigned long long FromDart(Dart_Handle handle) { int64_t result = 0; Dart_IntegerToInt64(handle, &result); return result; } static unsigned long long FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { int64_t result = 0; Dart_GetNativeIntegerArgument(args, index, &result); return result; } static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } static FfiType FromFfi(FfiType val) { TONIC_DCHECK(val <= 0x7fffffffffffffffLL); return val; } // FFI does a bitwise conversion from uint64_t in C to int64 in Dart. static FfiType ToFfi(FfiType val) { TONIC_DCHECK(val <= 0x7fffffffffffffffLL); return val; } }; // There is intentionally no DartConverter<float>, to avoid UB when Dart code // gives us a double that is greater than the max float or less than -max float. template <> struct DartConverter<double> { using FfiType = double; static constexpr const char* kFfiRepresentation = "Double"; static constexpr const char* kDartRepresentation = "double"; static constexpr bool kAllowedInLeafCall = true; static Dart_Handle ToDart(double val) { return Dart_NewDouble(val); } static void SetReturnValue(Dart_NativeArguments args, double val) { Dart_SetDoubleReturnValue(args, val); } static double FromDart(Dart_Handle handle) { double result = 0; Dart_DoubleValue(handle, &result); return result; } static double FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { double result = 0; Dart_GetNativeDoubleArgument(args, index, &result); return result; } static double FromFfi(FfiType val) { return val; } static FfiType ToFfi(double val) { return val; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } }; //////////////////////////////////////////////////////////////////////////////// // Enum Classes template <typename T> struct DartConverter<T, typename std::enable_if<std::is_enum<T>::value>::type> { using FfiType = int32_t; static constexpr const char* kFfiRepresentation = "Int32"; static constexpr const char* kDartRepresentation = "int"; static constexpr bool kAllowedInLeafCall = true; static Dart_Handle ToDart(T val) { return Dart_NewInteger( static_cast<typename std::underlying_type<T>::type>(val)); } static void SetReturnValue(Dart_NativeArguments args, T val) { Dart_SetIntegerReturnValue( args, static_cast<typename std::underlying_type<T>::type>(val)); } static T FromDart(Dart_Handle handle) { int64_t result = 0; Dart_IntegerToInt64(handle, &result); return static_cast<T>(result); } static T FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { int64_t result = 0; Dart_GetNativeIntegerArgument(args, index, &result); return static_cast<T>(result); } static T FromFfi(FfiType val) { return static_cast<T>(val); } static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } }; //////////////////////////////////////////////////////////////////////////////// // Strings template <> struct DartConverter<std::string> { using NativeType = std::string; using FfiType = Dart_Handle; static constexpr const char* kFfiRepresentation = "Handle"; static constexpr const char* kDartRepresentation = "String"; static constexpr bool kAllowedInLeafCall = false; static Dart_Handle ToDart(const NativeType& val) { return Dart_NewStringFromUTF8(reinterpret_cast<const uint8_t*>(val.data()), val.length()); } static void SetReturnValue(Dart_NativeArguments args, const NativeType& val) { Dart_SetReturnValue(args, ToDart(val)); } static NativeType FromDart(Dart_Handle handle) { if (Dart_IsNull(handle)) { return std::string(); } uint8_t* data = nullptr; intptr_t length = 0; if (Dart_IsError(Dart_StringToUTF8(handle, &data, &length))) return std::string(); return std::string(reinterpret_cast<char*>(data), length); } static NativeType FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { return FromDart(Dart_GetNativeArgument(args, index)); } static NativeType FromFfi(FfiType val) { return FromDart(val); } static FfiType ToFfi(NativeType val) { return ToDart(val); } static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } }; template <> struct DartConverter<std::u16string> { using NativeType = std::u16string; using FfiType = Dart_Handle; static constexpr const char* kFfiRepresentation = "Handle"; static constexpr const char* kDartRepresentation = "String"; static constexpr bool kAllowedInLeafCall = false; static Dart_Handle ToDart(const NativeType& val) { return Dart_NewStringFromUTF16( reinterpret_cast<const uint16_t*>(val.data()), val.length()); } static void SetReturnValue(Dart_NativeArguments args, const NativeType& val) { Dart_SetReturnValue(args, ToDart(val)); } static NativeType FromDart(Dart_Handle handle) { if (Dart_IsNull(handle)) { return std::u16string(); } intptr_t length = 0; Dart_StringLength(handle, &length); std::vector<uint16_t> data(length); Dart_StringToUTF16(handle, data.data(), &length); return std::u16string(reinterpret_cast<char16_t*>(data.data()), length); } static NativeType FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { return FromDart(Dart_GetNativeArgument(args, index)); } static NativeType FromFfi(FfiType val) { return FromDart(val); } static FfiType ToFfi(NativeType val) { return ToDart(val); } static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } }; template <> struct DartConverter<const char*> { static Dart_Handle ToDart(const char* val) { return Dart_NewStringFromCString(val); } static void SetReturnValue(Dart_NativeArguments args, const char* val) { Dart_SetReturnValue(args, ToDart(val)); } static const char* FromDart(Dart_Handle handle) { if (Dart_IsNull(handle)) { return nullptr; } const char* result = nullptr; Dart_StringToCString(handle, &result); return result; } static const char* FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { return FromDart(Dart_GetNativeArgument(args, index)); } }; //////////////////////////////////////////////////////////////////////////////// // Collections inline Dart_Handle LookupNonNullableType(const std::string& library_name, const std::string& type_name) { auto library = Dart_LookupLibrary(DartConverter<std::string>::ToDart(library_name)); if (CheckAndHandleError(library)) { return library; } auto type_string = DartConverter<std::string>::ToDart(type_name); if (CheckAndHandleError(type_string)) { return type_string; } auto type = Dart_GetNonNullableType(library, type_string, 0, nullptr); if (CheckAndHandleError(type)) { return type; } return type; } template <typename T, std::enable_if_t<std::is_same<std::string, T>::value, int> = 0> Dart_Handle ToDartTypeHandle() { return LookupNonNullableType("dart:core", "String"); } template <typename T, std::enable_if_t<std::is_integral<T>::value, int> = 0> Dart_Handle ToDartTypeHandle() { return LookupNonNullableType("dart:core", "int"); } template <typename T, std::enable_if_t<std::is_floating_point<T>::value, int> = 0> Dart_Handle ToDartTypeHandle() { return LookupNonNullableType("dart:core", "double"); } template <typename T> Dart_Handle CreateZeroInitializedDartObject( Dart_Handle type_handle_or_null = ::Dart_Null()) { if constexpr (std::is_same<std::string, T>::value) { return ::Dart_EmptyString(); } else if constexpr (std::is_integral<T>::value) { return ::Dart_NewIntegerFromUint64(0u); } else if constexpr (std::is_floating_point<T>::value) { return ::Dart_NewDouble(0.0); } else { auto object = ::Dart_New(type_handle_or_null, ::Dart_Null(), 0, nullptr); CheckAndHandleError(object); return object; } return ::Dart_Null(); } template <typename T, typename Enable = void> struct DartListFactory { static Dart_Handle NewList(Dart_Handle type_handle, intptr_t length) { bool is_nullable = false; auto is_nullable_handle = ::Dart_IsNullableType(type_handle, &is_nullable); if (CheckAndHandleError(is_nullable_handle)) { return is_nullable_handle; } if (is_nullable) { auto list = ::Dart_NewListOfType(type_handle, length); CheckAndHandleError(list); return list; } else { auto sentinel = CreateZeroInitializedDartObject<T>(type_handle); if (CheckAndHandleError(sentinel)) { return sentinel; } auto list = ::Dart_NewListOfTypeFilled(type_handle, sentinel, length); CheckAndHandleError(list); return list; } return ::Dart_Null(); } }; template <typename T> struct DartConverter<std::vector<T>> { using FfiType = Dart_Handle; static constexpr const char* kFfiRepresentation = "Handle"; static constexpr const char* kDartRepresentation = "List"; static constexpr bool kAllowedInLeafCall = false; using ValueType = typename DartConverterTypes<T>::ValueType; using ConverterType = typename DartConverterTypes<T>::ConverterType; static Dart_Handle ToDart(const std::vector<ValueType>& val) { Dart_Handle list = DartListFactory<ValueType>::NewList( ToDartTypeHandle<ValueType>(), val.size()); if (Dart_IsError(list)) return list; for (size_t i = 0; i < val.size(); i++) { Dart_Handle result = Dart_ListSetAt(list, i, DartConverter<ConverterType>::ToDart(val[i])); if (Dart_IsError(result)) return result; } return list; } static void SetReturnValue(Dart_NativeArguments args, const std::vector<ValueType>& val) { Dart_SetReturnValue(args, ToDart(val)); } static std::vector<ValueType> FromDart(Dart_Handle handle) { std::vector<ValueType> result; if (!Dart_IsList(handle)) return result; intptr_t length = 0; Dart_ListLength(handle, &length); if (length == 0) return result; result.reserve(length); std::vector<Dart_Handle> items(length); Dart_Handle items_result = Dart_ListGetRange(handle, 0, length, items.data()); TONIC_DCHECK(!Dart_IsError(items_result)); for (intptr_t i = 0; i < length; ++i) { TONIC_DCHECK(items[i]); result.push_back(DartConverter<ConverterType>::FromDart(items[i])); } return result; } static std::vector<ValueType> FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { return FromDart(Dart_GetNativeArgument(args, index)); } static std::vector<ValueType> FromFfi(FfiType val) { return FromDart(val); } static FfiType ToFfi(std::vector<ValueType> val) { return ToDart(val); } static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } }; //////////////////////////////////////////////////////////////////////////////// // Dart_Handle template <> struct DartConverter<Dart_Handle> { using NativeType = Dart_Handle; using FfiType = Dart_Handle; static constexpr const char* kFfiRepresentation = "Handle"; static constexpr const char* kDartRepresentation = "Object"; static constexpr bool kAllowedInLeafCall = false; static Dart_Handle ToDart(NativeType val) { return val; } static void SetReturnValue(Dart_NativeArguments args, Dart_Handle val) { Dart_SetReturnValue(args, val); } static NativeType FromDart(Dart_Handle handle) { return handle; } static NativeType FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { Dart_Handle result = Dart_GetNativeArgument(args, index); TONIC_DCHECK(!Dart_IsError(result)); return result; } static NativeType FromFfi(FfiType val) { return val; } static FfiType ToFfi(NativeType val) { return val; } static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } }; //////////////////////////////////////////////////////////////////////////////// // Convenience wrappers using type inference template <typename T> Dart_Handle ToDart(const T& object) { return DartConverter<T>::ToDart(object); } //////////////////////////////////////////////////////////////////////////////// // std::string support inline Dart_Handle StdStringToDart(const std::string& val) { return DartConverter<std::string>::ToDart(val); } inline std::string StdStringFromDart(Dart_Handle handle) { return DartConverter<std::string>::FromDart(handle); } // Alias Dart_NewStringFromCString for less typing. inline Dart_Handle ToDart(const char* val) { return Dart_NewStringFromCString(val); } } // namespace tonic #endif // LIB_CONVERTER_TONIC_DART_CONVERTER_H_
engine/third_party/tonic/converter/dart_converter.h/0
{ "file_path": "engine/third_party/tonic/converter/dart_converter.h", "repo_id": "engine", "token_count": 7443 }
420
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIB_TONIC_DART_PERSISTENT_VALUE_H_ #define LIB_TONIC_DART_PERSISTENT_VALUE_H_ #include <memory> #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/common/macros.h" namespace tonic { class DartState; // DartPersistentValue is a bookkeeping class to help pair calls to // Dart_NewPersistentHandle with Dart_DeletePersistentHandle. Consider using // this class instead of holding a Dart_PersistentHandle directly so that you // don't leak the Dart_PersistentHandle. class DartPersistentValue { public: DartPersistentValue(); DartPersistentValue(DartPersistentValue&& other); DartPersistentValue(DartState* dart_state, Dart_Handle value); ~DartPersistentValue(); Dart_PersistentHandle value() const { return value_; } bool is_empty() const { return !value_; } void Set(DartState* dart_state, Dart_Handle value); void Clear(); Dart_Handle Get(); Dart_Handle Release(); const std::weak_ptr<DartState>& dart_state() const { return dart_state_; } private: std::weak_ptr<DartState> dart_state_; Dart_PersistentHandle value_; TONIC_DISALLOW_COPY_AND_ASSIGN(DartPersistentValue); }; } // namespace tonic #endif // LIB_TONIC_DART_PERSISTENT_VALUE_H_
engine/third_party/tonic/dart_persistent_value.h/0
{ "file_path": "engine/third_party/tonic/dart_persistent_value.h", "repo_id": "engine", "token_count": 448 }
421
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FILESYSTEM_EINTR_WRAPPER_H_ #define FILESYSTEM_EINTR_WRAPPER_H_ #include <cerrno> #include "tonic/common/build_config.h" #if defined(OS_WIN) // Windows has no concept of EINTR. #define HANDLE_EINTR(x) (x) #define IGNORE_EINTR(x) (x) #else #if defined(NDEBUG) #define HANDLE_EINTR(x) \ ({ \ decltype(x) eintr_wrapper_result; \ do { \ eintr_wrapper_result = (x); \ } while (eintr_wrapper_result == -1 && errno == EINTR); \ eintr_wrapper_result; \ }) #else #define HANDLE_EINTR(x) \ ({ \ int eintr_wrapper_counter = 0; \ decltype(x) eintr_wrapper_result; \ do { \ eintr_wrapper_result = (x); \ } while (eintr_wrapper_result == -1 && errno == EINTR && \ eintr_wrapper_counter++ < 100); \ eintr_wrapper_result; \ }) #endif // NDEBUG #define IGNORE_EINTR(x) \ ({ \ decltype(x) eintr_wrapper_result; \ do { \ eintr_wrapper_result = (x); \ if (eintr_wrapper_result == -1 && errno == EINTR) { \ eintr_wrapper_result = 0; \ } \ } while (0); \ eintr_wrapper_result; \ }) #endif // defined(OS_WIN) #endif // FILESYSTEM_EINTR_WRAPPER_H_
engine/third_party/tonic/filesystem/filesystem/eintr_wrapper.h/0
{ "file_path": "engine/third_party/tonic/filesystem/filesystem/eintr_wrapper.h", "repo_id": "engine", "token_count": 1430 }
422
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tonic/logging/dart_invoke.h" #include "tonic/common/macros.h" #include "tonic/logging/dart_error.h" namespace tonic { Dart_Handle DartInvokeField(Dart_Handle target, const char* name, std::initializer_list<Dart_Handle> args) { Dart_Handle field = Dart_NewStringFromCString(name); return Dart_Invoke(target, field, args.size(), const_cast<Dart_Handle*>(args.begin())); } Dart_Handle DartInvoke(Dart_Handle closure, std::initializer_list<Dart_Handle> args) { int argc = args.size(); Dart_Handle* argv = const_cast<Dart_Handle*>(args.begin()); Dart_Handle handle = Dart_InvokeClosure(closure, argc, argv); CheckAndHandleError(handle); return handle; } Dart_Handle DartInvokeVoid(Dart_Handle closure) { Dart_Handle handle = Dart_InvokeClosure(closure, 0, nullptr); CheckAndHandleError(handle); return handle; } } // namespace tonic
engine/third_party/tonic/logging/dart_invoke.cc/0
{ "file_path": "engine/third_party/tonic/logging/dart_invoke.cc", "repo_id": "engine", "token_count": 449 }
423
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIB_TONIC_TYPED_DATA_FLOAT64_LIST_H_ #define LIB_TONIC_TYPED_DATA_FLOAT64_LIST_H_ #warning float64_list.h is deprecated; use typed_list.h instead. #include "tonic/typed_data/typed_list.h" #endif // LIB_TONIC_TYPED_DATA_FLOAT64_LIST_H_
engine/third_party/tonic/typed_data/float64_list.h/0
{ "file_path": "engine/third_party/tonic/typed_data/float64_list.h", "repo_id": "engine", "token_count": 157 }
424
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "txt/asset_font_manager.h" #include <memory> #include "flutter/fml/logging.h" #include "third_party/skia/include/core/SkString.h" #include "third_party/skia/include/core/SkTypeface.h" namespace txt { AssetFontManager::AssetFontManager( std::unique_ptr<FontAssetProvider> font_provider) : font_provider_(std::move(font_provider)) { FML_DCHECK(font_provider_ != nullptr); } AssetFontManager::~AssetFontManager() = default; int AssetFontManager::onCountFamilies() const { return font_provider_->GetFamilyCount(); } void AssetFontManager::onGetFamilyName(int index, SkString* familyName) const { familyName->set(font_provider_->GetFamilyName(index).c_str()); } sk_sp<SkFontStyleSet> AssetFontManager::onCreateStyleSet(int index) const { FML_DCHECK(false); return nullptr; } sk_sp<SkFontStyleSet> AssetFontManager::onMatchFamily( const char family_name_string[]) const { std::string family_name(family_name_string); return font_provider_->MatchFamily(family_name); } sk_sp<SkTypeface> AssetFontManager::onMatchFamilyStyle( const char familyName[], const SkFontStyle& style) const { sk_sp<SkFontStyleSet> font_style_set = font_provider_->MatchFamily(std::string(familyName)); if (font_style_set == nullptr) return nullptr; return font_style_set->matchStyle(style); } sk_sp<SkTypeface> AssetFontManager::onMatchFamilyStyleCharacter( const char familyName[], const SkFontStyle&, const char* bcp47[], int bcp47Count, SkUnichar character) const { return nullptr; } sk_sp<SkTypeface> AssetFontManager::onMakeFromData(sk_sp<SkData>, int ttcIndex) const { FML_DCHECK(false); return nullptr; } sk_sp<SkTypeface> AssetFontManager::onMakeFromStreamIndex( std::unique_ptr<SkStreamAsset>, int ttcIndex) const { FML_DCHECK(false); return nullptr; } sk_sp<SkTypeface> AssetFontManager::onMakeFromStreamArgs( std::unique_ptr<SkStreamAsset>, const SkFontArguments&) const { FML_DCHECK(false); return nullptr; } sk_sp<SkTypeface> AssetFontManager::onMakeFromFile(const char path[], int ttcIndex) const { FML_DCHECK(false); return nullptr; } sk_sp<SkTypeface> AssetFontManager::onLegacyMakeTypeface( const char familyName[], SkFontStyle) const { return nullptr; } } // namespace txt
engine/third_party/txt/src/txt/asset_font_manager.cc/0
{ "file_path": "engine/third_party/txt/src/txt/asset_font_manager.cc", "repo_id": "engine", "token_count": 1091 }
425
/* * Copyright 2018 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "text_shadow.h" #include "third_party/skia/include/core/SkColor.h" namespace txt { TextShadow::TextShadow() {} TextShadow::TextShadow(SkColor color, SkPoint offset, double blur_sigma) : color(color), offset(offset), blur_sigma(blur_sigma) {} bool TextShadow::operator==(const TextShadow& other) const { if (color != other.color) return false; if (offset != other.offset) return false; if (blur_sigma != other.blur_sigma) return false; return true; } bool TextShadow::operator!=(const TextShadow& other) const { return !(*this == other); } bool TextShadow::hasShadow() const { if (!offset.isZero()) return true; if (blur_sigma > 0.5) return true; return false; } } // namespace txt
engine/third_party/txt/src/txt/text_shadow.cc/0
{ "file_path": "engine/third_party/txt/src/txt/text_shadow.cc", "repo_id": "engine", "token_count": 422 }
426
<?xml version="1.0" encoding="UTF-8"?> <lint> <issue id="NewApi"> <!-- The NewApi lint also catches the usage of Java 8 APIs. The engine relies on being built with backwards support for Java 8 APIs enabled. BE CAREFUL ADDING TO THIS LIST. Not all Java 8 APIs are backwards compatible all the way back to API 16. See https://developer.android.com/studio/write/java8-support.html#supported_features --> <ignore regexp="^Try-with-resources requires API level 19"/> </issue> <issue id="UnknownNullness" severity="ignore" /> <issue id="SyntheticAccessor" severity="ignore" /> <!-- Flutter provides custom splash screens as a feature --> <issue id="CustomSplashScreen" severity="ignore" /> <!-- See https://github.com/flutter/flutter/issues/105061 --> <issue id="ScopedStorage" severity="ignore" /> <!-- See https://github.com/flutter/flutter/issues/105067 --> <issue id="LambdaLast" severity="ignore" /> </lint>
engine/tools/android_lint/lint.xml/0
{ "file_path": "engine/tools/android_lint/lint.xml", "repo_id": "engine", "token_count": 342 }
427
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:engine_repo_tools/engine_repo_tools.dart'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as path; import 'package:yaml/yaml.dart' as yaml; /// Tests that `HeaderFilterRegex` works as expected in `.clang_tidy`. void main() { // Find the root of the repo. final Engine engine = Engine.findWithin(path.dirname(Platform.script.path)); // Find the `.clang_tidy` file and "parse" it (it's YAML). final yaml.YamlDocument dotClangTidy = yaml.loadYamlDocument( File(path.join(engine.flutterDir.path, '.clang-tidy')).readAsStringSync(), ); // Find the `HeaderFilterRegex` entry. if (dotClangTidy.contents is! yaml.YamlMap) { stderr.writeln('Expected .clang-tidy to be a YAML map.'); exit(1); } final yaml.YamlMap nodes = dotClangTidy.contents as yaml.YamlMap; final yaml.YamlNode? headerFilterRegex = nodes.nodes['HeaderFilterRegex']; if (headerFilterRegex == null) { stderr.writeln('Expected .clang-tidy to have a HeaderFilterRegex entry.'); exit(1); } final RegExp regexValue = RegExp(headerFilterRegex.value.toString()); test('contains every root directory in the regex', () { // These are a list of directories that should _not_ be included. const Set<String> intentionallyOmitted = <String>{ '.git', '.github', 'build_overrides', 'prebuilts', 'third_party', }; // Find all the directories in the repo root aside from the ones above. final Set<String> rootDirs = <String>{}; for (final FileSystemEntity entity in engine.flutterDir.listSync()) { if (entity is! Directory) { continue; } final String name = path.basename(entity.path); if (intentionallyOmitted.contains(name)) { continue; } rootDirs.add(name); } // Create a fake file in that path, and assert that it matches the regex. for (final String rootDir in rootDirs) { final String file = path.join('..', '..', 'flutter', rootDir, 'foo'); if (!regexValue.hasMatch(file)) { // This is because reason: ... doesn't work in pkg/litetest. stderr.writeln('Expected "$file" to be caught by HeaderFilterRegex (${regexValue.pattern}).'); } expect(regexValue.hasMatch(file), isTrue); } }); }
engine/tools/clang_tidy/test/header_filter_regex_test.dart/0
{ "file_path": "engine/tools/clang_tidy/test/header_filter_regex_test.dart", "repo_id": "engine", "token_count": 923 }
428
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // If canonicalization uses deep structural hashing without memoizing, this // will exhibit superlinear time. // Compare with Dart version of this test at: // https://github.com/dart-lang/sdk/blob/ca3ad264a64937d5d336cd04dbf2746d1b7d8fc4/tests/language_2/canonicalize/hashing_memoize_instance_test.dart class Box { const Box(this.content1, this.content2); final Object? content1; // ignore: unreachable_from_main final Object? content2; // ignore: unreachable_from_main } const Box box1_0 = Box(null, null); const Box box1_1 = Box(box1_0, box1_0); const Box box1_2 = Box(box1_1, box1_1); const Box box1_3 = Box(box1_2, box1_2); const Box box1_4 = Box(box1_3, box1_3); const Box box1_5 = Box(box1_4, box1_4); const Box box1_6 = Box(box1_5, box1_5); const Box box1_7 = Box(box1_6, box1_6); const Box box1_8 = Box(box1_7, box1_7); const Box box1_9 = Box(box1_8, box1_8); const Box box1_10 = Box(box1_9, box1_9); const Box box1_11 = Box(box1_10, box1_10); const Box box1_12 = Box(box1_11, box1_11); const Box box1_13 = Box(box1_12, box1_12); const Box box1_14 = Box(box1_13, box1_13); const Box box1_15 = Box(box1_14, box1_14); const Box box1_16 = Box(box1_15, box1_15); const Box box1_17 = Box(box1_16, box1_16); const Box box1_18 = Box(box1_17, box1_17); const Box box1_19 = Box(box1_18, box1_18); const Box box1_20 = Box(box1_19, box1_19); const Box box1_21 = Box(box1_20, box1_20); const Box box1_22 = Box(box1_21, box1_21); const Box box1_23 = Box(box1_22, box1_22); const Box box1_24 = Box(box1_23, box1_23); const Box box1_25 = Box(box1_24, box1_24); const Box box1_26 = Box(box1_25, box1_25); const Box box1_27 = Box(box1_26, box1_26); const Box box1_28 = Box(box1_27, box1_27); const Box box1_29 = Box(box1_28, box1_28); const Box box1_30 = Box(box1_29, box1_29); const Box box1_31 = Box(box1_30, box1_30); const Box box1_32 = Box(box1_31, box1_31); const Box box1_33 = Box(box1_32, box1_32); const Box box1_34 = Box(box1_33, box1_33); const Box box1_35 = Box(box1_34, box1_34); const Box box1_36 = Box(box1_35, box1_35); const Box box1_37 = Box(box1_36, box1_36); const Box box1_38 = Box(box1_37, box1_37); const Box box1_39 = Box(box1_38, box1_38); const Box box1_40 = Box(box1_39, box1_39); const Box box1_41 = Box(box1_40, box1_40); const Box box1_42 = Box(box1_41, box1_41); const Box box1_43 = Box(box1_42, box1_42); const Box box1_44 = Box(box1_43, box1_43); const Box box1_45 = Box(box1_44, box1_44); const Box box1_46 = Box(box1_45, box1_45); const Box box1_47 = Box(box1_46, box1_46); const Box box1_48 = Box(box1_47, box1_47); const Box box1_49 = Box(box1_48, box1_48); const Box box1_50 = Box(box1_49, box1_49); const Box box1_51 = Box(box1_50, box1_50); const Box box1_52 = Box(box1_51, box1_51); const Box box1_53 = Box(box1_52, box1_52); const Box box1_54 = Box(box1_53, box1_53); const Box box1_55 = Box(box1_54, box1_54); const Box box1_56 = Box(box1_55, box1_55); const Box box1_57 = Box(box1_56, box1_56); const Box box1_58 = Box(box1_57, box1_57); const Box box1_59 = Box(box1_58, box1_58); const Box box1_60 = Box(box1_59, box1_59); const Box box1_61 = Box(box1_60, box1_60); const Box box1_62 = Box(box1_61, box1_61); const Box box1_63 = Box(box1_62, box1_62); const Box box1_64 = Box(box1_63, box1_63); const Box box1_65 = Box(box1_64, box1_64); const Box box1_66 = Box(box1_65, box1_65); const Box box1_67 = Box(box1_66, box1_66); const Box box1_68 = Box(box1_67, box1_67); const Box box1_69 = Box(box1_68, box1_68); const Box box1_70 = Box(box1_69, box1_69); const Box box1_71 = Box(box1_70, box1_70); const Box box1_72 = Box(box1_71, box1_71); const Box box1_73 = Box(box1_72, box1_72); const Box box1_74 = Box(box1_73, box1_73); const Box box1_75 = Box(box1_74, box1_74); const Box box1_76 = Box(box1_75, box1_75); const Box box1_77 = Box(box1_76, box1_76); const Box box1_78 = Box(box1_77, box1_77); const Box box1_79 = Box(box1_78, box1_78); const Box box1_80 = Box(box1_79, box1_79); const Box box1_81 = Box(box1_80, box1_80); const Box box1_82 = Box(box1_81, box1_81); const Box box1_83 = Box(box1_82, box1_82); const Box box1_84 = Box(box1_83, box1_83); const Box box1_85 = Box(box1_84, box1_84); const Box box1_86 = Box(box1_85, box1_85); const Box box1_87 = Box(box1_86, box1_86); const Box box1_88 = Box(box1_87, box1_87); const Box box1_89 = Box(box1_88, box1_88); const Box box1_90 = Box(box1_89, box1_89); const Box box1_91 = Box(box1_90, box1_90); const Box box1_92 = Box(box1_91, box1_91); const Box box1_93 = Box(box1_92, box1_92); const Box box1_94 = Box(box1_93, box1_93); const Box box1_95 = Box(box1_94, box1_94); const Box box1_96 = Box(box1_95, box1_95); const Box box1_97 = Box(box1_96, box1_96); const Box box1_98 = Box(box1_97, box1_97); const Box box1_99 = Box(box1_98, box1_98); const Box box2_0 = Box(null, null); const Box box2_1 = Box(box2_0, box2_0); const Box box2_2 = Box(box2_1, box2_1); const Box box2_3 = Box(box2_2, box2_2); const Box box2_4 = Box(box2_3, box2_3); const Box box2_5 = Box(box2_4, box2_4); const Box box2_6 = Box(box2_5, box2_5); const Box box2_7 = Box(box2_6, box2_6); const Box box2_8 = Box(box2_7, box2_7); const Box box2_9 = Box(box2_8, box2_8); const Box box2_10 = Box(box2_9, box2_9); const Box box2_11 = Box(box2_10, box2_10); const Box box2_12 = Box(box2_11, box2_11); const Box box2_13 = Box(box2_12, box2_12); const Box box2_14 = Box(box2_13, box2_13); const Box box2_15 = Box(box2_14, box2_14); const Box box2_16 = Box(box2_15, box2_15); const Box box2_17 = Box(box2_16, box2_16); const Box box2_18 = Box(box2_17, box2_17); const Box box2_19 = Box(box2_18, box2_18); const Box box2_20 = Box(box2_19, box2_19); const Box box2_21 = Box(box2_20, box2_20); const Box box2_22 = Box(box2_21, box2_21); const Box box2_23 = Box(box2_22, box2_22); const Box box2_24 = Box(box2_23, box2_23); const Box box2_25 = Box(box2_24, box2_24); const Box box2_26 = Box(box2_25, box2_25); const Box box2_27 = Box(box2_26, box2_26); const Box box2_28 = Box(box2_27, box2_27); const Box box2_29 = Box(box2_28, box2_28); const Box box2_30 = Box(box2_29, box2_29); const Box box2_31 = Box(box2_30, box2_30); const Box box2_32 = Box(box2_31, box2_31); const Box box2_33 = Box(box2_32, box2_32); const Box box2_34 = Box(box2_33, box2_33); const Box box2_35 = Box(box2_34, box2_34); const Box box2_36 = Box(box2_35, box2_35); const Box box2_37 = Box(box2_36, box2_36); const Box box2_38 = Box(box2_37, box2_37); const Box box2_39 = Box(box2_38, box2_38); const Box box2_40 = Box(box2_39, box2_39); const Box box2_41 = Box(box2_40, box2_40); const Box box2_42 = Box(box2_41, box2_41); const Box box2_43 = Box(box2_42, box2_42); const Box box2_44 = Box(box2_43, box2_43); const Box box2_45 = Box(box2_44, box2_44); const Box box2_46 = Box(box2_45, box2_45); const Box box2_47 = Box(box2_46, box2_46); const Box box2_48 = Box(box2_47, box2_47); const Box box2_49 = Box(box2_48, box2_48); const Box box2_50 = Box(box2_49, box2_49); const Box box2_51 = Box(box2_50, box2_50); const Box box2_52 = Box(box2_51, box2_51); const Box box2_53 = Box(box2_52, box2_52); const Box box2_54 = Box(box2_53, box2_53); const Box box2_55 = Box(box2_54, box2_54); const Box box2_56 = Box(box2_55, box2_55); const Box box2_57 = Box(box2_56, box2_56); const Box box2_58 = Box(box2_57, box2_57); const Box box2_59 = Box(box2_58, box2_58); const Box box2_60 = Box(box2_59, box2_59); const Box box2_61 = Box(box2_60, box2_60); const Box box2_62 = Box(box2_61, box2_61); const Box box2_63 = Box(box2_62, box2_62); const Box box2_64 = Box(box2_63, box2_63); const Box box2_65 = Box(box2_64, box2_64); const Box box2_66 = Box(box2_65, box2_65); const Box box2_67 = Box(box2_66, box2_66); const Box box2_68 = Box(box2_67, box2_67); const Box box2_69 = Box(box2_68, box2_68); const Box box2_70 = Box(box2_69, box2_69); const Box box2_71 = Box(box2_70, box2_70); const Box box2_72 = Box(box2_71, box2_71); const Box box2_73 = Box(box2_72, box2_72); const Box box2_74 = Box(box2_73, box2_73); const Box box2_75 = Box(box2_74, box2_74); const Box box2_76 = Box(box2_75, box2_75); const Box box2_77 = Box(box2_76, box2_76); const Box box2_78 = Box(box2_77, box2_77); const Box box2_79 = Box(box2_78, box2_78); const Box box2_80 = Box(box2_79, box2_79); const Box box2_81 = Box(box2_80, box2_80); const Box box2_82 = Box(box2_81, box2_81); const Box box2_83 = Box(box2_82, box2_82); const Box box2_84 = Box(box2_83, box2_83); const Box box2_85 = Box(box2_84, box2_84); const Box box2_86 = Box(box2_85, box2_85); const Box box2_87 = Box(box2_86, box2_86); const Box box2_88 = Box(box2_87, box2_87); const Box box2_89 = Box(box2_88, box2_88); const Box box2_90 = Box(box2_89, box2_89); const Box box2_91 = Box(box2_90, box2_90); const Box box2_92 = Box(box2_91, box2_91); const Box box2_93 = Box(box2_92, box2_92); const Box box2_94 = Box(box2_93, box2_93); const Box box2_95 = Box(box2_94, box2_94); const Box box2_96 = Box(box2_95, box2_95); const Box box2_97 = Box(box2_96, box2_96); const Box box2_98 = Box(box2_97, box2_97); const Box box2_99 = Box(box2_98, box2_98); Object confuse(Box x) { try { throw x; } catch (e) { return e; } // ignore: only_throw_errors } void main() { if (!identical(confuse(box1_99), confuse(box2_99))) { throw Exception('box1_99 !== box2_99'); } }
engine/tools/const_finder/test/fixtures/lib/box.dart/0
{ "file_path": "engine/tools/const_finder/test/fixtures/lib/box.dart", "repo_id": "engine", "token_count": 4278 }
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:io' show ProcessStartMode; import 'package:engine_build_configs/engine_build_configs.dart'; import 'package:process_runner/process_runner.dart'; import '../build_utils.dart'; import '../run_utils.dart'; import 'command.dart'; import 'flags.dart'; /// The root 'run' command. final class RunCommand extends CommandBase { /// Constructs the 'run' command. RunCommand({ required super.environment, required Map<String, BuilderConfig> configs, }) { builds = runnableBuilds(environment, configs); debugCheckBuilds(builds); argParser.addOption( configFlag, abbr: 'c', defaultsTo: '', help: 'Specify the build config to use for the target build (usually auto detected)', allowed: <String>[ for (final Build build in runnableBuilds(environment, configs)) build.name, ], allowedHelp: <String, String>{ for (final Build build in runnableBuilds(environment, configs)) build.name: build.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 => 'run'; @override String get description => 'Run a Flutter app with a local engine build. ' 'All arguments after -- are forwarded to flutter run, e.g.: ' 'et run -- --profile ' 'et run -- -d macos ' 'See `flutter run --help` for a listing'; Build? _lookup(String configName) { return builds.where((Build build) => build.name == configName).firstOrNull; } Build? _findHostBuild(Build? targetBuild) { if (targetBuild == null) { return null; } final String name = targetBuild.name; if (name.startsWith('host_')) { return targetBuild; } // TODO(johnmccutchan): This is brittle, it would be better if we encoded // the host config name in the target config. if (name.contains('_debug')) { return _lookup('host_debug'); } else if (name.contains('_profile')) { return _lookup('host_profile'); } else if (name.contains('_release')) { return _lookup('host_release'); } return null; } String _getDeviceId() { if (argResults!.rest.contains('-d')) { final int index = argResults!.rest.indexOf('-d') + 1; if (index < argResults!.rest.length) { return argResults!.rest[index]; } } if (argResults!.rest.contains('--device-id')) { final int index = argResults!.rest.indexOf('--device-id') + 1; if (index < argResults!.rest.length) { return argResults!.rest[index]; } } return ''; } String _getMode() { // Sniff the build mode from the args that will be passed to flutter run. String mode = 'debug'; if (argResults!.rest.contains('--profile')) { mode = 'profile'; } else if (argResults!.rest.contains('--release')) { mode = 'release'; } return mode; } Future<String?> _selectTargetConfig() async { final String configName = argResults![configFlag] as String; if (configName.isNotEmpty) { return configName; } final String deviceId = _getDeviceId(); final RunTarget? target = await detectAndSelectRunTarget(environment, deviceId); if (target == null) { return 'host_debug'; } environment.logger.status( 'Building to run on "${target.name}" running ${target.targetPlatform}'); return target.buildConfigFor(_getMode()); } @override Future<int> run() async { if (!environment.processRunner.processManager.canRun('flutter')) { environment.logger.error('Cannot find the flutter command in your path'); return 1; } final String? configName = await _selectTargetConfig(); if (configName == null) { environment.logger.error('Could not find target config'); return 1; } final Build? build = _lookup(configName); final Build? hostBuild = _findHostBuild(build); if (build == null) { environment.logger.error('Could not find build $configName'); return 1; } if (hostBuild == null) { environment.logger.error('Could not find host build for $configName'); return 1; } final bool useRbe = argResults![rbeFlag] as bool; final List<String> extraGnArgs = <String>[ if (!useRbe) '--no-rbe', ]; // First build the host. int r = await runBuild(environment, hostBuild, extraGnArgs: extraGnArgs); if (r != 0) { return r; } // Now build the target if it isn't the same. if (hostBuild.name != build.name) { r = await runBuild(environment, build, extraGnArgs: extraGnArgs); if (r != 0) { return r; } } // TODO(johnmccutchan): Be smart and if the user requested a profile // config, add the '--profile' flag when invoking flutter run. final ProcessRunnerResult result = await environment.processRunner.runProcess( <String>[ 'flutter', 'run', '--local-engine-src-path', environment.engine.srcDir.path, '--local-engine', build.name, '--local-engine-host', hostBuild.name, ...argResults!.rest, ], runInShell: true, startMode: ProcessStartMode.inheritStdio, ); return result.exitCode; } }
engine/tools/engine_tool/lib/src/commands/run_command.dart/0
{ "file_path": "engine/tools/engine_tool/lib/src/commands/run_command.dart", "repo_id": "engine", "token_count": 2172 }
430
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:engine_tool/src/logger.dart'; import 'package:litetest/litetest.dart'; import 'package:logging/logging.dart' as log; void main() { List<String> stringsFromLogs(List<log.LogRecord> logs) { return logs.map((log.LogRecord r) => r.message).toList(); } test('Setting the level works', () { final Logger logger = Logger.test(); logger.level = Logger.infoLevel; expect(logger.level, equals(Logger.infoLevel)); }); test('error messages are recorded at the default log level', () { final Logger logger = Logger.test(); logger.error('Error'); expect(stringsFromLogs(logger.testLogs), equals(<String>['Error\n'])); }); test('warning messages are recorded at the default log level', () { final Logger logger = Logger.test(); logger.warning('Warning'); expect(stringsFromLogs(logger.testLogs), equals(<String>['Warning\n'])); }); test('status messages are recorded at the default log level', () { final Logger logger = Logger.test(); logger.status('Status'); expect(stringsFromLogs(logger.testLogs), equals(<String>['Status\n'])); }); test('info messages are not recorded at the default log level', () { final Logger logger = Logger.test(); logger.info('info'); expect(stringsFromLogs(logger.testLogs), equals(<String>[])); }); test('info messages are recorded at the infoLevel log level', () { final Logger logger = Logger.test(); logger.level = Logger.infoLevel; logger.info('info'); expect(stringsFromLogs(logger.testLogs), equals(<String>['info\n'])); }); test('indent indents the message', () { final Logger logger = Logger.test(); logger.status('Status', indent: 1); expect(stringsFromLogs(logger.testLogs), equals(<String>[' Status\n'])); }); test('newlines in error() can be disabled', () { final Logger logger = Logger.test(); logger.error('Error', newline: false); expect(stringsFromLogs(logger.testLogs), equals(<String>['Error'])); }); test('newlines in warning() can be disabled', () { final Logger logger = Logger.test(); logger.warning('Warning', newline: false); expect(stringsFromLogs(logger.testLogs), equals(<String>['Warning'])); }); test('newlines in status() can be disabled', () { final Logger logger = Logger.test(); logger.status('Status', newline: false); expect(stringsFromLogs(logger.testLogs), equals(<String>['Status'])); }); test('newlines in info() can be disabled', () { final Logger logger = Logger.test(); logger.level = Logger.infoLevel; logger.info('info', newline: false); expect(stringsFromLogs(logger.testLogs), equals(<String>['info'])); }); test('fatal throws exception', () { final Logger logger = Logger.test(); logger.level = Logger.infoLevel; bool caught = false; try { logger.fatal('test', newline: false); } on FatalError catch (_) { caught = true; } expect(caught, equals(true)); expect(stringsFromLogs(logger.testLogs), equals(<String>['test'])); }); test('fitToWidth', () { expect(Logger.fitToWidth('hello', 0), equals('')); expect(Logger.fitToWidth('hello', 1), equals('.')); expect(Logger.fitToWidth('hello', 2), equals('..')); expect(Logger.fitToWidth('hello', 3), equals('...')); expect(Logger.fitToWidth('hello', 4), equals('...o')); expect(Logger.fitToWidth('hello', 5), equals('hello')); expect(Logger.fitToWidth('foobar', 5), equals('f...r')); expect(Logger.fitToWidth('foobarb', 5), equals('f...b')); expect(Logger.fitToWidth('foobarb', 6), equals('f...rb')); expect(Logger.fitToWidth('foobarba', 5), equals('f...a')); expect(Logger.fitToWidth('foobarba', 6), equals('f...ba')); expect(Logger.fitToWidth('foobarba', 7), equals('fo...ba')); expect(Logger.fitToWidth('hello\n', 0), equals('\n')); expect(Logger.fitToWidth('hello\n', 1), equals('.\n')); expect(Logger.fitToWidth('hello\n', 2), equals('..\n')); expect(Logger.fitToWidth('hello\n', 3), equals('...\n')); expect(Logger.fitToWidth('hello\n', 4), equals('...o\n')); expect(Logger.fitToWidth('hello\n', 5), equals('hello\n')); expect(Logger.fitToWidth('foobar\n', 5), equals('f...r\n')); expect(Logger.fitToWidth('foobarb\n', 5), equals('f...b\n')); expect(Logger.fitToWidth('foobarb\n', 6), equals('f...rb\n')); expect(Logger.fitToWidth('foobarba\n', 5), equals('f...a\n')); expect(Logger.fitToWidth('foobarba\n', 6), equals('f...ba\n')); expect(Logger.fitToWidth('foobarba\n', 7), equals('fo...ba\n')); }); test('Spinner calls onFinish callback', () { final Logger logger = Logger.test(); bool called = false; final Spinner spinner = logger.startSpinner( onFinish: () { called = true; }, ); spinner.finish(); expect(called, isTrue); }); }
engine/tools/engine_tool/test/logger_test.dart/0
{ "file_path": "engine/tools/engine_tool/test/logger_test.dart", "repo_id": "engine", "token_count": 1860 }
431
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/tools/fuchsia/dart/dart.gni") import("//flutter/tools/fuchsia/dart/dart_package_config.gni") import("//flutter/tools/fuchsia/dart/toolchain.gni") # Defines a Dart library # # Parameters # # sources # The list of all sources in this library. # These sources must be within source_dir. # # package_root (optional) # Path to the directory hosting the library. # This is useful for generated content, and can be ignored otherwise. # Defaults to ".". # # package_name (optional) # Name of the Dart package. This is used as an identifier in code that # depends on this library. # # language_version (optional) # Specify the Dart language version to use for this package. # If language_version is not specified but pubspec is then the language # version will be read from the pubspec. If no language version can be # determined then we will default to version "2.8". # It is recommended to specify a language_version if it is well known # instead of relying on the pubspec file since this will improve compilation # times. # # infer_package_name (optional) # Infer the package name based on the path to the package. # # NOTE: Exactly one of package_name or infer_package_name must be set. # # source_dir (optional) # Path to the directory containing the package sources, relative to # package_root. All non third-party dart files under source_dir must be # included in sources. # Defaults to "lib". # # deps (optional) # List of labels this library depends on. # # TODO(fxb/63133): non_dart_deps is deprecated. Use deps instead. # non_dart_deps (optional, deprecated) # List of labels this library depends on that are not Dart libraries. This # includes things like actions that generate Dart code. It typically doesn't # need to be set. # Note that these labels *must* have an explicit toolchain attached. # # TODO(fxbug.dev/71902): set up allowlist for disable_source_verification when # dart_test no longer depends on dart_library. # NOTE: Do NOT disable source verification unless you are 100% sure it is # absolutely necessary. # disable_source_verification (optional) # Prevents source verification from being run on this target. # # extra_sources (optional) # Additional sources to consider for analysis. # # pubspec (optional) # Path to the pubspec.yaml. If not provided, will default to looking for # the pubspec.yaml in the package root. It is not common that this value will # need to be set but can be useful for generated code. # # options_file (optional) # Path to the analysis_options.yaml file. If not provided, will default to # looking for the analysis_options.yaml in the package root. It is not common # that this value needs to be set but can be useful for generated code. # # disable_metadata_entry (optional) # Prevents metedata entry from being written to the dart_packag_config json file. # # Example of usage: # # dart_library("baz") { # package_name = "foo.bar.baz" # # sources = [ # "blah.dart", # ] # # deps = [ # "//foo/bar/owl", # ] # } if (current_toolchain == dart_toolchain) { template("dart_library") { forward_variables_from(invoker, [ "visibility", "hermetic_deps", ]) if (defined(invoker.package_name)) { package_name = invoker.package_name } else if (defined(invoker.infer_package_name) && invoker.infer_package_name) { # Compute a package name from the label: # //foo/bar --> foo.bar # //foo/bar:blah --> foo.bar._blah # //garnet/public/foo/bar --> foo.bar # Strip public directories. full_dir = get_label_info(":$target_name", "dir") package_name = full_dir package_name = string_replace(package_name, "//", "") package_name = string_replace(package_name, "/", ".") # If the last directory name does not match the target name, add the # target name to the resulting package name. name = get_label_info(":$target_name", "name") last_dir = get_path_info(full_dir, "name") if (last_dir != name) { package_name = "$package_name._$name" } } else { assert(false, "Must specify either a package_name or infer_package_name") } _dart_deps = [] if (defined(invoker.deps)) { foreach(dep, invoker.deps) { _dart_deps += [ get_label_info(dep, "label_no_toolchain") ] } } _non_dart_deps = [] if (defined(invoker.non_dart_deps)) { _non_dart_deps += invoker.non_dart_deps } package_root = "." if (defined(invoker.package_root)) { package_root = invoker.package_root } source_dir = "$package_root/lib" if (defined(invoker.source_dir)) { source_dir = "$package_root/${invoker.source_dir}" } assert(defined(invoker.sources), "Sources must be defined") disable_source_verification = defined(invoker.disable_source_verification) && invoker.disable_source_verification if (disable_source_verification && invoker.sources == []) { not_needed([ source_dir ]) } rebased_sources = [] foreach(source, invoker.sources) { rebased_source_dir = rebase_path(source_dir) rebased_sources += [ "$rebased_source_dir/$source" ] } if (defined(invoker.extra_sources)) { foreach(source, invoker.extra_sources) { rebased_sources += [ rebase_path(source) ] } } source_file = "$target_gen_dir/$target_name.sources" write_file(source_file, rebased_sources, "list lines") # Dependencies of the umbrella group for the targets in this file. group_deps = [] _public_deps = [] if (defined(invoker.public_deps)) { _public_deps = invoker.public_deps } _metadata = { package_config_entries = [ { name = package_name if (defined(invoker.language_version)) { language_version = invoker.language_version } else if (defined(invoker.pubspec)) { pubspec_path = rebase_path(invoker.pubspec, root_build_dir) } else { language_version = "2.12" } root_uri = rebase_path(package_root, root_build_dir) if (defined(invoker.source_dir)) { package_uri = invoker.source_dir } else { package_uri = "lib" } }, ] dart_build_info = [ { __is_current_target = false __package_name = package_name __deps = _dart_deps + _non_dart_deps __public_deps = _public_deps __rebased_sources = rebased_sources }, ] dart_build_info_barrier = [] } # When we generate a package_config for the analyzer we need to make sure # that we are including this library in that file. The dart_package_config # collects metadata from its dependencies so we create this group to expose # that data. We also expose this in the group target below so that users of # the dart_package_config target can just add the targets to the deps list. _publish_metadata_target_name = "${target_name}_package_metadata" group(_publish_metadata_target_name) { metadata = _metadata } _dart_package_config_target_name = "${target_name}_dart_package" _packages_path = "$target_gen_dir/${target_name}_package_config.json" dart_package_config(_dart_package_config_target_name) { # Do not publish the metadata to the dart_package_config json file if the # disable_metadata_entry flag is enabled in the dart_tool. The reason this is here # is to avoid entries that may have identical rootUris as fxb/58781 has highlighted. deps = _dart_deps if (!defined(invoker.disable_metadata_entry) || !invoker.disable_metadata_entry) { deps += [ ":$_publish_metadata_target_name" ] } public_deps = _non_dart_deps outputs = [ _packages_path ] forward_variables_from(invoker, [ "testonly" ]) } group_deps += [ ":$_dart_package_config_target_name" ] ################################ # Dart source "verification" # # Warn if there are dart sources from the source directory that are # not explicitly part of sources. This may cause a failure when syncing to # another repository, as they will be excluded from the resulting BUILD # file. # # Also warn if nonexistent files are included in sources. if (!disable_source_verification) { source_verification_target_name = "${target_name}_source_verification" action(source_verification_target_name) { script = "//flutter/tools/fuchsia/dart/verify_sources.py" output_file = "$target_gen_dir/$target_name.missing" sources = rebased_sources outputs = [ output_file ] args = [ "--source_dir", rebase_path(source_dir), "--stamp", rebase_path(output_file), ] + invoker.sources forward_variables_from(invoker, [ "testonly" ]) # Deps may include codegen dependencies that generate dart sources. deps = _dart_deps + _non_dart_deps } group_deps += [ ":$source_verification_target_name" ] } # Generate a file that lists files containing full (including all direct and # transitive dependencies) sources for this target's dependencies. _all_deps_sources_list_target = "${target_name}.all_deps_sources.list" _all_deps_sources_list_file = "${target_gen_dir}/${target_name}.all_deps_sources.list" generated_file(_all_deps_sources_list_target) { forward_variables_from(invoker, [ "testonly" ]) outputs = [ _all_deps_sources_list_file ] data_keys = [ "all_deps_sources" ] walk_keys = [ "all_deps_sources_barrier" ] deps = _dart_deps } # Generate full sources for this target by combining sources of this target # with full sources of all dependencies. # # The generated file contains sources of this target and all of its direct # and transitive dependencies. # # The output file is useful when writing depfiles for actions like dart # analyzer, which recursively reads all sources. _all_deps_sources_target = "${target_name}.all_deps_sources" _all_deps_sources_file = "${target_gen_dir}/${target_name}.all_deps_sources" action(_all_deps_sources_target) { forward_variables_from(invoker, [ "testonly" ]) script = "//flutter/tools/fuchsia/dart/merge_deps_sources.py" outputs = [ _all_deps_sources_file ] depfile = "${_all_deps_sources_file}.d" args = [ "--output", rebase_path(outputs[0], root_build_dir), "--depfile", rebase_path(depfile, root_build_dir), "--source_lists", "@" + rebase_path(_all_deps_sources_list_file, root_build_dir), "--sources", ] + rebase_path(rebased_sources, root_build_dir) inputs = [ _all_deps_sources_list_file ] deps = [ ":${_all_deps_sources_list_target}" ] metadata = { all_deps_sources = [ rebase_path(outputs[0], root_build_dir) ] all_deps_sources_barrier = [] } } group_deps += [ ":${_all_deps_sources_target}" ] not_needed(invoker, [ "options_file" ]) group(target_name) { # _dart_deps are added here to ensure they are fully built. # Up to this point, only the targets generating .packages had been # depended on. deps = _dart_deps + _non_dart_deps public_deps = group_deps metadata = _metadata forward_variables_from(invoker, [ "testonly" ]) } } } else { # Not the Dart toolchain. template("dart_library") { group(target_name) { forward_variables_from(invoker, [ "testonly" ]) not_needed(invoker, "*") public_deps = [ ":$target_name($dart_toolchain)" ] } } }
engine/tools/fuchsia/dart/dart_library.gni/0
{ "file_path": "engine/tools/fuchsia/dart/dart_library.gni", "repo_id": "engine", "token_count": 4972 }
432
#!/bin/bash # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # ### Checks out the version of Flutter engine in your Fuchsia source tree. ### This is necessary to avoid skew between the version of the Dart VM used in ### the flutter_runner and the version of the Dart SDK and VM used by the ### Flutter toolchain. See ### https://github.com/flutter/flutter/wiki/Compiling-the-engine#important-dart-version-synchronization-on-fuchsia ### for more details. ### ### Example: ### $ ./checkout_fuchsia_revision.sh set -e # Fail on any error. source "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"/lib/vars.sh || exit $? ensure_fuchsia_dir ensure_engine_dir engine-info "Fetching upstream/main to make sure we recognize Fuchsia's version of Flutter Engine..." git -C "$ENGINE_DIR"/flutter fetch upstream fuchsia_flutter_git_revision="$(cat $FUCHSIA_DIR/integration/jiri.lock | grep -A 1 "\"package\": \"flutter/fuchsia\"" | grep "git_revision" | tr ":" "\n" | sed -n 3p | tr "\"" "\n" | sed -n 1p)" engine-info "Checking out Fuchsia's revision of Flutter Engine ($fuchsia_flutter_git_revision)..." git -C "$ENGINE_DIR"/flutter checkout $fuchsia_flutter_git_revision engine-info "Syncing the Flutter Engine dependencies..." pushd $ENGINE_DIR gclient sync -D popd echo "Done. You're now working on Fuchsia's version of Flutter Engine ($fuchsia_flutter_git_revision)."
engine/tools/fuchsia/devshell/checkout_fuchsia_revision.sh/0
{ "file_path": "engine/tools/fuchsia/devshell/checkout_fuchsia_revision.sh", "repo_id": "engine", "token_count": 501 }
433
#!/usr/bin/env python3 # # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Generate a Fuchsia FAR Archive from an asset manifest. """ import argparse import collections import json import os import subprocess import sys from gather_flutter_runner_artifacts import CreateMetaPackage # Generates the manifest and returns the file. def GenerateManifest(package_dir): full_paths = [] for root, dirs, files in os.walk(package_dir): for f in files: common_prefix = os.path.commonprefix([root, package_dir]) rel_path = os.path.relpath(os.path.join(root, f), common_prefix) from_package = os.path.abspath(os.path.join(package_dir, rel_path)) assert from_package, 'Failed to create from_package for %s' % os.path.join(root, f) full_paths.append('%s=%s' % (rel_path, from_package)) parent_dir = os.path.abspath(os.path.join(package_dir, os.pardir)) manifest_file_name = os.path.basename(package_dir) + '.manifest' manifest_path = os.path.join(parent_dir, manifest_file_name) with open(manifest_path, 'w') as f: for item in full_paths: f.write("%s\n" % item) return manifest_path def CreateFarPackage(pm_bin, package_dir, signing_key, dst_dir, api_level): manifest_path = GenerateManifest(package_dir) pm_command_base = [ pm_bin, '-m', manifest_path, '-k', signing_key, '-o', dst_dir, '--api-level', api_level ] # Build the package subprocess.check_output(pm_command_base + ['build']) # Archive the package subprocess.check_output(pm_command_base + ['archive']) return 0 def main(): parser = argparse.ArgumentParser() parser.add_argument('--pm-bin', dest='pm_bin', action='store', required=True) parser.add_argument('--package-dir', dest='package_dir', action='store', required=True) parser.add_argument('--manifest-file', dest='manifest_file', action='store', required=False) parser.add_argument( '--manifest-json-file', dest='manifest_json_file', action='store', required=True ) parser.add_argument('--far-name', dest='far_name', action='store', required=False) parser.add_argument('--api-level', dest='api_level', action='store', required=False) args = parser.parse_args() assert os.path.exists(args.pm_bin) assert os.path.exists(args.package_dir) pkg_dir = args.package_dir if not os.path.exists(os.path.join(pkg_dir, 'meta', 'package')): CreateMetaPackage(pkg_dir, args.far_name) output_dir = os.path.abspath(pkg_dir + '_out') if not os.path.exists(output_dir): os.makedirs(output_dir) manifest_file = None if args.manifest_file is not None: assert os.path.exists(args.manifest_file) manifest_file = args.manifest_file else: manifest_file = GenerateManifest(args.package_dir) pm_command_base = [ args.pm_bin, '-o', output_dir, '-n', args.far_name, '-m', manifest_file, ] # Build and then archive the package # Use check_output so if anything goes wrong we get the output. try: build_command = ['build', '--output-package-manifest', args.manifest_json_file] if args.api_level is not None: build_command = ['--api-level', args.api_level] + build_command archive_command = [ 'archive', '--output=' + os.path.join(os.path.dirname(output_dir), args.far_name + "-0") ] pm_commands = [build_command, archive_command] for pm_command in pm_commands: subprocess.check_output(pm_command_base + pm_command) except subprocess.CalledProcessError as e: print('==================== Manifest contents =========================================') with open(manifest_file, 'r') as manifest: sys.stdout.write(manifest.read()) print('==================== End manifest contents =====================================') meta_contents_path = os.path.join(output_dir, 'meta', 'contents') if os.path.exists(meta_contents_path): print('==================== meta/contents =============================================') with open(meta_contents_path, 'r') as meta_contents: sys.stdout.write(meta_contents.read()) print('==================== End meta/contents =========================================') raise return 0 if __name__ == '__main__': sys.exit(main())
engine/tools/fuchsia/gen_package.py/0
{ "file_path": "engine/tools/fuchsia/gen_package.py", "repo_id": "engine", "token_count": 1544 }
434
# Web Locale Keymap Generator This script generates mapping data for `web_locale_keymap`. ## Usage 1. `cd` to this folder, and run `dart pub get`. 2. [Create a Github access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token), then store it to environment variable `$GITHUB_TOKEN`. This token is only for quota controlling and does not need any scopes. ``` # ~/.zshrc export GITHUB_TOKEN=<YOUR_TOKEN> ``` 3. Run ``` dart --enable-asserts bin/gen_web_locale_keymap.dart ``` ### Help For help on CLI, ``` dart --enable-asserts bin/gen_web_locale_keymap.dart -h ``` ## Explanation To derive a key map that allows international layout to properly trigger shortcuts, we can't [simply map logical keys from the current event](https://github.com/flutter/flutter/issues/100456). Instead, we need to analyze the entire current layout and plan ahead. This algorithm, which we call the benchmark planner, goes as follows: > Analyze every key of the current layout, > 1. If a key can produce an alnum under some modifier, then this key is mapped to this alnum. > 2. After the previous step, if some alnum is not mapped, they're mapped to their corresponding key on the US keyboard. > 3. The remaining keys are mapped to the unicode plane according to their produced character. However, we can't simply apply this algorithm to Web: unlike other desktop platforms, Web DOM API does not tell which keyboard layout the user is on, or how the current layout maps keys (there is a KeyboardLayout API that is supported only by Chrome, and explicitly refused by all other browsers). So we have to invent a "blind" algorithm that applies to any layout, while keeping the same result. Luckily, we're able to fetch a list of "all keyboard layouts" from `Microsoft/VSCode` repo, and we analyzed all layouts beforehand, and managed to combine the result into a huge `code -> key -> result` map. You would imagine it being impossible, since different layouts might use the same `(code, key)` pair for different characters, but in fact such conflicts are surprisingly few, and all the conflicts are mapped to letters. For example, `es-linux` maps `('KeyY', '←')` to `y`, while `de-linux` maps `('KeyY', '←')` to `z`. We can't distinguished these conflicts only by the `(code, key)` pair, but we can use other information: `keyCode`. Now, keyCode is a deprecated property, but we really don't see it being removed any time foreseeable. Also, although keyCode is infamous for being platform-dependent, for letter keys it is always equal to the letter character. Therefore such conflicting cases are all mapped to a special value, `kUseKeyCode`, indicating "use keyCode". Moreover, to reduce the size of the map, we noticed there are certain patterns that can be easily represented by some if statements. These patterns are extracted as the so-called "heuristic mapper". This reduces the map from over 1600 entries to ~450 entries. To further reduce the package size overhead, the map is encoded into a string that is decoded at run time. This reduces the package size over by 27% at the cost of code complexity.
engine/tools/gen_web_locale_keymap/README.md/0
{ "file_path": "engine/tools/gen_web_locale_keymap/README.md", "repo_id": "engine", "token_count": 844 }
435
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:args/command_runner.dart'; import 'package:clang_tidy/clang_tidy.dart'; import 'package:path/path.dart' as path; /// The command that implements the pre-push githook class PrePushCommand extends Command<bool> { @override final String name = 'pre-push'; @override final String description = 'Checks to run before a "git push"'; @override Future<bool> run() async { final Stopwatch sw = Stopwatch()..start(); final bool verbose = globalResults!['verbose']! as bool; final bool enableClangTidy = globalResults!['enable-clang-tidy']! as bool; final String flutterRoot = globalResults!['flutter']! as String; if (!enableClangTidy) { print('The clang-tidy check is disabled. To enable set the environment ' 'variable PRE_PUSH_CLANG_TIDY to any value.'); } final List<bool> checkResults = <bool>[ await _runFormatter(flutterRoot, verbose), if (enableClangTidy) await _runClangTidy(flutterRoot, verbose), ]; sw.stop(); io.stdout.writeln('pre-push checks finished in ${sw.elapsed}'); return !checkResults.contains(false); } Future<bool> _runClangTidy(String flutterRoot, bool verbose) async { io.stdout.writeln('Starting clang-tidy checks.'); final Stopwatch sw = Stopwatch()..start(); // First ensure that out/host_debug/compile_commands.json exists by running // //flutter/tools/gn. io.File compileCommands = io.File(path.join( flutterRoot, '..', 'out', 'host_debug', 'compile_commands.json', )); if (!compileCommands.existsSync()) { compileCommands = io.File(path.join( flutterRoot, '..', 'out', 'host_debug_unopt', 'compile_commands.json', )); if (!compileCommands.existsSync()) { io.stderr.writeln('clang-tidy requires a fully built host_debug or ' 'host_debug_unopt build directory'); return false; } } final StringBuffer outBuffer = StringBuffer(); final StringBuffer errBuffer = StringBuffer(); final ClangTidy clangTidy = ClangTidy( buildCommandsPath: compileCommands, outSink: outBuffer, errSink: errBuffer, ); final int clangTidyResult = await clangTidy.run(); sw.stop(); io.stdout.writeln('clang-tidy checks finished in ${sw.elapsed}'); if (clangTidyResult != 0) { io.stderr.write(errBuffer); return false; } return true; } Future<bool> _runFormatter(String flutterRoot, bool verbose) async { io.stdout.writeln('Starting formatting checks.'); final Stopwatch sw = Stopwatch()..start(); final String ext = io.Platform.isWindows ? '.bat' : '.sh'; final bool result = await _runCheck( flutterRoot, path.join(flutterRoot, 'ci', 'format$ext'), <String>[], 'Formatting check', verbose: verbose, ); sw.stop(); io.stdout.writeln('formatting checks finished in ${sw.elapsed}'); return result; } Future<bool> _runCheck( String flutterRoot, String scriptPath, List<String> scriptArgs, String checkName, { bool verbose = false, }) async { if (verbose) { io.stdout.writeln('Starting "$checkName": $scriptPath'); } final io.ProcessResult result = await io.Process.run( scriptPath, scriptArgs, workingDirectory: flutterRoot, ); if (result.exitCode != 0) { final StringBuffer message = StringBuffer(); message.writeln('Check "$checkName" failed.'); message.writeln('command: $scriptPath ${scriptArgs.join(" ")}'); message.writeln('working directory: $flutterRoot'); message.writeln('exit code: ${result.exitCode}'); message.writeln('stdout:'); message.writeln(result.stdout); message.writeln('stderr:'); message.writeln(result.stderr); io.stderr.write(message.toString()); return false; } if (verbose) { io.stdout.writeln('Check "$checkName" finished successfully.'); } return true; } }
engine/tools/githooks/lib/src/pre_push_command.dart/0
{ "file_path": "engine/tools/githooks/lib/src/pre_push_command.dart", "repo_id": "engine", "token_count": 1671 }
436
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:args/args.dart'; import 'package:golden_tests_harvester/golden_tests_harvester.dart'; import 'package:skia_gold_client/skia_gold_client.dart'; final bool _isLocalEnvWithoutSkiaGold = !SkiaGoldClient.isAvailable(environment: io.Platform.environment) || !SkiaGoldClient.isLuciEnv(environment: io.Platform.environment); final ArgParser _argParser = ArgParser() ..addFlag( 'help', abbr: 'h', negatable: false, help: 'Prints this usage information.', ) ..addFlag( 'dry-run', defaultsTo: _isLocalEnvWithoutSkiaGold, help: 'Do not upload images to Skia Gold.', ); Future<void> main(List<String> args) async { final ArgResults results = _argParser.parse(args); if (results['help'] as bool) { io.stdout.writeln(_argParser.usage); return; } final List<String> rest = results.rest; if (rest.length != 1) { io.stderr.writeln('Error: Must provide exactly one argument.'); io.stderr.writeln(_argParser.usage); io.exitCode = 1; return; } final io.Directory workDirectory = io.Directory(rest.single); final bool isDryRun = results['dry-run'] as bool; final Harvester harvester; if (isDryRun) { io.stderr.writeln('=== DRY RUN. Results not submitted to Skia Gold. ==='); harvester = await Harvester.create(workDirectory, io.stderr, addImageToSkiaGold: _dryRunAddImg); } else { harvester = await Harvester.create(workDirectory, io.stderr); } await harvest(harvester); } Future<void> _dryRunAddImg( String testName, io.File goldenFile, { required int screenshotSize, double differentPixelsRate = 0.01, int pixelColorDelta = 0, }) async { io.stderr.writeln('addImg ' 'testName:$testName ' 'goldenFile:${goldenFile.path} ' 'screenshotSize:$screenshotSize ' 'differentPixelsRate:$differentPixelsRate ' 'pixelColorDelta:$pixelColorDelta', ); }
engine/tools/golden_tests_harvester/bin/golden_tests_harvester.dart/0
{ "file_path": "engine/tools/golden_tests_harvester/bin/golden_tests_harvester.dart", "repo_id": "engine", "token_count": 777 }
437
# Update License Files ## Apply patch generated by CI If you're not working on a Linux box then you can't auto-generate license files. A workaround is provided via CI. Your build will fail one or more CI checks if your license files are not correct. Open the failing CI check. In the CI output you will find a patch diff that represents the changes that need to be made to your license files. > [!WARNING] > Do this only if the diff does not change _which_ licenses are being > included, but affects just the `FILE:` metadata and so forth in the > golden files. If the actual content of the licenses has changed, you > will need to rerun the script from a Linux box to update the actual > LICENSE file, as described below. ```sh cd flutter/ci/licenses_golden ``` If the file is to `my/patch/file` locally. The `-p2` strips two path components from the file paths in the diff. Adjust as necessary. ```sh patch -p2 < my/patch/file ``` If the patch file is copied in your clipboard. On Mac, you may apply the patch from there. ```sh pbpaste | patch -p2 ``` ## Check for license changes > [!WARNING] > Only works on Linux. This script has two sets of output files: "goldens", which describe the current license state of the repository, and the actual real LICENSE file, which is what matters. We look at changes to the goldens to determine if there are any actual changes to the licenses. To update the goldens, make sure you've rebased your branch to the latest upstream main and then run the following in this directory: ``` dart pub get gclient sync -D rm -rf ../../../out/licenses dart --enable-asserts lib/main.dart --src ../../.. --out ../../../out/licenses --golden ../../ci/licenses_golden ``` In order for the license script to work correctly, you need to remove any untracked files inside `engine/src` (the buildroot), not just `engine/src/flutter`. Once the script has finished, copy any affected files from `../../../out/licenses` to `../../ci/licenses_golden` and add them to your change, and examine the diffs to see what changed. ``` cp ../../../out/licenses/* ../../ci/licenses_golden git diff ``` > [!IMPORTANT] > If the only changes are to what files are included, then you're good > to go. However, if any of the _licenses_ changed, whether new licenses > are added, old ones removed, or any have their content changed in > _any_ way (including, e.g., whitespace changes), or if the affected > libraries change, **you must update the actual license file**. The `sky/packages/sky_engine/LICENSE` file is the one actually included in product releases and the one that should be updated any time the golden file changes in a way that involves changes to anything other than the `FILE` lines. To update this file, run: ``` dart pub get gclient sync -D dart --enable-asserts lib/main.dart --release --src ../../.. > ../../sky/packages/sky_engine/LICENSE ``` The bots do not verify that you did this step, it's important that you do it! When reviewing patches, if you see a change to the golden files, check to see if there's a corresponding change to the LICENSE file! ## Testing To run the tests: ``` dart pub get find -name "*_test.dart" | xargs -n 1 dart --enable-asserts ```
engine/tools/licenses/README.md/0
{ "file_path": "engine/tools/licenses/README.md", "repo_id": "engine", "token_count": 932 }
438
Unicode® Copyright and Terms of Use For the general privacy policy governing access to this site, see the Unicode Privacy Policy. A. Unicode Copyright 1. Copyright © 1991-2022 Unicode, Inc. All rights reserved. B. Definitions Unicode Data Files ("DATA FILES") include all data files under the directories: https://www.unicode.org/Public/ https://www.unicode.org/reports/ https://www.unicode.org/ivd/data/ Unicode Data Files do not include PDF online code charts under the directory: https://www.unicode.org/Public/ Unicode Software ("SOFTWARE") includes any source code published in the Unicode Standard or any source code or compiled code under the directories: https://www.unicode.org/Public/PROGRAMS/ https://www.unicode.org/Public/cldr/ http://site.icu-project.org/download/ C. Terms of Use 1. Certain documents and files on this website contain a legend indicating that "Modification is permitted." Any person is hereby authorized, without fee, to modify such documents and files to create derivative works conforming to the Unicode® Standard, subject to Terms and Conditions herein. 2. Any person is hereby authorized, without fee, to view, use, reproduce, and distribute all documents and files, subject to the Terms and Conditions herein. 3. Further specifications of rights and restrictions pertaining to the use of the Unicode DATA FILES and SOFTWARE can be found in the Unicode Data Files and Software License. 4. Each version of the Unicode Standard has further specifications of rights and restrictions of use. For the book editions (Unicode 5.0 and earlier), these are found on the back of the title page. 5. The Unicode PDF online code charts carry specific restrictions. Those restrictions are incorporated as the first page of each PDF code chart. 6. All other files, including online documentation of the core specification for Unicode 6.0 and later, are covered under these general Terms of Use. 7. No license is granted to "mirror" the Unicode website where a fee is charged for access to the "mirror" site. 8. Modification is not permitted with respect to this document. All copies of this document must be verbatim. D. Restricted Rights Legend 1. Any technical data or software which is licensed to the United States of America, its agencies and/or instrumentalities under this Agreement is commercial technical data or commercial computer software developed exclusively at private expense as defined in FAR 2.101, or DFARS 252.227-7014 (June 1995), as applicable. For technical data, use, duplication, or disclosure by the Government is subject to restrictions as set forth in DFARS 202.227-7015 Technical Data, Commercial and Items (Nov 1995) and this Agreement. For Software, in accordance with FAR 12-212 or DFARS 227-7202, as applicable, use, duplication or disclosure by the Government is subject to the restrictions set forth in this Agreement. E.Warranties and Disclaimers 1. This publication and/or website may include technical or typographical errors or other inaccuracies. Changes are periodically added to the information herein; these changes will be incorporated in new editions of the publication and/or website. Unicode, Inc. may make improvements and/or changes in the product(s) and/or program(s) described in this publication and/or website at any time. 2. If this file has been purchased on magnetic or optical media from Unicode, Inc. the sole and exclusive remedy for any claim will be exchange of the defective media within ninety (90) days of original purchase. 3. EXCEPT AS PROVIDED IN SECTION E.2, THIS PUBLICATION AND/OR SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND EITHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. UNICODE, INC. AND ITS LICENSORS ASSUME NO RESPONSIBILITY FOR ERRORS OR OMISSIONS IN THIS PUBLICATION AND/OR SOFTWARE OR OTHER DOCUMENTS WHICH ARE REFERENCED BY OR LINKED TO THIS PUBLICATION OR THE UNICODE WEBSITE. F. Waiver of Damages 1. In no event shall Unicode, Inc. or its licensors be liable for any special, incidental, indirect or consequential damages of any kind, or any damages whatsoever, whether or not Unicode, Inc. was advised of the possibility of the damage, including, without limitation, those resulting from the following: loss of use, data or profits, in connection with the use, modification or distribution of this information or its derivatives. G. Trademarks & Logos 1. The Unicode Word Mark and the Unicode Logo are trademarks of Unicode, Inc. “The Unicode Consortium” and “Unicode, Inc.” are trade names of Unicode, Inc. Use of the information and materials found on this website indicates your acknowledgement of Unicode, Inc.’s exclusive worldwide rights in the Unicode Word Mark, the Unicode Logo, and the Unicode trade names. 3. The Unicode Consortium Name and Trademark Usage Policy (“Trademark Policy”) are incorporated herein by reference and you agree to abide by the provisions of the Trademark Policy, which may be changed from time to time in the sole discretion of Unicode, Inc. 4. All third party trademarks referenced herein are the property of their respective owners. H. Miscellaneous 1. Jurisdiction and Venue. This website is operated from a location in the State of California, United States of America. Unicode, Inc. makes no representation that the materials are appropriate for use in other locations. If you access this website from other locations, you are responsible for compliance with local laws. This Agreement, all use of this website and any claims and damages resulting from use of this website are governed solely by the laws of the State of California without regard to any principles which would apply the laws of a different jurisdiction. The user agrees that any disputes regarding this website shall be resolved solely in the courts located in Santa Clara County, California. The user agrees said courts have personal jurisdiction and agree to waive any right to transfer the dispute to any other forum. 2. Modification by Unicode, Inc. Unicode, Inc. shall have the right to modify this Agreement at any time by posting it to this website. The user may not assign any part of this Agreement without Unicode, Inc.’s prior written consent. 3. Taxes. The user agrees to pay any taxes arising from access to this website or use of the information herein, except for those based on Unicode’s net income. 4. Severability. If any provision of this Agreement is declared invalid or unenforceable, the remaining provisions of this Agreement shall remain in effect. 5. Entire Agreement. This Agreement constitutes the entire agreement between the parties. EXHIBIT 1 UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE See Terms of Use <https://www.unicode.org/copyright.html> for definitions of Unicode Inc.’s Data Files and Software. NOTICE TO USER: Carefully read the following legal agreement. BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. COPYRIGHT AND PERMISSION NOTICE Copyright © 1991-2022 Unicode, Inc. All rights reserved. Distributed under the Terms of Use in https://www.unicode.org/copyright.html. Permission is hereby granted, free of charge, to any person obtaining a copy of the Unicode data files and any associated documentation (the "Data Files") or Unicode software and any associated documentation (the "Software") to deal in the Data Files or Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Data Files or Software, and to permit persons to whom the Data Files or Software are furnished to do so, provided that either (a) this copyright and permission notice appear with all copies of the Data Files or Software, or (b) this copyright and permission notice appear in associated Documentation. THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in these Data Files or Software without prior written authorization of the copyright holder.
engine/tools/licenses/data/unicode/0
{ "file_path": "engine/tools/licenses/data/unicode", "repo_id": "engine", "token_count": 2146 }
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. // ignore_for_file: camel_case_types, non_constant_identifier_names import 'dart:ffi' as ffi; import 'dart:io'; import 'dart:typed_data'; /// Determines the winding rule that decides how the interior of a Path is /// calculated. /// /// This enum is used by the [Path] constructor // must match ordering in //flutter/third_party/skia/include/core/SkPathTypes.h enum FillType { /// The interior is defined by a non-zero sum of signed edge crossings. nonZero, /// The interior is defined by an odd number of edge crossings. evenOdd, } /// A set of operations applied to two paths. // Sync with //flutter/third_party/skia/include/pathops/SkPathOps.h enum PathOp { /// Subtracts the second path from the first. difference, /// Creates a new path representing the intersection of the first and second. intersect, /// Creates a new path representing the union of the first and second /// (includive-or). union, /// Creates a new path representing the exclusive-or of two paths. xor, /// Creates a new path that subtracts the first path from the second.s reversedDifference, } /// The commands used in a [Path] object. /// /// This enumeration is a subset of the commands that SkPath supports. // Sync with //flutter/third_party/skia/include/core/SkPathTypes.h enum PathVerb { /// Picks up the pen and moves it without drawing. Uses two point values. moveTo, /// A straight line from the current point to the specified point. lineTo, _quadTo, _conicTo, /// A cubic bezier curve from the current point. /// /// The next two points are used as the first control point. The next two /// points form the second control point. The next two points form the /// target point. cubicTo, /// A straight line from the current point to the last [moveTo] point. close, } /// A proxy class for [Path.replay]. /// /// Allows implementations to easily inspect the contents of a [Path]. abstract class PathProxy { /// Picks up the pen and moves to absolute coordinates x,y. void moveTo(double x, double y); /// Draws a straight line from the current point to absolute coordinates x,y. void lineTo(double x, double y); /// Creates a cubic Bezier curve from the current point to point x3,y3 using /// x1,y1 as the first control point and x2,y2 as the second. void cubicTo( double x1, double y1, double x2, double y2, double x3, double y3); /// Draws a straight line from the current point to the last [moveTo] point. void close(); /// Called by [Path.replay] to indicate that a new path is being played. void reset() {} } /// A path proxy that can print the SVG path-data representation of this path. class SvgPathProxy implements PathProxy { final StringBuffer _buffer = StringBuffer(); @override void reset() { _buffer.clear(); } @override void close() { _buffer.write('Z'); } @override void cubicTo( double x1, double y1, double x2, double y2, double x3, double y3) { _buffer.write('C$x1,$y1 $x2,$y2 $x3,$y3'); } @override void lineTo(double x, double y) { _buffer.write('L$x,$y'); } @override void moveTo(double x, double y) { _buffer.write('M$x,$y'); } @override String toString() => _buffer.toString(); } /// Creates a path object to operate on. /// /// First, build up the path contours with the [moveTo], [lineTo], [cubicTo], /// and [close] methods. All methods expect absolute coordinates. /// /// Finally, use the [dispose] method to clean up native resources. After /// [dispose] has been called, this class must not be used again. class Path implements PathProxy { /// Creates an empty path object with the specified fill type. Path([FillType fillType = FillType.nonZero]) : _path = _createPathFn(fillType.index); /// Creates a copy of this path. factory Path.from(Path other) { final Path result = Path(other.fillType); other.replay(result); return result; } /// The [FillType] of this path. FillType get fillType { assert(_path != null); return FillType.values[_getFillTypeFn(_path!)]; } ffi.Pointer<_SkPath>? _path; ffi.Pointer<_PathData>? _pathData; /// The number of points used by each [PathVerb]. static const Map<PathVerb, int> pointsPerVerb = <PathVerb, int>{ PathVerb.moveTo: 2, PathVerb.lineTo: 2, PathVerb.cubicTo: 6, PathVerb.close: 0, }; /// Makes the appropriate calls using [verbs] and [points] to replay this path /// on [proxy]. /// /// Calls [PathProxy.reset] first if [reset] is true. void replay(PathProxy proxy, {bool reset = true}) { if (reset) { proxy.reset(); } int index = 0; for (final PathVerb verb in verbs.toList()) { switch (verb) { case PathVerb.moveTo: proxy.moveTo(points[index++], points[index++]); case PathVerb.lineTo: proxy.lineTo(points[index++], points[index++]); case PathVerb._quadTo: assert(false); case PathVerb._conicTo: assert(false); case PathVerb.cubicTo: proxy.cubicTo( points[index++], points[index++], points[index++], points[index++], points[index++], points[index++], ); case PathVerb.close: proxy.close(); } } assert(index == points.length); } /// The list of path verbs in this path. /// /// This may not match the verbs supplied by calls to [moveTo], [lineTo], /// [cubicTo], and [close] after [applyOp] is invoked. /// /// This list determines the meaning of the [points] array. Iterable<PathVerb> get verbs { _updatePathData(); final int count = _pathData!.ref.verb_count; return List<PathVerb>.generate(count, (int index) { return PathVerb.values[_pathData!.ref.verbs[index]]; }, growable: false); } /// The list of points to use with [verbs]. /// /// Each verb uses a specific number of points, specified by the /// [pointsPerVerb] map. Float32List get points { _updatePathData(); return _pathData!.ref.points.asTypedList(_pathData!.ref.point_count); } void _updatePathData() { assert(_path != null); _pathData ??= _dataFn(_path!); } void _resetPathData() { if (_pathData != null) { _destroyDataFn(_pathData!); } _pathData = null; } @override void moveTo(double x, double y) { assert(_path != null); _resetPathData(); _moveToFn(_path!, x, y); } @override void lineTo(double x, double y) { assert(_path != null); _resetPathData(); _lineToFn(_path!, x, y); } @override void cubicTo( double x1, double y1, double x2, double y2, double x3, double y3, ) { assert(_path != null); _resetPathData(); _cubicToFn(_path!, x1, y1, x2, y2, x3, y3); } @override void close() { assert(_path != null); _resetPathData(); _closeFn(_path!, true); } @override void reset() { assert(_path != null); _resetPathData(); _resetFn(_path!); } /// Releases native resources. /// /// After calling dispose, this class must not be used again. void dispose() { assert(_path != null); _resetPathData(); _destroyFn(_path!); _path = null; } /// Applies the operation described by [op] to this path using [other]. Path applyOp(Path other, PathOp op) { assert(_path != null); assert(other._path != null); final Path result = Path.from(this); _opFn(result._path!, other._path!, op.index); return result; } } // TODO(dnfield): Figure out where to put this. // https://github.com/flutter/flutter/issues/99563 final ffi.DynamicLibrary _dylib = () { if (Platform.isWindows) { return ffi.DynamicLibrary.open('path_ops.dll'); } else if (Platform.isIOS || Platform.isMacOS) { return ffi.DynamicLibrary.open('libpath_ops.dylib'); } else if (Platform.isAndroid || Platform.isLinux) { return ffi.DynamicLibrary.open('libpath_ops.so'); } throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}'); }(); final class _SkPath extends ffi.Opaque {} final class _PathData extends ffi.Struct { external ffi.Pointer<ffi.Uint8> verbs; @ffi.Size() external int verb_count; external ffi.Pointer<ffi.Float> points; @ffi.Size() external int point_count; } typedef _CreatePathType = ffi.Pointer<_SkPath> Function(int); typedef _create_path_type = ffi.Pointer<_SkPath> Function(ffi.Int); final _CreatePathType _createPathFn = _dylib.lookupFunction<_create_path_type, _CreatePathType>( 'CreatePath', ); typedef _MoveToType = void Function(ffi.Pointer<_SkPath>, double, double); typedef _move_to_type = ffi.Void Function( ffi.Pointer<_SkPath>, ffi.Float, ffi.Float); final _MoveToType _moveToFn = _dylib.lookupFunction<_move_to_type, _MoveToType>( 'MoveTo', ); typedef _LineToType = void Function(ffi.Pointer<_SkPath>, double, double); typedef _line_to_type = ffi.Void Function( ffi.Pointer<_SkPath>, ffi.Float, ffi.Float); final _LineToType _lineToFn = _dylib.lookupFunction<_line_to_type, _LineToType>( 'LineTo', ); typedef _CubicToType = void Function( ffi.Pointer<_SkPath>, double, double, double, double, double, double); typedef _cubic_to_type = ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Float, ffi.Float, ffi.Float, ffi.Float, ffi.Float, ffi.Float); final _CubicToType _cubicToFn = _dylib.lookupFunction<_cubic_to_type, _CubicToType>('CubicTo'); typedef _CloseType = void Function(ffi.Pointer<_SkPath>, bool); typedef _close_type = ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Bool); final _CloseType _closeFn = _dylib.lookupFunction<_close_type, _CloseType>('Close'); typedef _ResetType = void Function(ffi.Pointer<_SkPath>); typedef _reset_type = ffi.Void Function(ffi.Pointer<_SkPath>); final _ResetType _resetFn = _dylib.lookupFunction<_reset_type, _ResetType>('Reset'); typedef _DestroyType = void Function(ffi.Pointer<_SkPath>); typedef _destroy_type = ffi.Void Function(ffi.Pointer<_SkPath>); final _DestroyType _destroyFn = _dylib.lookupFunction<_destroy_type, _DestroyType>('DestroyPath'); typedef _OpType = void Function( ffi.Pointer<_SkPath>, ffi.Pointer<_SkPath>, int); typedef _op_type = ffi.Void Function( ffi.Pointer<_SkPath>, ffi.Pointer<_SkPath>, ffi.Int); final _OpType _opFn = _dylib.lookupFunction<_op_type, _OpType>('Op'); typedef _PathDataType = ffi.Pointer<_PathData> Function(ffi.Pointer<_SkPath>); typedef _path_data_type = ffi.Pointer<_PathData> Function(ffi.Pointer<_SkPath>); final _PathDataType _dataFn = _dylib.lookupFunction<_path_data_type, _PathDataType>('Data'); typedef _DestroyDataType = void Function(ffi.Pointer<_PathData>); typedef _destroy_data_type = ffi.Void Function(ffi.Pointer<_PathData>); final _DestroyDataType _destroyDataFn = _dylib.lookupFunction<_destroy_data_type, _DestroyDataType>('DestroyData'); typedef _GetFillTypeType = int Function(ffi.Pointer<_SkPath>); typedef _get_fill_type_type = ffi.Int32 Function(ffi.Pointer<_SkPath>); final _GetFillTypeType _getFillTypeFn = _dylib.lookupFunction<_get_fill_type_type, _GetFillTypeType>('GetFillType');
engine/tools/path_ops/dart/lib/path_ops.dart/0
{ "file_path": "engine/tools/path_ops/dart/lib/path_ops.dart", "repo_id": "engine", "token_count": 4189 }
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. import 'dart:convert' as convert; import 'dart:ffi' as ffi; import 'dart:io' as io; import 'package:engine_build_configs/src/build_config.dart'; import 'package:engine_build_configs/src/build_config_runner.dart'; import 'package:engine_repo_tools/engine_repo_tools.dart'; import 'package:litetest/litetest.dart'; import 'package:platform/platform.dart'; import 'package:process_fakes/process_fakes.dart'; import 'package:process_runner/process_runner.dart'; import 'fixtures.dart' as fixtures; void main() { // Find the engine repo. final Engine engine; try { engine = Engine.findWithin(); } catch (e) { io.stderr.writeln(e); io.exitCode = 1; return; } final BuilderConfig buildConfig = BuilderConfig.fromJson( path: 'linux_test_config', map: convert.jsonDecode(fixtures.buildConfigJson) as Map<String, Object?>, ); test('BuildTaskRunner runs the right commands', () async { final BuildTask generator = buildConfig.builds[0].generators[0]; final BuildTaskRunner taskRunner = BuildTaskRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, task: generator, dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await taskRunner.run(handler); expect(runResult, isTrue); expect(events[0] is RunnerStart, isTrue); expect(events[0].name, equals('generator_task')); expect(events[0].command[0], contains('python3')); expect(events[0].command[1], contains('gen/script.py')); expect(events[0].command[2], contains('--gen-param')); expect(events[1] is RunnerResult, isTrue); expect(events[1].name, equals('generator_task')); }); test('BuildTestRunner runs the right commands', () async { final BuildTest test = buildConfig.builds[0].tests[0]; final BuildTestRunner testRunner = BuildTestRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, test: test, dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await testRunner.run(handler); expect(runResult, isTrue); // Check that the events for the tests are correct. expect(events[0] is RunnerStart, isTrue); expect(events[0].name, equals('build_name tests')); expect(events[0].command[0], contains('python3')); expect(events[0].command[1], contains('test/script.py')); expect(events[0].command[2], contains('--test-params')); expect(events[1] is RunnerResult, isTrue); expect(events[1].name, equals('build_name tests')); }); test('GlobalBuildRunner runs the right commands', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isTrue); // Check that the events for the GN command are correct. expect(events[0] is RunnerStart, isTrue); expect(events[0].name, equals('$buildName: GN')); expect(events[0].command[0], contains('flutter/tools/gn')); for (final String gnArg in targetBuild.gn) { expect(events[0].command.contains(gnArg), isTrue); } expect(events[1] is RunnerResult, isTrue); expect(events[1].name, equals('$buildName: GN')); // Check that the events for the Ninja command are correct. expect(events[2] is RunnerStart, isTrue); expect(events[2].name, equals('$buildName: ninja')); expect(events[2].command[0], contains('ninja')); final String configPath = '${engine.srcDir.path}/out/${targetBuild.ninja.config}'; expect(events[2].command.contains(configPath), isTrue); for (final String target in targetBuild.ninja.targets) { expect(events[2].command.contains(target), isTrue); } expect(events[3] is RunnerResult, isTrue); expect(events[3].name, equals('$buildName: ninja')); // Check that the events for generators are correct. expect(events[4] is RunnerStart, isTrue); expect(events[4].name, equals('generator_task')); expect(events[4].command[0], contains('python3')); expect(events[4].command[1], contains('gen/script.py')); expect(events[4].command[2], contains('--gen-param')); expect(events[5] is RunnerResult, isTrue); expect(events[5].name, equals('generator_task')); // Check that the events for the tests are correct. expect(events[6] is RunnerStart, isTrue); expect(events[6].name, equals('$buildName tests')); expect(events[6].command[0], contains('python3')); expect(events[6].command[1], contains('test/script.py')); expect(events[6].command[2], contains('--test-params')); expect(events[7] is RunnerResult, isTrue); expect(events[7].name, equals('$buildName tests')); }); test('GlobalBuildRunner extra args are propagated correctly', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, extraGnArgs: <String>['--extra-gn-arg'], extraNinjaArgs: <String>['--extra-ninja-arg'], extraTestArgs: <String>['--extra-test-arg'], dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isTrue); // Check that the events for the GN command are correct. expect(events[0] is RunnerStart, isTrue); expect(events[0].name, equals('$buildName: GN')); expect(events[0].command.contains('--extra-gn-arg'), isTrue); // Check that the events for the Ninja command are correct. expect(events[2] is RunnerStart, isTrue); expect(events[2].name, equals('$buildName: ninja')); expect(events[2].command.contains('--extra-ninja-arg'), isTrue); // Check that the events for the tests are correct. expect(events[6] is RunnerStart, isTrue); expect(events[6].name, equals('$buildName tests')); expect(events[6].command.contains('--extra-test-arg'), isTrue); }); test('GlobalBuildRunner passes large -j for a goma build', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, extraGnArgs: <String>['--goma'], dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isTrue); // Check that the events for the Ninja command are correct. expect(events[2] is RunnerStart, isTrue); expect(events[2].name, equals('$buildName: ninja')); expect(events[2].command.contains('-j'), isTrue); expect(events[2].command.contains('200'), isTrue); }); test('GlobalBuildRunner passes large -j for an rbe build', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, extraGnArgs: <String>['--rbe'], dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isTrue); // Check that the events for the RBE bootstrap command are correct. expect(events[2] is RunnerStart, isTrue); expect(events[2].name, equals('$buildName: RBE startup')); expect(events[3] is RunnerResult, isTrue); expect(events[3].name, equals('$buildName: RBE startup')); // Check that the events for the Ninja command are correct. expect(events[4] is RunnerStart, isTrue); expect(events[4].name, equals('$buildName: ninja')); expect(events[4].command.contains('-j'), isTrue); expect(events[4].command.contains('200'), isTrue); expect(events[5] is RunnerResult, isTrue); expect(events[5].name, equals('$buildName: ninja')); expect(events[6] is RunnerStart, isTrue); expect(events[6].name, equals('$buildName: RBE shutdown')); expect(events[7] is RunnerResult, isTrue); expect(events[7].name, equals('$buildName: RBE shutdown')); }); test('GlobalBuildRunner skips GN when runGn is false', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, runGn: false, dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isTrue); // Check that the events for the Ninja command are correct. expect(events[0] is RunnerStart, isTrue); expect(events[0].name, equals('$buildName: ninja')); expect(events[0].command[0], contains('ninja')); final String configPath = '${engine.srcDir.path}/out/${targetBuild.ninja.config}'; expect(events[0].command.contains(configPath), isTrue); for (final String target in targetBuild.ninja.targets) { expect(events[0].command.contains(target), isTrue); } expect(events[1] is RunnerResult, isTrue); expect(events[1].name, equals('$buildName: ninja')); }); test('GlobalBuildRunner skips Ninja when runNinja is false', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, runNinja: false, dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isTrue); // Check that the events for the GN command are correct. expect(events[0] is RunnerStart, isTrue); expect(events[0].name, equals('$buildName: GN')); expect(events[0].command[0], contains('flutter/tools/gn')); for (final String gnArg in targetBuild.gn) { expect(events[0].command.contains(gnArg), isTrue); } expect(events[1] is RunnerResult, isTrue); expect(events[1].name, equals('$buildName: GN')); // Check that the events for generators are correct. expect(events[2] is RunnerStart, isTrue); expect(events[2].name, equals('generator_task')); expect(events[2].command[0], contains('python3')); expect(events[2].command[1], contains('gen/script.py')); expect(events[2].command[2], contains('--gen-param')); expect(events[3] is RunnerResult, isTrue); expect(events[3].name, equals('generator_task')); }); test('GlobalBuildRunner skips generators when runGenerators is false', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, runGenerators: false, dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isTrue); // Check that the events for the Ninja command are correct. expect(events[2] is RunnerStart, isTrue); expect(events[2].name, equals('$buildName: ninja')); expect(events[2].command[0], contains('ninja')); final String configPath = '${engine.srcDir.path}/out/${targetBuild.ninja.config}'; expect(events[2].command.contains(configPath), isTrue); for (final String target in targetBuild.ninja.targets) { expect(events[2].command.contains(target), isTrue); } expect(events[3] is RunnerResult, isTrue); expect(events[3].name, equals('$buildName: ninja')); // Check that the events for the tests are correct. expect(events[4] is RunnerStart, isTrue); expect(events[4].name, equals('$buildName tests')); expect(events[4].command[0], contains('python3')); expect(events[4].command[1], contains('test/script.py')); expect(events[4].command[2], contains('--test-params')); expect(events[5] is RunnerResult, isTrue); expect(events[5].name, equals('$buildName tests')); }); test('GlobalBuildRunner skips tests when runTests is false', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, runTests: false, dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); expect(runResult, isTrue); // Check that the events for generators are correct. expect(events[4] is RunnerStart, isTrue); expect(events[4].name, equals('generator_task')); expect(events[4].command[0], contains('python3')); expect(events[4].command[1], contains('gen/script.py')); expect(events[4].command[2], contains('--gen-param')); expect(events[5] is RunnerResult, isTrue); expect(events[5].name, equals('generator_task')); expect(events.length, equals(6)); }); test('GlobalBuildRunner extraGnArgs overrides build config args', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, extraGnArgs: <String>['--no-lto', '--no-goma', '--rbe'], dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isTrue); // Check that the events for the GN command are correct. expect(events[0] is RunnerStart, isTrue); expect(events[0].name, equals('$buildName: GN')); expect(events[0].command[0], contains('flutter/tools/gn')); expect(events[0].command.contains('--no-lto'), isTrue); expect(events[0].command.contains('--no-goma'), isTrue); expect(events[0].command.contains('--rbe'), isTrue); expect(events[0].command.contains('--lto'), isFalse); expect(events[0].command.contains('--goma'), isFalse); expect(events[0].command.contains('--no-rbe'), isFalse); expect(events[1] is RunnerResult, isTrue); expect(events[1].name, equals('$buildName: GN')); }); test('GlobalBuildRunner canRun returns false on OS mismatch', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.macOS), processRunner: ProcessRunner( // dryRun should not try to spawn any processes. processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, dryRun: true, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); expect(runResult, isFalse); expect(events[0] is RunnerError, isTrue); }); test('GlobalBuildRunner fails when gn fails', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( processManager: _fakeProcessManager( gnResult: io.ProcessResult(1, 1, '', ''), ), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isFalse); expect(events[0] is RunnerStart, isTrue); expect(events[0].name, equals('$buildName: GN')); expect(events[1] is RunnerResult, isTrue); expect((events[1] as RunnerResult).ok, isFalse); }); test('GlobalBuildRunner fails when ninja fails', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( processManager: _fakeProcessManager( ninjaResult: io.ProcessResult(1, 1, '', ''), ), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isFalse); expect(events[2] is RunnerStart, isTrue); expect(events[2].name, equals('$buildName: ninja')); expect(events[3] is RunnerResult, isTrue); expect((events[3] as RunnerResult).ok, isFalse); }); test('GlobalBuildRunner fails an RBE build when bootstrap fails', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( processManager: _fakeProcessManager( bootstrapResult: io.ProcessResult(1, 1, '', ''), ), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, extraGnArgs: <String>['--rbe'], ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); final String buildName = targetBuild.name; expect(runResult, isFalse); expect(events[2] is RunnerStart, isTrue); expect(events[2].name, equals('$buildName: RBE startup')); expect(events[3] is RunnerResult, isTrue); expect(events[3].name, equals('$buildName: RBE startup')); expect((events[3] as RunnerResult).ok, isFalse); }); test('GlobalBuildRunner fails an RBE build when bootstrap does not exist', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( processManager: _fakeProcessManager( canRun: (Object? exe, {String? workingDirectory}) { if (exe is String? && exe != null && exe.endsWith('bootstrap')) { return false; } return true; }, ), ), abi: ffi.Abi.linuxX64, engineSrcDir: engine.srcDir, build: targetBuild, extraGnArgs: <String>['--rbe'], ); final List<RunnerEvent> events = <RunnerEvent>[]; void handler(RunnerEvent event) => events.add(event); final bool runResult = await buildRunner.run(handler); expect(runResult, isFalse); expect(events[2] is RunnerError, isTrue); }); test('GlobalBuildRunner throws a StateError on an unsupported host cpu', () async { final Build targetBuild = buildConfig.builds[0]; final BuildRunner buildRunner = BuildRunner( platform: FakePlatform(operatingSystem: Platform.linux), processRunner: ProcessRunner( processManager: _fakeProcessManager(), ), abi: ffi.Abi.linuxRiscv32, engineSrcDir: engine.srcDir, build: targetBuild, extraGnArgs: <String>['--rbe'], ); bool caughtError = false; try { await buildRunner.run((RunnerEvent event) {}); } on StateError catch (_) { caughtError = true; } expect(caughtError, isTrue); }); } FakeProcessManager _fakeProcessManager({ io.ProcessResult? bootstrapResult, io.ProcessResult? gnResult, io.ProcessResult? ninjaResult, bool Function(Object?, {String? workingDirectory})? canRun, bool failUnknown = true, }) { final io.ProcessResult success = io.ProcessResult(1, 0, '', ''); FakeProcess fakeProcess(io.ProcessResult? result) => FakeProcess( exitCode: result?.exitCode ?? 0, stdout: result?.stdout as String? ?? '', stderr: result?.stderr as String? ?? '', ); return FakeProcessManager( canRun: canRun ?? (Object? exe, {String? workingDirectory}) => true, onRun: (List<String> cmd) => switch (cmd) { _ => failUnknown ? io.ProcessResult(1, 1, '', '') : success, }, onStart: (List<String> cmd) => switch (cmd) { [final String exe, ...] when exe.endsWith('gn') => fakeProcess(gnResult), [final String exe, ...] when exe.endsWith('bootstrap') => fakeProcess(bootstrapResult), [final String exe, ...] when exe.endsWith('ninja') => fakeProcess(ninjaResult), _ => failUnknown ? FakeProcess(exitCode: 1) : FakeProcess(), }, ); }
engine/tools/pkg/engine_build_configs/test/build_config_runner_test.dart/0
{ "file_path": "engine/tools/pkg/engine_build_configs/test/build_config_runner_test.dart", "repo_id": "engine", "token_count": 8769 }
441
// Copyright 2013 The Flutter 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_APPLICATION_H_ #define FLUTTER_VULKAN_VULKAN_APPLICATION_H_ #include <memory> #include <string> #include <vector> #include "flutter/fml/macros.h" #include "flutter/vulkan/procs/vulkan_handle.h" #include "vulkan_debug_report.h" namespace vulkan { static const size_t kGrCacheMaxByteSize = 512 * (1 << 20); class VulkanDevice; class VulkanProcTable; /// Applications using Vulkan acquire a VulkanApplication that attempts to /// create a VkInstance (with debug reporting optionally enabled). class VulkanApplication { public: VulkanApplication(VulkanProcTable& vk, // NOLINT const std::string& application_name, std::vector<std::string> enabled_extensions, uint32_t application_version = VK_MAKE_VERSION(1, 0, 0), uint32_t api_version = VK_MAKE_VERSION(1, 0, 0), bool enable_validation_layers = false); ~VulkanApplication(); bool IsValid() const; uint32_t GetAPIVersion() const; const VulkanHandle<VkInstance>& GetInstance() const; void ReleaseInstanceOwnership(); std::unique_ptr<VulkanDevice> AcquireFirstCompatibleLogicalDevice() const; private: VulkanProcTable& vk_; VulkanHandle<VkInstance> instance_; uint32_t api_version_; std::unique_ptr<VulkanDebugReport> debug_report_; bool valid_; bool enable_validation_layers_; std::vector<VkPhysicalDevice> GetPhysicalDevices() const; std::vector<VkExtensionProperties> GetSupportedInstanceExtensions( const VulkanProcTable& vk) const; bool ExtensionSupported( const std::vector<VkExtensionProperties>& supported_extensions, const std::string& extension_name); FML_DISALLOW_COPY_AND_ASSIGN(VulkanApplication); }; } // namespace vulkan #endif // FLUTTER_VULKAN_VULKAN_APPLICATION_H_
engine/vulkan/vulkan_application.h/0
{ "file_path": "engine/vulkan/vulkan_application.h", "repo_id": "engine", "token_count": 731 }
442
// Copyright 2013 The Flutter 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_PROVIDER_H_ #define FLUTTER_VULKAN_VULKAN_PROVIDER_H_ #include "flutter/vulkan/procs/vulkan_handle.h" #include "flutter/vulkan/procs/vulkan_proc_table.h" namespace vulkan { class VulkanProvider { public: virtual const vulkan::VulkanProcTable& vk() = 0; virtual const vulkan::VulkanHandle<VkDevice>& vk_device() = 0; vulkan::VulkanHandle<VkFence> CreateFence() { const VkFenceCreateInfo create_info = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = nullptr, .flags = 0, }; VkFence fence; if (VK_CALL_LOG_ERROR(vk().CreateFence(vk_device(), &create_info, nullptr, &fence)) != VK_SUCCESS) return vulkan::VulkanHandle<VkFence>(); return VulkanHandle<VkFence>{fence, [this](VkFence fence) { vk().DestroyFence(vk_device(), fence, nullptr); }}; } }; } // namespace vulkan #endif // FLUTTER_VULKAN_VULKAN_PROVIDER_H_
engine/vulkan/vulkan_provider.h/0
{ "file_path": "engine/vulkan/vulkan_provider.h", "repo_id": "engine", "token_count": 609 }
443
name: web_sdk_tests # Keep the SDK version range in sync with lib/web_ui/pubspec.yaml environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: args: 2.3.1 path: any # see dependency_overrides dev_dependencies: # Using the bundled analyzer (see dependency_overrides) to always be # up-to-date instead of a version from pub, which may not have the latest # language features enabled. analyzer: any test: 1.24.8 dependency_overrides: # Must include all transitive dependencies from the "any" packages above. _fe_analyzer_shared: path: ../../third_party/dart/pkg/_fe_analyzer_shared analyzer: path: ../../third_party/dart/pkg/analyzer async: path: ../../third_party/dart/third_party/pkg/async collection: path: ../../third_party/dart/third_party/pkg/collection convert: path: ../../third_party/dart/third_party/pkg/convert crypto: path: ../../third_party/dart/third_party/pkg/crypto dart_internal: path: ../../third_party/dart/pkg/dart_internal file: path: ../../third_party/dart/third_party/pkg/file/packages/file glob: path: ../../third_party/dart/third_party/pkg/glob meta: path: ../../third_party/dart/pkg/meta package_config: path: ../../third_party/dart/third_party/pkg/package_config path: path: ../../third_party/dart/third_party/pkg/path pub_semver: path: ../../third_party/dart/third_party/pkg/pub_semver source_span: path: ../../third_party/dart/third_party/pkg/source_span string_scanner: path: ../../third_party/dart/third_party/pkg/string_scanner term_glyph: path: ../../third_party/dart/third_party/pkg/term_glyph typed_data: path: ../../third_party/dart/third_party/pkg/typed_data watcher: path: ../../third_party/dart/third_party/pkg/watcher yaml: path: ../../third_party/dart/third_party/pkg/yaml
engine/web_sdk/pubspec.yaml/0
{ "file_path": "engine/web_sdk/pubspec.yaml", "repo_id": "engine", "token_count": 733 }
444
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="flutter-idea [runIde]" type="GradleRunConfiguration" factoryName="Gradle"> <ExternalSystemSettings> <option name="executionName" /> <option name="externalProjectPath" value="$PROJECT_DIR$/flutter-idea" /> <option name="externalSystemIdString" value="GRADLE" /> <option name="scriptParameters" value="" /> <option name="taskDescriptions"> <list /> </option> <option name="taskNames"> <list> <option value="runIde" /> </list> </option> <option name="vmOptions" value="" /> </ExternalSystemSettings> <ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess> <ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess> <DebugAllEnabled>false</DebugAllEnabled> <method v="2" /> </configuration> </component>
flutter-intellij/.idea/runConfigurations/flutter_idea__runIde_.xml/0
{ "file_path": "flutter-intellij/.idea/runConfigurations/flutter_idea__runIde_.xml", "repo_id": "flutter-intellij", "token_count": 332 }
445
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ buildscript { repositories { mavenCentral() maven { url=uri("https://www.jetbrains.com/intellij-repository/snapshots/") } maven { url=uri("https://oss.sonatype.org/content/repositories/snapshots/") } maven { url=uri("https://www.jetbrains.com/intellij-repository/releases") } gradlePluginPortal() } } plugins { id("org.jetbrains.intellij") version "1.17.2" id("org.jetbrains.kotlin.jvm") version "2.0.0-Beta4" } repositories { mavenLocal() mavenCentral() maven { url=uri("https://www.jetbrains.com/intellij-repository/snapshots/") } maven { url=uri("https://oss.sonatype.org/content/repositories/snapshots/") } maven { url=uri("https://www.jetbrains.com/intellij-repository/releases") } } // Specify UTF-8 for all compilations so we avoid Windows-1252. allprojects { tasks.withType<JavaCompile>() { options.encoding = "UTF-8" } tasks.withType<Test>() { systemProperty("file.encoding", "UTF-8") } } val ide: String by project val flutterPluginVersion: String by project val javaVersion: String by project val androidVersion: String by project val dartVersion: String by project val baseVersion: String by project val name: String by project val buildSpec: String by project val smaliPlugin: String by project val langPlugin: String by project val ideVersion: String by project group = "io.flutter" version = flutterPluginVersion java { sourceCompatibility = JavaVersion.toVersion(javaVersion) targetCompatibility = JavaVersion.toVersion(javaVersion) } intellij { pluginName.set(name) // This adds nullability assertions, but also compiles forms. instrumentCode.set(true) updateSinceUntilBuild.set(false) version.set(ideVersion) downloadSources.set(false) val pluginList = mutableListOf( project(":flutter-idea"), "java", "properties", "junit", "Git4Idea", "Kotlin", "gradle", "Groovy", "Dart:$dartVersion") // If 2023.3+ and IDEA (not AS), then "org.jetbrains.android:$androidVersion", otherwise "org.jetbrains.android", // see https://github.com/flutter/flutter-intellij/issues/7145 if(ide == "android-studio") { pluginList.add("org.jetbrains.android"); } else if (ide == "ideaIC") { pluginList.add("org.jetbrains.android:$androidVersion"); } if (ide == "android-studio") { pluginList.add(smaliPlugin) } pluginList.add(langPlugin) if (ide == "android-studio") { type.set("AI") pluginList += listOf(project(":flutter-studio")) } plugins.set(pluginList) } tasks { buildSearchableOptions { enabled = false } prepareSandbox { dependsOn(":flutter-idea:prepareSandbox") if (ide == "android-studio") { dependsOn(":flutter-studio:prepareSandbox") } } } dependencies { implementation(project("flutter-idea", "instrumentedJar")) // Second arg is required to use forms if (ide == "android-studio") { implementation(project("flutter-studio")) } } tasks { instrumentCode { compilerVersion.set("$baseVersion") } instrumentTestCode { compilerVersion.set("$baseVersion") } }
flutter-intellij/build.gradle.kts/0
{ "file_path": "flutter-intellij/build.gradle.kts", "repo_id": "flutter-intellij", "token_count": 1199 }
446
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.tests.gui import com.intellij.testGuiFramework.fixtures.ActionButtonFixture import com.intellij.testGuiFramework.fixtures.ExecutionToolWindowFixture import com.intellij.testGuiFramework.fixtures.IdeFrameFixture import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.util.step import org.fest.swing.exception.ComponentLookupException import org.fest.swing.timing.Condition import org.fest.swing.timing.Pause fun IdeFrameFixture.launchFlutterApp() { step("Launch Flutter app") { tryFindRunAppButton().click() val runner = runner() Pause.pause(object : Condition("Start app") { override fun test(): Boolean { return runner.isExecutionInProgress } }, Timeouts.seconds30) } } fun IdeFrameFixture.tryFindRunAppButton(): ActionButtonFixture { while (true) { try { return findRunApplicationButton() } catch (ex: ComponentLookupException) { Pause.pause() } } } fun IdeFrameFixture.runner(): ExecutionToolWindowFixture.ContentFixture { return runToolWindow.findContent("main.dart") }
flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/Utils.kt/0
{ "file_path": "flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/Utils.kt", "repo_id": "flutter-intellij", "token_count": 430 }
447
/* * 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; import org.jetbrains.annotations.Nullable; import java.util.HashSet; import java.util.Set; // TODO(kenz): it would be nice to consolidate all notifications to use a single manager. Perhaps we should // make `FlutterMessages` a private class in this file. Optionally, we could also move this functionality // into `FlutterMessages`. public class NotificationManager { private static final Set<String> shownNotifications = new HashSet<>(); public static void showError(String title, String message, @Nullable String id, @Nullable Boolean showOnce) { if (shouldNotify(id, showOnce)) { shownNotifications.add(id); FlutterMessages.showError(title, message, null); } } public static void showWarning(String title, String message, @Nullable String id, @Nullable Boolean showOnce) { if (shouldNotify(id, showOnce)) { shownNotifications.add(id); FlutterMessages.showWarning(title, message, null); } } public static void showInfo(String title, String message, @Nullable String id, @Nullable Boolean showOnce) { if (shouldNotify(id, showOnce)) { shownNotifications.add(id); FlutterMessages.showInfo(title, message, null); } } private static boolean shouldNotify(@Nullable String id, @Nullable Boolean showOnce) { // This notification has already been shown and it can only be shown once. return id == null || !shownNotifications.contains(id) || showOnce == null || !showOnce; } public static void reset() { shownNotifications.clear(); } }
flutter-intellij/flutter-idea/src/io/flutter/NotificationManager.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/NotificationManager.java", "repo_id": "flutter-intellij", "token_count": 525 }
448
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.android; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.ColoredProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.util.ReflectionUtil; import io.flutter.FlutterMessages; import io.flutter.utils.MostlySilentColoredProcessHandler; import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class AndroidEmulator { private static final Logger LOG = Logger.getInstance(AndroidEmulator.class); @NotNull final AndroidSdk androidSdk; @NotNull final String id; ProcessAdapter listener; AndroidEmulator(@NotNull AndroidSdk androidSdk, @NotNull String id) { this.androidSdk = androidSdk; this.id = id; } public String getName() { return id.replaceAll("_", " "); } public void startEmulator() { if (androidSdk.project.isDisposed()) { return; } final VirtualFile emulator = androidSdk.getEmulatorToolExecutable(); if (emulator == null) { FlutterMessages.showError( "Error Opening Emulator", "Unable to locate the emulator tool in the Android SDK.", androidSdk.project); return; } final String emulatorPath = emulator.getCanonicalPath(); assert (emulatorPath != null); final GeneralCommandLine cmd = new GeneralCommandLine() .withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE) .withWorkDirectory(androidSdk.getHome().getCanonicalPath()) .withExePath(emulatorPath) .withParameters("-avd", this.id); final boolean shouldLaunchEmulatorInToolWindow = getLaunchInToolWindow(); if (shouldLaunchEmulatorInToolWindow) { cmd.addParameter("-qt-hide-window"); cmd.addParameter("-grpc-use-token"); cmd.addParameters("-idle-grpc-timeout", "300"); } try { final StringBuilder stdout = new StringBuilder(); final ColoredProcessHandler process = new MostlySilentColoredProcessHandler(cmd); listener = new ProcessAdapter() { @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { if (androidSdk.project.isDisposed()) { return; } if (outputType == ProcessOutputTypes.STDERR || outputType == ProcessOutputTypes.STDOUT) { stdout.append(event.getText()); } openEmulatorToolWindow(shouldLaunchEmulatorInToolWindow); } public void processTerminated(@NotNull ProcessEvent event) { process.removeProcessListener(listener); final int exitCode = event.getExitCode(); if (exitCode != 0) { final String message = stdout.isEmpty() ? "Android emulator terminated with exit code " + exitCode : stdout.toString().trim(); FlutterMessages.showError("Error Opening Emulator", message, androidSdk.project); } } }; process.addProcessListener(listener); process.startNotify(); } catch (ExecutionException | RuntimeException e) { FlutterMessages.showError("Error Opening Emulator", e.toString(), androidSdk.project); } } private void openEmulatorToolWindow(boolean shouldLaunchEmulatorInToolWindow) { if (!shouldLaunchEmulatorInToolWindow) { return; } if (androidSdk.project.isDisposed()) { return; } final ToolWindowManager wm = ToolWindowManager.getInstance(androidSdk.project); final ToolWindow tw = wm.getToolWindow("Android Emulator"); if (tw == null || tw.isVisible()) { return; } assert ApplicationManager.getApplication() != null; ApplicationManager.getApplication().invokeLater(() -> { tw.setAutoHide(false); tw.show(); }, ModalityState.stateForComponent(tw.getComponent())); } @Override public boolean equals(Object obj) { return obj instanceof AndroidEmulator && ((AndroidEmulator)obj).id.equals(id); } @Override public int hashCode() { return id.hashCode(); } // This is: EmulatorSettings.getInstance().getLaunchInToolWindow(); // Beginning in 2022.2, Android Studio moved this class to a different package. // IntelliJ did not adopt that change, and we cannot build separate plugins for the two. @SuppressWarnings("ConstantConditions") private boolean getLaunchInToolWindow() { Class<?> aClass; try { // IntelliJ aClass = Class.forName("com.android.tools.idea.emulator.EmulatorSettings"); } catch (ClassNotFoundException e) { try { // Android Studio aClass = Class.forName("com.android.tools.idea.streaming.EmulatorSettings"); } catch (ClassNotFoundException ex) { return false; } } Method method = ReflectionUtil.getDeclaredMethod(aClass, "getInstance"); try { Object instance = method.invoke(null); Method option = ReflectionUtil.getDeclaredMethod(aClass, "getLaunchInToolWindow"); return (boolean)option.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { return false; } } }
flutter-intellij/flutter-idea/src/io/flutter/android/AndroidEmulator.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/android/AndroidEmulator.java", "repo_id": "flutter-intellij", "token_count": 2127 }
449
/* * Copyright 2018 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.dart; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Uninterruptibles; import com.google.dart.server.AnalysisServerListenerAdapter; import com.google.dart.server.ResponseListener; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService; import io.flutter.FlutterInitializer; import io.flutter.analytics.TimeTracker; import io.flutter.utils.JsonUtils; import org.dartlang.analysis.server.protocol.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class FlutterDartAnalysisServer implements Disposable { private static final String FLUTTER_NOTIFICATION_OUTLINE = "flutter.outline"; private static final String FLUTTER_NOTIFICATION_OUTLINE_KEY = "\"flutter.outline\""; @NotNull final Project project; /** * Each key is a notification identifier. * Each value is the set of files subscribed to the notification. */ private final Map<String, List<String>> subscriptions = new HashMap<>(); @VisibleForTesting protected final Map<String, List<FlutterOutlineListener>> fileOutlineListeners = new HashMap<>(); /** * Each key is a request identifier. * Each value is the {@link Consumer} for the response. */ private final Map<String, Consumer<JsonObject>> responseConsumers = new HashMap<>(); private boolean isDisposed = false; @NotNull public static FlutterDartAnalysisServer getInstance(@NotNull final Project project) { return Objects.requireNonNull(project.getService(FlutterDartAnalysisServer.class)); } @NotNull private DartAnalysisServerService getAnalysisService() { return Objects.requireNonNull(DartPlugin.getInstance().getAnalysisService(project)); } @VisibleForTesting public FlutterDartAnalysisServer(@NotNull Project project) { this.project = project; DartAnalysisServerService analysisService = getAnalysisService(); analysisService.addResponseListener(new CompatibleResponseListener()); analysisService.addAnalysisServerListener(new AnalysisServerListenerAdapter() { private boolean hasComputedErrors = false; @Override public void serverConnected(String s) { // If the server reconnected we need to let it know that we still care // about our subscriptions. if (!subscriptions.isEmpty()) { sendSubscriptions(); } } @Override public void computedErrors(String file, List<AnalysisError> errors) { if (!hasComputedErrors && project.isOpen()) { FlutterInitializer.getAnalytics().sendEventMetric( "startup", "analysisComputedErrors", TimeTracker.getInstance(project).millisSinceProjectOpen() ); hasComputedErrors = true; } super.computedErrors(file, errors); } }); Disposer.register(project, this); } public void addOutlineListener(@NotNull final String filePath, @NotNull final FlutterOutlineListener listener) { synchronized (fileOutlineListeners) { final List<FlutterOutlineListener> listeners = fileOutlineListeners.computeIfAbsent(filePath, k -> new ArrayList<>()); listeners.add(listener); } addSubscription(FlutterService.OUTLINE, filePath); } public void removeOutlineListener(@NotNull final String filePath, @NotNull final FlutterOutlineListener listener) { final boolean removeSubscription; synchronized (fileOutlineListeners) { final List<FlutterOutlineListener> listeners = fileOutlineListeners.get(filePath); removeSubscription = listeners != null && listeners.remove(listener); } if (removeSubscription) { removeSubscription(FlutterService.OUTLINE, filePath); } } /** * Adds a flutter event subscription to the analysis server. * <p> * Note that <code>filePath</code> must be an absolute path. */ private void addSubscription(@NotNull final String service, @NotNull final String filePath) { final List<String> files = subscriptions.computeIfAbsent(service, k -> new ArrayList<>()); if (!files.contains(filePath)) { files.add(filePath); sendSubscriptions(); } } /** * Removes a flutter event subscription from the analysis server. * <p> * Note that <code>filePath</code> must be an absolute path. */ private void removeSubscription(@NotNull final String service, @NotNull final String filePath) { final List<String> files = subscriptions.get(service); if (files != null && files.remove(filePath)) { sendSubscriptions(); } } private void sendSubscriptions() { DartAnalysisServerService analysisService = getAnalysisService(); final String id = analysisService.generateUniqueId(); analysisService.sendRequest(id, FlutterRequestUtilities.generateAnalysisSetSubscriptions(id, subscriptions)); } @NotNull public List<SourceChange> edit_getAssists(@NotNull VirtualFile file, int offset, int length) { DartAnalysisServerService analysisService = getAnalysisService(); return analysisService.edit_getAssists(file, offset, length); } @Nullable public CompletableFuture<List<FlutterWidgetProperty>> getWidgetDescription(@NotNull VirtualFile file, int _offset) { final CompletableFuture<List<FlutterWidgetProperty>> result = new CompletableFuture<>(); final String filePath = FileUtil.toSystemDependentName(file.getPath()); DartAnalysisServerService analysisService = getAnalysisService(); final int offset = analysisService.getOriginalOffset(file, _offset); final String id = analysisService.generateUniqueId(); synchronized (responseConsumers) { responseConsumers.put(id, (resultObject) -> { try { final JsonArray propertiesObject = resultObject.getAsJsonArray("properties"); final ArrayList<FlutterWidgetProperty> properties = new ArrayList<>(); for (JsonElement propertyObject : propertiesObject) { properties.add(FlutterWidgetProperty.fromJson(propertyObject.getAsJsonObject())); } result.complete(properties); } catch (Throwable ignored) { } }); } final JsonObject request = FlutterRequestUtilities.generateFlutterGetWidgetDescription(id, filePath, offset); analysisService.sendRequest(id, request); return result; } @Nullable public SourceChange setWidgetPropertyValue(int propertyId, FlutterWidgetPropertyValue value) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<SourceChange> result = new AtomicReference<>(); DartAnalysisServerService analysisService = getAnalysisService(); final String id = analysisService.generateUniqueId(); synchronized (responseConsumers) { responseConsumers.put(id, (resultObject) -> { try { final JsonObject propertiesObject = resultObject.getAsJsonObject("change"); result.set(SourceChange.fromJson(propertiesObject)); } catch (Throwable ignored) { } latch.countDown(); }); } final JsonObject request = FlutterRequestUtilities.generateFlutterSetWidgetPropertyValue(id, propertyId, value); analysisService.sendRequest(id, request); Uninterruptibles.awaitUninterruptibly(latch, 100, TimeUnit.MILLISECONDS); return result.get(); } private void processString(String jsonString) { if (isDisposed) return; ApplicationManager.getApplication().executeOnPooledThread(() -> { // Short circuit just in case we have been disposed in the time it took // for us to get around to listening for the response. if (isDisposed) return; processResponse(JsonUtils.parseString(jsonString).getAsJsonObject()); }); } /** * Handle the given {@link JsonObject} response. */ private void processResponse(JsonObject response) { final JsonElement eventName = response.get("event"); if (eventName != null && eventName.isJsonPrimitive()) { processNotification(response, eventName); return; } if (response.has("error")) { return; } final JsonObject resultObject = response.getAsJsonObject("result"); if (resultObject == null) { return; } final JsonPrimitive idJsonPrimitive = (JsonPrimitive)response.get("id"); if (idJsonPrimitive == null) { return; } final String idString = idJsonPrimitive.getAsString(); final Consumer<JsonObject> consumer; synchronized (responseConsumers) { consumer = responseConsumers.remove(idString); } if (consumer == null) { return; } consumer.consume(resultObject); } /** * Attempts to handle the given {@link JsonObject} as a notification. */ private void processNotification(JsonObject response, @NotNull JsonElement eventName) { // If we add code to handle more event types below, update the filter in processString(). final String event = eventName.getAsString(); if (event.equals(FLUTTER_NOTIFICATION_OUTLINE)) { final JsonObject paramsObject = response.get("params").getAsJsonObject(); final String file = paramsObject.get("file").getAsString(); final JsonElement instrumentedCodeElement = paramsObject.get("instrumentedCode"); final String instrumentedCode = instrumentedCodeElement != null ? instrumentedCodeElement.getAsString() : null; final JsonObject outlineObject = paramsObject.get("outline").getAsJsonObject(); final FlutterOutline outline = FlutterOutline.fromJson(outlineObject); final List<FlutterOutlineListener> listenersUpdated; synchronized (fileOutlineListeners) { final List<FlutterOutlineListener> listeners = fileOutlineListeners.get(file); listenersUpdated = listeners != null ? Lists.newArrayList(listeners) : null; } if (listenersUpdated != null) { for (FlutterOutlineListener listener : listenersUpdated) { listener.outlineUpdated(file, outline, instrumentedCode); } } } } class CompatibleResponseListener implements ResponseListener { // TODO(anyone): Remove this once 192 is the minimum supported base. @SuppressWarnings({"override", "RedundantSuppression"}) public void onResponse(JsonObject jsonObject) { processResponse(jsonObject); } @SuppressWarnings({"override", "RedundantSuppression"}) public void onResponse(String jsonString) { processString(jsonString); } } @Override public void dispose() { isDisposed = true; } }
flutter-intellij/flutter-idea/src/io/flutter/dart/FlutterDartAnalysisServer.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/dart/FlutterDartAnalysisServer.java", "repo_id": "flutter-intellij", "token_count": 3756 }
450
/* * Copyright 2018 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.editor; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.project.Project; import com.intellij.util.ui.ColorIcon; import com.intellij.util.ui.EmptyIcon; import com.jetbrains.lang.dart.ide.completion.DartCompletionExtension; import com.jetbrains.lang.dart.ide.completion.DartServerCompletionContributor; import org.apache.commons.lang3.StringUtils; import org.dartlang.analysis.server.protocol.CompletionSuggestion; import org.dartlang.analysis.server.protocol.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Objects; public class FlutterCompletionContributor extends DartCompletionExtension { private static final int ICON_SIZE = 16; private static final Icon EMPTY_ICON = EmptyIcon.create(ICON_SIZE); @Override @Nullable public LookupElementBuilder createLookupElement(@NotNull final Project project, @NotNull final CompletionSuggestion suggestion) { final Icon icon = findIcon(suggestion); if (icon != null) { final LookupElementBuilder lookup = DartServerCompletionContributor.createLookupElement(project, suggestion).withTypeText("", icon, false); // Specify right alignment for type icons. return lookup.withTypeIconRightAligned(true); } return null; } private static Icon findIcon(@NotNull final CompletionSuggestion suggestion) { final Element element = suggestion.getElement(); if (element != null) { final String returnType = element.getReturnType(); if (!StringUtils.isEmpty(returnType)) { final String name = element.getName(); if (name != null) { final String declaringType = suggestion.getDeclaringType(); if (Objects.equals(declaringType, "Colors")) { final FlutterColors.FlutterColor color = FlutterColors.getColor(name); if (color != null) { return new ColorIcon(ICON_SIZE, color.getAWTColor()); } } else if (Objects.equals(declaringType, "CupertinoColors")) { final FlutterColors.FlutterColor color = FlutterCupertinoColors.getColor(name); if (color != null) { return new ColorIcon(ICON_SIZE, color.getAWTColor()); } } else if (Objects.equals(declaringType, "Icons")) { final Icon icon = FlutterMaterialIcons.getIconForName(name); // If we have no icon, show an empty node (which is preferable to the default "IconData" text). return icon != null ? icon : EMPTY_ICON; } else if (Objects.equals(declaringType, "CupertinoIcons")) { final Icon icon = FlutterCupertinoIcons.getIconForName(name); // If we have no icon, show an empty node (which is preferable to the default "IconData" text). return icon != null ? icon : EMPTY_ICON; } } } } return null; } }
flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterCompletionContributor.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterCompletionContributor.java", "repo_id": "flutter-intellij", "token_count": 1185 }
451
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.editor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import org.dartlang.analysis.server.protocol.FlutterOutline; import org.jetbrains.annotations.Nullable; class TextRangeTracker { private final TextRange rawRange; private RangeMarker marker; private String endingWord; TextRangeTracker(int offset, int endOffset) { rawRange = new TextRange(offset, endOffset); } void track(Document document) { if (marker != null) { assert (document == marker.getDocument()); return; } // Create a range marker that goes from the start of the indent for the line // to the column of the actual entity. final int docLength = document.getTextLength(); final int startOffset = Math.min(rawRange.getStartOffset(), docLength); final int endOffset = Math.min(rawRange.getEndOffset(), docLength); endingWord = getCurrentWord(document, endOffset - 1); marker = document.createRangeMarker(startOffset, endOffset); } @Nullable TextRange getRange() { if (marker == null) { return rawRange; } if (!marker.isValid()) { return null; } return new TextRange(marker.getStartOffset(), marker.getEndOffset()); } void dispose() { if (marker != null) { marker.dispose(); } marker = null; } public boolean isTracking() { return marker != null && marker.isValid(); } /** * Get the next word in the document starting at offset. * <p> * This helper is used to avoid displaying outline guides where it appears * that the word at the start of the outline (e.g. the Widget constructor * name) has changed since the guide was created. This catches edge cases * where RangeMarkers go off the rails and return strange values after * running a code formatter or other tool that generates widespread edits. */ public static String getCurrentWord(Document document, int offset) { final int documentLength = document.getTextLength(); offset = Math.max(0, offset); if (offset < 0 || offset >= documentLength) return ""; final CharSequence chars = document.getCharsSequence(); // Clamp the max current word length at 20 to avoid slow behavior if the // next "word" in the document happened to be incredibly long. final int maxWordEnd = Math.min(documentLength, offset + 20); int end = offset; while (end < maxWordEnd && Character.isAlphabetic(chars.charAt(end))) { end++; } if (offset == end) return ""; return chars.subSequence(offset, end).toString(); } public boolean isConsistentEndingWord() { if (marker == null) { return true; } if (!marker.isValid()) { return false; } return // Verify that the word starting at the end of the marker matches // its expected value. This is sometimes not the case if the logic // to update marker locations has hit a bad edge case as sometimes // happens when there is a large document edit due to running a // code formatter. endingWord.equals(TextRangeTracker.getCurrentWord(marker.getDocument(), marker.getEndOffset() - 1)); } } /** * Class that tracks the location of a FlutterOutline node in a document. * <p> * Once the track method has been called, edits to the document are reflected * by by all locations returned by the outline location. */ public class OutlineLocation implements Comparable<OutlineLocation> { private final int line; private final int column; private final int indent; private final int offset; /** * Tracker for the range of lines indent guides for the outline should show. */ private final TextRangeTracker guideTracker; /** * Tracker for the entire range of text describing this outline location. */ private final TextRangeTracker fullTracker; @Nullable private String nodeStartingWord; private Document document; public OutlineLocation( FlutterOutline node, int line, int column, int indent, VirtualFile file, WidgetIndentsHighlightingPass pass ) { this.line = line; this.column = column; // These asserts catch cases where the outline is based on inconsistent // state with the document. // TODO(jacobr): tweak values so if these errors occur they will not // cause exceptions to be thrown in release mode. assert (indent >= 0); assert (column >= 0); // It makes no sense for the indent of the line to be greater than the // indent of the actual widget. assert (column >= indent); assert (line >= 0); this.indent = indent; final int nodeOffset = pass.getConvertedOffset(node); final int endOffset = pass.getConvertedOffset(node.getOffset() + node.getLength()); fullTracker = new TextRangeTracker(nodeOffset, endOffset); final int delta = Math.max(column - indent, 0); this.offset = Math.max(nodeOffset - delta, 0); guideTracker = new TextRangeTracker(offset, nodeOffset + 1); } public void dispose() { if (guideTracker != null) { guideTracker.dispose(); } if (fullTracker != null) { fullTracker.dispose(); } } /** * This method must be called if the location is set to update to reflect * edits to the document. * <p> * This method must be called at most once and if it is called, dispose must * also be called to ensure the range marker is disposed. */ public void track(Document document) { this.document = document; assert (indent <= column); fullTracker.track(document); guideTracker.track(document); } @Override public int hashCode() { int hashCode = line; hashCode = hashCode * 31 + column; hashCode = hashCode * 31 + indent; hashCode = hashCode * 31 + offset; return hashCode; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OutlineLocation)) return false; final OutlineLocation other = (OutlineLocation)o; return line == other.line && column == other.column && indent == other.indent && offset == other.offset && getGuideOffset() == other.getGuideOffset(); } /** * Offset in the document accurate even if the document has been edited. */ public int getGuideOffset() { if (guideTracker.isTracking() && guideTracker.getRange() != null) { return guideTracker.getRange().getStartOffset(); } return offset; } // Sometimes markers stop being valid in which case we need to stop // displaying the rendering until they are valid again. public boolean isValid() { if (!guideTracker.isTracking()) return true; return guideTracker.isConsistentEndingWord(); } /** * Line in the document this outline node is at. */ public int getLine() { if (guideTracker.isTracking() && guideTracker.getRange() != null) { return document.getLineNumber(guideTracker.getRange().getStartOffset()); } return line; } public int getColumnForOffset(int offset) { assert (document != null); final int currentLine = document.getLineNumber(offset); return offset - document.getLineStartOffset(currentLine); } /* * Indent of the line to use for line visualization. * * This may intentionally differ from the column as for the line * ` child: Text(` * The indent will be 2 while the column is 9. */ public int getIndent() { if (!guideTracker.isTracking()) { return indent; } final TextRange range = guideTracker.getRange(); assert (range != null); return getColumnForOffset(range.getStartOffset()); } /** * Column this outline node is at. * <p> * This is the column offset of the start of the widget constructor call. */ public int getColumn() { if (!guideTracker.isTracking()) { return column; } final TextRange range = guideTracker.getRange(); assert (range != null); return getColumnForOffset(Math.max(range.getStartOffset(), range.getEndOffset() - 1)); } public TextRange getGuideTextRange() { return guideTracker.getRange(); } public TextRange getFullRange() { return fullTracker.getRange(); } @Override public int compareTo(OutlineLocation o) { // We use the initial location of the outline location when performing // comparisons rather than the current location for efficiency // and stability. int delta = Integer.compare(line, o.line); if (delta != 0) return delta; delta = Integer.compare(column, o.column); if (delta != 0) return delta; return Integer.compare(indent, o.indent); } }
flutter-intellij/flutter-idea/src/io/flutter/editor/OutlineLocation.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/OutlineLocation.java", "repo_id": "flutter-intellij", "token_count": 2841 }
452
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.hotui; import com.google.common.collect.ImmutableList; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtil; import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService; import io.flutter.dart.FlutterDartAnalysisServer; import io.flutter.dart.FlutterOutlineListener; import io.flutter.inspector.InspectorService; import io.flutter.preview.OutlineOffsetConverter; import io.flutter.utils.EventStream; import org.dartlang.analysis.server.protocol.FlutterOutline; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Class that uses the FlutterOutline to maintain the source location for a * Widget even when code edits that would otherwise confuse location tracking * occur. */ public class StableWidgetTracker implements Disposable { private final String currentFilePath; private final InspectorService.Location initialLocation; private final FlutterDartAnalysisServer flutterAnalysisServer; private final OutlineOffsetConverter converter; // Path to the current outline private ArrayList<FlutterOutline> lastPath; FlutterOutline root; private final FlutterOutlineListener outlineListener = new FlutterOutlineListener() { @Override public void outlineUpdated(@NotNull String filePath, @NotNull FlutterOutline outline, @Nullable String instrumentedCode) { if (Objects.equals(currentFilePath, filePath)) { ApplicationManager.getApplication().invokeLater(() -> outlineChanged(outline)); } } }; private void outlineChanged(FlutterOutline outline) { this.root = outline; FlutterOutline match; if (lastPath == null) { // First outline. lastPath = new ArrayList<>(); findOutlineAtOffset(root, initialLocation.getOffset(), lastPath); } else { lastPath = findSimilarPath(root, lastPath); } currentOutlines.setValue(lastPath.isEmpty() ? ImmutableList.of() : ImmutableList.of(lastPath.get(lastPath.size() - 1))); } private static int findChildIndex(FlutterOutline node, FlutterOutline child) { final List<FlutterOutline> children = node.getChildren(); for (int i = 0; i < children.size(); i++) { if (children.get(i) == child) return i; } return -1; } private ArrayList<FlutterOutline> findSimilarPath(FlutterOutline root, ArrayList<FlutterOutline> lastPath) { final ArrayList<FlutterOutline> path = new ArrayList<>(); FlutterOutline node = root; path.add(node); int i = 1; while (i < lastPath.size() && node != null && !node.getChildren().isEmpty()) { final FlutterOutline oldChild = lastPath.get(i); final int expectedIndex = findChildIndex(lastPath.get(i - 1), oldChild); assert (expectedIndex != -1); final List<FlutterOutline> children = node.getChildren(); final int index = Math.min(Math.max(0, expectedIndex), children.size()); node = children.get(index); if (!Objects.equals(node.getClassName(), oldChild.getClassName()) && node.getChildren().size() == 1) { final FlutterOutline child = node.getChildren().get(0); if (Objects.equals(child.getClassName(), oldChild.getClassName())) { // We have detected that the previous widget was wrapped by a new widget. // Add the wrapping widget to the path and otherwise proceed normally. path.add(node); node = child; } } // TODO(jacobr): consider doing some additional validation that the children have the same class names, etc. // We could use that to be reslient to small changes such as adding a new parent widget, etc. path.add(node); i++; } return path; } private boolean findOutlineAtOffset(FlutterOutline outline, int offset, ArrayList<FlutterOutline> path) { if (outline == null) { return false; } path.add(outline); if (converter.getConvertedOutlineOffset(outline) <= offset && offset <= converter.getConvertedOutlineEnd(outline)) { final List<FlutterOutline> children = outline.getChildren(); if (children != null) { for (FlutterOutline child : children) { final boolean foundChild = findOutlineAtOffset(child, offset, path); if (foundChild) { return true; } } } return true; } path.remove(path.size() - 1); return false; } private final EventStream<List<FlutterOutline>> currentOutlines; public EventStream<List<FlutterOutline>> getCurrentOutlines() { return currentOutlines; } public StableWidgetTracker( InspectorService.Location initialLocation, FlutterDartAnalysisServer flutterAnalysisServer, Project project, Disposable parentDisposable ) { Disposer.register(parentDisposable, this); converter = new OutlineOffsetConverter(project, initialLocation.getFile()); currentOutlines = new EventStream<>(ImmutableList.of()); this.flutterAnalysisServer = flutterAnalysisServer; this.initialLocation = initialLocation; final DartAnalysisServerService analysisServerService = DartAnalysisServerService.getInstance(project); currentFilePath = FileUtil.toSystemDependentName(initialLocation.getFile().getPath()); flutterAnalysisServer.addOutlineListener(currentFilePath, outlineListener); } @Override public void dispose() { flutterAnalysisServer.removeOutlineListener(currentFilePath, outlineListener); } public boolean isValid() { return !getCurrentOutlines().getValue().isEmpty(); } public int getOffset() { final List<FlutterOutline> outlines = getCurrentOutlines().getValue(); if (outlines.isEmpty()) return 0; final FlutterOutline outline = outlines.get(0); return converter.getConvertedOutlineOffset(outline); } }
flutter-intellij/flutter-idea/src/io/flutter/hotui/StableWidgetTracker.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/hotui/StableWidgetTracker.java", "repo_id": "flutter-intellij", "token_count": 2064 }
453
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.inspector; import com.google.common.base.Joiner; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider; import com.intellij.xdebugger.impl.XSourcePositionImpl; import com.jetbrains.lang.dart.psi.DartCallExpression; import com.jetbrains.lang.dart.psi.DartExpression; import com.jetbrains.lang.dart.psi.DartReferenceExpression; import io.flutter.bazel.Workspace; import io.flutter.bazel.WorkspaceCache; import io.flutter.pub.PubRoot; import io.flutter.run.FlutterDebugProcess; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.JsonUtils; import io.flutter.utils.StreamSubscription; import io.flutter.utils.VmServiceListenerAdapter; import io.flutter.vmService.ServiceExtensions; import io.flutter.vmService.VmServiceConsumers; import io.flutter.vmService.frame.DartVmServiceValue; import org.dartlang.analysis.server.protocol.FlutterOutline; import org.dartlang.vm.service.VmService; import org.dartlang.vm.service.consumer.ServiceExtensionConsumer; import org.dartlang.vm.service.element.Event; import org.dartlang.vm.service.element.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.BiConsumer; import java.util.function.Supplier; /** * Manages all communication between inspector code running on the DartVM and inspector code running in the IDE. */ public class InspectorService implements Disposable { public static class Location { public Location(@NotNull VirtualFile file, int line, int column, int offset) { this.file = file; this.line = line; this.column = column; this.offset = offset; } @NotNull private final VirtualFile file; private final int line; private final int column; private final int offset; public int getLine() { return line; } public int getColumn() { return column; } public int getOffset() { return offset; } @NotNull public VirtualFile getFile() { return file; } @NotNull public String getPath() { return toSourceLocationUri(file.getPath()); } @Nullable public XSourcePosition getXSourcePosition() { final int line = getLine(); final int column = getColumn(); if (line < 0 || column < 0) { return null; } return XSourcePositionImpl.create(file, line - 1, column - 1); } public static InspectorService.Location outlineToLocation(Project project, VirtualFile file, FlutterOutline outline, Document document) { if (file == null) return null; if (document == null) return null; if (outline == null || outline.getClassName() == null) return null; final int documentLength = document.getTextLength(); int nodeOffset = Math.max(0, Math.min(outline.getCodeOffset(), documentLength)); final int nodeEndOffset = Math.max(0, Math.min(outline.getCodeOffset() + outline.getCodeLength(), documentLength)); // The DartOutline will give us the offset of // 'child: Foo.bar(...)' // but we need the offset of 'bar(...)' for consistentency with the // Flutter kernel transformer. if (outline.getClassName() != null) { final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document); if (psiFile != null) { final PsiElement element = psiFile.findElementAt(nodeOffset); final DartCallExpression callExpression = PsiTreeUtil.getParentOfType(element, DartCallExpression.class); PsiElement match = null; if (callExpression != null) { final DartExpression expression = callExpression.getExpression(); if (expression instanceof DartReferenceExpression) { final DartReferenceExpression referenceExpression = (DartReferenceExpression)expression; final PsiElement[] children = referenceExpression.getChildren(); if (children.length > 1) { // This case handles expressions like 'ClassName.namedConstructor' // and 'libraryPrefix.ClassName.namedConstructor' match = children[children.length - 1]; } else { // this case handles the simple 'ClassName' case. match = referenceExpression; } } } if (match != null) { nodeOffset = match.getTextOffset(); } } } final int line = document.getLineNumber(nodeOffset); final int lineStartOffset = document.getLineStartOffset(line); final int column = nodeOffset - lineStartOffset; return new InspectorService.Location(file, line + 1, column + 1, nodeOffset); } /** * Returns a location for a FlutterOutline object that makes a best effort * to be compatible with the locations generated by the flutter kernel * transformer to track creation locations. */ @Nullable public static InspectorService.Location outlineToLocation(Editor editor, FlutterOutline outline) { if (!(editor instanceof EditorEx)) return null; final EditorEx editorEx = (EditorEx)editor; return outlineToLocation(editor.getProject(), editorEx.getVirtualFile(), outline, editor.getDocument()); } } private static int nextGroupId = 0; public static class InteractiveScreenshot { InteractiveScreenshot(Screenshot screenshot, ArrayList<DiagnosticsNode> boxes, ArrayList<DiagnosticsNode> elements) { this.screenshot = screenshot; this.boxes = boxes; this.elements = elements; } public final Screenshot screenshot; public final ArrayList<DiagnosticsNode> boxes; public final ArrayList<DiagnosticsNode> elements; } @NotNull private final FlutterApp app; @NotNull private final FlutterDebugProcess debugProcess; @NotNull private final VmService vmService; @NotNull private final Set<InspectorServiceClient> clients; @NotNull private final EvalOnDartLibrary inspectorLibrary; @NotNull private final Set<String> supportedServiceMethods; private final StreamSubscription<Boolean> setPubRootDirectoriesSubscription; /** * Convenience ObjectGroup constructor for users who need to use DiagnosticsNode objects before the InspectorService is available. */ public static CompletableFuture<InspectorService.ObjectGroup> createGroup( @NotNull FlutterApp app, @NotNull FlutterDebugProcess debugProcess, @NotNull VmService vmService, String groupName) { return create(app, debugProcess, vmService).thenApplyAsync((service) -> service.createObjectGroup(groupName)); } public static CompletableFuture<InspectorService> create(@NotNull FlutterApp app, @NotNull FlutterDebugProcess debugProcess, @NotNull VmService vmService) { assert app.getVMServiceManager() != null; final Set<String> inspectorLibraryNames = new HashSet<>(); inspectorLibraryNames.add("package:flutter/src/widgets/widget_inspector.dart"); final EvalOnDartLibrary inspectorLibrary = new EvalOnDartLibrary( inspectorLibraryNames, vmService, app.getVMServiceManager() ); final CompletableFuture<Library> libraryFuture = inspectorLibrary.libraryRef.thenComposeAsync((library) -> inspectorLibrary.getLibrary(library, null)); return libraryFuture.thenComposeAsync((Library library) -> { for (ClassRef classRef : library.getClasses()) { if ("WidgetInspectorService".equals(classRef.getName())) { return inspectorLibrary.getClass(classRef, null).thenApplyAsync((ClassObj classObj) -> { final Set<String> functionNames = new HashSet<>(); for (FuncRef funcRef : classObj.getFunctions()) { functionNames.add(funcRef.getName()); } return functionNames; }); } } throw new RuntimeException("WidgetInspectorService class not found"); }).thenApplyAsync( (supportedServiceMethods) -> new InspectorService( app, debugProcess, vmService, inspectorLibrary, supportedServiceMethods)); } private InspectorService(@NotNull FlutterApp app, @NotNull FlutterDebugProcess debugProcess, @NotNull VmService vmService, @NotNull EvalOnDartLibrary inspectorLibrary, @NotNull Set<String> supportedServiceMethods) { this.vmService = vmService; this.app = app; this.debugProcess = debugProcess; this.inspectorLibrary = inspectorLibrary; this.supportedServiceMethods = supportedServiceMethods; clients = new HashSet<>(); vmService.addVmServiceListener(new VmServiceListenerAdapter() { @Override public void received(String streamId, Event event) { onVmServiceReceived(streamId, event); } @Override public void connectionClosed() { // TODO(jacobr): dispose? } }); vmService.streamListen(VmService.EXTENSION_STREAM_ID, VmServiceConsumers.EMPTY_SUCCESS_CONSUMER); assert (app.getVMServiceManager() != null); setPubRootDirectoriesSubscription = app.getVMServiceManager().hasServiceExtension(ServiceExtensions.setPubRootDirectories, (Boolean available) -> { if (!available) { return; } final Workspace workspace = WorkspaceCache.getInstance(app.getProject()).get(); final ArrayList<String> rootDirectories = new ArrayList<>(); if (workspace != null) { for (VirtualFile root : rootsForProject(app.getProject())) { final String relativePath = workspace.getRelativePath(root); // TODO(jacobr): is it an error that the relative path can sometimes be null? if (relativePath != null) { rootDirectories.add(Workspace.BAZEL_URI_SCHEME + "/" + relativePath); } } } else { for (PubRoot root : app.getPubRoots()) { String path = root.getRoot().getCanonicalPath(); if (SystemInfo.isWindows) { // TODO(jacobr): remove after https://github.com/flutter/flutter-intellij/issues/2217. // The problem is setPubRootDirectories is currently expecting // valid URIs as opposed to windows paths. path = "file:///" + path; } rootDirectories.add(path); } } setPubRootDirectories(rootDirectories); }); } @NotNull private static List<VirtualFile> rootsForProject(@NotNull Project project) { final List<VirtualFile> result = new ArrayList<>(); for (Module module : ModuleManager.getInstance(project).getModules()) { Collections.addAll(result, ModuleRootManager.getInstance(module).getContentRoots()); } return result; } /** * Returns whether to use the VM service extension API or use eval to invoke * the protocol directly. * <p> * Eval must be used when paused at a breakpoint as the VM Service extensions * API calls won't execute until after the current frame is done rendering. * TODO(jacobr): evaluate whether we should really be trying to execute while * a frame is rendering at all as the Element tree may be in a broken state. */ private boolean useServiceExtensionApi() { return !app.isFlutterIsolateSuspended(); } public boolean isDetailsSummaryViewSupported() { return hasServiceMethod("getSelectedSummaryWidget"); } public boolean isHotUiScreenMirrorSupported() { // Somewhat arbitrarily chosen new API that is required for full Hot UI // support. return hasServiceMethod("getBoundingBoxes"); } /** * Use this method to write code that is backwards compatible with versions * of Flutter that are too old to contain specific service methods. */ private boolean hasServiceMethod(String methodName) { return supportedServiceMethods.contains(methodName); } @NotNull public FlutterDebugProcess getDebugProcess() { return debugProcess; } public FlutterApp getApp() { return debugProcess.getApp(); } public ObjectGroup createObjectGroup(String debugName) { return new ObjectGroup(this, debugName); } @NotNull private EvalOnDartLibrary getInspectorLibrary() { return inspectorLibrary; } @Override public void dispose() { Disposer.dispose(inspectorLibrary); Disposer.dispose(setPubRootDirectoriesSubscription); } public CompletableFuture<?> forceRefresh() { final List<CompletableFuture<?>> futures = new ArrayList<>(); for (InspectorServiceClient client : clients) { final CompletableFuture<?> future = client.onForceRefresh(); if (future != null && !future.isDone()) { futures.add(future); } } if (futures.isEmpty()) { return CompletableFuture.completedFuture(null); } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); } private void notifySelectionChanged(boolean uiAlreadyUpdated, boolean textEditorUpdated) { ApplicationManager.getApplication().invokeLater(() -> { for (InspectorServiceClient client : clients) { client.onInspectorSelectionChanged(uiAlreadyUpdated, textEditorUpdated); } }); } public void addClient(InspectorServiceClient client) { clients.add(client); } public void removeClient(InspectorServiceClient client) { clients.remove(client); } private void onVmServiceReceived(String streamId, Event event) { switch (streamId) { case VmService.DEBUG_STREAM_ID: { if (event.getKind() == EventKind.Inspect) { // Assume the inspector in Flutter DevTools or on the device widget // inspector has already set the selection on the device so we don't // have to. Having multiple clients set the selection risks race // conditions where the selection ping-pongs back and forth. // Update the UI in IntelliJ. notifySelectionChanged(false, false); } break; } case VmService.EXTENSION_STREAM_ID: { if ("Flutter.Frame".equals(event.getExtensionKind())) { ApplicationManager.getApplication().invokeLater(() -> { for (InspectorServiceClient client : clients) { client.onFlutterFrame(); } }); } break; } case "ToolEvent": { Optional<Event> eventOrNull = Optional.ofNullable(event); if ("navigate".equals(eventOrNull.map(Event::getExtensionKind).orElse(null))) { JsonObject json = eventOrNull.map(Event::getExtensionData).map(ExtensionData::getJson).orElse(null); if (json == null) return; String fileUri = JsonUtils.getStringMember(json, "fileUri"); if (fileUri == null) return; String path; try { path = new URL(fileUri).getFile(); } catch (MalformedURLException e) { return; } if (path == null) return; VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); final int line = JsonUtils.getIntMember(json, "line"); final int column = JsonUtils.getIntMember(json, "column"); ApplicationManager.getApplication().invokeLater(() -> { if (file != null && line >= 0 && column >= 0) { XSourcePositionImpl position = XSourcePositionImpl.create(file, line - 1, column - 1); position.createNavigatable(app.getProject()).navigate(false); } }); } break; } default: } } /** * If the widget tree is not ready, the application should wait for the next * Flutter.Frame event before attempting to display the widget tree. If the * application is ready, the next Flutter.Frame event may never come as no * new frames will be triggered to draw unless something changes in the UI. */ public CompletableFuture<Boolean> isWidgetTreeReady() { if (useServiceExtensionApi()) { return invokeServiceExtensionNoGroup("isWidgetTreeReady", new JsonObject()) .thenApplyAsync(JsonElement::getAsBoolean); } else { return invokeEvalNoGroup("isWidgetTreeReady") .thenApplyAsync((InstanceRef ref) -> "true".equals(ref.getValueAsString())); } } CompletableFuture<JsonElement> invokeServiceExtensionNoGroup(String methodName, List<String> args) { final JsonObject params = new JsonObject(); for (int i = 0; i < args.size(); ++i) { params.addProperty("arg" + i, args.get(i)); } return invokeServiceExtensionNoGroup(methodName, params); } private CompletableFuture<Void> setPubRootDirectories(List<String> rootDirectories) { if (useServiceExtensionApi()) { return invokeServiceExtensionNoGroup("setPubRootDirectories", rootDirectories).thenApplyAsync((ignored) -> null); } else { // TODO(jacobr): remove this call as soon as // `ext.flutter.inspector.*` has been in two revs of the Flutter Beta // channel. The feature landed in the Flutter dev chanel on // April 16, 2018. final JsonArray jsonArray = new JsonArray(); for (String rootDirectory : rootDirectories) { jsonArray.add(rootDirectory); } return getInspectorLibrary().eval( "WidgetInspectorService.instance.setPubRootDirectories(" + new Gson().toJson(jsonArray) + ")", null, null) .thenApplyAsync((instance) -> null); } } CompletableFuture<InstanceRef> invokeEvalNoGroup(String methodName) { return getInspectorLibrary().eval("WidgetInspectorService.instance." + methodName + "()", null, null); } CompletableFuture<JsonElement> invokeServiceExtensionNoGroup(String methodName, JsonObject params) { return invokeServiceExtensionHelper(methodName, params); } private CompletableFuture<JsonElement> invokeServiceExtensionHelper(String methodName, JsonObject params) { // Workaround null values turning into the string "null" when using the VM Service extension protocol. final ArrayList<String> keysToRemove = new ArrayList<>(); for (String key : JsonUtils.getKeySet(params)) { if (params.get(key).isJsonNull()) { keysToRemove.add(key); } } for (String key : keysToRemove) { params.remove(key); } final CompletableFuture<JsonElement> ret = new CompletableFuture<>(); vmService.callServiceExtension( getInspectorLibrary().getIsolateId(), ServiceExtensions.inspectorPrefix + methodName, params, new ServiceExtensionConsumer() { @Override public void received(JsonObject object) { if (object == null) { ret.complete(null); } else { ret.complete(object.get("result")); } } @Override public void onError(RPCError error) { ret.completeExceptionally(new RuntimeException("RPCError calling " + methodName + ": " + error.getMessage())); } } ); return ret; } /** * Class managing a group of inspector objects that can be freed by * a single call to dispose(). * After dispose is called, all pending requests made with the ObjectGroup * will be skipped. This means that clients should not have to write any * special logic to handle orphaned requests. * <p> * safeWhenComplete is the recommended way to await futures returned by the * ObjectGroup as with that method the callback will be skipped if the * ObjectGroup is disposed making it easy to get the correct behavior of * skipping orphaned requests. Otherwise, code needs to handle getting back * futures that return null values for requests from disposed ObjectGroup * objects. */ @SuppressWarnings("CodeBlock2Expr") public class ObjectGroup implements Disposable { final InspectorService service; /** * Object group all objects in this arena are allocated with. */ final String groupName; volatile boolean disposed; final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private ObjectGroup(InspectorService service, String debugName) { this.service = service; this.groupName = debugName + "_" + nextGroupId; nextGroupId++; } public InspectorService getInspectorService() { return service; } /** * Once an ObjectGroup has been disposed, all methods returning * DiagnosticsNode objects will return a placeholder dummy node and all methods * returning lists or maps will return empty lists and all other methods will * return null. Generally code should never call methods on a disposed object * group but sometimes due to chained futures that can be difficult to avoid * and it is simpler return an empty result that will be ignored anyway than to * attempt carefully cancel futures. */ @Override public void dispose() { if (disposed) { return; } lock.writeLock().lock(); invokeVoidServiceMethod("disposeGroup", groupName); disposed = true; lock.writeLock().unlock(); } private <T> CompletableFuture<T> nullIfDisposed(Supplier<CompletableFuture<T>> supplier) { lock.readLock().lock(); if (disposed) { lock.readLock().unlock(); return CompletableFuture.completedFuture(null); } try { return supplier.get(); } finally { lock.readLock().unlock(); } } private <T> T nullValueIfDisposed(Supplier<T> supplier) { lock.readLock().lock(); if (disposed) { lock.readLock().unlock(); return null; } try { return supplier.get(); } finally { lock.readLock().unlock(); } } private void skipIfDisposed(Runnable runnable) { lock.readLock().lock(); if (disposed) { return; } try { runnable.run(); } finally { lock.readLock().unlock(); } } public CompletableFuture<XSourcePosition> getPropertyLocation(InstanceRef instanceRef, String name) { return nullIfDisposed(() -> getInstance(instanceRef) .thenComposeAsync((Instance instance) -> nullValueIfDisposed(() -> getPropertyLocationHelper(instance.getClassRef(), name)))); } public CompletableFuture<XSourcePosition> getPropertyLocationHelper(ClassRef classRef, String name) { return nullIfDisposed(() -> inspectorLibrary.getClass(classRef, this).thenComposeAsync((ClassObj clazz) -> { return nullIfDisposed(() -> { for (FuncRef f : clazz.getFunctions()) { // TODO(pq): check for private properties that match name. if (f.getName().equals(name)) { return inspectorLibrary.getFunc(f, this).thenComposeAsync((Func func) -> nullIfDisposed(() -> { final SourceLocation location = func.getLocation(); return inspectorLibrary.getSourcePosition(debugProcess, location.getScript(), location.getTokenPos(), this); })); } } final ClassRef superClass = clazz.getSuperClass(); return superClass == null ? CompletableFuture.completedFuture(null) : getPropertyLocationHelper(superClass, name); }); })); } public CompletableFuture<DiagnosticsNode> getRoot(FlutterTreeType type) { // There is no excuse to call this method on a disposed group. assert (!disposed); switch (type) { case widget: return getRootWidget(); case renderObject: return getRootRenderObject(); } throw new RuntimeException("Unexpected FlutterTreeType"); } /** * Invokes a static method on the WidgetInspectorService class passing in the specified * arguments. * <p> * Intent is we could refactor how the API is invoked by only changing this call. */ CompletableFuture<InstanceRef> invokeEval(String methodName) { return nullIfDisposed(() -> invokeEval(methodName, groupName)); } CompletableFuture<InstanceRef> invokeEval(String methodName, String arg1) { return nullIfDisposed( () -> getInspectorLibrary().eval("WidgetInspectorService.instance." + methodName + "(\"" + arg1 + "\")", null, this)); } CompletableFuture<JsonElement> invokeVmServiceExtension(String methodName) { return invokeVmServiceExtension(methodName, groupName); } CompletableFuture<JsonElement> invokeVmServiceExtension(String methodName, String objectGroup) { final JsonObject params = new JsonObject(); params.addProperty("objectGroup", objectGroup); return invokeVmServiceExtension(methodName, params); } CompletableFuture<JsonElement> invokeVmServiceExtension(String methodName, String arg, String objectGroup) { final JsonObject params = new JsonObject(); params.addProperty("arg", arg); params.addProperty("objectGroup", objectGroup); return invokeVmServiceExtension(methodName, params); } // All calls to invokeVmServiceExtension bottom out to this call. CompletableFuture<JsonElement> invokeVmServiceExtension(String methodName, JsonObject paramsMap) { return getInspectorLibrary().addRequest( this, methodName, () -> invokeServiceExtensionHelper(methodName, paramsMap) ); } CompletableFuture<JsonElement> invokeVmServiceExtension(String methodName, InspectorInstanceRef arg) { if (arg == null || arg.getId() == null) { return invokeVmServiceExtension(methodName, null, groupName); } return invokeVmServiceExtension(methodName, arg.getId(), groupName); } private void addLocationToParams(Location location, JsonObject params) { if (location == null) return; params.addProperty("file", location.getPath()); params.addProperty("line", location.getLine()); params.addProperty("column", location.getColumn()); } public CompletableFuture<ArrayList<DiagnosticsNode>> getElementsAtLocation(Location location, int count) { final JsonObject params = new JsonObject(); addLocationToParams(location, params); params.addProperty("count", count); params.addProperty("groupName", groupName); return parseDiagnosticsNodesDaemon( inspectorLibrary.invokeServiceMethod("ext.flutter.inspector.getElementsAtLocation", params).thenApplyAsync((o) -> { if (o == null) return null; return o.get("result"); }), null); } public CompletableFuture<ArrayList<DiagnosticsNode>> getBoundingBoxes(DiagnosticsNode root, DiagnosticsNode target) { final JsonObject params = new JsonObject(); if (root == null || target == null || root.getValueRef() == null || target.getValueRef() == null) { return CompletableFuture.completedFuture(new ArrayList<>()); } params.addProperty("rootId", root.getValueRef().getId()); params.addProperty("targetId", target.getValueRef().getId()); params.addProperty("groupName", groupName); return parseDiagnosticsNodesDaemon( inspectorLibrary.invokeServiceMethod("ext.flutter.inspector.getBoundingBoxes", params).thenApplyAsync((o) -> { if (o == null) return null; return o.get("result"); }), null); } public CompletableFuture<ArrayList<DiagnosticsNode>> hitTest(DiagnosticsNode root, double dx, double dy, String file, int startLine, int endLine) { final JsonObject params = new JsonObject(); if (root == null || root.getValueRef() == null) { return CompletableFuture.completedFuture(new ArrayList<>()); } params.addProperty("id", root.getValueRef().getId()); params.addProperty("dx", dx); params.addProperty("dy", dy); if (file != null) { params.addProperty("file", file); } if (startLine >= 0 && endLine >= 0) { params.addProperty("startLine", startLine); params.addProperty("endLine", endLine); } params.addProperty("groupName", groupName); return parseDiagnosticsNodesDaemon( inspectorLibrary.invokeServiceMethod("ext.flutter.inspector.hitTest", params).thenApplyAsync((o) -> { if (o == null) return null; return o.get("result"); }), null); } public CompletableFuture<Boolean> setColorProperty(DiagnosticsNode target, Color color) { // We implement this method directly here rather than landing it in // package:flutter as the right long term solution is to optimize hot reloads of single property changes. // This method only supports Container and Text widgets and will intentionally fail for all other cases. if (target == null || target.getValueRef() == null || color == null) return CompletableFuture.completedFuture(false); final String command = "final object = WidgetInspectorService.instance.toObject('" + target.getValueRef().getId() + "');" + "if (object is! Element) return false;\n" + "final Element element = object;\n" + "final color = Color.fromARGB(" + color.getAlpha() + "," + color.getRed() + "," + color.getGreen() + "," + color.getBlue() + ");\n" + "RenderObject render = element?.renderObject;\n" + "\n" + "if (render is RenderParagraph) {\n" + " RenderParagraph paragraph = render;\n" + " final InlineSpan inlineSpan = paragraph.text;\n" + " if (inlineSpan is! TextSpan) return false;\n" + " final TextSpan existing = inlineSpan;\n" + " paragraph.text = TextSpan(text: existing.text,\n" + " children: existing.children,\n" + " style: existing.style.copyWith(color: color),\n" + " recognizer: existing.recognizer,\n" + " semanticsLabel: existing.semanticsLabel,\n" + " );\n" + " return true;\n" + "} else {\n" + " RenderDecoratedBox findFirstMatching(Element root) {\n" + " RenderDecoratedBox match = null;\n" + " void _matchHelper(Element e) {\n" + " if (match != null || !identical(e, root) && _isLocalCreationLocation(e)) return;\n" + " final r = e.renderObject;\n" + " if (r is RenderDecoratedBox) {\n" + " match = r;\n" + " return;\n" + " }\n" + " e.visitChildElements(_matchHelper);\n" + " }\n" + " _matchHelper(root);\n" + " return match;\n" + " }\n" + "\n" + " final RenderDecoratedBox render = findFirstMatching(element);\n" + " if (render != null) {\n" + " final BoxDecoration existingDecoration = render.decoration;\n" + " BoxDecoration decoration;\n" + " if (existingDecoration is BoxDecoration) {\n" + " decoration = existingDecoration.copyWith(color: color);\n" + " } else if (existingDecoration == null) {\n" + " decoration = BoxDecoration(color: color);\n" + " }\n" + " if (decoration != null) {\n" + " render.decoration = decoration;\n" + " return true;\n" + " }\n" + " }\n" + "}\n" + "return false;\n"; return evaluateCustomApiHelper(command, new HashMap<>()).thenApplyAsync((instanceRef) -> { return instanceRef != null && "true".equals(instanceRef.getValueAsString()); }); } private CompletableFuture<InstanceRef> evaluateCustomApiHelper(String command, Map<String, String> scope) { // Avoid running command if we interrupted executing code as results will // be weird. Repeatedly run the command until we hit idle. // We cannot execute the command at a later point due to eval bugs where // the VM crashes executing a closure created by eval asynchronously. if (isDisposed()) return CompletableFuture.completedFuture(null); final ArrayList<String> lines = new ArrayList<>(); lines.add("((){"); lines.add("if (SchedulerBinding.instance.schedulerPhase != SchedulerPhase.idle) return null;"); final String[] commandLines = command.split("\n"); Collections.addAll(lines, commandLines); lines.add(")()"); // Strip out line breaks as that makes the VM evaluate expression api unhappy. final String expression = Joiner.on("").join(lines); return evalWithRetry(expression, scope); } private CompletableFuture<InstanceRef> evalWithRetry(String expression, Map<String, String> scope) { if (isDisposed()) return CompletableFuture.completedFuture(null); return inspectorLibrary.eval(expression, scope, this).thenComposeAsync( (instanceRef) -> { if (instanceRef == null) { // A null value indicates the request was cancelled. return CompletableFuture.completedFuture(null); } if (instanceRef.isNull()) { // An InstanceRef with an explicitly null return value indicates we should issue the request again. return evalWithRetry(expression, scope); } return CompletableFuture.completedFuture(instanceRef); } ); } public CompletableFuture<InteractiveScreenshot> getScreenshotAtLocation( Location location, int count, int width, int height, double maxPixelRatio) { final JsonObject params = new JsonObject(); addLocationToParams(location, params); params.addProperty("count", count); params.addProperty("width", width); params.addProperty("height", height); params.addProperty("maxPixelRatio", maxPixelRatio); params.addProperty("groupName", groupName); return nullIfDisposed(() -> { return inspectorLibrary.invokeServiceMethod("ext.flutter.inspector.screenshotAtLocation", params).thenApplyAsync( (JsonObject response) -> { if (response == null || response.get("result").isJsonNull()) { // No screenshot available. return null; } final JsonObject result = response.getAsJsonObject("result"); Screenshot screenshot = null; final JsonElement screenshotJson = result.get("screenshot"); if (screenshotJson != null && !screenshotJson.isJsonNull()) { screenshot = getScreenshotFromJson(screenshotJson.getAsJsonObject()); } return new InteractiveScreenshot( screenshot, parseDiagnosticsNodesHelper(result.get("boxes"), null), parseDiagnosticsNodesHelper(result.get("elements"), null) ); }); }); } public CompletableFuture<Screenshot> getScreenshot(InspectorInstanceRef ref, int width, int height, double maxPixelRatio) { final JsonObject params = new JsonObject(); params.addProperty("width", width); params.addProperty("height", height); params.addProperty("maxPixelRatio", maxPixelRatio); params.addProperty("id", ref.getId()); return nullIfDisposed( () -> inspectorLibrary.invokeServiceMethod("ext.flutter.inspector.screenshot", params).thenApplyAsync((JsonObject response) -> { if (response == null || response.get("result").isJsonNull()) { // No screenshot avaiable. return null; } final JsonObject result = response.getAsJsonObject("result"); return getScreenshotFromJson(result); })); } @NotNull private Screenshot getScreenshotFromJson(JsonObject result) { final String imageString = result.getAsJsonPrimitive("image").getAsString(); // create a buffered image final Base64.Decoder decoder = Base64.getDecoder(); final byte[] imageBytes = decoder.decode(imageString); final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageBytes); final BufferedImage image; try { image = ImageIO.read(byteArrayInputStream); byteArrayInputStream.close(); } catch (IOException e) { throw new RuntimeException("Error decoding image: " + e.getMessage()); } final TransformedRect transformedRect = new TransformedRect(result.getAsJsonObject("transformedRect")); return new Screenshot(image, transformedRect); } CompletableFuture<InstanceRef> invokeEval(String methodName, InspectorInstanceRef arg) { return nullIfDisposed(() -> { if (arg == null || arg.getId() == null) { return getInspectorLibrary().eval("WidgetInspectorService.instance." + methodName + "(null, \"" + groupName + "\")", null, this); } return getInspectorLibrary() .eval("WidgetInspectorService.instance." + methodName + "(\"" + arg.getId() + "\", \"" + groupName + "\")", null, this); }); } /** * Call a service method passing in an VM Service instance reference. * <p> * This call is useful when receiving an "inspect" event from the * VM Service and future use cases such as inspecting a Widget from the * IntelliJ watch window. * <p> * This method will always need to use the VM Service as the input * parameter is an VM Service InstanceRef.. */ CompletableFuture<InstanceRef> invokeServiceMethodOnRefEval(String methodName, InstanceRef arg) { return nullIfDisposed(() -> { final HashMap<String, String> scope = new HashMap<>(); if (arg == null) { return getInspectorLibrary().eval("WidgetInspectorService.instance." + methodName + "(null, \"" + groupName + "\")", scope, this); } scope.put("arg1", arg.getId()); return getInspectorLibrary().eval("WidgetInspectorService.instance." + methodName + "(arg1, \"" + groupName + "\")", scope, this); }); } CompletableFuture<DiagnosticsNode> parseDiagnosticsNodeVmService(CompletableFuture<InstanceRef> instanceRefFuture) { return nullIfDisposed(() -> instanceRefFuture.thenComposeAsync(this::parseDiagnosticsNodeVmService)); } /** * Returns a CompletableFuture with a Map of property names to VM Service * InstanceRef objects. This method is shorthand for individually evaluating * each of the getters specified by property names. * <p> * It would be nice if the VM Service protocol provided a built in method * to get InstanceRef objects for a list of properties but this is * sufficient although slightly less efficient. The VM Service protocol * does provide fast access to all fields as part of an Instance object * but that is inadequate as for many Flutter data objects that we want * to display visually we care about properties that are not necessarily * fields. * <p> * The future will immediately complete to null if the inspectorInstanceRef is null. */ public CompletableFuture<Map<String, InstanceRef>> getDartObjectProperties( InspectorInstanceRef inspectorInstanceRef, final String[] propertyNames) { return nullIfDisposed( () -> toVmServiceInstanceRef(inspectorInstanceRef).thenComposeAsync((InstanceRef instanceRef) -> nullIfDisposed(() -> { final StringBuilder sb = new StringBuilder(); final List<String> propertyAccessors = new ArrayList<>(); final String objectName = "that"; for (String propertyName : propertyNames) { propertyAccessors.add(objectName + "." + propertyName); } sb.append("["); sb.append(Joiner.on(',').join(propertyAccessors)); sb.append("]"); final Map<String, String> scope = new HashMap<>(); scope.put(objectName, instanceRef.getId()); return getInstance(inspectorLibrary.eval(sb.toString(), scope, this)).thenApplyAsync( (Instance instance) -> nullValueIfDisposed(() -> { // We now have an instance object that is a Dart array of all the // property values. Convert it back to a map from property name to // property values. final Map<String, InstanceRef> properties = new HashMap<>(); final ElementList<InstanceRef> values = instance.getElements(); assert (values.size() == propertyNames.length); for (int i = 0; i < propertyNames.length; ++i) { properties.put(propertyNames[i], values.get(i)); } return properties; })); }))); } public CompletableFuture<InstanceRef> toVmServiceInstanceRef(InspectorInstanceRef inspectorInstanceRef) { return nullIfDisposed(() -> invokeEval("toObject", inspectorInstanceRef)); } private CompletableFuture<Instance> getInstance(InstanceRef instanceRef) { return nullIfDisposed(() -> getInspectorLibrary().getInstance(instanceRef, this)); } CompletableFuture<Instance> getInstance(CompletableFuture<InstanceRef> instanceRefFuture) { return nullIfDisposed(() -> instanceRefFuture.thenComposeAsync(this::getInstance)); } CompletableFuture<DiagnosticsNode> parseDiagnosticsNodeVmService(InstanceRef instanceRef) { return nullIfDisposed(() -> instanceRefToJson(instanceRef).thenApplyAsync(this::parseDiagnosticsNodeHelper)); } CompletableFuture<DiagnosticsNode> parseDiagnosticsNodeDaemon(CompletableFuture<JsonElement> json) { return nullIfDisposed(() -> json.thenApplyAsync(this::parseDiagnosticsNodeHelper)); } DiagnosticsNode parseDiagnosticsNodeHelper(JsonElement jsonElement) { return nullValueIfDisposed(() -> { if (jsonElement == null || jsonElement.isJsonNull()) { return null; } return new DiagnosticsNode(jsonElement.getAsJsonObject(), this, false, null); }); } CompletableFuture<JsonElement> instanceRefToJson(CompletableFuture<InstanceRef> instanceRefFuture) { return nullIfDisposed(() -> instanceRefFuture.thenComposeAsync(this::instanceRefToJson)); } /** * Requires that the InstanceRef is really referring to a String that is valid JSON. */ CompletableFuture<JsonElement> instanceRefToJson(InstanceRef instanceRef) { if (instanceRef.getValueAsString() != null && !instanceRef.getValueAsStringIsTruncated()) { // In some situations, the string may already be fully populated. final JsonElement json = JsonUtils.parseString(instanceRef.getValueAsString()); return CompletableFuture.completedFuture(json); } else { // Otherwise, retrieve the full value of the string. return nullIfDisposed(() -> getInspectorLibrary().getInstance(instanceRef, this).thenApplyAsync((Instance instance) -> { return nullValueIfDisposed(() -> { final String json = instance.getValueAsString(); return JsonUtils.parseString(json); }); })); } } CompletableFuture<ArrayList<DiagnosticsNode>> parseDiagnosticsNodesVmService(InstanceRef instanceRef, DiagnosticsNode parent) { return nullIfDisposed(() -> instanceRefToJson(instanceRef).thenApplyAsync((JsonElement jsonElement) -> { return nullValueIfDisposed(() -> { final JsonArray jsonArray = jsonElement != null ? jsonElement.getAsJsonArray() : null; return parseDiagnosticsNodesHelper(jsonArray, parent); }); })); } ArrayList<DiagnosticsNode> parseDiagnosticsNodesHelper(JsonElement jsonObject, DiagnosticsNode parent) { return parseDiagnosticsNodesHelper(jsonObject != null && !jsonObject.isJsonNull() ? jsonObject.getAsJsonArray() : null, parent); } ArrayList<DiagnosticsNode> parseDiagnosticsNodesHelper(JsonArray jsonArray, DiagnosticsNode parent) { return nullValueIfDisposed(() -> { if (jsonArray == null) { return null; } final ArrayList<DiagnosticsNode> nodes = new ArrayList<>(); for (JsonElement element : jsonArray) { nodes.add(new DiagnosticsNode(element.getAsJsonObject(), this, false, parent)); } return nodes; }); } /** * Converts an inspector ref to value suitable for use by generic intellij * debugging tools. * <p> * Warning: FlutterVmServiceValue references do not make any lifetime guarantees * so code keeping them around for a long period of time must be prepared to * handle reference expiration gracefully. */ public CompletableFuture<DartVmServiceValue> toDartVmServiceValue(InspectorInstanceRef inspectorInstanceRef) { return invokeEval("toObject", inspectorInstanceRef).thenApplyAsync( (InstanceRef instanceRef) -> nullValueIfDisposed(() -> { //noinspection CodeBlock2Expr return new DartVmServiceValue(debugProcess, inspectorLibrary.getIsolateId(), "inspectedObject", instanceRef, null, null, false); })); } /** * Converts an inspector ref to value suitable for use by generic intellij * debugging tools. * <p> * Warning: FlutterVmServiceValue references do not make any lifetime guarantees * so code keeping them around for a long period of time must be prepared to * handle reference expiration gracefully. */ public CompletableFuture<DartVmServiceValue> toDartVmServiceValueForSourceLocation(InspectorInstanceRef inspectorInstanceRef) { return invokeEval("toObjectForSourceLocation", inspectorInstanceRef).thenApplyAsync( (InstanceRef instanceRef) -> nullValueIfDisposed(() -> { //noinspection CodeBlock2Expr return new DartVmServiceValue(debugProcess, inspectorLibrary.getIsolateId(), "inspectedObject", instanceRef, null, null, false); })); } CompletableFuture<ArrayList<DiagnosticsNode>> parseDiagnosticsNodesVmService(CompletableFuture<InstanceRef> instanceRefFuture, DiagnosticsNode parent) { return nullIfDisposed( () -> instanceRefFuture.thenComposeAsync((instanceRef) -> parseDiagnosticsNodesVmService(instanceRef, parent))); } CompletableFuture<ArrayList<DiagnosticsNode>> parseDiagnosticsNodesDaemon(CompletableFuture<JsonElement> jsonFuture, DiagnosticsNode parent) { return nullIfDisposed(() -> jsonFuture.thenApplyAsync((json) -> parseDiagnosticsNodesHelper(json, parent))); } CompletableFuture<ArrayList<DiagnosticsNode>> getChildren(InspectorInstanceRef instanceRef, boolean summaryTree, DiagnosticsNode parent) { if (isDetailsSummaryViewSupported()) { return getListHelper(instanceRef, summaryTree ? "getChildrenSummaryTree" : "getChildrenDetailsSubtree", parent); } else { return getListHelper(instanceRef, "getChildren", parent); } } CompletableFuture<ArrayList<DiagnosticsNode>> getProperties(InspectorInstanceRef instanceRef) { return getListHelper(instanceRef, "getProperties", null); } private CompletableFuture<ArrayList<DiagnosticsNode>> getListHelper( InspectorInstanceRef instanceRef, String methodName, DiagnosticsNode parent) { return nullIfDisposed(() -> { if (useServiceExtensionApi()) { return parseDiagnosticsNodesDaemon(invokeVmServiceExtension(methodName, instanceRef), parent); } else { return parseDiagnosticsNodesVmService(invokeEval(methodName, instanceRef), parent); } }); } public CompletableFuture<DiagnosticsNode> invokeServiceMethodReturningNode(String methodName) { return nullIfDisposed(() -> { if (useServiceExtensionApi()) { return parseDiagnosticsNodeDaemon(invokeVmServiceExtension(methodName)); } else { return parseDiagnosticsNodeVmService(invokeEval(methodName)); } }); } public CompletableFuture<DiagnosticsNode> invokeServiceMethodReturningNode(String methodName, InspectorInstanceRef ref) { return nullIfDisposed(() -> { if (useServiceExtensionApi()) { return parseDiagnosticsNodeDaemon(invokeVmServiceExtension(methodName, ref)); } else { return parseDiagnosticsNodeVmService(invokeEval(methodName, ref)); } }); } public CompletableFuture<Void> invokeVoidServiceMethod(String methodName, String arg1) { return nullIfDisposed(() -> { if (useServiceExtensionApi()) { return invokeVmServiceExtension(methodName, arg1).thenApply((ignored) -> null); } else { return invokeEval(methodName, arg1).thenApply((ignored) -> null); } }); } public CompletableFuture<Void> invokeVoidServiceMethod(String methodName, InspectorInstanceRef ref) { return nullIfDisposed(() -> { if (useServiceExtensionApi()) { return invokeVmServiceExtension(methodName, ref).thenApply((ignored) -> null); } else { return invokeEval(methodName, ref).thenApply((ignored) -> null); } }); } public CompletableFuture<DiagnosticsNode> getRootWidget() { return invokeServiceMethodReturningNode(isDetailsSummaryViewSupported() ? "getRootWidgetSummaryTree" : "getRootWidget"); } public CompletableFuture<DiagnosticsNode> getElementForScreenshot() { return invokeServiceMethodReturningNode("getElementForScreenshot"); } public CompletableFuture<DiagnosticsNode> getSummaryTreeWithoutIds() { return parseDiagnosticsNodeDaemon(invokeVmServiceExtension("getRootWidgetSummaryTree", new JsonObject())); } public CompletableFuture<DiagnosticsNode> getRootRenderObject() { assert (!disposed); return invokeServiceMethodReturningNode("getRootRenderObject"); } public CompletableFuture<ArrayList<DiagnosticsPathNode>> getParentChain(DiagnosticsNode target) { return nullIfDisposed(() -> { if (useServiceExtensionApi()) { return parseDiagnosticsPathDaemon(invokeVmServiceExtension("getParentChain", target.getValueRef())); } else { return parseDiagnosticsPathVmService(invokeEval("getParentChain", target.getValueRef())); } }); } CompletableFuture<ArrayList<DiagnosticsPathNode>> parseDiagnosticsPathVmService(CompletableFuture<InstanceRef> instanceRefFuture) { return nullIfDisposed(() -> instanceRefFuture.thenComposeAsync(this::parseDiagnosticsPathVmService)); } private CompletableFuture<ArrayList<DiagnosticsPathNode>> parseDiagnosticsPathVmService(InstanceRef pathRef) { return nullIfDisposed(() -> instanceRefToJson(pathRef).thenApplyAsync(this::parseDiagnosticsPathHelper)); } CompletableFuture<ArrayList<DiagnosticsPathNode>> parseDiagnosticsPathDaemon(CompletableFuture<JsonElement> jsonFuture) { return nullIfDisposed(() -> jsonFuture.thenApplyAsync(this::parseDiagnosticsPathHelper)); } private ArrayList<DiagnosticsPathNode> parseDiagnosticsPathHelper(JsonElement jsonElement) { return nullValueIfDisposed(() -> { final JsonArray jsonArray = jsonElement.getAsJsonArray(); final ArrayList<DiagnosticsPathNode> pathNodes = new ArrayList<>(); for (JsonElement element : jsonArray) { pathNodes.add(new DiagnosticsPathNode(element.getAsJsonObject(), this)); } return pathNodes; }); } public CompletableFuture<DiagnosticsNode> getSelection(DiagnosticsNode previousSelection, FlutterTreeType treeType, boolean localOnly) { // There is no reason to allow calling this method on a disposed group. assert (!disposed); return nullIfDisposed(() -> { CompletableFuture<DiagnosticsNode> result = null; final InspectorInstanceRef previousSelectionRef = previousSelection != null ? previousSelection.getDartDiagnosticRef() : null; switch (treeType) { case widget: result = invokeServiceMethodReturningNode(localOnly ? "getSelectedSummaryWidget" : "getSelectedWidget", previousSelectionRef); break; case renderObject: result = invokeServiceMethodReturningNode("getSelectedRenderObject", previousSelectionRef); break; } return result.thenApplyAsync((DiagnosticsNode newSelection) -> nullValueIfDisposed(() -> { if (newSelection != null && newSelection.getDartDiagnosticRef().equals(previousSelectionRef)) { return previousSelection; } else { return newSelection; } })); }); } public void setSelection(InspectorInstanceRef selection, boolean uiAlreadyUpdated, boolean textEditorUpdated) { if (disposed) { return; } if (selection == null || selection.getId() == null) { return; } if (useServiceExtensionApi()) { handleSetSelectionDaemon(invokeVmServiceExtension("setSelectionById", selection), uiAlreadyUpdated, textEditorUpdated); } else { handleSetSelectionVmService(invokeEval("setSelectionById", selection), uiAlreadyUpdated, textEditorUpdated); } } public void setSelection(Location location, boolean uiAlreadyUpdated, boolean textEditorUpdated) { if (disposed) { return; } if (location == null) { return; } if (useServiceExtensionApi()) { final JsonObject params = new JsonObject(); addLocationToParams(location, params); handleSetSelectionDaemon(invokeVmServiceExtension("setSelectionByLocation", params), uiAlreadyUpdated, textEditorUpdated); } // skip if the vm service is expected to be used directly. } /** * Helper when we need to set selection given an VM Service InstanceRef * instead of an InspectorInstanceRef. */ public void setSelection(InstanceRef selection, boolean uiAlreadyUpdated, boolean textEditorUpdated) { // There is no excuse for calling setSelection using a disposed ObjectGroup. assert (!disposed); // This call requires the VM Service protocol as an VM Service InstanceRef is specified. handleSetSelectionVmService(invokeServiceMethodOnRefEval("setSelection", selection), uiAlreadyUpdated, textEditorUpdated); } private void handleSetSelectionVmService(CompletableFuture<InstanceRef> setSelectionResult, boolean uiAlreadyUpdated, boolean textEditorUpdated) { // TODO(jacobr): we need to cancel if another inspect request comes in while we are trying this one. skipIfDisposed(() -> setSelectionResult.thenAcceptAsync((InstanceRef instanceRef) -> skipIfDisposed(() -> { handleSetSelectionHelper("true".equals(instanceRef.getValueAsString()), uiAlreadyUpdated, textEditorUpdated); }))); } private void handleSetSelectionHelper(boolean selectionChanged, boolean uiAlreadyUpdated, boolean textEditorUpdated) { if (selectionChanged) { notifySelectionChanged(uiAlreadyUpdated, textEditorUpdated); } } private void handleSetSelectionDaemon(CompletableFuture<JsonElement> setSelectionResult, boolean uiAlreadyUpdated, boolean textEditorUpdated) { skipIfDisposed(() -> // TODO(jacobr): we need to cancel if another inspect request comes in while we are trying this one. setSelectionResult.thenAcceptAsync( (JsonElement json) -> skipIfDisposed( () -> handleSetSelectionHelper(json.getAsBoolean(), uiAlreadyUpdated, textEditorUpdated))) ); } public CompletableFuture<Map<String, InstanceRef>> getEnumPropertyValues(InspectorInstanceRef ref) { return nullIfDisposed(() -> { if (ref == null || ref.getId() == null) { return CompletableFuture.completedFuture(null); } return getInstance(toVmServiceInstanceRef(ref)) .thenComposeAsync( (Instance instance) -> nullIfDisposed(() -> getInspectorLibrary().getClass(instance.getClassRef(), this).thenApplyAsync( (ClassObj clazz) -> nullValueIfDisposed(() -> { final Map<String, InstanceRef> properties = new LinkedHashMap<>(); for (FieldRef field : clazz.getFields()) { final String name = field.getName(); if (name.startsWith("_")) { // Needed to filter out _deleted_enum_sentinel synthetic property. // If showing private enum values is useful we could special case // just the _deleted_enum_sentinel property name. continue; } if (name.equals("values")) { // Need to filter out the synthetic "values" member. // TODO(jacobr): detect that this properties return type is // different and filter that way. continue; } if (field.isConst() && field.isStatic()) { properties.put(field.getName(), field.getDeclaredType()); } } return properties; }) ))); }); } public CompletableFuture<DiagnosticsNode> getDetailsSubtree(DiagnosticsNode node) { if (node == null) { return CompletableFuture.completedFuture(null); } return nullIfDisposed(() -> invokeServiceMethodReturningNode("getDetailsSubtree", node.getDartDiagnosticRef())); } public XDebuggerEditorsProvider getEditorsProvider() { return InspectorService.this.getDebugProcess().getEditorsProvider(); } FlutterApp getApp() { return InspectorService.this.getApp(); } /** * Await a Future invoking the callback on completion on the UI thread only if the * rhis ObjectGroup is still alive when the Future completes. */ public <T> void safeWhenComplete(CompletableFuture<T> future, BiConsumer<? super T, ? super Throwable> action) { if (future == null) { return; } future.whenCompleteAsync( (T value, Throwable throwable) -> skipIfDisposed(() -> { ApplicationManager.getApplication().invokeLater(() -> { action.accept(value, throwable); }); }) ); } public boolean isDisposed() { return disposed; } } public static String getFileUriPrefix() { return SystemInfo.isWindows ? "file:///" : "file://"; } // TODO(jacobr): remove this method as soon as the // track-widget-creation kernel transformer is fixed to return paths instead // of URIs. public static String toSourceLocationUri(String path) { return getFileUriPrefix() + path; } public static String fromSourceLocationUri(String path, Project project) { final Workspace workspace = WorkspaceCache.getInstance(project).get(); if (workspace != null) { path = workspace.convertPath(path); } final String filePrefix = getFileUriPrefix(); return path.startsWith(filePrefix) ? path.substring(filePrefix.length()) : path; } public enum FlutterTreeType { widget("Widget"), renderObject("Render"); // TODO(jacobr): add semantics, and layer trees. public final String displayName; FlutterTreeType(String displayName) { this.displayName = displayName; } } public interface InspectorServiceClient { void onInspectorSelectionChanged(boolean uiAlreadyUpdated, boolean textEditorUpdated); void onFlutterFrame(); CompletableFuture<?> onForceRefresh(); } }
flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorService.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorService.java", "repo_id": "flutter-intellij", "token_count": 23704 }
454
/* * Copyright 2020 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.jxbrowser; import com.google.common.annotations.VisibleForTesting; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfo; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.download.DownloadableFileDescription; import com.intellij.util.download.DownloadableFileService; import com.intellij.util.download.FileDownloader; import com.teamdev.jxbrowser.browser.UnsupportedRenderingModeException; import com.teamdev.jxbrowser.engine.RenderingMode; import io.flutter.FlutterInitializer; import io.flutter.analytics.Analytics; import io.flutter.settings.FlutterSettings; import io.flutter.utils.FileUtils; import io.flutter.utils.JxBrowserUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * JxBrowser provides Chromium to display web pages within IntelliJ. This class manages downloading the required files and adding them to * the class path. */ public class JxBrowserManager { private static JxBrowserManager manager; private static String getPluginLoaderDir() { try { final ApplicationInfo info = ApplicationInfo.getInstance(); assert info != null; if (Objects.equals(info.getMajorVersion(), "2021")) { if (Objects.equals(info.getMinorVersion(), "3")) { return "flutter-idea"; } else { return "flutter-intellij"; } } else if (Objects.equals(info.getMajorVersion(), "2020")) { return "flutter-intellij"; } } catch (NullPointerException ex) { // ignored; unit tests } return "flutter-idea"; } @NotNull protected static final String DOWNLOAD_PATH = PathManager.getPluginsPath() + File.separatorChar + getPluginLoaderDir() + File.separatorChar + "jxbrowser"; @NotNull private static final AtomicReference<JxBrowserStatus> status = new AtomicReference<>(JxBrowserStatus.NOT_INSTALLED); @NotNull private static final AtomicBoolean listeningForSetting = new AtomicBoolean(false); @NotNull private static final Logger LOG = Logger.getInstance(JxBrowserManager.class); @NotNull private static CompletableFuture<JxBrowserStatus> installation = new CompletableFuture<>(); @NotNull public static final String ANALYTICS_CATEGORY = "jxbrowser"; private static InstallationFailedReason latestFailureReason; private final JxBrowserUtils jxBrowserUtils; private final Analytics analytics; private final FileUtils fileUtils; @VisibleForTesting protected JxBrowserManager(@NotNull JxBrowserUtils jxBrowserUtils, @NotNull Analytics analytics, @NotNull FileUtils fileUtils) { this.jxBrowserUtils = jxBrowserUtils; this.analytics = analytics; this.fileUtils = fileUtils; } @NotNull public static JxBrowserManager getInstance() { if (manager == null) { //noinspection ConstantConditions manager = new JxBrowserManager(new JxBrowserUtils(), FlutterInitializer.getAnalytics(), FileUtils.getInstance()); } return manager; } @VisibleForTesting protected static void resetForTest() { status.set(JxBrowserStatus.NOT_INSTALLED); } @NotNull public JxBrowserStatus getStatus() { //noinspection ConstantConditions return status.get(); } @Nullable public InstallationFailedReason getLatestFailureReason() { return latestFailureReason; } /** * Call {@link #setUp} before this function to ensure that an installation has started. */ @Nullable public JxBrowserStatus waitForInstallation(int seconds) throws TimeoutException { try { return installation.get(seconds, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException e) { LOG.info("Waiting for JxBrowser to install threw an exception"); return null; } } public void retryFromFailed(@NotNull Project project) { if (!status.compareAndSet(JxBrowserStatus.INSTALLATION_FAILED, JxBrowserStatus.NOT_INSTALLED)) { return; } LOG.info(project.getName() + ": Retrying JxBrowser installation"); setUp(project); } private class SettingsListener implements FlutterSettings.Listener { final Project project; public SettingsListener(@NotNull Project project) { this.project = project; } @Override public void settingsChanged() { final FlutterSettings settings = FlutterSettings.getInstance(); // Set up JxBrowser files if the embedded inspector option has been turned on and the files aren't already loaded. //noinspection ConstantConditions if (getStatus().equals(JxBrowserStatus.NOT_INSTALLED)) { setUp(project); } } } private void setStatusFailed(@NotNull InstallationFailedReason reason) { setStatusFailed(reason, null); } private void setStatusFailed(@NotNull InstallationFailedReason reason, @Nullable Long time) { final StringBuilder eventName = new StringBuilder(); eventName.append("installationFailed-"); eventName.append(reason.failureType); if (reason.detail != null) { eventName.append("-"); eventName.append(reason.detail); } if (time != null) { analytics.sendEventMetric(ANALYTICS_CATEGORY, eventName.toString(), time.intValue()); } else { analytics.sendEvent(ANALYTICS_CATEGORY, eventName.toString()); } latestFailureReason = reason; status.set(JxBrowserStatus.INSTALLATION_FAILED); installation.complete(JxBrowserStatus.INSTALLATION_FAILED); } public void listenForSettingChanges(@NotNull Project project) { if (!listeningForSetting.compareAndSet(false, true)) { // We can return early because another project already triggered the listener. return; } //noinspection ConstantConditions FlutterSettings.getInstance().addListener(new SettingsListener(project)); } public void setUp(@NotNull Project project) { if (jxBrowserUtils.skipInstallation()) { status.set(JxBrowserStatus.INSTALLATION_SKIPPED); return; } if (!jxBrowserUtils.skipInstallation() && status.get().equals(JxBrowserStatus.INSTALLATION_SKIPPED)) { // This check returns status to NOT_INSTALLED so that JxBrowser can be downloaded and installed in cases where it is enabled after being disabled. status.compareAndSet(JxBrowserStatus.INSTALLATION_SKIPPED, JxBrowserStatus.NOT_INSTALLED); } if (!status.compareAndSet(JxBrowserStatus.NOT_INSTALLED, JxBrowserStatus.INSTALLATION_IN_PROGRESS)) { // This check ensures that an IDE only downloads and installs JxBrowser once, even if multiple projects are open. // If already in progress, let calling point wait until success or failure (it may make sense to call setUp but proceed). // If already succeeded or failed, no need to continue. return; } // Retrieve key try { final String key = jxBrowserUtils.getJxBrowserKey(); System.setProperty(JxBrowserUtils.LICENSE_PROPERTY_NAME, key); } catch (FileNotFoundException e) { LOG.info(project.getName() + ": Unable to find JxBrowser license key file", e); setStatusFailed(new InstallationFailedReason(FailureType.MISSING_KEY)); return; } // If installation future has not finished, we don't want to overwrite it. There could be other code listening for the previous attempt // to succeed or fail. // We expect to create a new CompletableFuture only if the previous installation attempt failed. if (installation.isDone()) { installation = new CompletableFuture<>(); } LOG.info(project.getName() + ": Installing JxBrowser"); final boolean directoryExists = fileUtils.makeDirectory(DOWNLOAD_PATH); if (!directoryExists) { LOG.info(project.getName() + ": Unable to create directory for JxBrowser files"); setStatusFailed(new InstallationFailedReason(FailureType.DIRECTORY_CREATION_FAILED)); return; } final String platformFileName; try { platformFileName = jxBrowserUtils.getPlatformFileName(); } catch (FileNotFoundException e) { LOG.info(project.getName() + ": Unable to find JxBrowser platform file for " + SystemInfo.getOsNameAndVersion()); setStatusFailed(new InstallationFailedReason(FailureType.MISSING_PLATFORM_FILES, SystemInfo.getOsNameAndVersion())); return; } // Check whether the files already exist. final String[] fileNames = {platformFileName, jxBrowserUtils.getApiFileName(), jxBrowserUtils.getSwingFileName()}; boolean allDownloaded = true; for (String fileName : fileNames) { assert fileName != null; if (!fileUtils.fileExists(getFilePath(fileName))) { allDownloaded = false; break; } } if (allDownloaded) { LOG.info(project.getName() + ": JxBrowser platform files already exist, skipping download"); loadClasses(fileNames); return; } // Delete any already existing files. // TODO(helin24): Handle if files cannot be deleted. for (String fileName : fileNames) { assert fileName != null; final String filePath = getFilePath(fileName); if (!fileUtils.deleteFile(filePath)) { LOG.info(project.getName() + ": Existing file could not be deleted - " + filePath); } } downloadJxBrowser(project, fileNames); } protected void downloadJxBrowser(@NotNull Project project, @NotNull String[] fileNames) { // The FileDownloader API is used by other plugins - e.g. // https://github.com/JetBrains/intellij-community/blob/b09f8151e0d189d70363266c3bb6edb5f6bfeca4/plugins/markdown/src/org/intellij/plugins/markdown/ui/preview/javafx/JavaFXInstallator.java#L48 final List<FileDownloader> fileDownloaders = new ArrayList<>(); final DownloadableFileService service = DownloadableFileService.getInstance(); assert service != null; for (String fileName : fileNames) { assert fileName != null; final DownloadableFileDescription description = service.createFileDescription(jxBrowserUtils.getDistributionLink(fileName), fileName); fileDownloaders.add(service.createDownloader(Collections.singletonList(description), fileName)); } final Task.Backgroundable task = new Task.Backgroundable(project, "Downloading jxbrowser") { @Override public void run(@NotNull ProgressIndicator indicator) { if (project.isDisposed()) { return; } String currentFileName = null; final long startTime = System.currentTimeMillis(); try { for (int i = 0; i < fileDownloaders.size(); i++) { final FileDownloader downloader = fileDownloaders.get(i); assert downloader != null; currentFileName = fileNames[i]; final Pair<File, DownloadableFileDescription> download = ContainerUtil.getFirstItem(downloader.download(new File(DOWNLOAD_PATH))); final File file = download != null ? download.first : null; if (file != null) { LOG.info(project.getName() + ": JxBrowser file downloaded: " + file.getAbsolutePath()); } } analytics.sendEvent(ANALYTICS_CATEGORY, "filesDownloaded"); loadClasses(fileNames); } catch (IOException e) { final long elapsedTime = System.currentTimeMillis() - startTime; LOG.info(project.getName() + ": JxBrowser file downloaded failed: " + currentFileName); setStatusFailed(new InstallationFailedReason(FailureType.FILE_DOWNLOAD_FAILED, currentFileName + ":" + e.getMessage()), elapsedTime); } } }; final BackgroundableProcessIndicator processIndicator = new BackgroundableProcessIndicator(task); processIndicator.setIndeterminate(false); ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, processIndicator); } private void loadClasses2020(@NotNull String[] fileNames) { final ClassLoader current = Thread.currentThread().getContextClassLoader(); try { //noinspection ConstantConditions Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); //noinspection ConstantConditions for (String fileName : fileNames) { final String fullPath = getFilePath(fileName); try { //noinspection ConstantConditions fileUtils.loadClass(this.getClass().getClassLoader(), fullPath); } catch (Exception ex) { LOG.info("Failed to load JxBrowser file", ex); setStatusFailed(new InstallationFailedReason(FailureType.CLASS_LOAD_FAILED)); return; } LOG.info("Loaded JxBrowser file successfully: " + fullPath); } try { final Class<?> clazz = Class.forName("com.teamdev.jxbrowser.browser.UnsupportedRenderingModeException"); final Constructor<?> constructor = clazz.getConstructor(RenderingMode.class); constructor.newInstance(RenderingMode.HARDWARE_ACCELERATED); } catch (NoClassDefFoundError | ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { LOG.info("Failed to find JxBrowser class: " + e.getMessage()); setStatusFailed(new InstallationFailedReason(FailureType.CLASS_NOT_FOUND)); return; } } finally { Thread.currentThread().setContextClassLoader(current); } analytics.sendEvent(ANALYTICS_CATEGORY, "installed"); status.set(JxBrowserStatus.INSTALLED); installation.complete(JxBrowserStatus.INSTALLED); } private void loadClasses(@NotNull String[] fileNames) { final List<Path> paths = new ArrayList<>(); final ClassLoader current = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); try { for (String fileName : fileNames) { assert fileName != null; paths.add(Paths.get(getFilePath(fileName))); } //noinspection ConstantConditions fileUtils.loadPaths(this.getClass().getClassLoader(), paths); } catch (Exception ex) { LOG.info("Failed to load JxBrowser file", ex); setStatusFailed(new InstallationFailedReason(FailureType.CLASS_LOAD_FAILED)); return; } LOG.info("Loaded JxBrowser files successfully: " + paths); try { final Class<?> clazz = Class.forName("com.teamdev.jxbrowser.browser.UnsupportedRenderingModeException"); final Constructor<?> constructor = clazz.getConstructor(RenderingMode.class); constructor.newInstance(RenderingMode.HARDWARE_ACCELERATED); //noinspection ThrowableNotThrown final UnsupportedRenderingModeException test = new UnsupportedRenderingModeException(RenderingMode.HARDWARE_ACCELERATED); } catch (NoClassDefFoundError | ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { LOG.info("Failed to find JxBrowser class: ", e); setStatusFailed(new InstallationFailedReason(FailureType.CLASS_NOT_FOUND)); return; } } finally { Thread.currentThread().setContextClassLoader(current); } analytics.sendEvent(ANALYTICS_CATEGORY, "installed"); status.set(JxBrowserStatus.INSTALLED); installation.complete(JxBrowserStatus.INSTALLED); } @NotNull private String getFilePath(@NotNull String fileName) { return DOWNLOAD_PATH + File.separatorChar + fileName; } }
flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/JxBrowserManager.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/JxBrowserManager.java", "repo_id": "flutter-intellij", "token_count": 5858 }
455
<?xml version="1.0" encoding="UTF-8"?> <form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="io.flutter.module.settings.RadiosForm"> <grid id="27dc6" binding="radiosPanel" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> <margin top="0" left="0" bottom="0" right="0"/> <constraints> <xy x="20" y="20" width="500" height="400"/> </constraints> <properties/> <border type="none"/> <children> <component id="e66fc" class="javax.swing.JRadioButton" binding="radio1"> <constraints> <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"> <minimum-size width="125" height="-1"/> </grid> </constraints> <properties> <text value="RadioButton"/> </properties> </component> <vspacer id="54bf5"> <constraints> <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/> </constraints> </vspacer> <component id="4c96b" class="javax.swing.JRadioButton" binding="radio2"> <constraints> <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <text value="RadioButton"/> </properties> </component> <hspacer id="c64a5"> <constraints> <grid row="0" column="2" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/> </constraints> </hspacer> </children> </grid> </form>
flutter-intellij/flutter-idea/src/io/flutter/module/settings/RadiosForm.form/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/settings/RadiosForm.form", "repo_id": "flutter-intellij", "token_count": 853 }
456
/* * 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; /** * Base class for all view models displaying performance stats */ public interface PerfModel { void markAppIdle(); void clear(); void onFrame(); boolean isAnimationActive(); }
flutter-intellij/flutter-idea/src/io/flutter/perf/PerfModel.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/PerfModel.java", "repo_id": "flutter-intellij", "token_count": 106 }
457
/* * 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.performance; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.Disposer; import com.intellij.ui.JBColor; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBPanel; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import io.flutter.run.daemon.FlutterApp; import io.flutter.vmService.DisplayRefreshRateManager; import io.flutter.vmService.FlutterFramesMonitor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.geom.Path2D; import java.text.DecimalFormat; import java.util.List; import java.util.*; // TODO(devoncarew): We have a drawing artifacts issue - tall frame columns can be left behind // as artifacts when they scroll off the screen. public class FrameRenderingDisplay { static final DecimalFormat df = new DecimalFormat(); static { df.setMaximumFractionDigits(1); } public static JPanel createJPanelView(@NotNull Disposable parentDisposable, @NotNull FlutterApp app) { final JPanel panel = new JPanel(new StackLayout()); panel.setDoubleBuffered(true); assert app.getVMServiceManager() != null; final FlutterFramesMonitor flutterFramesMonitor = app.getVMServiceManager().getFlutterFramesMonitor(); final FrameRenderingPanel frameRenderingPanel = new FrameRenderingPanel(flutterFramesMonitor, app.getDisplayRefreshRateManager()); final JBLabel targetFrameTimeLabel = new JBLabel(); targetFrameTimeLabel.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL)); targetFrameTimeLabel.setForeground(UIUtil.getLabelDisabledForeground()); targetFrameTimeLabel.setBorder(JBUI.Borders.empty(2)); targetFrameTimeLabel.setOpaque(false); updateTargetLabelForRefreshRate( app.getDisplayRefreshRateManager().getCurrentDisplayRefreshRateRaw(), DisplayRefreshRateManager.defaultRefreshRate, targetFrameTimeLabel ); // Listen for updates to the display refresh rate. app.getDisplayRefreshRateManager().getCurrentDisplayRefreshRate((fps) -> { updateTargetLabelForRefreshRate(fps, DisplayRefreshRateManager.defaultRefreshRate, targetFrameTimeLabel); }, false); //noinspection rawtypes final JBPanel targetFrameTimePanel = new JBPanel(); targetFrameTimePanel.setLayout(new BoxLayout(targetFrameTimePanel, BoxLayout.Y_AXIS)); targetFrameTimePanel.setOpaque(false); targetFrameTimePanel.add(Box.createVerticalGlue()); targetFrameTimePanel.add(targetFrameTimeLabel); targetFrameTimePanel.add(Box.createVerticalGlue()); panel.add(frameRenderingPanel); panel.add(targetFrameTimePanel); final FlutterFramesMonitor.Listener listener = event -> { frameRenderingPanel.update(); // Repaint this after each frame so that the label does not get painted over by the frame rendering panel. SwingUtilities.invokeLater(targetFrameTimeLabel::repaint); }; flutterFramesMonitor.addListener(listener); Disposer.register(parentDisposable, () -> flutterFramesMonitor.removeListener(listener)); return panel; } private static void updateTargetLabelForRefreshRate(@Nullable Double fps, @NotNull Double defaultRefreshRate, JBLabel targetLabel) { if (fps == null) { fps = defaultRefreshRate; } final double targetFrameTime = Math.floor(1000.0f / fps); final String targetFrameTimeText = Math.round(targetFrameTime) + "ms"; targetLabel.setText(targetFrameTimeText); targetLabel .setToolTipText("Targeting " + targetFrameTimeText + " per frame will\nresult in " + Math.round(fps) + " frames per second. "); SwingUtilities.invokeLater(targetLabel::repaint); } } class FrameRenderingPanel extends JPanel { private final FlutterFramesMonitor framesMonitor; private final DisplayRefreshRateManager displayRefreshRateManager; private final Map<FlutterFramesMonitor.FlutterFrameEvent, JComponent> frameWidgets = new HashMap<>(); private Rectangle lastSavedBounds; FrameRenderingPanel(@NotNull FlutterFramesMonitor framesMonitor, @NotNull DisplayRefreshRateManager displayRefreshRateManager) { this.framesMonitor = framesMonitor; this.displayRefreshRateManager = displayRefreshRateManager; setLayout(null); final Color color = UIUtil.getLabelDisabledForeground(); //noinspection UseJBColor setForeground(new Color(color.getRed(), color.getGreen(), color.getBlue(), 0x7f)); } public void update() { SwingUtilities.invokeLater(this::updateFromFramesMonitor); } public void doLayout() { if (lastSavedBounds != null && !lastSavedBounds.equals(getBounds())) { lastSavedBounds = null; SwingUtilities.invokeLater(this::updateFromFramesMonitor); } } private static final Stroke STROKE = new BasicStroke( 0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{2.0f, 2.0f}, 0.0f); @Override protected void paintComponent(Graphics g) { super.paintComponent(g); final Rectangle bounds = getBounds(); final int height = bounds.height; if (height <= 20) { return; } final Graphics2D g2 = (Graphics2D)g; final float msPerPixel = (2.0f * 1000000.0f / 60.0f) / height; final float y = displayRefreshRateManager.getTargetMicrosPerFrame() / msPerPixel; final Stroke oldStroke = g2.getStroke(); try { g2.setStroke(STROKE); final Path2D path = new Path2D.Float(); // Slight left indent to allow space for [targetFrameTimeLabel]. path.moveTo(34, height - y); path.lineTo(bounds.width, height - y); g2.draw(path); } finally { g2.setStroke(oldStroke); } } void updateFromFramesMonitor() { final Set<FlutterFramesMonitor.FlutterFrameEvent> frames = new HashSet<>(frameWidgets.keySet()); final Rectangle bounds = getBounds(); lastSavedBounds = bounds; final int height = bounds.height; final int inc = height <= 20 ? 1 : 2; int x = bounds.width; final int widgetWidth = Math.min(Math.max(Math.round(height / 8.0f), 2), 5); synchronized (framesMonitor) { for (FlutterFramesMonitor.FlutterFrameEvent frame : framesMonitor.frames) { if (x + widgetWidth < 0) { break; } x -= (widgetWidth + inc); final float msPerPixel = (2.0f * 1000000.0f / 60.0f) / height; JComponent widget = frameWidgets.get(frame); if (widget != null) { frames.remove(frame); } else { widget = new JLabel(); widget.setOpaque(true); widget.setBackground(frame.isSlowFrame() ? JBColor.RED : UIUtil.getLabelForeground()); widget.setToolTipText(frame.isSlowFrame() ? "This frame took " + FrameRenderingDisplay.df.format(frame.elapsedMicros / 1000.0d) + "ms to render, which\ncan cause frame rate to drop below " + Math.round(displayRefreshRateManager.getCurrentDisplayRefreshRateRaw()) + " FPS." : "This frame took " + FrameRenderingDisplay.df.format(frame.elapsedMicros / 1000.0d) + "ms to render."); frameWidgets.put(frame, widget); add(widget); } int pixelHeight = Math.round(frame.elapsedMicros / msPerPixel); if (pixelHeight > height) { pixelHeight = height; } pixelHeight = Math.max(1, pixelHeight); widget.setPreferredSize(new Dimension(widgetWidth, pixelHeight)); widget.setBounds(x, height - pixelHeight, widgetWidth, pixelHeight); // Add a gap between sets of frames. if (frame.frameSetStart) { x -= widgetWidth; } } } if (!frames.isEmpty()) { for (FlutterFramesMonitor.FlutterFrameEvent frame : frames) { final JComponent widget = frameWidgets.remove(frame); remove(widget); } } } } class StackLayout implements LayoutManager2 { public static final String BOTTOM = "bottom"; public static final String TOP = "top"; private final List<Component> components = new LinkedList<>(); public StackLayout() { } public void addLayoutComponent(Component comp, Object constraints) { synchronized (comp.getTreeLock()) { if ("bottom".equals(constraints)) { this.components.add(0, comp); } else if ("top".equals(constraints)) { this.components.add(comp); } else { this.components.add(comp); } } } public void addLayoutComponent(String name, Component comp) { this.addLayoutComponent(comp, "top"); } public void removeLayoutComponent(Component comp) { synchronized (comp.getTreeLock()) { this.components.remove(comp); } } public float getLayoutAlignmentX(Container target) { return 0.5F; } public float getLayoutAlignmentY(Container target) { return 0.5F; } public void invalidateLayout(Container target) { } public Dimension preferredLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { int width = 0; int height = 0; Dimension size; for (final Iterator<Component> i$ = this.components.iterator(); i$.hasNext(); height = Math.max(size.height, height)) { final Component comp = i$.next(); size = comp.getPreferredSize(); width = Math.max(size.width, width); } final Insets insets = parent.getInsets(); width += insets.left + insets.right; height += insets.top + insets.bottom; return new Dimension(width, height); } } public Dimension minimumLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { int width = 0; int height = 0; Dimension size; for (final Iterator<Component> i$ = this.components.iterator(); i$.hasNext(); height = Math.max(size.height, height)) { final Component comp = i$.next(); size = comp.getMinimumSize(); width = Math.max(size.width, width); } final Insets insets = parent.getInsets(); width += insets.left + insets.right; height += insets.top + insets.bottom; return new Dimension(width, height); } } public Dimension maximumLayoutSize(Container target) { return new Dimension(2147483647, 2147483647); } public void layoutContainer(Container parent) { synchronized (parent.getTreeLock()) { final Insets insets = parent.getInsets(); final int width = parent.getWidth() - insets.left - insets.right; final int height = parent.getHeight() - insets.top - insets.bottom; final Rectangle bounds = new Rectangle(insets.left, insets.top, width, height); final int componentsCount = this.components.size(); for (int i = 0; i < componentsCount; ++i) { final Component comp = this.components.get(i); comp.setBounds(bounds); parent.setComponentZOrder(comp, componentsCount - i - 1); } } } }
flutter-intellij/flutter-idea/src/io/flutter/performance/FrameRenderingDisplay.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/performance/FrameRenderingDisplay.java", "repo_id": "flutter-intellij", "token_count": 4153 }
458
/* * 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.project; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.projectImport.ProjectOpenProcessor; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.FlutterUtils; import io.flutter.ProjectOpenActivity; import io.flutter.pub.PubRoot; import io.flutter.utils.FlutterModuleUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Arrays; import java.util.Objects; public class FlutterProjectOpenProcessor extends ProjectOpenProcessor { private static final Logger LOG = Logger.getInstance(FlutterProjectOpenProcessor.class); @NotNull @Override public String getName() { return FlutterBundle.message("flutter.module.name"); } @Override public Icon getIcon() { return FlutterIcons.Flutter; } @Override public boolean canOpenProject(@Nullable VirtualFile file) { if (file == null) return false; final ApplicationInfo info = ApplicationInfo.getInstance(); if (FlutterUtils.isAndroidStudio()) { return false; } final PubRoot root = PubRoot.forDirectory(file); return root != null && root.declaresFlutter(); } /** * Runs when a project is opened by selecting the project directly, possibly for import. * <p> * Doesn't run when a project is opened via recent projects menu (and so on). Actions that * should run every time a project is opened should be in * {@link ProjectOpenActivity} or {@link io.flutter.FlutterInitializer}. */ @Nullable @Override public Project doOpenProject(@NotNull VirtualFile file, @Nullable Project projectToClose, boolean forceOpenInNewFrame) { // Delegate opening to the platform open processor. final ProjectOpenProcessor importProvider = getDelegateImportProvider(file); if (importProvider == null) return null; final Project project = importProvider.doOpenProject(file, projectToClose, forceOpenInNewFrame); if (project == null || project.isDisposed()) return project; // Convert any modules that use Flutter but don't have IntelliJ Flutter metadata. convertToFlutterProject(project); // Project gets reloaded; should this be: FlutterUtils.findProject(file.getPath()); return project; } @Nullable protected ProjectOpenProcessor getDelegateImportProvider(@NotNull VirtualFile file) { return Arrays.stream(Extensions.getExtensions(EXTENSION_POINT_NAME)).filter( processor -> processor.canOpenProject(file) && !Objects.equals(processor.getName(), getName()) ).findFirst().orElse(null); } /** * Sets up a project that doesn't have any Flutter modules. * <p> * (It probably wasn't created with "flutter create" and probably didn't have any IntelliJ configuration before.) */ private static void convertToFlutterProject(@NotNull Project project) { for (Module module : FlutterModuleUtils.getModules(project)) { if (FlutterModuleUtils.declaresFlutter(module) && !FlutterModuleUtils.isFlutterModule(module)) { FlutterModuleUtils.setFlutterModuleAndReload(module, project); } } } @Override public boolean isStrongProjectInfoHolder() { return true; } }
flutter-intellij/flutter-idea/src/io/flutter/project/FlutterProjectOpenProcessor.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/project/FlutterProjectOpenProcessor.java", "repo_id": "flutter-intellij", "token_count": 1126 }
459
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.run; import com.intellij.AppTopics; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.concurrency.JobScheduler; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.ide.actions.SaveAllAction; import com.intellij.notification.Notification; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileDocumentManagerListener; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiErrorElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.LightweightHint; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import com.jetbrains.lang.dart.ide.errorTreeView.DartProblemsView; import com.jetbrains.lang.dart.psi.DartFile; import icons.FlutterIcons; import io.flutter.FlutterConstants; import io.flutter.FlutterUtils; import io.flutter.actions.FlutterAppAction; import io.flutter.actions.ProjectActions; import io.flutter.actions.ReloadFlutterApp; import io.flutter.bazel.Workspace; import io.flutter.bazel.WorkspaceCache; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.FlutterApp; import io.flutter.settings.FlutterSettings; import io.flutter.utils.FlutterModuleUtils; import io.flutter.utils.MostlySilentColoredProcessHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; /** * Handle the mechanics of performing a hot reload on file save. */ public class FlutterReloadManager { private static final Logger LOG = Logger.getInstance(FlutterReloadManager.class); private static final Map<String, NotificationGroup> toolWindowNotificationGroups = new HashMap<>(); private static NotificationGroup getNotificationGroup(String toolWindowId) { if (!toolWindowNotificationGroups.containsKey(toolWindowId)) { final NotificationGroup notificationGroup = NotificationGroup.toolWindowGroup("Flutter " + toolWindowId, toolWindowId, false); toolWindowNotificationGroups.put(toolWindowId, notificationGroup); } return toolWindowNotificationGroups.get(toolWindowId); } private final @NotNull Project myProject; private Notification lastNotification; /** * Initialize the reload manager for the given project. */ public static void init(@NotNull Project project) { // Call getInstance() will init FlutterReloadManager for the given project. getInstance(project); } @Nullable public static FlutterReloadManager getInstance(@NotNull Project project) { return project.getService(FlutterReloadManager.class); } private FlutterReloadManager(@NotNull Project project) { this.myProject = project; final MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(project); connection.subscribe(AnActionListener.TOPIC, new AnActionListener() { private @Nullable Project eventProject; private @Nullable Editor eventEditor; /** * WARNING on the deprecation of this API: the modification of this file was made at one point to resolve this error, but Flutter * Hot Reload was broken, see https://github.com/flutter/flutter-intellij/issues/6996, the change had to be rolled back. */ public void beforeActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) { if (!(action instanceof SaveAllAction)) { return; } // Save the current project value here. If we access later (in afterActionPerformed), we can get // exceptions if another event occurs before afterActionPerformed is called. try { eventProject = event.getProject(); eventEditor = CommonDataKeys.EDITOR.getData(event.getDataContext()); } catch (Throwable t) { // A catch-all, so any exceptions don't bubble through to the users. LOG.warn("Exception from FlutterReloadManager", t); } } /** * See note above on {{@link #beforeActionPerformed(AnAction, DataContext, AnActionEvent)}}. */ public void afterActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) { if (!(action instanceof SaveAllAction)) { return; } // If this save all action is not for the current project, return. if (myProject != eventProject) { return; } try { handleSaveAllNotification(eventEditor); } catch (Throwable t) { FlutterUtils.warn(LOG, "Exception from hot reload on save", t); } } }); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerListener() { @Override public void beforeAllDocumentsSaving() { if (!FlutterSettings.getInstance().isReloadOnSave()) return; if (myProject.isDisposed()) return; if (!FlutterModuleUtils.hasFlutterModule(myProject)) return; // The "Save files if the IDE is idle ..." option runs whether there are any changes or not. boolean isModified = false; for (FileEditor fileEditor : FileEditorManager.getInstance(myProject).getAllEditors()) { if (fileEditor.isModified()) { isModified = true; break; } } if (!isModified) return; ApplicationManager.getApplication().invokeLater(() -> { // Find a Dart editor to trigger the reload. final Editor anEditor = ApplicationManager.getApplication().runReadAction((Computable<Editor>)() -> { Editor someEditor = null; for (Editor editor : EditorFactory.getInstance().getAllEditors()) { if (editor.isDisposed()) continue; if (editor.getProject() != myProject) continue; final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument()); if (psiFile instanceof DartFile && someEditor == null) { someEditor = editor; } if (null != PsiTreeUtil.findChildOfType(psiFile, PsiErrorElement.class, false)) { // The Dart plugin may create empty files that it then claims have a syntax error. Ignore them. if (editor.getDocument().getTextLength() != 0) { // If there are analysis errors we want to silently exit, without showing a notification. return null; } } } return someEditor; }); handleSaveAllNotification(anEditor); }, ModalityState.any()); } }); } private void handleSaveAllNotification(@Nullable Editor editor) { if (!FlutterSettings.getInstance().isReloadOnSave() || editor == null) { return; } @NotNull String configPath = PathManager.getConfigDir().toString(); if (SystemInfo.isWindows) { configPath = configPath.replace('\\', '/'); } @Nullable VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument()); if (file == null) { return; } if (file.getPath().startsWith(configPath.toString())) { return; // Ignore changes to scratch files. } if (System.currentTimeMillis() - file.getTimeStamp() > 500) { // If the file was saved in the last half-second, assume it should trigger hot reload // because it was probably just saved before this notification was generated. // Files saved a long time ago should not trigger hot reload. return; } final AnAction reloadAction = ProjectActions.getAction(myProject, ReloadFlutterApp.ID); final FlutterApp app = getApp(reloadAction); if (app == null) { return; } if (!app.getLaunchMode().supportsReload() || !app.appSupportsHotReload()) { return; } if (!app.isStarted() || app.isReloading()) { return; } // Transition the app to an about-to-reload state. final FlutterApp.State previousAppState = app.transitionStartingHotReload(); JobScheduler.getScheduler().schedule(() -> { if (WorkspaceCache.getInstance(myProject).isBazel()) { syncFiles(); } clearLastNotification(); if (!app.isConnected()) { return; } // Don't reload if we find structural errors with the current file. if (hasErrorsInFile(editor.getDocument())) { app.cancelHotReloadState(previousAppState); showAnalysisNotification("Reload not performed", "Analysis issues found", true); return; } final Notification notification = showRunNotification(app, null, "Reloading…", false); final long startTime = System.currentTimeMillis(); app.performHotReload(true, FlutterConstants.RELOAD_REASON_SAVE).thenAccept(result -> { if (!result.ok()) { notification.expire(); showRunNotification(app, "Hot Reload Error", result.getMessage(), true); } else { // Make sure the reloading message is displayed for at least 2 seconds (so it doesn't just flash by). final long delay = Math.max(0, 2000 - (System.currentTimeMillis() - startTime)); JobScheduler.getScheduler().schedule(() -> UIUtil.invokeLaterIfNeeded(() -> { notification.expire(); // If the 'Reloading…' notification is still the most recent one, then clear it. if (isLastNotification(notification)) { removeRunNotifications(app); } }), delay, TimeUnit.MILLISECONDS); } }); }, 0, TimeUnit.MILLISECONDS); } private void syncFiles() { final Workspace workspace = WorkspaceCache.getInstance(myProject).get(); assert workspace != null; final String script = workspace.getRoot().getPath() + "/" + workspace.getSyncScript(); final GeneralCommandLine commandLine = new GeneralCommandLine().withWorkDirectory(workspace.getRoot().getPath()); commandLine.setCharset(StandardCharsets.UTF_8); commandLine.setExePath(FileUtil.toSystemDependentName(script)); try { final MostlySilentColoredProcessHandler handler = new MostlySilentColoredProcessHandler(commandLine); handler.startNotify(); if (!handler.getProcess().waitFor(10, TimeUnit.SECONDS)) { LOG.error("Syncing files timed out"); } } catch (ExecutionException | InterruptedException e) { LOG.error("Unable to sync files: " + e); } } private void reloadApp(@NotNull FlutterApp app, @NotNull String reason) { if (app.isStarted()) { app.performHotReload(true, reason).thenAccept(result -> { if (!result.ok()) { showRunNotification(app, "Hot Reload Error", result.getMessage(), true); } }).exceptionally(throwable -> { showRunNotification(app, "Hot Reload Error", throwable.getMessage(), true); return null; }); } } public void saveAllAndReload(@NotNull FlutterApp app, @NotNull String reason) { FileDocumentManager.getInstance().saveAllDocuments(); clearLastNotification(); reloadApp(app, reason); } public void saveAllAndReloadAll(@NotNull List<FlutterApp> appsToReload, @NotNull String reason) { FileDocumentManager.getInstance().saveAllDocuments(); clearLastNotification(); for (FlutterApp app : appsToReload) { reloadApp(app, reason); } } private void restartApp(@NotNull FlutterApp app, @NotNull String reason) { if (app.isStarted()) { app.performRestartApp(reason).thenAccept(result -> { if (!result.ok()) { showRunNotification(app, "Hot Restart Error", result.getMessage(), true); } }).exceptionally(throwable -> { showRunNotification(app, "Hot Restart Error", throwable.getMessage(), true); return null; }); final FlutterDevice device = app.device(); if (device != null) { device.bringToFront(); } } } public void saveAllAndRestart(@NotNull FlutterApp app, @NotNull String reason) { FileDocumentManager.getInstance().saveAllDocuments(); clearLastNotification(); restartApp(app, reason); } public void saveAllAndRestartAll(@NotNull List<FlutterApp> appsToRestart, @NotNull String reason) { FileDocumentManager.getInstance().saveAllDocuments(); clearLastNotification(); for (FlutterApp app : appsToRestart) { restartApp(app, reason); } } @Nullable private FlutterApp getApp(AnAction reloadAction) { if (reloadAction instanceof FlutterAppAction) { return ((FlutterAppAction)reloadAction).getApp(); } else { return null; } } private void showAnalysisNotification(@NotNull String title, @NotNull String content, boolean isError) { final ToolWindow dartProblemsView = ToolWindowManager.getInstance(myProject).getToolWindow(DartProblemsView.TOOLWINDOW_ID); if (dartProblemsView != null && !dartProblemsView.isVisible()) { content += " (<a href='open.analysis.view'>view issues</a>)"; } final NotificationGroup notificationGroup = getNotificationGroup(DartProblemsView.TOOLWINDOW_ID); final Notification notification = notificationGroup.createNotification( title, content, isError ? NotificationType.ERROR : NotificationType.INFORMATION, new NotificationListener.Adapter() { @Override protected void hyperlinkActivated(@NotNull final Notification notification, @NotNull final HyperlinkEvent e) { notification.expire(); final ToolWindow dartProblemsView = ToolWindowManager.getInstance(myProject).getToolWindow(DartProblemsView.TOOLWINDOW_ID); if (dartProblemsView != null) { dartProblemsView.activate(null); } } }); notification.setIcon(FlutterIcons.Flutter); notification.notify(myProject); lastNotification = notification; } private Notification showRunNotification(@NotNull FlutterApp app, @Nullable String title, @NotNull String content, boolean isError) { final String toolWindowId = app.getMode() == RunMode.DEBUG ? ToolWindowId.DEBUG : ToolWindowId.RUN; final NotificationGroup notificationGroup = getNotificationGroup(toolWindowId); final Notification notification; if (title == null) { notification = notificationGroup.createNotification(content, isError ? NotificationType.ERROR : NotificationType.INFORMATION); } else { notification = notificationGroup.createNotification(title, content, isError ? NotificationType.ERROR : NotificationType.INFORMATION, null); } notification.setIcon(FlutterIcons.Flutter); notification.notify(myProject); lastNotification = notification; return notification; } private boolean isLastNotification(final Notification notification) { return notification == lastNotification; } private void clearLastNotification() { lastNotification = null; } private void removeRunNotifications(FlutterApp app) { final String toolWindowId = app.getMode() == RunMode.DEBUG ? ToolWindowId.DEBUG : ToolWindowId.RUN; final Balloon balloon = ToolWindowManager.getInstance(myProject).getToolWindowBalloon(toolWindowId); if (balloon != null) { balloon.hide(); } } private boolean hasErrorsInFile(@NotNull Document document) { // We use the IntelliJ parser and look for syntax errors in the current document. // We block reload if we find issues in the immediate file. We don't block reload if there // are analysis issues in other files; the compilation errors from the flutter tool // will indicate to the user where the problems are. final PsiErrorElement firstError = ApplicationManager.getApplication().runReadAction((Computable<PsiErrorElement>)() -> { final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); if (psiFile instanceof DartFile) { return PsiTreeUtil.findChildOfType(psiFile, PsiErrorElement.class, false); } else { return null; } }); return firstError != null; } private LightweightHint showEditorHint(@NotNull Editor editor, String message, boolean isError) { final AtomicReference<LightweightHint> ref = new AtomicReference<>(); ApplicationManager.getApplication().invokeAndWait(() -> { final JComponent component = isError ? HintUtil.createErrorLabel(message) : HintUtil.createInformationLabel(message); final LightweightHint hint = new LightweightHint(component); ref.set(hint); HintManagerImpl.getInstanceImpl().showEditorHint( hint, editor, HintManager.UNDER, HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING | HintManager.HIDE_BY_OTHER_HINT, isError ? 0 : 3000, false); }); return ref.get(); } }
flutter-intellij/flutter-idea/src/io/flutter/run/FlutterReloadManager.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/FlutterReloadManager.java", "repo_id": "flutter-intellij", "token_count": 6721 }
460
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.run.bazel; import io.flutter.run.LaunchState; import org.jetbrains.annotations.NotNull; public class BazelRunner extends LaunchState.Runner<BazelRunConfig> { public BazelRunner() { super(BazelRunConfig.class); } @NotNull @Override public String getRunnerId() { return "FlutterBazelRunner"; } }
flutter-intellij/flutter-idea/src/io/flutter/run/bazel/BazelRunner.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazel/BazelRunner.java", "repo_id": "flutter-intellij", "token_count": 162 }
461
/* * 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.common; import static org.dartlang.analysis.server.protocol.ElementKind.UNIT_TEST_GROUP; import static org.dartlang.analysis.server.protocol.ElementKind.UNIT_TEST_TEST; import com.google.common.annotations.VisibleForTesting; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.jetbrains.lang.dart.psi.DartCallExpression; import com.jetbrains.lang.dart.psi.DartStringLiteralExpression; import io.flutter.dart.DartSyntax; import io.flutter.editor.ActiveEditorsOutlineService; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringEscapeUtils; import org.dartlang.analysis.server.protocol.ElementKind; import org.dartlang.analysis.server.protocol.FlutterOutline; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Common utilities for processing Flutter tests. * <p> * This class is useful for identifying the {@link TestType} of different Dart objects */ public abstract class CommonTestConfigUtils { public static String convertHttpServiceProtocolToWs(String url) { return StringUtil.trimTrailing( url.replaceFirst("http:", "ws:"), '/') + "/ws"; } public void refreshOutline(@NotNull PsiElement element) { getTestsFromOutline(element.getContainingFile()); } /** * Determines if {@param element} is a test call and returns its type. * * <p> * A test call is one of the following: * <ul> * <li>{@link TestType#SINGLE} if the call is a {@link DartCallExpression} marked by the {@link FlutterOutline} as {@link ElementKind#UNIT_TEST_TEST}</li> * <li>{@link TestType#GROUP} if the call is a {@link DartCallExpression} marked by the {@link FlutterOutline} as {@link ElementKind#UNIT_TEST_GROUP}</li> * </ul> * * @return a {@link TestType} if {@param element} corresponds to a test call site, or null if {@param element} is not a test call site. */ public TestType asTestCall(@NotNull PsiElement element) { // Named tests. final TestType namedTestCall = findNamedTestCall(element); //noinspection RedundantIfStatement if (namedTestCall != null) { return namedTestCall; } return null; } private final Map<String, OutlineCache> cache = new HashMap<>(); private void clearCachedInfo(String path) { synchronized (this) { cache.remove(path); } } /** * Gets the elements from the outline that are runnable tests. */ @NotNull private Map<Integer, TestType> getTestsFromOutline(@NotNull PsiFile file) { final Project project = file.getProject(); final ActiveEditorsOutlineService outlineService = getActiveEditorsOutlineService(project); if (outlineService == null) { return new HashMap<>(); } final FlutterOutline outline = outlineService.getIfUpdated(file); final String path = file.getVirtualFile().getPath(); final boolean outlineOutdated; synchronized (this) { final OutlineCache entry = cache.get(path); outlineOutdated = cache.containsKey(path) && outline != entry.outline; } // If the outline is outdated, then request a new pass to generate line markers. if (outline == null || outlineOutdated) { clearCachedInfo(path); final LineMarkerUpdatingListener listener = getListenerForFile(file); if (listener != null) { outlineService.addListener(listener); } return new HashMap<>(); } synchronized (this) { final OutlineCache entry = new OutlineCache(outline, file); cache.put(path, entry); return entry.callToTestType; } } @Nullable protected TestType findNamedTestCall(@NotNull PsiElement element) { if (element instanceof DartCallExpression) { final DartCallExpression call = (DartCallExpression)element; return getTestsFromOutline(element.getContainingFile()).get(call.getTextOffset()); } return null; } /** * Returns the name of the test containing this element, or null if it can't be calculated. */ @Nullable public String findTestName(@Nullable PsiElement elt) { if (elt == null) return null; final DartCallExpression call = findEnclosingTestCall(elt, getTestsFromOutline(elt.getContainingFile())); if (call == null) return null; final DartStringLiteralExpression lit = DartSyntax.getArgument(call, 0, DartStringLiteralExpression.class); if (lit == null) return null; final String name = DartSyntax.unquote(lit); if (name == null) return null; return StringEscapeUtils.unescapeJava(name); } /** * Finds the {@link DartCallExpression} in the key set of {@param callToTestType} and also the closest parent of {@param element}. */ @Nullable private DartCallExpression findEnclosingTestCall(@NotNull PsiElement element, @NotNull Map<Integer, TestType> callToTestType) { while (element != null) { if (element instanceof DartCallExpression) { final DartCallExpression call = (DartCallExpression)element; if (callToTestType.containsKey(call.getTextOffset())) { return call; } // If we found nothing, move up to the element's parent before finding the enclosing function call. // This avoids an infinite loop found during testing. element = element.getParent(); } element = DartSyntax.findClosestEnclosingFunctionCall(element); } return null; } @VisibleForTesting @Nullable protected ActiveEditorsOutlineService getActiveEditorsOutlineService(@NotNull Project project) { return ActiveEditorsOutlineService.getInstance(project); } /** * The cache of listeners for the path of each {@link PsiFile} that has an outded {@link FlutterOutline}. */ private static final Map<String, LineMarkerUpdatingListener> listenerCache = new HashMap<>(); private LineMarkerUpdatingListener getListenerForFile(@NotNull final PsiFile file) { final String path = file.getVirtualFile().getCanonicalPath(); final ActiveEditorsOutlineService service = getActiveEditorsOutlineService(file.getProject()); if (!listenerCache.containsKey(path) && service != null) { listenerCache.put(path, new LineMarkerUpdatingListener(this, file.getProject(), service)); Disposer.register(file.getProject(), () -> { listenerCache.remove(path); }); } return listenerCache.get(path); } private static class OutlineCache { final Map<Integer, TestType> callToTestType; final FlutterOutline outline; private OutlineCache(FlutterOutline outline, PsiFile file) { this.callToTestType = new HashMap<>(); this.outline = outline; populateTestTypeMap(outline, file); } /** * Traverses the {@param outline} tree and adds to {@link OutlineCache#callToTestType } the {@link DartCallExpression}s that are tests or test groups. */ private void populateTestTypeMap(@NotNull FlutterOutline outline, @NotNull PsiFile file) { if (outline.getDartElement() != null) { final PsiElement element; switch (outline.getDartElement().getKind()) { case UNIT_TEST_GROUP: { // We found a test group. element = file.findElementAt(outline.getOffset()); final DartCallExpression enclosingCall = DartSyntax.findClosestEnclosingFunctionCall(element); if (enclosingCall != null) { callToTestType.put(enclosingCall.getTextOffset(), TestType.GROUP); } } break; case UNIT_TEST_TEST: { // We found a unit test. element = file.findElementAt(outline.getOffset()); final DartCallExpression enclosingCall = DartSyntax.findClosestEnclosingFunctionCall(element); if (enclosingCall != null) { callToTestType.put(enclosingCall.getTextOffset(), TestType.SINGLE); } } break; default: // We found no test. break; } } if (outline.getChildren() != null) { for (FlutterOutline child : outline.getChildren()) { populateTestTypeMap(child, file); } } } } /** * {@link ActiveEditorsOutlineService.Listener} that forces IntelliJ to recompute line markers and other file annotations when the * {@link FlutterOutline} updates. * * <p> * Used to ensure that we don't get stuck with out-of-date line markers. */ private static class LineMarkerUpdatingListener implements ActiveEditorsOutlineService.Listener { @NotNull final CommonTestConfigUtils commonTestConfigUtils; @NotNull final Project project; @NotNull final ActiveEditorsOutlineService service; private LineMarkerUpdatingListener(@NotNull CommonTestConfigUtils commonTestConfigUtils, @NotNull Project project, @NotNull ActiveEditorsOutlineService service) { this.commonTestConfigUtils = commonTestConfigUtils; this.project = project; this.service = service; } @Override public void onOutlineChanged(@NotNull String filePath, @Nullable FlutterOutline outline) { commonTestConfigUtils.clearCachedInfo(filePath); forceFileAnnotation(); service.removeListener(this); } // TODO(djshuckerow): this can be merged with the Dart plugin's forceFileAnnotation: // https://github.com/JetBrains/intellij-plugins/blob/master/Dart/src/com/jetbrains/lang/dart/analyzer/DartServerData.java#L300 private void forceFileAnnotation() { // It's ok to call DaemonCodeAnalyzer.restart() right in this thread, without invokeLater(), // but it will cache RemoteAnalysisServerImpl$ServerResponseReaderThread in FileStatusMap.threads and as a result, // DartAnalysisServerService.myProject will be leaked in tests ApplicationManager.getApplication().invokeLater( () -> DaemonCodeAnalyzer.getInstance(project).restart(), ModalityState.NON_MODAL, project.getDisposed() ); } } }
flutter-intellij/flutter-idea/src/io/flutter/run/common/CommonTestConfigUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/common/CommonTestConfigUtils.java", "repo_id": "flutter-intellij", "token_count": 3782 }
462
/* * 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.run.daemon; import com.google.common.collect.ImmutableList; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Version; import com.intellij.openapi.util.io.FileUtil; import com.jetbrains.lang.dart.ide.devtools.DartDevToolsService; import com.jetbrains.lang.dart.sdk.DartSdk; import io.flutter.FlutterInitializer; import io.flutter.FlutterUtils; import io.flutter.bazel.Workspace; import io.flutter.bazel.WorkspaceCache; import io.flutter.console.FlutterConsoles; import io.flutter.sdk.FlutterCommand; import io.flutter.sdk.FlutterSdk; import io.flutter.sdk.FlutterSdkUtil; import io.flutter.utils.JsonUtils; import io.flutter.utils.MostlySilentColoredProcessHandler; import org.jetbrains.annotations.NotNull; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; public class DevToolsService { private static final Logger LOG = Logger.getInstance(DevToolsService.class); private static class DevToolsServiceListener implements DaemonEvent.Listener { } @NotNull private final Project project; private DaemonApi daemonApi; private ProcessHandler process; private AtomicReference<CompletableFuture<DevToolsInstance>> devToolsFutureRef = new AtomicReference<>(null); @NotNull public static DevToolsService getInstance(@NotNull final Project project) { return Objects.requireNonNull(project.getService(DevToolsService.class)); } private DevToolsService(@NotNull final Project project) { this.project = project; } public CompletableFuture<DevToolsInstance> getDevToolsInstance() { // Create instance if it doesn't exist yet, or if the previous attempt failed. if (devToolsFutureRef.compareAndSet(null, new CompletableFuture<>())) { startServer(); } if (devToolsFutureRef.updateAndGet((future) -> { if (future.isCompletedExceptionally()) { return null; } else { return future; } }) == null) { devToolsFutureRef.set(new CompletableFuture<>()); startServer(); } return devToolsFutureRef.get(); } public CompletableFuture<DevToolsInstance> getDevToolsInstanceWithForcedRestart() { final CompletableFuture<DevToolsInstance> futureInstance = devToolsFutureRef.updateAndGet((future) -> { if (future.isCompletedExceptionally() || future.isCancelled()) { return null; } else { return future; } }); if (futureInstance == null) { devToolsFutureRef.set(new CompletableFuture<>()); startServer(); } else if (!futureInstance.isDone()) { futureInstance.cancel(true); devToolsFutureRef.set(new CompletableFuture<>()); startServer(); } return devToolsFutureRef.get(); } private void startServer() { ApplicationManager.getApplication().executeOnPooledThread(() -> { final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project); boolean dartDevToolsSupported = false; final DartSdk dartSdk = DartSdk.getDartSdk(project); if (dartSdk != null) { final Version version = Version.parseVersion(dartSdk.getVersion()); assert version != null; dartDevToolsSupported = version.compareTo(2, 15, 0) >= 0; } if (dartDevToolsSupported) { final WorkspaceCache workspaceCache = WorkspaceCache.getInstance(project); if (workspaceCache.isBazel()) { setUpWithDart(createCommand(workspaceCache.get().getRoot().getPath(), workspaceCache.get().getDevToolsScript(), ImmutableList.of("--machine"))); } else { // The Dart plugin should start DevTools with DTD, so try to use this instance of DevTools before trying to start another. final String dartPluginUri = DartDevToolsService.getInstance(project).getDevToolsHostAndPort(); if (dartPluginUri != null) { String[] parts = dartPluginUri.split(":"); String host = parts[0]; Integer port = Integer.parseInt(parts[1]); if (host != null && port != null) { devToolsFutureRef.get().complete(new DevToolsInstance(host, port)); return; } } setUpWithDart(createCommand(DartSdk.getDartSdk(project).getHomePath(), DartSdk.getDartSdk(project).getHomePath() + File.separatorChar + "bin" + File.separatorChar + "dart", ImmutableList.of("devtools", "--machine"))); } } else if (sdk != null && sdk.getVersion().useDaemonForDevTools()) { setUpWithDaemon(); } else { // For earlier flutter versions we need to use pub directly to run the latest DevTools server. setUpWithPub(); } }); } private void setUpWithDart(GeneralCommandLine command) { try { this.process = new MostlySilentColoredProcessHandler(command); this.process.addProcessListener(new ProcessAdapter() { @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { final String text = event.getText().trim(); if (text.startsWith("{") && text.endsWith("}")) { // {"event":"server.started","params":{"host":"127.0.0.1","port":9100}} try { final JsonElement element = JsonUtils.parseString(text); final JsonObject obj = element.getAsJsonObject(); if (JsonUtils.getStringMember(obj, "event").equals("server.started")) { final JsonObject params = obj.getAsJsonObject("params"); final String host = JsonUtils.getStringMember(params, "host"); final int port = JsonUtils.getIntMember(params, "port"); if (port != -1) { devToolsFutureRef.get().complete(new DevToolsInstance(host, port)); } else { logExceptionAndComplete("DevTools port was invalid"); } } } catch (JsonSyntaxException e) { logExceptionAndComplete(e); } } } }); process.startNotify(); ProjectManager.getInstance().addProjectManagerListener(project, new ProjectManagerListener() { @Override public void projectClosing(@NotNull Project project) { devToolsFutureRef.set(null); process.destroyProcess(); } }); } catch (ExecutionException e) { logExceptionAndComplete(e); } } private void setUpWithDaemon() { try { final GeneralCommandLine command = chooseCommand(project); if (command == null) { logExceptionAndComplete("Unable to find daemon command for project"); return; } this.process = new MostlySilentColoredProcessHandler(command); daemonApi = new DaemonApi(process); daemonApi.listen(process, new DevToolsServiceListener()); daemonApi.devToolsServe().thenAccept((DaemonApi.DevToolsAddress address) -> { if (!project.isOpen()) { // We should skip starting DevTools (and doing any UI work) if the project has been closed. return; } if (address == null) { logExceptionAndComplete("DevTools address was null"); } else { devToolsFutureRef.get().complete(new DevToolsInstance(address.host, address.port)); } }); } catch (ExecutionException e) { logExceptionAndComplete(e); } ProjectManager.getInstance().addProjectManagerListener(project, new ProjectManagerListener() { @Override public void projectClosing(@NotNull Project project) { devToolsFutureRef.set(null); try { daemonApi.daemonShutdown().get(5, TimeUnit.SECONDS); } catch (InterruptedException | java.util.concurrent.ExecutionException | TimeoutException e) { LOG.error("DevTools daemon did not shut down normally: " + e); if (!process.isProcessTerminated()) { process.destroyProcess(); } } } }); } private void setUpWithPub() { final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project); if (sdk == null) { logExceptionAndComplete("Flutter SDK is null"); return; } pubActivateDevTools(sdk).thenAccept(success -> { if (success) { pubRunDevTools(sdk); } else { logExceptionAndComplete("pub activate of DevTools failed"); } }); } private void pubRunDevTools(FlutterSdk sdk) { final FlutterCommand command = sdk.flutterPub(null, "global", "run", "devtools", "--machine", "--port=0"); final ColoredProcessHandler handler = command.startProcessOrShowError(project); if (handler == null) { logExceptionAndComplete("Handler was null for pub global run command"); return; } handler.addProcessListener(new ProcessAdapter() { @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { final String text = event.getText().trim(); if (text.startsWith("{") && text.endsWith("}")) { // {"event":"server.started","params":{"host":"127.0.0.1","port":9100}} try { final JsonElement element = JsonUtils.parseString(text); // params.port final JsonObject obj = element.getAsJsonObject(); final JsonObject params = obj.getAsJsonObject("params"); final String host = JsonUtils.getStringMember(params, "host"); final int port = JsonUtils.getIntMember(params, "port"); if (port != -1) { devToolsFutureRef.get().complete(new DevToolsInstance(host, port)); } else { logExceptionAndComplete("DevTools port was invalid"); handler.destroyProcess(); } } catch (JsonSyntaxException e) { logExceptionAndComplete(e); handler.destroyProcess(); } } } }); handler.startNotify(); ProjectManager.getInstance().addProjectManagerListener(project, new ProjectManagerListener() { @Override public void projectClosing(@NotNull Project project) { devToolsFutureRef.set(null); handler.destroyProcess(); } }); } private CompletableFuture<Boolean> pubActivateDevTools(FlutterSdk sdk) { final FlutterCommand command = sdk.flutterPub(null, "global", "activate", "devtools"); final CompletableFuture<Boolean> result = new CompletableFuture<>(); final Process process = command.start((ProcessOutput output) -> { if (output.getExitCode() != 0) { final String message = (output.getStdout() + "\n" + output.getStderr()).trim(); FlutterConsoles.displayMessage(project, null, message, true); } }, null); try { final int resultCode = process.waitFor(); result.complete(resultCode == 0); } catch (RuntimeException | InterruptedException re) { if (!result.isDone()) { result.complete(false); } } return result; } private void logExceptionAndComplete(String message) { logExceptionAndComplete(new Exception(message)); } private void logExceptionAndComplete(Exception exception) { LOG.info(exception); FlutterInitializer.getAnalytics().sendExpectedException("devtools-service", exception); final CompletableFuture<DevToolsInstance> future = devToolsFutureRef.get(); if (future != null) { future.completeExceptionally(exception); } } private static GeneralCommandLine chooseCommand(@NotNull final Project project) { // Use daemon script if this is a bazel project. final Workspace workspace = WorkspaceCache.getInstance(project).get(); if (workspace != null) { final String script = workspace.getDaemonScript(); if (script != null) { return createCommand(workspace.getRoot().getPath(), script, ImmutableList.of()); } } // Otherwise, use the Flutter SDK. final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project); if (sdk == null) { return null; } try { final String path = FlutterSdkUtil.pathToFlutterTool(sdk.getHomePath()); return createCommand(sdk.getHomePath(), path, ImmutableList.of("daemon")); } catch (ExecutionException e) { FlutterUtils.warn(LOG, "Unable to calculate command to start Flutter daemon", e); return null; } } private static GeneralCommandLine createCommand(String workDir, String command, ImmutableList<String> arguments) { final GeneralCommandLine result = new GeneralCommandLine().withWorkDirectory(workDir); result.setCharset(StandardCharsets.UTF_8); result.setExePath(FileUtil.toSystemDependentName(command)); result.withEnvironment(FlutterSdkUtil.FLUTTER_HOST_ENV, (new FlutterSdkUtil()).getFlutterHostEnvValue()); for (String argument : arguments) { result.addParameter(argument); } return result; } }
flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DevToolsService.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DevToolsService.java", "repo_id": "flutter-intellij", "token_count": 5393 }
463
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.run.test; import com.google.common.annotations.VisibleForTesting; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.RuntimeConfigurationError; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.execution.ParametersListUtil; import io.flutter.pub.PubRoot; import io.flutter.run.FlutterDevice; import io.flutter.run.MainFile; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.DeviceService; import io.flutter.sdk.FlutterCommandStartResult; import io.flutter.sdk.FlutterSdk; import io.flutter.utils.ElementIO; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * Settings for running a Flutter test. */ public class TestFields { @Nullable private final String testName; @Nullable private final String testFile; @Nullable private final String testDir; @Nullable private String additionalArgs; private boolean useRegexp = false; private TestFields(@Nullable String testName, @Nullable String testFile, @Nullable String testDir, @Nullable String additionalArgs) { if (testFile == null && testDir == null) { throw new IllegalArgumentException("either testFile or testDir must be non-null"); } else if (testFile != null && testDir != null) { throw new IllegalArgumentException("either testFile or testDir must be null"); } else if (testName != null && testFile == null) { throw new IllegalArgumentException("testName can only be specified along with a testFile"); } this.testName = testName; this.testFile = testFile; this.testDir = testDir; this.additionalArgs = additionalArgs; } public TestFields useRegexp(boolean useRegexp) { this.useRegexp = useRegexp; return this; } @VisibleForTesting public boolean getUseRegexp() { return useRegexp; } public TestFields copy() { return new TestFields(testName, testFile, testDir, additionalArgs).useRegexp(useRegexp); } /** * Creates settings for running tests with the given name within a Dart file. */ public static TestFields forTestName(String testName, String path) { return new TestFields(testName, path, null, null); } /** * Creates settings for running all the tests in a Dart file. */ public static TestFields forFile(String path) { return new TestFields(null, path, null, null); } /** * Creates settings for running all the tests in directory. */ public static TestFields forDir(String path) { return new TestFields(null, null, path, null); } /** * Returns a value indicating whether we're running tests in a file or in a directory. */ @NotNull public Scope getScope() { if (testName != null) { return Scope.NAME; } else if (testFile != null) { return Scope.FILE; } else { return Scope.DIRECTORY; } } /** * If not null, tests will only be run if their name contains this string. */ @Nullable public String getTestName() { return testName; } /** * The Dart file containing the tests to run, or null if we are running tests in a directory. */ @Nullable public String getTestFile() { return testFile; } /** * The directory containing the tests to run, or null if we are running tests in a file. */ @Nullable public String getTestDir() { return testDir; } /** * The additional arguments to pass to the test runner. */ @Nullable public String getAdditionalArgs() { return additionalArgs; } public void setAdditionalArgs(@Nullable String args) { additionalArgs = args; } /** * Returns the file or directory containing the tests to run, or null if it doesn't exist. */ @Nullable public VirtualFile getFileOrDir() { final String path = testFile != null ? testFile : testDir; if (path == null) return null; return LocalFileSystem.getInstance().findFileByPath(path); } /** * Returns the PubRoot containing the file or directory being tested, or null if none. */ @Nullable public PubRoot getPubRoot(@NotNull Project project) { final VirtualFile dir = getFileOrDir(); if (dir == null) return null; final PubRoot root = PubRoot.forFile(dir); if (root != null) return root; return PubRoot.forDescendant(dir, project); } /** * Returns the relative path to the file or directory from the pub root, or null if not in a pub root. */ @Nullable public String getRelativePath(@NotNull Project project) { final PubRoot root = getPubRoot(project); if (root == null) return null; final VirtualFile fileOrDir = getFileOrDir(); if (fileOrDir == null) return null; return root.getRelativePath(fileOrDir); } /** * Generates a name for these test settings, if they are valid. */ @NotNull public String getSuggestedName(@NotNull Project project, @NotNull String defaultName) { switch (getScope()) { case NAME: final String name = getTestName(); if (name == null) return defaultName; return name; case FILE: final VirtualFile file = getFileOrDir(); if (file == null) return defaultName; return "tests in " + file.getName(); case DIRECTORY: final String relativePath = getRelativePath(project); if (relativePath != null) return "tests in " + relativePath; // check if it's the pub root itself. final PubRoot root = getPubRoot(project); if (root != null && root.getRoot().equals(getFileOrDir())) { return "all tests in " + root.getRoot().getName(); } } return defaultName; } void writeTo(Element elt) { ElementIO.addOption(elt, "testName", testName); ElementIO.addOption(elt, "testFile", testFile); ElementIO.addOption(elt, "testDir", testDir); ElementIO.addOption(elt, "useRegexp", useRegexp ? "true" : "false"); ElementIO.addOption(elt, "additionalArgs", additionalArgs); } /** * Reads the fields from an XML Element, if available. */ @NotNull static TestFields readFrom(Element elt) throws InvalidDataException { final Map<String, String> options = ElementIO.readOptions(elt); final String testName = options.get("testName"); final String testFile = options.get("testFile"); final String testDir = options.get("testDir"); final String useRegexp = options.get("useRegexp"); final String additionalArgs = options.get("additionalArgs"); try { return new TestFields(testName, testFile, testDir, additionalArgs).useRegexp("true".equals(useRegexp)); } catch (IllegalArgumentException e) { throw new InvalidDataException(e.getMessage()); } } /** * Reports any errors that the user should correct. * <p> * This will be called while the user is typing; see RunConfiguration.checkConfiguration. */ void checkRunnable(@NotNull Project project) throws RuntimeConfigurationError { checkSdk(project); getScope().checkRunnable(this, project); } /** * Starts running the tests. */ @NotNull FlutterCommandStartResult run(@NotNull Project project, @NotNull RunMode mode) throws ExecutionException { final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project); if (sdk == null) { throw new ExecutionException("The Flutter SDK is not configured"); } final VirtualFile fileOrDir = getFileOrDir(); if (fileOrDir == null) { throw new ExecutionException("File or directory not found"); } final String testName = getTestName(); final PubRoot root = getPubRoot(project); if (root == null) { throw new ExecutionException("Test file isn't within a Flutter pub root"); } final String args = adjustArgs(root, fileOrDir, project); return sdk.flutterTest(root, fileOrDir, testName, mode, args, getScope(), useRegexp).startProcess(project); } @Nullable private String adjustArgs(@NotNull PubRoot root, @NotNull VirtualFile fileOrDir, @NotNull Project project) { final VirtualFile testDir = root.getIntegrationTestDir(); if (testDir == null || !VfsUtilCore.isAncestor(testDir, fileOrDir, false)) { return additionalArgs; } final List<String> args = additionalArgs == null ? new ArrayList<>() : ParametersListUtil.parse(additionalArgs); if (args.contains("-d") || args.contains("--device-id")) { return additionalArgs; } final FlutterDevice device = DeviceService.getInstance(project).getSelectedDevice(); if (device == null) { return additionalArgs; } args.add(0, "-d"); args.add(1, device.deviceId()); return String.join(" ", args); } private void checkSdk(@NotNull Project project) throws RuntimeConfigurationError { if (FlutterSdk.getFlutterSdk(project) == null) { throw new RuntimeConfigurationError("Flutter SDK isn't set"); } } /** * Selects which tests to run. */ public enum Scope { NAME("Tests in file, filtered by name") { @Override public void checkRunnable(@NotNull TestFields fields, @NotNull Project project) throws RuntimeConfigurationError { final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project); if (sdk != null && !sdk.getVersion().flutterTestSupportsFiltering()) { throw new RuntimeConfigurationError("Flutter SDK is too old to filter tests by name"); } FILE.checkRunnable(fields, project); } }, FILE("All in file") { @Override public void checkRunnable(@NotNull TestFields fields, @NotNull Project project) throws RuntimeConfigurationError { final MainFile.Result main = MainFile.verify(fields.testFile, project); if (!main.canLaunch()) { throw new RuntimeConfigurationError(main.getError()); } final PubRoot root = PubRoot.forDirectory(main.get().getAppDir()); if (root == null) { throw new RuntimeConfigurationError("Test file isn't within a Flutter pub root"); } } }, DIRECTORY("All in directory") { @Override public void checkRunnable(@NotNull TestFields fields, @NotNull Project project) throws RuntimeConfigurationError { final VirtualFile dir = fields.getFileOrDir(); if (dir == null) { throw new RuntimeConfigurationError("Directory not found"); } final PubRoot root = PubRoot.forDescendant(dir, project); if (root == null) { throw new RuntimeConfigurationError("Directory is not in a pub root"); } } }; private final String displayName; Scope(String displayName) { this.displayName = displayName; } public String getDisplayName() { return displayName; } public abstract void checkRunnable(@NotNull TestFields fields, @NotNull Project project) throws RuntimeConfigurationError; } }
flutter-intellij/flutter-idea/src/io/flutter/run/test/TestFields.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/TestFields.java", "repo_id": "flutter-intellij", "token_count": 3916 }
464
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.sdk; import com.intellij.ProjectTopics; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.roots.ModuleRootListener; import com.intellij.openapi.roots.libraries.PersistentLibraryKind; import com.intellij.openapi.vfs.*; import com.jetbrains.lang.dart.util.DotPackagesFileUtil; import io.flutter.pub.PubRoot; import io.flutter.pub.PubRoots; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.jetbrains.lang.dart.util.PubspecYamlUtil.PUBSPEC_YAML; /** * Manages the Flutter Plugins library, which hooks the packages used by plugins referenced in a project * into the project, so full editing support is available. * * @see FlutterPluginLibraryType * @see FlutterPluginLibraryProperties */ public class FlutterPluginsLibraryManager extends AbstractLibraryManager<FlutterPluginLibraryProperties> { private final AtomicBoolean isUpdating = new AtomicBoolean(false); public FlutterPluginsLibraryManager(@NotNull Project project) { super(project); } public void startWatching() { VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileContentsChangedAdapter() { @Override protected void onFileChange(@NotNull VirtualFile file) { fileChanged(getProject(), file); } @Override protected void onBeforeFileChange(@NotNull VirtualFile file) { } }, getProject()); getProject().getMessageBus().connect().subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { @Override public void rootsChanged(@NotNull ModuleRootEvent event) { scheduleUpdate(); } }); scheduleUpdate(); } @Override @NotNull protected String getLibraryName() { return FlutterPluginLibraryType.FLUTTER_PLUGINS_LIBRARY_NAME; } @Override @NotNull protected PersistentLibraryKind<FlutterPluginLibraryProperties> getLibraryKind() { return FlutterPluginLibraryType.LIBRARY_KIND; } private boolean isPackagesFile(@NotNull final VirtualFile file) { final VirtualFile parent = file.getParent(); return file.getName().equals(DotPackagesFileUtil.DOT_PACKAGES) && parent != null && parent.findChild(PUBSPEC_YAML) != null; } private boolean isPackageConfigFile(@NotNull final VirtualFile file) { final VirtualFile parent = file.getParent(); return file.getName().equals(DotPackagesFileUtil.PACKAGE_CONFIG_JSON) && parent != null && parent.getName().equals(DotPackagesFileUtil.DART_TOOL_DIR); } private void fileChanged(@NotNull final Project project, @NotNull final VirtualFile file) { if (!isPackageConfigFile(file) && !isPackagesFile(file)) return; if (LocalFileSystem.getInstance() != file.getFileSystem() && !ApplicationManager.getApplication().isUnitTestMode()) return; scheduleUpdate(); } private void scheduleUpdate() { if (isUpdating.get()) { return; } final Runnable runnable = this::updateFlutterPlugins; DumbService.getInstance(getProject()).smartInvokeLater(runnable, ModalityState.NON_MODAL); } private void updateFlutterPlugins() { if (!isUpdating.compareAndSet(false, true)) { return; } try { updateFlutterPluginsImpl(); } finally { isUpdating.set(false); } } private void updateFlutterPluginsImpl() { final Set<String> flutterPluginPaths = getFlutterPluginPaths(PubRoots.forProject(getProject())); final Set<String> flutterPluginUrls = new HashSet<>(); for (String path : flutterPluginPaths) { flutterPluginUrls.add(VfsUtilCore.pathToUrl(path)); } updateLibraryContent(flutterPluginUrls); } private static Set<String> getFlutterPluginPaths(List<PubRoot> roots) { final Set<String> paths = new HashSet<>(); for (PubRoot pubRoot : roots) { final var packagesMap = pubRoot.getPackagesMap(); if (packagesMap == null) { continue; } for (String packagePath : packagesMap.values()) { final VirtualFile libFolder = LocalFileSystem.getInstance().findFileByPath(packagePath); if (libFolder == null) { continue; } final PubRoot pluginRoot = PubRoot.forDirectory(libFolder.getParent()); if (pluginRoot == null) { continue; } if (pluginRoot.isFlutterPlugin()) { paths.add(pluginRoot.getPath()); } } } return paths; } }
flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterPluginsLibraryManager.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterPluginsLibraryManager.java", "repo_id": "flutter-intellij", "token_count": 1696 }
465
/* * 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.template; import com.intellij.codeInsight.template.impl.DefaultLiveTemplatesProvider; import org.jetbrains.annotations.NonNls; public class FlutterLiveTemplatesProvider implements DefaultLiveTemplatesProvider { private static final @NonNls String[] DEFAULT_TEMPLATES = new String[]{"/liveTemplates/flutter_miscellaneous"}; public String[] getDefaultLiveTemplateFiles() { return DEFAULT_TEMPLATES; } @Override public String[] getHiddenLiveTemplateFiles() { return null; } }
flutter-intellij/flutter-idea/src/io/flutter/template/FlutterLiveTemplatesProvider.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/template/FlutterLiveTemplatesProvider.java", "repo_id": "flutter-intellij", "token_count": 204 }
466
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.utils; public class HtmlBuilder { public static String span(String style, String contents) { return "<span style = \"" + style + "\"> " + contents + "</span>"; } public static String span(String contents) { return tag("span", contents); } public static String attr(String attribute, String value) { return attribute + " = \"" + value + "\""; } public static String html(String... contents) { return tag("html", join(contents)); } public static String pre(String... contents) { return tag("pre", join(contents)); } public static String body(String... contents) { return join(contents); } private static String join(String... contents) { final StringBuilder sb = new StringBuilder(); for (String c : contents) { sb.append(c); sb.append('\n'); } return sb.toString(); } public static String tag(String tag, String contents) { return "<" + tag + ">" + contents + "</" + tag + ">"; } public static String div(String attrs, String contents) { return "<div " + attrs + ">" + contents + "</div>"; } public static String cls(String value) { return attr("class", value); } }
flutter-intellij/flutter-idea/src/io/flutter/utils/HtmlBuilder.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/HtmlBuilder.java", "repo_id": "flutter-intellij", "token_count": 441 }
467
/* * Copyright 2018 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.utils.animation; /// A cubic polynomial mapping of the unit interval. /// /// The Curves class contains some commonly used cubic curves: /// /// * Curves.EASE /// * Curves.EASE_IN /// * Curves.EASE_OUT /// * Curves.EASE_IN_OUT /// /// https://flutter.github.io/assets-for-api-docs/animation/curve_ease.png /// https://flutter.github.io/assets-for-api-docs/animation/curve_ease_in.png /// https://flutter.github.io/assets-for-api-docs/animation/curve_ease_out.png /// https://flutter.github.io/assets-for-api-docs/animation/curve_ease_in_out.png /// /// The Cubic class implements third-order Bézier curves. class Cubic extends Curve { /// Creates a cubic curve. /// /// Rather than creating a new instance, consider using one of the common /// cubic curves in Curves. Cubic(double a, double b, double c, double d) { this.a = a; this.b = b; this.c = c; this.d = d; } /// The x coordinate of the first control point. /// /// The line through the point (0, 0) and the first control point is tangent /// to the curve at the point (0, 0). final double a; /// The y coordinate of the first control point. /// /// The line through the point (0, 0) and the first control point is tangent /// to the curve at the point (0, 0). final double b; /// The x coordinate of the second control point. /// /// The line through the point (1, 1) and the second control point is tangent /// to the curve at the point (1, 1). final double c; /// The y coordinate of the second control point. /// /// The line through the point (1, 1) and the second control point is tangent /// to the curve at the point (1, 1). final double d; static final double _kCubicErrorBound = 0.001; double evaluateCubic(double a, double b, double m) { return 3 * a * (1 - m) * (1 - m) * m + 3 * b * (1 - m) * m * m + m * m * m; } @Override public double transform(double t) { assert (t >= 0.0 && t <= 1.0); double start = 0.0; double end = 1.0; while (true) { final double midpoint = (start + end) / 2; final double estimate = evaluateCubic(a, c, midpoint); if (Math.abs(t - estimate) < _kCubicErrorBound) { return evaluateCubic(b, d, midpoint); } if (estimate < t) { start = midpoint; } else { end = midpoint; } } } @Override public String toString() { return getClass() + "(" + a + ", " + b + ", " + c + ", " + d + ")"; } }
flutter-intellij/flutter-idea/src/io/flutter/utils/animation/Cubic.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/animation/Cubic.java", "repo_id": "flutter-intellij", "token_count": 980 }
468
/* * 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.view; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.ui.content.ContentManager; import com.intellij.ui.jcef.JBCefBrowser; import io.flutter.jxbrowser.JxBrowserManager; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.Dimension; class EmbeddedJcefBrowserTab implements EmbeddedTab { private JBCefBrowser browser; public EmbeddedJcefBrowserTab() throws Exception { this.browser = new JBCefBrowser(); } @Override public void loadUrl(String url) { browser.loadURL(url); } @Override public void close() { } @Override public JComponent getTabComponent(ContentManager contentManager) { browser.getComponent().setPreferredSize(new Dimension(contentManager.getComponent().getWidth(), contentManager.getComponent().getHeight())); return browser.getComponent(); } } public class EmbeddedJcefBrowser extends EmbeddedBrowser { private static final Logger LOG = Logger.getInstance(JxBrowserManager.class); public EmbeddedJcefBrowser(Project project) { super(project); } @NotNull public static EmbeddedJcefBrowser getInstance(Project project) { return ServiceManager.getService(project, EmbeddedJcefBrowser.class); } public Logger logger() { return LOG; } @Override public EmbeddedTab openEmbeddedTab() throws Exception { return new EmbeddedJcefBrowserTab(); } }
flutter-intellij/flutter-idea/src/io/flutter/view/EmbeddedJcefBrowser.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/EmbeddedJcefBrowser.java", "repo_id": "flutter-intellij", "token_count": 520 }
469
/* * 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.actionSystem.AnActionEvent; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import icons.FlutterIcons; import io.flutter.FlutterInitializer; import io.flutter.FlutterMessages; import org.jetbrains.annotations.NotNull; @SuppressWarnings("ComponentNotRegistered") public class OpenFlutterViewAction extends DumbAwareAction { private final Computable<Boolean> myIsApplicable; public OpenFlutterViewAction(@NotNull final Computable<Boolean> isApplicable) { super("Open Flutter Inspector", "Open Flutter Inspector", FlutterIcons.Flutter_inspect); myIsApplicable = isApplicable; } @Override public void update(@NotNull final AnActionEvent e) { e.getPresentation().setEnabled(myIsApplicable.compute()); } @Override public void actionPerformed(@NotNull final AnActionEvent e) { final Project project = e.getProject(); if (project == null) { return; } FlutterInitializer.sendAnalyticsAction(this); final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(FlutterView.TOOL_WINDOW_ID); if (toolWindow == null) { FlutterMessages.showError( "Unable to open view", "Unable to open the Flutter tool window - no Flutter modules found", project); } else { toolWindow.show(null); } } }
flutter-intellij/flutter-idea/src/io/flutter/view/OpenFlutterViewAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/OpenFlutterViewAction.java", "repo_id": "flutter-intellij", "token_count": 577 }
470
/* * 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.vmService; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; // Each service extension needs to be manually added to [toggleableExtensionDescriptions]. public class ServiceExtensions { public static final ToggleableServiceExtensionDescription<Boolean> debugAllowBanner = new ToggleableServiceExtensionDescription<>( "ext.flutter.debugAllowBanner", "Debug Banner", true, false, "Hide Debug Mode Banner", "Show Debug Mode Banner"); public static final ToggleableServiceExtensionDescription<Boolean> debugPaint = new ToggleableServiceExtensionDescription<>( "ext.flutter.debugPaint", "Debug Paint", true, false, "Hide Debug Paint", "Show Debug Paint"); public static final ToggleableServiceExtensionDescription<Boolean> debugPaintBaselines = new ToggleableServiceExtensionDescription<>( "ext.flutter.debugPaintBaselinesEnabled", "Paint Baselines", true, false, "Hide Paint Baselines", "Show Paint Baselines"); public static final ToggleableServiceExtensionDescription<Boolean> performanceOverlay = new ToggleableServiceExtensionDescription<>( "ext.flutter.showPerformanceOverlay", "Performance Overlay", true, false, "Hide Performance Overlay", "Show Performance Overlay"); public static final ToggleableServiceExtensionDescription<Boolean> repaintRainbow = new ToggleableServiceExtensionDescription<>( "ext.flutter.repaintRainbow", "Repaint Rainbow", true, false, "Hide Repaint Rainbow", "Show Repaint Rainbow"); public static final ToggleableServiceExtensionDescription<Double> slowAnimations = new ToggleableServiceExtensionDescription<>( "ext.flutter.timeDilation", "Slow Animations", 5.0, 1.0, "Disable Slow Animations", "Enable Slow Animations"); public static final ServiceExtensionDescription<String> togglePlatformMode = new ServiceExtensionDescription<>( "ext.flutter.platformOverride", "Override Target Platform", Arrays.asList("iOS", "android", "fuchsia"), Arrays.asList("Platform: iOS", "Platform: Android", "Platform: Fuchsia")); /** * Toggle whether interacting with the device selects widgets or triggers * normal interactions. */ public static final ToggleableServiceExtensionDescription<Boolean> toggleSelectWidgetMode = new ToggleableServiceExtensionDescription<>( "ext.flutter.inspector.selectMode", "Select Widget Mode", true, false, "Disable Select Widget Mode", "Enable Select Widget Mode"); public static final ToggleableServiceExtensionDescription<Boolean> toggleOnDeviceWidgetInspector = new ToggleableServiceExtensionDescription<>( "ext.flutter.inspector.show", "Select Widget Mode", true, false, // Technically this enables the on-device widget inspector but for older // versions of package:flutter it makes sense to describe this extension as // toggling widget select mode as it is the only way to toggle that mode. "Disable Select Widget Mode", "Enable Select Widget Mode"); /** * Toggle whether the inspector on-device overlay is enabled. * <p> * When available, the inspector overlay can be enabled at any time as it will * not interfere with user interaction with the app unless inspector select * mode is triggered. */ public static final ToggleableServiceExtensionDescription<Boolean> enableOnDeviceInspector = new ToggleableServiceExtensionDescription<>( "ext.flutter.inspector.enable", "Enable on-device inspector", true, false, "Exit on-device inspector", "Enter on-device inspector"); public static final ToggleableServiceExtensionDescription<Boolean> toggleShowStructuredErrors = new ToggleableServiceExtensionDescription<>( "ext.flutter.inspector.structuredErrors", "Structured Errors", true, false, "Disable Showing Structured Errors", "Show Structured Errors"); public static final ToggleableServiceExtensionDescription<Boolean> trackRebuildWidgets = new ToggleableServiceExtensionDescription<>( "ext.flutter.inspector.trackRebuildDirtyWidgets", "Track Widget Rebuilds", true, false, "Do Not Track Widget Rebuilds", "Track Widget Rebuilds"); public static final ToggleableServiceExtensionDescription<Boolean> trackRepaintWidgets = new ToggleableServiceExtensionDescription<>( "ext.flutter.inspector.trackRepaintWidgets", "Track Widget Repaints", true, false, "Do Not Track Widget Repaints", "Track Widget Repaints"); // This extension should never be displayed as a button so does not need to be a // ToggleableServiceExtensionDescription object. public static final String didSendFirstFrameEvent = "ext.flutter.didSendFirstFrameEvent"; // These extensions are not toggleable and do not need to be stored as a ToggleableServiceExtensionDescription object. public static final String flutterPrefix = "ext.flutter."; public static final String inspectorPrefix = "ext.flutter.inspector."; public static final String setPubRootDirectories = "ext.flutter.inspector.setPubRootDirectories"; public static final String enableLogs = "ext.flutter.logs.enable"; public static final String loggingChannels = "ext.flutter.logs.loggingChannels"; public static final String designerRender = "ext.flutter.designer.render"; public static final String flutterListViews = "_flutter.listViews"; public static final String displayRefreshRate = "_flutter.getDisplayRefreshRate"; static final List<ServiceExtensionDescription<?>> toggleableExtensionDescriptions = Arrays.asList( debugAllowBanner, debugPaint, debugPaintBaselines, enableOnDeviceInspector, performanceOverlay, repaintRainbow, slowAnimations, toggleOnDeviceWidgetInspector, togglePlatformMode, toggleSelectWidgetMode, toggleShowStructuredErrors, trackRebuildWidgets, trackRepaintWidgets ); public static final Map<String, ServiceExtensionDescription<?>> toggleableExtensionsAllowList = toggleableExtensionDescriptions.stream().collect( Collectors.toMap( ServiceExtensionDescription::getExtension, extensionDescription -> extensionDescription)); }
flutter-intellij/flutter-idea/src/io/flutter/vmService/ServiceExtensions.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/ServiceExtensions.java", "repo_id": "flutter-intellij", "token_count": 2147 }
471
/* * 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; import com.google.common.collect.Lists; import com.google.dart.server.utilities.general.ObjectUtilities; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * An attribute for a FlutterOutline. * * @coverage dart.server.generated.types */ @SuppressWarnings("unused") public class FlutterOutlineAttribute { public static final FlutterOutlineAttribute[] EMPTY_ARRAY = new FlutterOutlineAttribute[0]; public static final List<FlutterOutlineAttribute> EMPTY_LIST = Lists.newArrayList(); /** * The name of the attribute. */ private final String name; /** * The label of the attribute value, usually the Dart code. It might be quite long, the client * should abbreviate as needed. */ private final String label; /** * The boolean literal value of the attribute. This field is absent if the value is not a boolean * literal. */ private final Boolean literalValueBoolean; /** * The integer literal value of the attribute. This field is absent if the value is not an integer * literal. */ private final Integer literalValueInteger; /** * The string literal value of the attribute. This field is absent if the value is not a string * literal. */ private final String literalValueString; /** * If the attribute is a named argument, the location of the name, without the colon. */ private final Location nameLocation; /** * The location of the value. * <p> * This field is always available, but marked optional for backward compatibility between new * clients with older servers. */ private final Location valueLocation; /** * Constructor for {@link FlutterOutlineAttribute}. */ public FlutterOutlineAttribute(String name, String label, Boolean literalValueBoolean, Integer literalValueInteger, String literalValueString, Location nameLocation, Location valueLocation) { this.name = name; this.label = label; this.literalValueBoolean = literalValueBoolean; this.literalValueInteger = literalValueInteger; this.literalValueString = literalValueString; this.nameLocation = nameLocation; this.valueLocation = valueLocation; } @Override public boolean equals(Object obj) { if (obj instanceof FlutterOutlineAttribute) { FlutterOutlineAttribute other = (FlutterOutlineAttribute)obj; return ObjectUtilities.equals(other.name, name) && ObjectUtilities.equals(other.label, label) && ObjectUtilities.equals(other.literalValueBoolean, literalValueBoolean) && ObjectUtilities.equals(other.literalValueInteger, literalValueInteger) && ObjectUtilities.equals(other.literalValueString, literalValueString) && ObjectUtilities.equals(other.nameLocation, nameLocation) && ObjectUtilities.equals(other.valueLocation, valueLocation); } return false; } public static FlutterOutlineAttribute fromJson(JsonObject jsonObject) { String name = jsonObject.get("name").getAsString(); String label = jsonObject.get("label").getAsString(); Boolean literalValueBoolean = jsonObject.get("literalValueBoolean") == null ? null : jsonObject.get("literalValueBoolean").getAsBoolean(); Integer literalValueInteger = jsonObject.get("literalValueInteger") == null ? null : jsonObject.get("literalValueInteger").getAsInt(); String literalValueString = jsonObject.get("literalValueString") == null ? null : jsonObject.get("literalValueString").getAsString(); Location nameLocation = jsonObject.get("nameLocation") == null ? null : Location.fromJson(jsonObject.get("nameLocation").getAsJsonObject()); Location valueLocation = jsonObject.get("valueLocation") == null ? null : Location.fromJson(jsonObject.get("valueLocation").getAsJsonObject()); return new FlutterOutlineAttribute(name, label, literalValueBoolean, literalValueInteger, literalValueString, nameLocation, valueLocation); } public static List<FlutterOutlineAttribute> fromJsonArray(JsonArray jsonArray) { if (jsonArray == null) { return EMPTY_LIST; } ArrayList<FlutterOutlineAttribute> list = new ArrayList<FlutterOutlineAttribute>(jsonArray.size()); Iterator<JsonElement> iterator = jsonArray.iterator(); while (iterator.hasNext()) { list.add(fromJson(iterator.next().getAsJsonObject())); } return list; } /** * The label of the attribute value, usually the Dart code. It might be quite long, the client * should abbreviate as needed. */ public String getLabel() { return label; } /** * The boolean literal value of the attribute. This field is absent if the value is not a boolean * literal. */ public Boolean getLiteralValueBoolean() { return literalValueBoolean; } /** * The integer literal value of the attribute. This field is absent if the value is not an integer * literal. */ public Integer getLiteralValueInteger() { return literalValueInteger; } /** * The string literal value of the attribute. This field is absent if the value is not a string * literal. */ public String getLiteralValueString() { return literalValueString; } /** * The name of the attribute. */ public String getName() { return name; } /** * If the attribute is a named argument, the location of the name, without the colon. */ public Location getNameLocation() { return nameLocation; } /** * The location of the value. * <p> * This field is always available, but marked optional for backward compatibility between new * clients with older servers. */ public Location getValueLocation() { return valueLocation; } @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); builder.append(name); builder.append(label); builder.append(literalValueBoolean); builder.append(literalValueInteger); builder.append(literalValueString); builder.append(nameLocation); builder.append(valueLocation); return builder.toHashCode(); } public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("name", name); jsonObject.addProperty("label", label); if (literalValueBoolean != null) { jsonObject.addProperty("literalValueBoolean", literalValueBoolean); } if (literalValueInteger != null) { jsonObject.addProperty("literalValueInteger", literalValueInteger); } if (literalValueString != null) { jsonObject.addProperty("literalValueString", literalValueString); } if (nameLocation != null) { jsonObject.add("nameLocation", nameLocation.toJson()); } if (valueLocation != null) { jsonObject.add("valueLocation", valueLocation.toJson()); } return jsonObject; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("["); builder.append("name="); builder.append(name).append(", "); builder.append("label="); builder.append(label).append(", "); builder.append("literalValueBoolean="); builder.append(literalValueBoolean).append(", "); builder.append("literalValueInteger="); builder.append(literalValueInteger).append(", "); builder.append("literalValueString="); builder.append(literalValueString).append(", "); builder.append("nameLocation="); builder.append(nameLocation).append(", "); builder.append("valueLocation="); builder.append(valueLocation); builder.append("]"); return builder.toString(); } }
flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterOutlineAttribute.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterOutlineAttribute.java", "repo_id": "flutter-intellij", "token_count": 2787 }
472
/* * 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.analytics; import com.intellij.codeInsight.completion.PrefixMatcher; import com.intellij.codeInsight.lookup.*; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.testFramework.fixtures.CodeInsightTestFixture; import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService; import com.jetbrains.lang.dart.fixes.DartQuickFix; import com.jetbrains.lang.dart.fixes.DartQuickFixSet; import io.flutter.FlutterInitializer; import io.flutter.testing.CodeInsightProjectFixture; import io.flutter.testing.Testing; import org.dartlang.analysis.server.protocol.AnalysisError; import org.dartlang.analysis.server.protocol.AnalysisStatus; import org.dartlang.analysis.server.protocol.PubStatus; import org.dartlang.analysis.server.protocol.RequestError; import org.jetbrains.annotations.NotNull; import org.junit.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import static io.flutter.analytics.Analytics.TIMING_COMPLETE; import static io.flutter.analytics.FlutterAnalysisServerListener.*; import static org.junit.Assert.*; @SuppressWarnings({"LocalCanBeFinal"}) public class FlutterAnalysisServerListenerTest { private static final String fileContents = "void main() {\n" + " group('group 1', () {\n" + " test('test 1', () {});\n" + " });\n" + "}"; @Rule public final @NotNull CodeInsightProjectFixture projectFixture = Testing.makeCodeInsightModule(); private @NotNull CodeInsightTestFixture innerFixture; private @NotNull Project project; private @NotNull PsiFile mainFile; private @NotNull MockAnalyticsTransport transport; private @NotNull Analytics analytics; private @NotNull FlutterAnalysisServerListener fasl; @SuppressWarnings("ConstantConditions") @Before public void setUp() { assert projectFixture.getInner() != null; innerFixture = projectFixture.getInner(); assert innerFixture != null; project = innerFixture.getProject(); assert project != null; mainFile = innerFixture.addFileToProject("lib/main.dart", fileContents); transport = new MockAnalyticsTransport(); analytics = new Analytics("123e4567-e89b-12d3-a456-426655440000", "1.0", "IntelliJ CE", "2021.3.2"); analytics.setTransport(transport); analytics.setCanSend(true); FlutterInitializer.setAnalytics(analytics); fasl = FlutterAnalysisServerListener.getInstance(project); } @After public void tearDown() { fasl.dispose(); } @Test @Ignore public void requestError() throws Exception { RequestError error = new RequestError("101", "error", "trace"); fasl.requestError(error); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertNotNull(map.get("exd")); assertTrue(map.get("exd").endsWith("trace")); assertTrue(map.get("exd").startsWith("R 101")); } @Test @Ignore public void requestErrorNoCode() throws Exception { RequestError error = new RequestError(null, "error", "trace"); fasl.requestError(error); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertNotNull(map.get("exd")); assertTrue(map.get("exd").endsWith("trace")); assertTrue(map.get("exd").startsWith("R error")); } @Test @Ignore public void serverError() throws Exception { fasl.serverError(true, "message", "trace"); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertNotNull(map.get("exd")); assertEquals("1", map.get("'exf'")); // extra quotes since 2016 assertTrue(map.get("exd").endsWith("trace")); assertTrue(map.get("exd").contains("message")); } @Test @Ignore public void acceptedCompletion() throws Exception { Editor editor = editor(); Testing.runOnDispatchThread(() -> { editor.getSelectionModel().setSelection(18, 18); fasl.setLookupSelectionHandler(); LookupImpl lookup = new LookupImpl(project, editor, new LookupArranger.DefaultArranger()); LookupItem item = new LookupItem(LookupItem.TYPE_TEXT_ATTR, "gr"); lookup.addItem(item, PrefixMatcher.ALWAYS_TRUE); lookup.addLookupListener(fasl.lookupSelectionHandler); LookupEvent lookupEvent = new LookupEvent(lookup, item, 'o'); fasl.lookupSelectionHandler.itemSelected(lookupEvent); }); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertEquals(ACCEPTED_COMPLETION, map.get("ec")); assertEquals("gr", map.get("ea")); assertEquals("0", map.get("ev")); } @Test @Ignore public void lookupCanceled() throws Exception { Editor editor = editor(); Testing.runOnDispatchThread(() -> { editor.getSelectionModel().setSelection(18, 18); fasl.setLookupSelectionHandler(); LookupImpl lookup = new LookupImpl(project, editor, new LookupArranger.DefaultArranger()); LookupItem item = new LookupItem(LookupItem.TYPE_TEXT_ATTR, "gr"); lookup.addItem(item, PrefixMatcher.ALWAYS_TRUE); lookup.addLookupListener(fasl.lookupSelectionHandler); LookupEvent lookupEvent = new LookupEvent(lookup, true); fasl.lookupSelectionHandler.lookupCanceled(lookupEvent); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertEquals(REJECTED_COMPLETION, map.get("ec")); assertEquals(UNKNOWN_LOOKUP_STRING, map.get("ea")); }); } @Test @Ignore public void computedErrors() throws Exception { editor(); // Ensure file is open. String path = mainFile.getVirtualFile().getPath(); List<AnalysisError> list = new ArrayList<>(); list.add(new AnalysisError("ERROR", "", null, "", "", "101", "", null, false)); fasl.computedErrors(path, list); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertNotNull(map.get("ev")); assertEquals(DURATION, map.get("ea")); assertEquals(INITIAL_COMPUTE_ERRORS_TIME, map.get("ec")); } @SuppressWarnings("ConstantConditions") @Test @Ignore public void serverStatus() throws Exception { fasl.serverStatus(new AnalysisStatus(false, null), new PubStatus(false)); assertEquals(4, transport.sentValues.size()); checkStatus(transport.sentValues.get(0), ERRORS, "1"); checkStatus(transport.sentValues.get(1), WARNINGS, "1"); checkStatus(transport.sentValues.get(2), HINTS, "1"); checkStatus(transport.sentValues.get(3), LINTS, "1"); } private void checkStatus(@NotNull Map<String, String> map, String label, String value) { assertEquals("analysisServerStatus", map.get("ec")); assertEquals(label, map.get("ea")); assertEquals(value, map.get("ev")); } @Test @Ignore public void quickFix() throws Exception { Editor editor = editor(); DartAnalysisServerService analysisServer = DartAnalysisServerService.getInstance(project); PsiManager manager = PsiManager.getInstance(project); DartQuickFixSet quickFixSet = new DartQuickFixSet(manager, mainFile.getVirtualFile(), 18, null); DartQuickFix fix = new DartQuickFix(quickFixSet, 0); analysisServer.fireBeforeQuickFixInvoked(fix, editor, mainFile); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertEquals(QUICK_FIX, map.get("ec")); assertEquals("", map.get("ea")); assertEquals("0", map.get("ev")); } @Test @Ignore public void computedSearchResults() throws Exception { fasl.requestListener.onRequest("{\"method\":\"" + FIND_REFERENCES + "\",\"id\":\"2\"}"); fasl.responseListener.onResponse("{\"event\":\"none\",\"id\":\"2\"}"); fasl.computedSearchResults("2", new ArrayList<>(), true); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertEquals(TIMING_COMPLETE, map.get("ea")); assertEquals(ROUND_TRIP_TIME, map.get("ec")); assertEquals(FIND_REFERENCES, map.get("el")); String value = map.get("ev"); assertNotNull(value); assertTrue(0 <= Integer.parseInt(value)); } @Test @Ignore public void computedCompletion() throws Exception { fasl.requestListener.onRequest("{\"method\":\"" + GET_SUGGESTIONS + "\",\"id\":\"2\"}"); fasl.responseListener.onResponse("{\"event\":\"none\",\"id\":\"2\"}"); List none = new ArrayList(); fasl.computedCompletion("2", 0, 0, none, none, none, none, true, ""); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertEquals(TIMING_COMPLETE, map.get("ea")); assertEquals(ROUND_TRIP_TIME, map.get("ec")); assertEquals(GET_SUGGESTIONS, map.get("el")); String value = map.get("ev"); assertNotNull(value); assertTrue(0 <= Integer.parseInt(value)); } @Test @Ignore public void dasListenerLogging() throws Exception { fasl.requestListener.onRequest("{\"method\":\"test\",\"id\":\"2\"}"); fasl.responseListener.onResponse("{\"event\":\"server.log\",\"params\":{\"entry\":{\"time\":\"1\",\"kind\":\"\",\"data\":\"\"}}}"); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertEquals(ANALYSIS_SERVER_LOG, map.get("ec")); assertEquals("time|1|kind||data|", map.get("ea")); } @Test @Ignore public void dasListenerLoggingWithSdk() throws Exception { fasl.requestListener.onRequest("{\"method\":\"test\",\"id\":\"2\"}"); fasl.responseListener.onResponse("{\"event\":\"server.log\",\"params\":{\"entry\":{\"time\":\"1\",\"kind\":\"\",\"data\":\"\",\"sdkVersion\":\"1\"}}}"); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertEquals(ANALYSIS_SERVER_LOG, map.get("ec")); assertEquals("time|1|kind||data|", map.get("ea")); assertEquals("1", map.get("cd2")); } @Test @Ignore public void logE2ECompletionSuccessMS() throws Exception { DartCompletionTimerListener dctl = new DartCompletionTimerListener(); dctl.dasListener = fasl; dctl.dartCompletionStart(); dctl.dartCompletionEnd(); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertEquals(TIMING_COMPLETE, map.get("ea")); assertEquals(E2E_IJ_COMPLETION_TIME, map.get("ec")); assertEquals(SUCCESS, map.get("el")); } @Test @Ignore public void logE2ECompletionErrorMS() throws Exception { DartCompletionTimerListener dctl = new DartCompletionTimerListener(); dctl.dasListener = fasl; dctl.dartCompletionStart(); dctl.dartCompletionError("101", "message", "trace"); assertEquals(1, transport.sentValues.size()); Map<String, String> map = transport.sentValues.get(0); assertEquals(TIMING_COMPLETE, map.get("ea")); assertEquals(E2E_IJ_COMPLETION_TIME, map.get("ec")); assertEquals(FAILURE, map.get("el")); String value = map.get("ev"); assertNotNull(value); assertTrue(0 <= Integer.parseInt(value)); } @NotNull private Editor editor() throws Exception{ //noinspection ConstantConditions Testing.runOnDispatchThread(() -> innerFixture.openFileInEditor(mainFile.getVirtualFile())); Editor e = innerFixture.getEditor(); assert e != null; return e; } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/analytics/FlutterAnalysisServerListenerTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/analytics/FlutterAnalysisServerListenerTest.java", "repo_id": "flutter-intellij", "token_count": 4390 }
473
/* * 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.ide; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.util.SmartList; import com.jetbrains.lang.dart.DartLanguage; import io.flutter.sdk.FlutterSdkUtil; import junit.framework.TestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.junit.Assert; import java.util.List; import java.util.Objects; /** * Adapted from similar class in the Dart plugin. */ public class DartTestUtils { public static final String BASE_TEST_DATA_PATH = findTestDataPath(); public static final String SDK_HOME_PATH = BASE_TEST_DATA_PATH + "/sdk"; @TestOnly public static void configureFlutterSdk(@NotNull final Module module, @NotNull final Disposable disposable, final boolean realSdk) { final String sdkHome; if (realSdk) { sdkHome = System.getProperty("flutter.sdk"); if (sdkHome == null) { Assert.fail( "To run tests that use Dart Analysis Server you need to add '-Dflutter.sdk=[real SDK home]' to the VM Options field of " + "the corresponding JUnit run configuration (Run | Edit Configurations)"); } if (!FlutterSdkUtil.isFlutterSdkHome(sdkHome)) { Assert.fail("Incorrect path to the Flutter SDK (" + sdkHome + ") is set as '-Dflutter.sdk' VM option of " + "the corresponding JUnit run configuration (Run | Edit Configurations)"); } } else { sdkHome = SDK_HOME_PATH; } VfsRootAccess.allowRootAccess(disposable, sdkHome); //final String dartSdkHome = sdkHome + "bin/cache/dart-sdk"; //VfsRootAccess.allowRootAccess(disposable, dartSdkHome); //noinspection ConstantConditions //ApplicationManager.getApplication().runWriteAction(() -> { // Disposer.register(disposable, DartSdkLibUtil.configureDartSdkAndReturnUndoingDisposable(module.getProject(), dartSdkHome)); // Disposer.register(disposable, DartSdkLibUtil.enableDartSdkAndReturnUndoingDisposable(module)); //}); } /** * Use this method in finally{} clause if the test modifies excluded roots or configures module libraries */ public static void resetModuleRoots(@NotNull final Module module) { //noinspection ConstantConditions ApplicationManager.getApplication().runWriteAction(() -> { final ModifiableRootModel modifiableModel = Objects.requireNonNull(ModuleRootManager.getInstance(module)).getModifiableModel(); try { final List<OrderEntry> entriesToRemove = new SmartList<>(); for (OrderEntry orderEntry : modifiableModel.getOrderEntries()) { if (orderEntry instanceof LibraryOrderEntry) { entriesToRemove.add(orderEntry); } } for (OrderEntry orderEntry : entriesToRemove) { assert orderEntry != null; modifiableModel.removeOrderEntry(orderEntry); } final ContentEntry[] contentEntries = modifiableModel.getContentEntries(); TestCase.assertEquals("Expected one content root, got: " + contentEntries.length, 1, contentEntries.length); final ContentEntry oldContentEntry = contentEntries[0]; assert oldContentEntry != null; if (oldContentEntry.getSourceFolders().length != 1 || !oldContentEntry.getExcludeFolderUrls().isEmpty()) { modifiableModel.removeContentEntry(oldContentEntry); final ContentEntry newContentEntry = modifiableModel.addContentEntry(oldContentEntry.getUrl()); newContentEntry.addSourceFolder(newContentEntry.getUrl(), false); } if (modifiableModel.isChanged()) { modifiableModel.commit(); } } finally { if (!modifiableModel.isDisposed()) { modifiableModel.dispose(); } } }); } /** * Creates the syntax tree for a Dart file at a specific path and returns the innermost element with the given text. */ @NotNull public static <E extends PsiElement> E setUpDartElement(@Nullable String filePath, @NotNull String fileText, @NotNull String elementText, @NotNull Class<E> expectedClass, @NotNull Project project) { final int offset = fileText.indexOf(elementText); if (offset < 0) { throw new IllegalArgumentException("'" + elementText + "' not found in '" + fileText + "'"); } final PsiFileFactory factory = PsiFileFactory.getInstance(project); assert factory != null; final PsiFile file; if (filePath != null) { file = factory.createFileFromText(filePath, DartLanguage.INSTANCE, fileText); } else { file = factory.createFileFromText(DartLanguage.INSTANCE, fileText); } assert file != null; PsiElement elt = file.findElementAt(offset); while (elt != null) { if (elementText.equals(elt.getText())) { return expectedClass.cast(elt); } elt = elt.getParent(); } throw new RuntimeException("unable to find element with text: " + elementText); } private static String findTestDataPath() { return "testData/sdk"; } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/ide/DartTestUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/ide/DartTestUtils.java", "repo_id": "flutter-intellij", "token_count": 2235 }
474
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.run; import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters; import com.intellij.util.xmlb.XmlSerializer; import org.jdom.Element; import org.junit.Test; import java.util.Set; import java.util.TreeSet; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /** * Verifies run configuration persistence. */ public class SdkFieldsTest { @Test public void shouldReadFieldsFromXml() { final Element elt = new Element("test"); addOption(elt, "filePath", "lib/main.dart"); addOption(elt, "additionalArgs", "--trace-startup"); final SdkFields fields = new SdkFields(); XmlSerializer.deserializeInto(fields, elt); assertEquals("lib/main.dart", fields.getFilePath()); assertEquals("--trace-startup", fields.getAdditionalArgs()); } @Test public void shouldReadFieldsFromOldXml() { final Element elt = new Element("test"); addOption(elt, "filePath", "lib/main.dart"); addOption(elt, "additionalArgs", "--trace-startup"); addOption(elt, "workingDirectory", "/tmp/test/example"); // obsolete final SdkFields fields = new SdkFields(); XmlSerializer.deserializeInto(fields, elt); assertEquals("lib/main.dart", fields.getFilePath()); assertEquals("--trace-startup", fields.getAdditionalArgs()); } @Test public void roundTripShouldPreserveFields() { final SdkFields before = new SdkFields(); before.setFilePath("main.dart"); before.setAdditionalArgs("--trace-startup"); final Element elt = new Element("test"); XmlSerializer.serializeInto(before, elt, new SkipDefaultValuesSerializationFilters()); // Make sure we no longer serialize workingDirectory assertArrayEquals(new String[]{"additionalArgs", "filePath"}, getOptionNames(elt).toArray()); final SdkFields after = new SdkFields(); XmlSerializer.deserializeInto(after, elt); assertEquals("main.dart", before.getFilePath()); assertEquals("--trace-startup", before.getAdditionalArgs()); } @Test public void supportsSpacesInAdditionalArgs() { final SdkFields sdkFields = new SdkFields(); sdkFields.setAdditionalArgs("--dart-define='VALUE=foo bar' --other=baz"); assertArrayEquals(new String[]{ "--dart-define=VALUE=foo bar", "--other=baz" }, sdkFields.getAdditionalArgsParsed()); } @Test public void supportsSpacesInAttachArgs() { final SdkFields sdkFields = new SdkFields(); sdkFields.setAttachArgs("--dart-define='VALUE=foo bar' --other=baz"); assertArrayEquals(new String[]{ "--dart-define=VALUE=foo bar", "--other=baz" }, sdkFields.getAttachArgsParsed()); } private void addOption(Element elt, String name, String value) { final Element child = new Element("option"); child.setAttribute("name", name); child.setAttribute("value", value); elt.addContent(child); } private Set<String> getOptionNames(Element elt) { final Set<String> result = new TreeSet<>(); for (Element child : elt.getChildren()) { result.add(child.getAttributeValue("name")); } return result; } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/SdkFieldsTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/SdkFieldsTest.java", "repo_id": "flutter-intellij", "token_count": 1163 }
475
/* * 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.testing; import com.intellij.testFramework.fixtures.IdeaTestFixture; import org.jetbrains.annotations.NotNull; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * Wraps an IDEA fixture so it works as a Junit 4 Rule. * * <p>(That is, it can be used with the @Rule annotation.) */ abstract public class AdaptedFixture<T extends IdeaTestFixture> implements TestRule { public final Factory<T> factory; private final boolean runOnDispatchThread; private T inner; public AdaptedFixture(Factory<T> factory, boolean runOnDispatchThread) { this.factory = factory; this.runOnDispatchThread = runOnDispatchThread; } public T getInner() { return inner; } @Override public Statement apply(@NotNull Statement base, @NotNull Description description) { return new Statement() { public void evaluate() throws Throwable { inner = factory.create(description.getClassName()); if (runOnDispatchThread) { Testing.runOnDispatchThread(inner::setUp); } else { inner.setUp(); } try { base.evaluate(); } finally { if (runOnDispatchThread) { Testing.runOnDispatchThread(inner::tearDown); } else { try { inner.tearDown(); } catch (RuntimeException ex) { // TraceableDisposable.DisposalException is private. // It gets thrown during CodeInsightTestFixtureImpl.tearDown, // apparently because of a Kotlin test framework convenience // feature that we don't have. } } inner = null; } } }; } public interface Factory<T extends IdeaTestFixture> { T create(String testClassName); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/AdaptedFixture.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/AdaptedFixture.java", "repo_id": "flutter-intellij", "token_count": 805 }
476
/* * 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.utils; import org.junit.Test; import static io.flutter.utils.TypedDataList.*; import static org.junit.Assert.assertEquals; // Note, all the data is interpreted as little-endian. public class TypedDataListTest { final byte[] signedBytes = new byte[]{1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6, 7, -7, -2, 2}; final byte[] unsignedBytes = new byte[]{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; @Test public void testInt8List() { Int8List list = new Int8List(signedBytes); assertEquals("1", list.getValue(0)); assertEquals("-2", list.getValue(3)); list = new Int8List(unsignedBytes); assertEquals("-1", list.getValue(0)); } @Test public void testUint8List() { Uint8List b = new Uint8List(new byte[]{6, 7, -1, -7, -6, -5, -4, -3, -2, 8}); assertEquals("0x6", b.getValue(0)); assertEquals("0x7", b.getValue(1)); assertEquals("0xff", b.getValue(2)); assertEquals("0xf9", b.getValue(3)); assertEquals("0xfa", b.getValue(4)); assertEquals("0xfb", b.getValue(5)); assertEquals("0xfc", b.getValue(6)); assertEquals("0xfd", b.getValue(7)); assertEquals("0xfe", b.getValue(8)); assertEquals("0x8", b.getValue(9)); Uint8List list = new Uint8List(signedBytes); assertEquals("0x1", list.getValue(0)); assertEquals("0xff", list.getValue(1)); list = new Uint8List(unsignedBytes); assertEquals("0xff", list.getValue(0)); } @Test public void testInt16List() { Int16List list = new Int16List(signedBytes); assertEquals("-255", list.getValue(0)); assertEquals("-510", list.getValue(1)); list = new Int16List(unsignedBytes); assertEquals("-1", list.getValue(0)); } @Test public void testUint16List() { Uint16List list = new Uint16List(signedBytes); assertEquals("0xff01", list.getValue(0)); assertEquals("0xfe02", list.getValue(1)); list = new Uint16List(unsignedBytes); assertEquals("0xffff", list.getValue(0)); } @Test public void testInt32List() { Int32List list = new Int32List(signedBytes); assertEquals("-33358079", list.getValue(0)); assertEquals("-66781949", list.getValue(1)); list = new Int32List(unsignedBytes); assertEquals("-1", list.getValue(0)); } @Test public void testUint32List() { Uint32List list = new Uint32List(signedBytes); assertEquals("0xfe02ff01", list.getValue(0)); assertEquals("0xfc04fd03", list.getValue(1)); list = new Uint32List(unsignedBytes); assertEquals("0xffffffff", list.getValue(0)); } @Test public void testInt64List() { Int64List list = new Int64List(signedBytes); assertEquals("-286826282656530687", list.getValue(0)); list = new Int64List(unsignedBytes); assertEquals("-1", list.getValue(0)); } @Test public void testUint64List() { Uint64List list = new Uint64List(signedBytes); assertEquals("0xfc04fd03fe02ff01", list.getValue(0)); list = new Uint64List(unsignedBytes); assertEquals("0xffffffffffffffff", list.getValue(0)); } @Test public void testFloat32List() { byte[] bytes = new byte[]{0, 0, -128, 63}; Float32List list = new Float32List(bytes); assertEquals("1.0", list.getValue(0)); } @Test public void testFloat64List() { byte[] bytes = new byte[]{0, 0, 0, 0, 0, 0, -16, 63}; Float64List list = new Float64List(bytes); assertEquals("1.0", list.getValue(0)); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/TypedDataListTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/TypedDataListTest.java", "repo_id": "flutter-intellij", "token_count": 1460 }
477
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * {@link ErrorRef} is a reference to an {@link ErrorObj}. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class ErrorRef extends ObjRef { public ErrorRef(JsonObject json) { super(json); } /** * What kind of error is this? */ public ErrorKind getKind() { final JsonElement value = json.get("kind"); try { return value == null ? ErrorKind.Unknown : ErrorKind.valueOf(value.getAsString()); } catch (IllegalArgumentException e) { return ErrorKind.Unknown; } } /** * A description of the error. */ public String getMessage() { return getAsString("message"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ErrorRef.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ErrorRef.java", "repo_id": "flutter-intellij", "token_count": 452 }
478