diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 042890e6b7..e968f9fd68 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1098,6 +1098,8 @@ FILE: ../../../flutter/shell/platform/darwin/macos/framework/Headers/FlutterPlug FILE: ../../../flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h FILE: ../../../flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h FILE: ../../../flutter/shell/platform/darwin/macos/framework/Info.plist +FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.h +FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.mm FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate.mm FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.mm @@ -1132,6 +1134,9 @@ FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMouse FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.mm FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRendererTest.mm +FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h +FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.mm +FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMacTest.mm FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderingBackend.h FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderingBackend.mm diff --git a/engine/src/flutter/shell/platform/common/accessibility_bridge.cc b/engine/src/flutter/shell/platform/common/accessibility_bridge.cc index 20e42914bb..3923815952 100644 --- a/engine/src/flutter/shell/platform/common/accessibility_bridge.cc +++ b/engine/src/flutter/shell/platform/common/accessibility_bridge.cc @@ -104,6 +104,13 @@ const ui::AXTreeData& AccessibilityBridge::GetAXTreeData() const { return tree_.data(); } +const std::vector +AccessibilityBridge::GetPendingEvents() { + std::vector result( + event_generator_.begin(), event_generator_.end()); + return result; +} + void AccessibilityBridge::OnNodeWillBeDeleted(ui::AXTree* tree, ui::AXNode* node) {} diff --git a/engine/src/flutter/shell/platform/common/accessibility_bridge.h b/engine/src/flutter/shell/platform/common/accessibility_bridge.h index 4b4dedff5d..01c270dab0 100644 --- a/engine/src/flutter/shell/platform/common/accessibility_bridge.h +++ b/engine/src/flutter/shell/platform/common/accessibility_bridge.h @@ -86,9 +86,10 @@ class AccessibilityBridge /// @param[in] action The generated flutter semantics action. /// @param[in] data Additional data associated with the /// action. - virtual void DispatchAccessibilityAction(AccessibilityNodeId target, - FlutterSemanticsAction action, - std::vector data) = 0; + virtual void DispatchAccessibilityAction( + AccessibilityNodeId target, + FlutterSemanticsAction action, + const std::vector& data) = 0; //--------------------------------------------------------------------------- /// @brief Creates a platform specific FlutterPlatformNodeDelegate. @@ -154,6 +155,14 @@ class AccessibilityBridge /// has the keyboard focus or the text selection range. const ui::AXTreeData& GetAXTreeData() const; + //------------------------------------------------------------------------------ + /// @brief Gets all pending accessibility events generated during + /// semantics updates. This is useful when deciding how to handle + /// events in AccessibilityBridgeDelegate::OnAccessibilityEvent in + /// case one may decide to handle an event differently based on + /// all pending events. + const std::vector GetPendingEvents(); + private: // See FlutterSemanticsNode in embedder.h typedef struct { diff --git a/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.h b/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.h index 4581e928fa..ca65ff708f 100644 --- a/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.h +++ b/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.h @@ -37,7 +37,7 @@ class FlutterPlatformNodeDelegate : public ui::AXPlatformNodeDelegateBase { /// delegate. class OwnerBridge { public: - ~OwnerBridge() = default; + virtual ~OwnerBridge() = default; protected: friend class FlutterPlatformNodeDelegate; @@ -96,7 +96,7 @@ class FlutterPlatformNodeDelegate : public ui::AXPlatformNodeDelegateBase { FlutterPlatformNodeDelegate(); // |ui::AXPlatformNodeDelegateBase| - ~FlutterPlatformNodeDelegate() override; + virtual ~FlutterPlatformNodeDelegate() override; // |ui::AXPlatformNodeDelegateBase| const ui::AXNodeData& GetData() const override; diff --git a/engine/src/flutter/shell/platform/common/test_accessibility_bridge.cc b/engine/src/flutter/shell/platform/common/test_accessibility_bridge.cc index 22f88ea1f3..79677a9660 100644 --- a/engine/src/flutter/shell/platform/common/test_accessibility_bridge.cc +++ b/engine/src/flutter/shell/platform/common/test_accessibility_bridge.cc @@ -19,7 +19,7 @@ void TestAccessibilityBridgeDelegate::OnAccessibilityEvent( void TestAccessibilityBridgeDelegate::DispatchAccessibilityAction( AccessibilityNodeId target, FlutterSemanticsAction action, - std::vector data) { + const std::vector& data) { performed_actions.push_back(action); } diff --git a/engine/src/flutter/shell/platform/common/test_accessibility_bridge.h b/engine/src/flutter/shell/platform/common/test_accessibility_bridge.h index ace8661129..892a00d122 100644 --- a/engine/src/flutter/shell/platform/common/test_accessibility_bridge.h +++ b/engine/src/flutter/shell/platform/common/test_accessibility_bridge.h @@ -18,7 +18,7 @@ class TestAccessibilityBridgeDelegate ui::AXEventGenerator::TargetedEvent targeted_event) override; void DispatchAccessibilityAction(AccessibilityNodeId target, FlutterSemanticsAction action, - std::vector data) override; + const std::vector& data) override; std::unique_ptr CreateFlutterPlatformNodeDelegate(); diff --git a/engine/src/flutter/shell/platform/darwin/macos/BUILD.gn b/engine/src/flutter/shell/platform/darwin/macos/BUILD.gn index 9422bd1f54..404ebc5730 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/BUILD.gn +++ b/engine/src/flutter/shell/platform/darwin/macos/BUILD.gn @@ -52,6 +52,8 @@ source_set("flutter_framework_source") { visibility = [ ":*" ] sources = [ + "framework/Source/AccessibilityBridgeMacDelegate.h", + "framework/Source/AccessibilityBridgeMacDelegate.mm", "framework/Source/FlutterAppDelegate.mm", "framework/Source/FlutterBackingStore.h", "framework/Source/FlutterBackingStore.mm", @@ -81,6 +83,8 @@ source_set("flutter_framework_source") { "framework/Source/FlutterMouseCursorPlugin.mm", "framework/Source/FlutterOpenGLRenderer.h", "framework/Source/FlutterOpenGLRenderer.mm", + "framework/Source/FlutterPlatformNodeDelegateMac.h", + "framework/Source/FlutterPlatformNodeDelegateMac.mm", "framework/Source/FlutterRenderer.h", "framework/Source/FlutterRenderingBackend.h", "framework/Source/FlutterRenderingBackend.mm", @@ -108,6 +112,7 @@ source_set("flutter_framework_source") { ":macos_gpu_configuration", "//flutter/flow:flow", "//flutter/fml", + "//flutter/shell/platform/common:common_cpp_accessibility", "//flutter/shell/platform/common:common_cpp_input", "//flutter/shell/platform/common:common_cpp_switches", "//flutter/shell/platform/darwin/common:framework_shared", @@ -159,6 +164,7 @@ executable("flutter_desktop_darwin_unittests") { "framework/Source/FlutterMetalRendererTest.mm", "framework/Source/FlutterMetalSurfaceManagerTest.mm", "framework/Source/FlutterOpenGLRendererTest.mm", + "framework/Source/FlutterPlatformNodeDelegateMacTest.mm", "framework/Source/FlutterViewControllerTest.mm", "framework/Source/FlutterViewControllerTestUtils.h", "framework/Source/FlutterViewControllerTestUtils.mm", @@ -171,6 +177,7 @@ executable("flutter_desktop_darwin_unittests") { deps = [ ":flutter_desktop_darwin_fixtures", ":flutter_framework_source", + "//flutter/shell/platform/common:common_cpp_accessibility", "//flutter/shell/platform/darwin/common:framework_shared", "//flutter/shell/platform/darwin/graphics", "//flutter/shell/platform/embedder:embedder_as_internal_library", diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.h new file mode 100644 index 0000000000..b2977e514d --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.h @@ -0,0 +1,83 @@ +// 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_DARWIN_MACOS_FRAMEWORK_SOURCE_ACCESSIBILITYBRIDGEMACDELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_ACCESSIBILITYBRIDGEMACDELEGATE_H_ + +#import + +#include "flutter/shell/platform/common/accessibility_bridge.h" + +@class FlutterEngine; + +namespace flutter { + +//------------------------------------------------------------------------------ +/// The macOS implementation of AccessibilityBridge::AccessibilityBridgeDelegate. +/// This delegate is used to create AccessibilityBridge in the macOS embedding. +class AccessibilityBridgeMacDelegate : public AccessibilityBridge::AccessibilityBridgeDelegate { + public: + //--------------------------------------------------------------------------- + /// @brief Creates an AccessibilityBridgeMacDelegate. + /// @param[in] flutterEngine The weak reference to the FlutterEngine. + explicit AccessibilityBridgeMacDelegate(__weak FlutterEngine* flutter_engine); + virtual ~AccessibilityBridgeMacDelegate() = default; + + // |AccessibilityBridge::AccessibilityBridgeDelegate| + void OnAccessibilityEvent(ui::AXEventGenerator::TargetedEvent targeted_event) override; + + // |AccessibilityBridge::AccessibilityBridgeDelegate| + void DispatchAccessibilityAction(AccessibilityNodeId target, + FlutterSemanticsAction action, + const std::vector& data) override; + + // |AccessibilityBridge::AccessibilityBridgeDelegate| + std::unique_ptr CreateFlutterPlatformNodeDelegate() override; + + private: + /// A wrapper structure to wraps macOS native accessibility events. + struct NSAccessibilityEvent { + NSAccessibilityNotificationName name; + gfx::NativeViewAccessible target; + NSDictionary* user_info; + }; + + //--------------------------------------------------------------------------- + /// @brief Posts the given event against the given node to the macOS + /// accessibility notification system. + /// @param[in] native_node The event target, must not be nil. + /// @param[in] mac_notification The event name, must not be nil. + void DispatchMacOSNotification(gfx::NativeViewAccessible native_node, + NSAccessibilityNotificationName mac_notification); + + //--------------------------------------------------------------------------- + /// @brief Posts the given event against the given node with the + /// additional attributes to the macOS accessibility notification + /// system. + /// @param[in] native_node The event target, must not be nil. + /// @param[in] mac_notification The event name, must not be nil. + /// @param[in] user_info The additional attributes, must not be nil. + void DispatchMacOSNotificationWithUserInfo(gfx::NativeViewAccessible native_node, + NSAccessibilityNotificationName mac_notification, + NSDictionary* user_info); + + //--------------------------------------------------------------------------- + /// @brief Whether the given event is in current pending events. + /// @param[in] event_type The event you would like to look up. + bool HasPendingEvent(ui::AXEventGenerator::Event event) const; + + //--------------------------------------------------------------------------- + /// @brief Converts the give ui::AXEventGenerator::Event into + /// macOS native accessibility event[s] + /// @param[in] event_type The original event type. + /// @param[in] ax_node The original event target. + std::vector MacOSEventsFromAXEvent(ui::AXEventGenerator::Event event_type, + const ui::AXNode& ax_node) const; + + __weak FlutterEngine* flutter_engine_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_ACCESSIBILITYBRIDGEMACDELEGATE_H_ diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.mm new file mode 100644 index 0000000000..193c1ea135 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.mm @@ -0,0 +1,378 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" +#include "flutter/shell/platform/embedder/embedder.h" + +namespace flutter { + +inline constexpr int32_t kRootNode = 0; + +// Native mac notifications fired. These notifications are not publicly documented. +// We have to define them ourselves. +static NSString* const AccessibilityLoadCompleteNotification = @"AXLoadComplete"; +static NSString* const AccessibilityInvalidStatusChangedNotification = @"AXInvalidStatusChanged"; +static NSString* const AccessibilityLiveRegionCreatedNotification = @"AXLiveRegionCreated"; +static NSString* const AccessibilityLiveRegionChangedNotification = @"AXLiveRegionChanged"; +static NSString* const AccessibilityExpandedChanged = @"AXExpandedChanged"; +static NSString* const AccessibilityMenuItemSelectedNotification = @"AXMenuItemSelected"; + +AccessibilityBridgeMacDelegate::AccessibilityBridgeMacDelegate(__weak FlutterEngine* flutter_engine) + : flutter_engine_(flutter_engine) {} + +void AccessibilityBridgeMacDelegate::OnAccessibilityEvent( + ui::AXEventGenerator::TargetedEvent targeted_event) { + ui::AXNode* ax_node = targeted_event.node; + std::vector events = + MacOSEventsFromAXEvent(targeted_event.event_params.event, *ax_node); + for (AccessibilityBridgeMacDelegate::NSAccessibilityEvent event : events) { + if (event.user_info != nil) { + DispatchMacOSNotificationWithUserInfo(event.target, event.name, event.user_info); + } else { + DispatchMacOSNotification(event.target, event.name); + } + } +} + +std::vector +AccessibilityBridgeMacDelegate::MacOSEventsFromAXEvent(ui::AXEventGenerator::Event event_type, + const ui::AXNode& ax_node) const { + // Gets the native_node with the node_id. + NSCAssert(flutter_engine_, @"Flutter engine should not be deallocated"); + auto bridge = flutter_engine_.accessibilityBridge.lock(); + NSCAssert(bridge, @"Accessibility bridge in flutter engine must not be null."); + auto platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(ax_node.id()).lock(); + NSCAssert(platform_node_delegate, @"Event target must exist in accessibility bridge."); + auto mac_platform_node_delegate = + std::static_pointer_cast(platform_node_delegate); + gfx::NativeViewAccessible native_node = mac_platform_node_delegate->GetNativeViewAccessible(); + + std::vector events; + switch (event_type) { + case ui::AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED: + if (ax_node.data().role == ax::mojom::Role::kTree) { + events.push_back({ + .name = NSAccessibilitySelectedRowsChangedNotification, + .target = native_node, + .user_info = nil, + }); + } else if (ax_node.data().role == ax::mojom::Role::kTextFieldWithComboBox) { + // Even though the selected item in the combo box has changed, we don't + // want to post a focus change because this will take the focus out of + // the combo box where the user might be typing. + events.push_back({ + .name = NSAccessibilitySelectedChildrenChangedNotification, + .target = native_node, + .user_info = nil, + }); + } + // In all other cases we should post + // |NSAccessibilityFocusedUIElementChangedNotification|, but this is + // handled elsewhere. + break; + case ui::AXEventGenerator::Event::LOAD_COMPLETE: + events.push_back({ + .name = AccessibilityLoadCompleteNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::INVALID_STATUS_CHANGED: + events.push_back({ + .name = AccessibilityInvalidStatusChangedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::SELECTED_CHILDREN_CHANGED: + if (ui::IsTableLike(ax_node.data().role)) { + events.push_back({ + .name = NSAccessibilitySelectedRowsChangedNotification, + .target = native_node, + .user_info = nil, + }); + } else { + // VoiceOver does not read anything if selection changes on the + // currently focused object, and the focus did not move. Fire a + // selection change if the focus did not change. + NSAccessibilityElement* native_accessibility_node = (NSAccessibilityElement*)native_node; + if (native_accessibility_node.accessibilityFocusedUIElement && + ax_node.data().HasState(ax::mojom::State::kMultiselectable) && + !HasPendingEvent(ui::AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED) && + !HasPendingEvent(ui::AXEventGenerator::Event::FOCUS_CHANGED)) { + // Don't fire selected children change, it will sometimes override + // announcement of current focus. + break; + } + events.push_back({ + .name = NSAccessibilitySelectedChildrenChangedNotification, + .target = native_node, + .user_info = nil, + }); + } + break; + case ui::AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED: { + // This event always fires at root + events.push_back({ + .name = NSAccessibilitySelectedTextChangedNotification, + .target = native_node, + .user_info = nil, + }); + // WebKit fires a notification both on the focused object and the page + // root. + const ui::AXTreeData& tree_data = bridge->GetAXTreeData(); + int32_t focus = tree_data.focus_id; + if (focus == ui::AXNode::kInvalidAXID || focus != tree_data.sel_anchor_object_id) { + break; // Just fire a notification on the root. + } + auto focus_node = bridge->GetFlutterPlatformNodeDelegateFromID(focus).lock(); + if (!focus_node) { + break; // Just fire a notification on the root. + } + events.push_back({ + .name = NSAccessibilitySelectedTextChangedNotification, + .target = focus_node->GetNativeViewAccessible(), + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::CHECKED_STATE_CHANGED: + events.push_back({ + .name = NSAccessibilityValueChangedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::VALUE_CHANGED: + events.push_back({ + .name = NSAccessibilityValueChangedNotification, + .target = native_node, + .user_info = nil, + }); + if (@available(macOS 10.11, *)) { + if (ax_node.data().HasState(ax::mojom::State::kEditable)) { + events.push_back({ + .name = NSAccessibilityValueChangedNotification, + .target = bridge->GetFlutterPlatformNodeDelegateFromID(kRootNode) + .lock() + ->GetNativeViewAccessible(), + .user_info = nil, + }); + } + } + break; + case ui::AXEventGenerator::Event::LIVE_REGION_CREATED: + events.push_back({ + .name = AccessibilityLiveRegionCreatedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::ALERT: { + events.push_back({ + .name = AccessibilityLiveRegionCreatedNotification, + .target = native_node, + .user_info = nil, + }); + // Voiceover requires a live region changed notification to actually + // announce the live region. + auto live_region_events = + MacOSEventsFromAXEvent(ui::AXEventGenerator::Event::LIVE_REGION_CHANGED, ax_node); + events.insert(events.end(), live_region_events.begin(), live_region_events.end()); + break; + } + case ui::AXEventGenerator::Event::LIVE_REGION_CHANGED: { + if (@available(macOS 10.14, *)) { + // Do nothing on macOS >=10.14. + } else { + // Uses the announcement API to get around OS <= 10.13 VoiceOver bug + // where it stops announcing live regions after the first time focus + // leaves any content area. + // Unfortunately this produces an annoying boing sound with each live + // announcement, but the alternative is almost no live region support. + NSString* announcement = [[NSString alloc] + initWithUTF8String:mac_platform_node_delegate->GetLiveRegionText().c_str()]; + NSDictionary* notification_info = @{ + NSAccessibilityAnnouncementKey : announcement, + NSAccessibilityPriorityKey : @(NSAccessibilityPriorityLow) + }; + // Triggers VoiceOver speech and show on Braille display, if available. + // The Braille will only appear for a few seconds, and then will be replaced + // with the previous announcement. + events.push_back({ + .name = NSAccessibilityAnnouncementRequestedNotification, + .target = [NSApp mainWindow], + .user_info = notification_info, + }); + break; + } + // Uses native VoiceOver support for live regions. + events.push_back({ + .name = AccessibilityLiveRegionChangedNotification, + .target = native_node, + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::ROW_COUNT_CHANGED: + events.push_back({ + .name = NSAccessibilityRowCountChangedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::EXPANDED: { + NSAccessibilityNotificationName mac_notification; + if (ax_node.data().role == ax::mojom::Role::kRow || + ax_node.data().role == ax::mojom::Role::kTreeItem) { + mac_notification = NSAccessibilityRowExpandedNotification; + } else { + mac_notification = AccessibilityExpandedChanged; + } + events.push_back({ + .name = mac_notification, + .target = native_node, + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::COLLAPSED: { + NSAccessibilityNotificationName mac_notification; + if (ax_node.data().role == ax::mojom::Role::kRow || + ax_node.data().role == ax::mojom::Role::kTreeItem) { + mac_notification = NSAccessibilityRowCollapsedNotification; + } else { + mac_notification = AccessibilityExpandedChanged; + } + events.push_back({ + .name = mac_notification, + .target = native_node, + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::MENU_ITEM_SELECTED: + events.push_back({ + .name = AccessibilityMenuItemSelectedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::CHILDREN_CHANGED: { + // NSAccessibilityCreatedNotification seems to be the only way to let + // Voiceover pick up layout changes. + events.push_back({ + .name = NSAccessibilityCreatedNotification, + .target = [NSApp mainWindow], + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::SUBTREE_CREATED: + case ui::AXEventGenerator::Event::ACCESS_KEY_CHANGED: + case ui::AXEventGenerator::Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED: + case ui::AXEventGenerator::Event::ATOMIC_CHANGED: + case ui::AXEventGenerator::Event::AUTO_COMPLETE_CHANGED: + case ui::AXEventGenerator::Event::BUSY_CHANGED: + case ui::AXEventGenerator::Event::CONTROLS_CHANGED: + case ui::AXEventGenerator::Event::CLASS_NAME_CHANGED: + case ui::AXEventGenerator::Event::DESCRIBED_BY_CHANGED: + case ui::AXEventGenerator::Event::DESCRIPTION_CHANGED: + case ui::AXEventGenerator::Event::DOCUMENT_TITLE_CHANGED: + case ui::AXEventGenerator::Event::DROPEFFECT_CHANGED: + case ui::AXEventGenerator::Event::ENABLED_CHANGED: + case ui::AXEventGenerator::Event::FOCUS_CHANGED: + case ui::AXEventGenerator::Event::FLOW_FROM_CHANGED: + case ui::AXEventGenerator::Event::FLOW_TO_CHANGED: + case ui::AXEventGenerator::Event::GRABBED_CHANGED: + case ui::AXEventGenerator::Event::HASPOPUP_CHANGED: + case ui::AXEventGenerator::Event::HIERARCHICAL_LEVEL_CHANGED: + case ui::AXEventGenerator::Event::IGNORED_CHANGED: + case ui::AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED: + case ui::AXEventGenerator::Event::KEY_SHORTCUTS_CHANGED: + case ui::AXEventGenerator::Event::LABELED_BY_CHANGED: + case ui::AXEventGenerator::Event::LANGUAGE_CHANGED: + case ui::AXEventGenerator::Event::LAYOUT_INVALIDATED: + case ui::AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED: + case ui::AXEventGenerator::Event::LIVE_RELEVANT_CHANGED: + case ui::AXEventGenerator::Event::LIVE_STATUS_CHANGED: + case ui::AXEventGenerator::Event::LOAD_START: + case ui::AXEventGenerator::Event::MULTILINE_STATE_CHANGED: + case ui::AXEventGenerator::Event::MULTISELECTABLE_STATE_CHANGED: + case ui::AXEventGenerator::Event::NAME_CHANGED: + case ui::AXEventGenerator::Event::OBJECT_ATTRIBUTE_CHANGED: + case ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED: + case ui::AXEventGenerator::Event::PLACEHOLDER_CHANGED: + case ui::AXEventGenerator::Event::PORTAL_ACTIVATED: + case ui::AXEventGenerator::Event::POSITION_IN_SET_CHANGED: + case ui::AXEventGenerator::Event::READONLY_CHANGED: + case ui::AXEventGenerator::Event::RELATED_NODE_CHANGED: + case ui::AXEventGenerator::Event::REQUIRED_STATE_CHANGED: + case ui::AXEventGenerator::Event::ROLE_CHANGED: + case ui::AXEventGenerator::Event::SCROLL_HORIZONTAL_POSITION_CHANGED: + case ui::AXEventGenerator::Event::SCROLL_VERTICAL_POSITION_CHANGED: + case ui::AXEventGenerator::Event::SELECTED_CHANGED: + case ui::AXEventGenerator::Event::SET_SIZE_CHANGED: + case ui::AXEventGenerator::Event::SORT_CHANGED: + case ui::AXEventGenerator::Event::STATE_CHANGED: + case ui::AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED: + case ui::AXEventGenerator::Event::VALUE_MAX_CHANGED: + case ui::AXEventGenerator::Event::VALUE_MIN_CHANGED: + case ui::AXEventGenerator::Event::VALUE_STEP_CHANGED: + case ui::AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED: + // There are some notifications that aren't meaningful on Mac. + // It's okay to skip them. + break; + } + return events; +} + +void AccessibilityBridgeMacDelegate::DispatchAccessibilityAction(ui::AXNode::AXID target, + FlutterSemanticsAction action, + const std::vector& data) { + NSCAssert(flutter_engine_, @"Flutter engine should not be deallocated"); + [flutter_engine_ dispatchSemanticsAction:action toTarget:target withData:data]; +} + +std::unique_ptr +AccessibilityBridgeMacDelegate::CreateFlutterPlatformNodeDelegate() { + return std::make_unique(flutter_engine_); +} + +// Private method +void AccessibilityBridgeMacDelegate::DispatchMacOSNotification( + gfx::NativeViewAccessible native_node, + NSAccessibilityNotificationName mac_notification) { + NSCAssert(mac_notification, @"The notification must not be null."); + NSCAssert(native_node, @"The notification target must not be null."); + NSAccessibilityPostNotification(native_node, mac_notification); +} + +void AccessibilityBridgeMacDelegate::DispatchMacOSNotificationWithUserInfo( + gfx::NativeViewAccessible native_node, + NSAccessibilityNotificationName mac_notification, + NSDictionary* user_info) { + NSCAssert(mac_notification, @"The notification must not be null."); + NSCAssert(native_node, @"The notification target must not be null."); + NSCAssert(user_info, @"The notification data must not be null."); + NSAccessibilityPostNotificationWithUserInfo(native_node, mac_notification, user_info); +} + +bool AccessibilityBridgeMacDelegate::HasPendingEvent(ui::AXEventGenerator::Event event) const { + NSCAssert(flutter_engine_, @"Flutter engine should not be deallocated"); + auto bridge = flutter_engine_.accessibilityBridge.lock(); + NSCAssert(bridge, @"Accessibility bridge in flutter engine must not be null."); + std::vector pending_events = bridge->GetPendingEvents(); + for (const auto& pending_event : bridge->GetPendingEvents()) { + if (pending_event.event_params.event == event) { + return true; + } + } + return false; +} + +} // namespace flutter diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm index eab43a4da2..68a710a3aa 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm @@ -8,6 +8,7 @@ #include #include +#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTextureGL.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterGLCompositor.h" @@ -15,7 +16,7 @@ #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderingBackend.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" -#import "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/embedder.h" /** * Constructs and returns a FlutterLocale struct corresponding to |locale|, which must outlive @@ -120,6 +121,9 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi // The embedding-API-level engine object. FLUTTER_API_SYMBOL(FlutterEngine) _engine; + // The private member for accessibility. + std::shared_ptr _bridge; + // The project being run by this engine. FlutterDartProject* _project; @@ -153,6 +157,7 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi _project = project ?: [[FlutterDartProject alloc] init]; _messageHandlers = [[NSMutableDictionary alloc] init]; _allowHeadlessExecution = allowHeadlessExecution; + _semanticsEnabled = NO; _embedderAPI.struct_size = sizeof(FlutterEngineProcTable); FlutterEngineGetProcAddresses(&_embedderAPI); @@ -211,6 +216,16 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi flutterArguments.command_line_argc = static_cast(argv.size()); flutterArguments.command_line_argv = argv.size() > 0 ? argv.data() : nullptr; flutterArguments.platform_message_callback = (FlutterPlatformMessageCallback)OnPlatformMessage; + flutterArguments.update_semantics_node_callback = [](const FlutterSemanticsNode* node, + void* user_data) { + FlutterEngine* engine = (__bridge FlutterEngine*)user_data; + [engine updateSemanticsNode:node]; + }; + flutterArguments.update_semantics_custom_action_callback = + [](const FlutterSemanticsCustomAction* action, void* user_data) { + FlutterEngine* engine = (__bridge FlutterEngine*)user_data; + [engine updateSemanticsCustomActions:action]; + }; flutterArguments.custom_dart_entrypoint = entrypoint.UTF8String; flutterArguments.shutdown_dart_vm_when_done = true; flutterArguments.dart_entrypoint_argc = dartEntrypointArgs.size(); @@ -397,6 +412,10 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi return _embedderAPI; } +- (std::weak_ptr)accessibilityBridge { + return _bridge; +} + - (void)updateWindowMetrics { if (!_engine) { return; @@ -421,6 +440,29 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi _embedderAPI.SendPointerEvent(_engine, &event, 1); } +- (void)setSemanticsEnabled:(BOOL)enabled { + if (_semanticsEnabled == enabled) { + return; + } + _semanticsEnabled = enabled; + if (!_semanticsEnabled && _bridge) { + _bridge.reset(); + } else if (_semanticsEnabled && !_bridge) { + _bridge = std::make_shared( + std::make_unique(self)); + } + if (!_semanticsEnabled) { + self.viewController.view.accessibilityChildren = nil; + } + _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled); +} + +- (void)dispatchSemanticsAction:(FlutterSemanticsAction)action + toTarget:(uint16_t)target + withData:(const std::vector&)data { + _embedderAPI.DispatchSemanticsAction(_engine, target, action, data.data(), data.size()); +} + #pragma mark - Private methods - (void)sendUserLocales { @@ -602,6 +644,35 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess; } +- (void)updateSemanticsNode:(const FlutterSemanticsNode*)node { + NSAssert(_bridge, @"The accessibility bridge must be initialized."); + if (node->id == kFlutterSemanticsNodeIdBatchEnd) { + return; + } + _bridge->AddFlutterSemanticsNodeUpdate(node); +} + +- (void)updateSemanticsCustomActions:(const FlutterSemanticsCustomAction*)action { + NSAssert(_bridge, @"The accessibility bridge must be initialized."); + if (action->id == kFlutterSemanticsNodeIdBatchEnd) { + // Custom action with id = kFlutterSemanticsNodeIdBatchEnd indicates this is + // the end of the update batch. + _bridge->CommitUpdates(); + // Attaches the accessibility root to the flutter view. + auto root = _bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + if (root) { + if ([self.viewController.view.accessibilityChildren count] == 0) { + NSAccessibilityElement* native_root = root->GetNativeViewAccessible(); + self.viewController.view.accessibilityChildren = @[ native_root ]; + } + } else { + self.viewController.view.accessibilityChildren = nil; + } + return; + } + _bridge->AddFlutterSemanticsCustomActionUpdate(action); +} + #pragma mark - Task runner integration - (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime { diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm index b011f55972..60a94b2e8e 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm @@ -4,9 +4,12 @@ #import +#include "flutter/shell/platform/common/accessibility_bridge.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" #include "flutter/testing/testing.h" @@ -52,4 +55,105 @@ TEST(FlutterEngine, MessengerSend) { [engine shutDownEngine]; } +TEST(FlutterEngine, CanToggleAccessibility) { + FlutterEngine* engine = CreateTestEngine(); + // Capture the update callbacks before the embedder API initializes. + auto original_init = engine.embedderAPI.Initialize; + std::function update_node_callback; + std::function update_action_callback; + engine.embedderAPI.Initialize = MOCK_ENGINE_PROC( + Initialize, ([&update_action_callback, &update_node_callback, &original_init]( + size_t version, const FlutterRendererConfig* config, + const FlutterProjectArgs* args, void* user_data, auto engine_out) { + update_node_callback = args->update_semantics_node_callback; + update_action_callback = args->update_semantics_custom_action_callback; + return original_init(version, config, args, user_data, engine_out); + })); + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + // Set up view controller. + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:project]; + [engine setViewController:viewController]; + // Enable the semantics. + bool enabled_called = false; + engine.embedderAPI.UpdateSemanticsEnabled = + MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) { + enabled_called = enabled; + return kSuccess; + })); + engine.semanticsEnabled = YES; + EXPECT_TRUE(enabled_called); + // Send flutter semantics updates. + FlutterSemanticsNode root; + root.id = 0; + root.flags = static_cast(0); + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + update_node_callback(&root, (void*)CFBridgingRetain(engine)); + + FlutterSemanticsNode child1; + child1.id = 1; + child1.flags = static_cast(0); + child1.actions = static_cast(0); + child1.text_selection_base = -1; + child1.text_selection_extent = -1; + child1.label = "child 1"; + child1.hint = ""; + child1.value = ""; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + update_node_callback(&child1, (void*)CFBridgingRetain(engine)); + + FlutterSemanticsNode node_batch_end; + node_batch_end.id = kFlutterSemanticsNodeIdBatchEnd; + update_node_callback(&node_batch_end, (void*)CFBridgingRetain(engine)); + + FlutterSemanticsCustomAction action_batch_end; + action_batch_end.id = kFlutterSemanticsNodeIdBatchEnd; + update_action_callback(&action_batch_end, (void*)CFBridgingRetain(engine)); + + // Verify the accessibility tree is attached to the flutter view. + EXPECT_EQ([engine.viewController.view.accessibilityChildren count], 1u); + NSAccessibilityElement* native_root = engine.viewController.view.accessibilityChildren[0]; + std::string root_label = [native_root.accessibilityLabel UTF8String]; + EXPECT_TRUE(root_label == "root"); + EXPECT_EQ(native_root.accessibilityRole, NSAccessibilityGroupRole); + EXPECT_EQ([native_root.accessibilityChildren count], 1u); + NSAccessibilityElement* native_child1 = native_root.accessibilityChildren[0]; + std::string child1_value = [native_child1.accessibilityValue UTF8String]; + EXPECT_TRUE(child1_value == "child 1"); + EXPECT_EQ(native_child1.accessibilityRole, NSAccessibilityStaticTextRole); + EXPECT_EQ([native_child1.accessibilityChildren count], 0u); + + // Disable the semantics. + bool semanticsEnabled = true; + engine.embedderAPI.UpdateSemanticsEnabled = + MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&semanticsEnabled](auto engine, bool enabled) { + semanticsEnabled = enabled; + return kSuccess; + })); + engine.semanticsEnabled = NO; + EXPECT_FALSE(semanticsEnabled); + // Verify the accessibility tree is removed from the view. + EXPECT_EQ([engine.viewController.view.accessibilityChildren count], 0u); + + [engine setViewController:nil]; + [engine shutDownEngine]; +} + } // namespace flutter::testing diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h index a4a1228f63..f13ea02e45 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h @@ -6,8 +6,10 @@ #import +#include + +#include "flutter/shell/platform/common/accessibility_bridge.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h" -#include "flutter/shell/platform/embedder/embedder.h" @interface FlutterEngine () @@ -27,6 +29,14 @@ */ @property(nonatomic) FlutterEngineProcTable& embedderAPI; +@property(nonatomic, readonly) std::weak_ptr accessibilityBridge; + +/** + * True if the semantics is enabled. The Flutter framework starts sending + * semantics update through the embedder as soon as it is set to YES. + */ +@property(nonatomic) BOOL semanticsEnabled; + /** * Informs the engine that the associated view controller's view size has changed. */ @@ -52,4 +62,14 @@ */ - (BOOL)unregisterTextureWithID:(int64_t)textureID; +// Accessibility API. + +/** + * Dispatches semantics action back to the framework. The semantics must be enabled by calling + * the updateSemanticsEnabled before dispatching semantics actions. + */ +- (void)dispatchSemanticsAction:(FlutterSemanticsAction)action + toTarget:(uint16_t)target + withData:(const std::vector&)data; + @end diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h new file mode 100644 index 0000000000..0ef94fbba2 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h @@ -0,0 +1,58 @@ +// 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_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMNODEDELEGATEMAC_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMNODEDELEGATEMAC_H_ + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" + +#include "flutter/shell/platform/common/flutter_platform_node_delegate.h" +#include "flutter/shell/platform/embedder/embedder.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// The macOS implementation of FlutterPlatformNodeDelegate. This class uses +/// AXPlatformNodeMac to manage the macOS-specific accessibility objects. +class FlutterPlatformNodeDelegateMac : public FlutterPlatformNodeDelegate { + public: + explicit FlutterPlatformNodeDelegateMac(__weak FlutterEngine* engine); + virtual ~FlutterPlatformNodeDelegateMac(); + + //--------------------------------------------------------------------------- + /// @brief Gets the live region text of this node in UTF-8 format. This + /// is useful to determine the changes in between semantics + /// updates when generating accessibility events. + std::string GetLiveRegionText() const; + + // |ui::AXPlatformNodeDelegate| + gfx::NativeViewAccessible GetNativeViewAccessible() override; + + // |ui::AXPlatformNodeDelegate| + gfx::NativeViewAccessible GetNSWindow() override; + + // |FlutterPlatformNodeDelegate| + gfx::NativeViewAccessible GetParent() override; + + // |FlutterPlatformNodeDelegate| + gfx::Rect GetBoundsRect( + const ui::AXCoordinateSystem coordinate_system, + const ui::AXClippingBehavior clipping_behavior, + ui::AXOffscreenResult* offscreen_result) const override; + + private: + ui::AXPlatformNode* ax_platform_node_; + __weak FlutterEngine* engine_; + + gfx::RectF ConvertBoundsFromLocalToScreen( + const gfx::RectF& local_bounds) const; + gfx::RectF ConvertBoundsFromScreenToGlobal( + const gfx::RectF& window_bounds) const; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMNODEDELEGATEMAC_H_ diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.mm new file mode 100644 index 0000000000..d48f44ece3 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.mm @@ -0,0 +1,118 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" + +#include "flutter/shell/platform/common/accessibility_bridge.h" +#include "flutter/third_party/accessibility/ax/ax_action_data.h" +#include "flutter/third_party/accessibility/ax/ax_node_position.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_node.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_node_base.h" +#include "flutter/third_party/accessibility/base/string_utils.h" +#include "flutter/third_party/accessibility/gfx/geometry/rect_conversions.h" + +namespace flutter { // namespace + +FlutterPlatformNodeDelegateMac::FlutterPlatformNodeDelegateMac(FlutterEngine* engine) + : engine_(engine) { + ax_platform_node_ = ui::AXPlatformNode::Create(this); + NSCAssert(ax_platform_node_, @"Failed to create platform node."); +} + +FlutterPlatformNodeDelegateMac::~FlutterPlatformNodeDelegateMac() { + ax_platform_node_->Destroy(); +} + +gfx::NativeViewAccessible FlutterPlatformNodeDelegateMac::GetNativeViewAccessible() { + NSCAssert(ax_platform_node_, @"Platform node does not exist."); + return ax_platform_node_->GetNativeViewAccessible(); +} + +gfx::NativeViewAccessible FlutterPlatformNodeDelegateMac::GetParent() { + gfx::NativeViewAccessible parent = FlutterPlatformNodeDelegate::GetParent(); + if (!parent) { + NSCAssert(engine_, @"Flutter engine should not be deallocated"); + return engine_.viewController.view; + } + return parent; +} + +gfx::Rect FlutterPlatformNodeDelegateMac::GetBoundsRect( + const ui::AXCoordinateSystem coordinate_system, + const ui::AXClippingBehavior clipping_behavior, + ui::AXOffscreenResult* offscreen_result) const { + gfx::Rect local_bounds = FlutterPlatformNodeDelegate::GetBoundsRect( + coordinate_system, clipping_behavior, offscreen_result); + gfx::RectF local_bounds_f(local_bounds); + gfx::RectF screen_bounds = ConvertBoundsFromLocalToScreen(local_bounds_f); + return gfx::ToEnclosingRect(ConvertBoundsFromScreenToGlobal(screen_bounds)); +} + +gfx::NativeViewAccessible FlutterPlatformNodeDelegateMac::GetNSWindow() { + FlutterAppDelegate* appDelegate = (FlutterAppDelegate*)[NSApp delegate]; + return appDelegate.mainFlutterWindow; +} + +std::string FlutterPlatformNodeDelegateMac::GetLiveRegionText() const { + if (GetAXNode()->IsIgnored()) { + return ""; + } + + std::string text = GetData().GetStringAttribute(ax::mojom::StringAttribute::kName); + if (!text.empty()) { + return text; + }; + NSCAssert(engine_, @"Flutter engine should not be deallocated"); + auto bridge_ptr = engine_.accessibilityBridge.lock(); + NSCAssert(bridge_ptr, @"Accessibility bridge in flutter engine must not be null."); + for (int32_t child : GetData().child_ids) { + auto delegate_child = bridge_ptr->GetFlutterPlatformNodeDelegateFromID(child).lock(); + if (!delegate_child) { + continue; + } + text += std::static_pointer_cast(delegate_child) + ->GetLiveRegionText(); + } + return text; +} + +gfx::RectF FlutterPlatformNodeDelegateMac::ConvertBoundsFromLocalToScreen( + const gfx::RectF& local_bounds) const { + // Converts to NSRect to use NSView rect conversion. + NSRect ns_local_bounds = + NSMakeRect(local_bounds.x(), local_bounds.y(), local_bounds.width(), local_bounds.height()); + // The macOS XY coordinates start at bottom-left and increase toward top-right, + // which is different from the Flutter's XY coordinates that start at top-left + // increasing to bottom-right. Therefore, We need to flip the y coordinate when + // we convert from flutter coordinates to macOS coordinates. + ns_local_bounds.origin.y = -ns_local_bounds.origin.y - ns_local_bounds.size.height; + __strong FlutterEngine* strong_engine = engine_; + NSCAssert(strong_engine, @"Flutter engine should not be deallocated"); + NSRect ns_view_bounds = + [strong_engine.viewController.view convertRectFromBacking:ns_local_bounds]; + NSRect ns_window_bounds = [strong_engine.viewController.view convertRect:ns_view_bounds + toView:nil]; + NSRect ns_screen_bounds = + [[strong_engine.viewController.view window] convertRectToScreen:ns_window_bounds]; + gfx::RectF screen_bounds(ns_screen_bounds.origin.x, ns_screen_bounds.origin.y, + ns_screen_bounds.size.width, ns_screen_bounds.size.height); + return screen_bounds; +} + +gfx::RectF FlutterPlatformNodeDelegateMac::ConvertBoundsFromScreenToGlobal( + const gfx::RectF& screen_bounds) const { + // The voiceover seems to only accept bounds that are relative to primary screen. + // Thus, we use [[NSScreen screens] firstObject] instead of [NSScreen mainScreen]. + NSScreen* screen = [[NSScreen screens] firstObject]; + NSRect primary_screen_bounds = [screen frame]; + // The screen is flipped against y axis. + float flipped_y = primary_screen_bounds.size.height - screen_bounds.y() - screen_bounds.height(); + return {screen_bounds.x(), flipped_y, screen_bounds.width(), screen_bounds.height()}; +} + +} // namespace flutter diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMacTest.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMacTest.mm new file mode 100644 index 0000000000..2bb83ef0a8 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMacTest.mm @@ -0,0 +1,118 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#include "flutter/testing/testing.h" + +#include "flutter/shell/platform/common/accessibility_bridge.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" +#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" +#include "flutter/third_party/accessibility/ax/ax_action_data.h" + +namespace flutter::testing { + +namespace { +// Returns an engine configured for the text fixture resource configuration. +FlutterEngine* CreateTestEngine() { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + return [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:true]; +} +} // namespace + +TEST(FlutterPlatformNodeDelegateMac, Basics) { + FlutterEngine* engine = CreateTestEngine(); + engine.semanticsEnabled = YES; + auto bridge = engine.accessibilityBridge.lock(); + // Initialize ax node data. + FlutterSemanticsNode root; + root.id = 0; + root.flags = static_cast(0); + ; + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "accessibility"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.child_count = 0; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(&root); + + bridge->CommitUpdates(); + + auto root_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + // Verify the accessibility attribute matches. + NSAccessibilityElement* native_accessibility = + root_platform_node_delegate->GetNativeViewAccessible(); + std::string value = [native_accessibility.accessibilityValue UTF8String]; + EXPECT_TRUE(value == "accessibility"); + EXPECT_EQ(native_accessibility.accessibilityRole, NSAccessibilityStaticTextRole); + EXPECT_EQ([native_accessibility.accessibilityChildren count], 0u); + [engine shutDownEngine]; +} + +TEST(FlutterPlatformNodeDelegateMac, CanPerformAction) { + FlutterEngine* engine = CreateTestEngine(); + engine.semanticsEnabled = YES; + auto bridge = engine.accessibilityBridge.lock(); + // Initialize ax node data. + FlutterSemanticsNode root; + root.id = 0; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(&root); + + FlutterSemanticsNode child1; + child1.id = 1; + child1.label = "child 1"; + child1.hint = ""; + child1.value = ""; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(&child1); + + bridge->CommitUpdates(); + + auto root_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + + // Set up embedder API mock. + FlutterSemanticsAction called_action; + uint64_t called_id; + + engine.embedderAPI.DispatchSemanticsAction = MOCK_ENGINE_PROC( + DispatchSemanticsAction, + ([&called_id, &called_action](auto engine, uint64_t id, FlutterSemanticsAction action, + const uint8_t* data, size_t data_length) { + called_id = id; + called_action = action; + return kSuccess; + })); + + // Performs an AXAction. + ui::AXActionData action_data; + action_data.action = ax::mojom::Action::kDoDefault; + root_platform_node_delegate->AccessibilityPerformAction(action_data); + + EXPECT_EQ(called_action, FlutterSemanticsAction::kFlutterSemanticsActionTap); + EXPECT_EQ(called_id, 1u); + [engine shutDownEngine]; +} + +} // flutter::testing diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.mm index 46faff76cb..be421bd2c3 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.mm @@ -119,5 +119,26 @@ - (void)shutdown { [_resizeSynchronizer shutdown]; } +#pragma mark - NSAccessibility overrides + +- (BOOL)isAccessibilityElement { + return YES; +} + +- (NSAccessibilityRole)accessibilityRole { + return NSAccessibilityGroupRole; +} + +- (NSString*)accessibilityLabel { + // TODO(chunhtai): Provides a way to let developer customize the accessibility + // label. + // https://github.com/flutter/flutter/issues/75446 + NSString* applicationName = + [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; + if (!applicationName) { + applicationName = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleName"]; + } + return applicationName; +} @end diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm index 8b4a62ec72..1381241623 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm @@ -22,6 +22,11 @@ namespace { /// Clipboard plain text format. constexpr char kTextPlainFormat[] = "text/plain"; +/// The private notification for voice over. +static NSString* const EnhancedUserInterfaceNotification = + @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification"; +static NSString* const EnhancedUserInterfaceKey = @"AXEnhancedUserInterface"; + /** * State tracking for mouse events, to adapt between the events coming from the system and the * events that the embedding API expects. @@ -165,6 +170,11 @@ struct KeyboardState { */ - (void)onSettingsChanged:(NSNotification*)notification; +/** + * Responds to updates in accessibility. + */ +- (void)onAccessibilityStatusChanged:(NSNotification*)notification; + /** * Handles messages received from the Flutter engine on the _*Channel channels. */ @@ -229,6 +239,13 @@ static void CommonInit(FlutterViewController* controller) { } controller->_additionalKeyResponders = [[NSMutableOrderedSet alloc] init]; controller->_mouseTrackingMode = FlutterMouseTrackingModeInKeyWindow; + + NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; + // macOS fires this private message when voiceover turns on or off. + [center addObserver:controller + selector:@selector(onAccessibilityStatusChanged:) + name:EnhancedUserInterfaceNotification + object:nil]; } - (instancetype)initWithCoder:(NSCoder*)coder { @@ -575,6 +592,13 @@ static void CommonInit(FlutterViewController* controller) { [_keyEventChannel sendMessage:keyMessage reply:replyHandler]; } +- (void)onAccessibilityStatusChanged:(NSNotification*)notification { + if (!_engine) { + return; + } + _engine.semanticsEnabled = !!notification.userInfo[EnhancedUserInterfaceKey]; +} + - (void)onSettingsChanged:(NSNotification*)notification { // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015. NSString* brightness =