diff --git a/engine/src/flutter/lib/web_ui/lib/platform_dispatcher.dart b/engine/src/flutter/lib/web_ui/lib/platform_dispatcher.dart index 24aa93a651..f463595697 100644 --- a/engine/src/flutter/lib/web_ui/lib/platform_dispatcher.dart +++ b/engine/src/flutter/lib/web_ui/lib/platform_dispatcher.dart @@ -545,4 +545,7 @@ class SemanticsActionEvent { arguments: arguments == _noArgumentPlaceholder ? this.arguments : arguments, ); } + + @override + String toString() => 'SemanticsActionEvent($type, view: $viewId, node: $nodeId)'; } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/initialization.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/initialization.dart index c8badf914c..fd31ac6022 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/initialization.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/initialization.dart @@ -50,8 +50,15 @@ void registerHotRestartListener(ui.VoidCallback listener) { /// such as removing static DOM listeners, prior to allowing the Dart runtime /// to re-initialize the program. void debugEmulateHotRestart() { - for (final ui.VoidCallback listener in _hotRestartListeners) { - listener(); + // While hot restart listeners are executing, more listeners may be added. To + // avoid concurrent modification, the listeners are copies and emptied. If new + // listeners are added in the process, the loop will pick them up. + while (_hotRestartListeners.isNotEmpty) { + final List copyOfListeners = _hotRestartListeners.toList(); + _hotRestartListeners.clear(); + for (final ui.VoidCallback listener in copyOfListeners) { + listener(); + } } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard_binding.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard_binding.dart index c12d1a36a9..95d2f533ea 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard_binding.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard_binding.dart @@ -148,7 +148,7 @@ class KeyboardBinding { if (_debugLogKeyEvents) { print(event.type); } - if (EngineSemanticsOwner.instance.receiveGlobalEvent(event)) { + if (EngineSemantics.instance.receiveGlobalEvent(event)) { handler(event); } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/platform_dispatcher.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/platform_dispatcher.dart index ff0951cf1c..636e4da331 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/platform_dispatcher.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/platform_dispatcher.dart @@ -806,7 +806,7 @@ class EnginePlatformDispatcher extends ui.PlatformDispatcher { call `updateSemantics`. ''') void updateSemantics(ui.SemanticsUpdate update) { - EngineSemanticsOwner.instance.updateSemantics(update); + implicitView?.semantics.updateSemantics(update); } /// This is equivalent to `locales.first`, except that it will provide an diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart index bb2f1421d7..0aaa60cae4 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart @@ -523,7 +523,7 @@ abstract class _BaseAdapter { // Report the event to semantics. This information is used to debounce // browser gestures. Semantics tells us whether it is safe to forward // the event to the framework. - if (EngineSemanticsOwner.instance.receiveGlobalEvent(event)) { + if (EngineSemantics.instance.receiveGlobalEvent(event)) { handler(event); } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding/event_position_helper.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding/event_position_helper.dart index 2331a05b09..34777699a7 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding/event_position_helper.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding/event_position_helper.dart @@ -8,7 +8,7 @@ import 'package:ui/ui.dart' as ui show Offset; import '../dom.dart'; import '../platform_dispatcher.dart'; -import '../semantics.dart' show EngineSemanticsOwner; +import '../semantics.dart' show EngineSemantics; import '../text_editing/text_editing.dart'; import '../vector_math.dart'; @@ -25,7 +25,7 @@ import '../vector_math.dart'; /// offsetX, offsetY == 0 (TalkBack events). ui.Offset computeEventOffsetToTarget(DomMouseEvent event, DomElement actualTarget) { // On a TalkBack event - if (EngineSemanticsOwner.instance.semanticsEnabled && event.offsetX == 0 && event.offsetY == 0) { + if (EngineSemantics.instance.semanticsEnabled && event.offsetX == 0 && event.offsetY == 0) { return _computeOffsetForTalkbackEvent(event, actualTarget); } @@ -109,7 +109,7 @@ ui.Offset _computeOffsetForInputs(DomMouseEvent event, EditableTextGeometry inpu /// positions. Finally, we deduct that from clientX, clientY of the event. // TODO(dit): Make this understand 3D transforms, https://github.com/flutter/flutter/issues/117091 ui.Offset _computeOffsetForTalkbackEvent(DomMouseEvent event, DomElement actualTarget) { - assert(EngineSemanticsOwner.instance.semanticsEnabled); + assert(EngineSemantics.instance.semanticsEnabled); // Use clientX/clientY as the position of the event (this is relative to // the top left of the page, including scroll) double offsetX = event.clientX; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/incrementable.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/incrementable.dart index 7ad693b628..5dceb9582c 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/incrementable.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/incrementable.dart @@ -55,7 +55,7 @@ class Incrementable extends PrimaryRoleManager { _gestureModeListener = (GestureMode mode) { update(); }; - semanticsObject.owner.addGestureModeListener(_gestureModeListener); + EngineSemantics.instance.addGestureModeListener(_gestureModeListener); _focusManager.manage(semanticsObject.id, _element); } @@ -76,7 +76,7 @@ class Incrementable extends PrimaryRoleManager { /// Disables the input [_element] when the gesture mode switches to /// [GestureMode.pointerEvents], and enables it when the mode switches back to /// [GestureMode.browserGestures]. - GestureModeCallback? _gestureModeListener; + late final GestureModeCallback _gestureModeListener; /// Whether we forwarded a semantics action to the framework and awaiting an /// update. @@ -89,7 +89,7 @@ class Incrementable extends PrimaryRoleManager { void update() { super.update(); - switch (semanticsObject.owner.gestureMode) { + switch (EngineSemantics.instance.gestureMode) { case GestureMode.browserGestures: _enableBrowserGestureHandling(); _updateInputValues(); @@ -100,7 +100,7 @@ class Incrementable extends PrimaryRoleManager { } void _enableBrowserGestureHandling() { - assert(semanticsObject.owner.gestureMode == GestureMode.browserGestures); + assert(EngineSemantics.instance.gestureMode == GestureMode.browserGestures); if (!_element.disabled!) { return; } @@ -108,7 +108,7 @@ class Incrementable extends PrimaryRoleManager { } void _updateInputValues() { - assert(semanticsObject.owner.gestureMode == GestureMode.browserGestures); + assert(EngineSemantics.instance.gestureMode == GestureMode.browserGestures); final bool updateNeeded = _pendingResync || semanticsObject.isValueDirty || @@ -148,11 +148,9 @@ class Incrementable extends PrimaryRoleManager { @override void dispose() { - assert(_gestureModeListener != null); super.dispose(); _focusManager.stopManaging(); - semanticsObject.owner.removeGestureModeListener(_gestureModeListener); - _gestureModeListener = null; + EngineSemantics.instance.removeGestureModeListener(_gestureModeListener); _disableBrowserGestureHandling(); _element.remove(); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/scrollable.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/scrollable.dart index 61f912304e..61cb17f6ae 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/scrollable.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/scrollable.dart @@ -62,7 +62,7 @@ class Scrollable extends PrimaryRoleManager { /// Responds to browser-detected "scroll" gestures. void _recomputeScrollPosition() { if (_domScrollPosition != _effectiveNeutralScrollPosition) { - if (!semanticsObject.owner.shouldAcceptBrowserGesture('scroll')) { + if (!EngineSemantics.instance.shouldAcceptBrowserGesture('scroll')) { return; } final bool doScrollForward = @@ -121,7 +121,7 @@ class Scrollable extends PrimaryRoleManager { _gestureModeListener = (_) { _gestureModeDidChange(); }; - semanticsObject.owner.addGestureModeListener(_gestureModeListener); + EngineSemantics.instance.addGestureModeListener(_gestureModeListener!); _scrollListener = createDomEventListener((_) { _recomputeScrollPosition(); @@ -196,7 +196,7 @@ class Scrollable extends PrimaryRoleManager { } void _gestureModeDidChange() { - switch (semanticsObject.owner.gestureMode) { + switch (EngineSemantics.instance.gestureMode) { case GestureMode.browserGestures: // overflow:scroll will cause the browser report "scroll" events when // the accessibility focus shifts outside the visible bounds. @@ -232,8 +232,11 @@ class Scrollable extends PrimaryRoleManager { style.removeProperty('touch-action'); if (_scrollListener != null) { removeEventListener('scroll', _scrollListener); + _scrollListener = null; + } + if (_gestureModeListener != null) { + EngineSemantics.instance.removeGestureModeListener(_gestureModeListener!); + _gestureModeListener = null; } - semanticsObject.owner.removeGestureModeListener(_gestureModeListener); - _gestureModeListener = null; } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart index b27c9233f1..8747391b6b 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart @@ -17,6 +17,7 @@ import '../dom.dart'; import '../platform_dispatcher.dart'; import '../util.dart'; import '../vector_math.dart'; +import '../window.dart'; import 'checkable.dart'; import 'dialog.dart'; import 'focusable.dart'; @@ -1737,6 +1738,17 @@ class SemanticsObject { }()); return result; } + + bool _isDisposed = false; + + void dispose() { + assert(!_isDisposed); + _isDisposed = true; + element.remove(); + _parent = null; + primaryRole?.dispose(); + primaryRole = null; + } } /// Controls how pointer events and browser-detected gestures are treated by @@ -1792,20 +1804,19 @@ enum SemanticsUpdatePhase { postUpdate, } -/// The top-level service that manages everything semantics-related. -class EngineSemanticsOwner { - EngineSemanticsOwner._() { - registerHotRestartListener(() { - _rootSemanticsElement?.remove(); - }); - } +/// The semantics system of the Web Engine. +/// +/// Maintains global properties and behaviors of semantics in the engine, such +/// as whether semantics is currently enabled or disabled. +class EngineSemantics { + EngineSemantics._(); /// The singleton instance that manages semantics. - static EngineSemanticsOwner get instance { - return _instance ??= EngineSemanticsOwner._(); + static EngineSemantics get instance { + return _instance ??= EngineSemantics._(); } - static EngineSemanticsOwner? _instance; + static EngineSemantics? _instance; /// Disables semantics and uninitializes the singleton [instance]. /// @@ -1820,125 +1831,6 @@ class EngineSemanticsOwner { _instance = null; } - /// The current update phase of this semantics owner. - SemanticsUpdatePhase get phase => _phase; - SemanticsUpdatePhase _phase = SemanticsUpdatePhase.idle; - - final Map _semanticsTree = {}; - - /// Map [SemanticsObject.id] to parent [SemanticsObject] it was attached to - /// this frame. - Map _attachments = {}; - - /// Declares that the [child] must be attached to the [parent]. - /// - /// Attachments take precedence over detachments (see [_detachObject]). This - /// allows the same node to be detached from one parent in the tree and - /// reattached to another parent. - void _attachObject({required SemanticsObject parent, required SemanticsObject child}) { - child._parent = parent; - _attachments[child.id] = parent; - } - - /// List of objects that were detached this frame. - /// - /// The objects in this list will be detached permanently unless they are - /// reattached via the [_attachObject] method. - List _detachments = []; - - /// Declares that the [SemanticsObject] with the given [id] was detached from - /// its current parent object. - /// - /// The object will be detached permanently unless it is reattached via the - /// [_attachObject] method. - void _detachObject(int id) { - final SemanticsObject? object = _semanticsTree[id]; - assert(object != null); - if (object != null) { - _detachments.add(object); - } - } - - /// Callbacks called after all objects in the tree have their properties - /// populated and their sizes and locations computed. - /// - /// This list is reset to empty after all callbacks are called. - List _oneTimePostUpdateCallbacks = []; - - /// Schedules a one-time callback to be called after all objects in the tree - /// have their properties populated and their sizes and locations computed. - void addOneTimePostUpdateCallback(ui.VoidCallback callback) { - _oneTimePostUpdateCallbacks.add(callback); - } - - /// Reconciles [_attachments] and [_detachments], and after that calls all - /// the one-time callbacks scheduled via the [addOneTimePostUpdateCallback] - /// method. - void _finalizeTree() { - for (final SemanticsObject detachmentRoot in _detachments) { - // A detached node may or may not have some of its descendants reattached - // elsewhere. Walk the descendant tree and find all descendants that were - // reattached to a parent. Those descendants need to be removed. - final List removals = []; - detachmentRoot.visitDepthFirst((SemanticsObject node) { - final SemanticsObject? parent = _attachments[node.id]; - if (parent == null) { - // Was not reparented and is removed permanently from the tree. - removals.add(node); - } else { - assert(node._parent == parent); - assert(node.element.parentNode == parent._childContainerElement); - } - }); - - for (final SemanticsObject removal in removals) { - _semanticsTree.remove(removal.id); - removal._parent = null; - removal.element.remove(); - } - } - _detachments = []; - _attachments = {}; - - _phase = SemanticsUpdatePhase.postUpdate; - try { - if (_oneTimePostUpdateCallbacks.isNotEmpty) { - for (final ui.VoidCallback callback in _oneTimePostUpdateCallbacks) { - callback(); - } - _oneTimePostUpdateCallbacks = []; - } - } finally { - _phase = SemanticsUpdatePhase.idle; - } - } - - /// Returns the entire semantics tree for testing. - /// - /// Works only in debug mode. - Map? get debugSemanticsTree { - Map? result; - assert(() { - result = _semanticsTree; - return true; - }()); - return result; - } - - /// The top-level DOM element of the semantics DOM element tree. - DomElement? _rootSemanticsElement; - TimestampFunction _now = () => DateTime.now(); - - void debugOverrideTimestampFunction(TimestampFunction value) { - _now = value; - } - - void debugResetTimestampFunction() { - _now = () => DateTime.now(); - } - - final SemanticsHelper semanticsHelper = SemanticsHelper(); - /// Whether the user has requested that [updateSemantics] be called when the /// semantic contents of window changes. /// @@ -1972,19 +1864,54 @@ class EngineSemanticsOwner { _gestureMode = GestureMode.pointerEvents; _notifyGestureModeListeners(); } - final List keys = _semanticsTree.keys.toList(); - final int len = keys.length; - for (int i = 0; i < len; i++) { - _detachObject(keys[i]); + for (final EngineFlutterView view in EnginePlatformDispatcher.instance.views) { + view.semantics.reset(); } - _finalizeTree(); - _rootSemanticsElement?.remove(); - _rootSemanticsElement = null; _gestureModeClock?.datetime = null; } EnginePlatformDispatcher.instance.updateSemanticsEnabled(_semanticsEnabled); } + /// Prepares the semantics system for a semantic tree update. + /// + /// This method must be called prior to updating the semantics inside any + /// individual view. + /// + /// Automatically enables semantics in a production setting. In Flutter test + /// environment keeps engine semantics turned off due to tests frequently + /// sending inconsistent semantics updates. + /// + /// The caller is expected to check if [semanticsEnabled] is true prior to + /// actually updating the semantic DOM. + void didReceiveSemanticsUpdate() { + if (!_semanticsEnabled) { + if (ui_web.debugEmulateFlutterTesterEnvironment) { + // Running Flutter widget tests in a fake environment. Don't enable + // engine semantics. Test semantics trees violate invariants in ways + // production implementation isn't built to handle. For example, tests + // routinely reset semantics node IDs, which is messing up the update + // process. + return; + } else { + // Running a real app. Auto-enable engine semantics. + semanticsHelper.dispose(); // placeholder no longer needed + semanticsEnabled = true; + } + } + } + + TimestampFunction _now = () => DateTime.now(); + + void debugOverrideTimestampFunction(TimestampFunction value) { + _now = value; + } + + void debugResetTimestampFunction() { + _now = () => DateTime.now(); + } + + final SemanticsHelper semanticsHelper = SemanticsHelper(); + /// Controls how pointer events and browser-detected gestures are treated by /// the Web Engine. /// @@ -2095,14 +2022,14 @@ class EngineSemanticsOwner { /// Callbacks are called synchronously. HTML DOM updates made in a callback /// take effect in the current animation frame and/or the current message loop /// event. - final List _gestureModeListeners = []; + final List _gestureModeListeners = []; /// Calls the [callback] every time the current [GestureMode] changes. /// /// The callback is called synchronously. HTML DOM updates made in the /// callback take effect in the current animation frame and/or the current /// message loop event. - void addGestureModeListener(GestureModeCallback? callback) { + void addGestureModeListener(GestureModeCallback callback) { _gestureModeListeners.add(callback); } @@ -2110,14 +2037,14 @@ class EngineSemanticsOwner { /// /// The passed [callback] must be the exact same object as the one passed to /// [addGestureModeListener]. - void removeGestureModeListener(GestureModeCallback? callback) { + void removeGestureModeListener(GestureModeCallback callback) { assert(_gestureModeListeners.contains(callback)); _gestureModeListeners.remove(callback); } void _notifyGestureModeListeners() { for (int i = 0; i < _gestureModeListeners.length; i++) { - _gestureModeListeners[i]!(_gestureMode); + _gestureModeListeners[i](_gestureMode); } } @@ -2149,6 +2076,141 @@ class EngineSemanticsOwner { return false; } +} + +/// The top-level service that manages everything semantics-related. +class EngineSemanticsOwner { + EngineSemanticsOwner(this.semanticsHost) { + registerHotRestartListener(() { + _rootSemanticsElement?.remove(); + }); + } + + /// The permanent element in the view's DOM structure that hosts the semantics + /// tree. + /// + /// The only child of this element is the [rootSemanticsElement]. Unlike the + /// root element, this element is never replaced. It is always part of the + /// DOM structure of the respective [FlutterView]. + // TODO(yjbanov): rename to hostElement + final DomElement semanticsHost; + + /// The DOM element corresponding to the root semantics node in the semantics + /// tree. + /// + /// This element is the direct child of the [semanticsHost] and it is + /// replaceable. + // TODO(yjbanov): rename to rootElement + DomElement? get rootSemanticsElement => _rootSemanticsElement; + DomElement? _rootSemanticsElement; + + /// The current update phase of this semantics owner. + SemanticsUpdatePhase get phase => _phase; + SemanticsUpdatePhase _phase = SemanticsUpdatePhase.idle; + + final Map _semanticsTree = {}; + + /// Map [SemanticsObject.id] to parent [SemanticsObject] it was attached to + /// this frame. + Map _attachments = {}; + + /// Declares that the [child] must be attached to the [parent]. + /// + /// Attachments take precedence over detachments (see [_detachObject]). This + /// allows the same node to be detached from one parent in the tree and + /// reattached to another parent. + void _attachObject({required SemanticsObject parent, required SemanticsObject child}) { + child._parent = parent; + _attachments[child.id] = parent; + } + + /// List of objects that were detached this frame. + /// + /// The objects in this list will be detached permanently unless they are + /// reattached via the [_attachObject] method. + List _detachments = []; + + /// Declares that the [SemanticsObject] with the given [id] was detached from + /// its current parent object. + /// + /// The object will be detached permanently unless it is reattached via the + /// [_attachObject] method. + void _detachObject(int id) { + final SemanticsObject? object = _semanticsTree[id]; + assert(object != null); + if (object != null) { + _detachments.add(object); + } + } + + /// Callbacks called after all objects in the tree have their properties + /// populated and their sizes and locations computed. + /// + /// This list is reset to empty after all callbacks are called. + List _oneTimePostUpdateCallbacks = []; + + /// Schedules a one-time callback to be called after all objects in the tree + /// have their properties populated and their sizes and locations computed. + void addOneTimePostUpdateCallback(ui.VoidCallback callback) { + _oneTimePostUpdateCallbacks.add(callback); + } + + /// Reconciles [_attachments] and [_detachments], and after that calls all + /// the one-time callbacks scheduled via the [addOneTimePostUpdateCallback] + /// method. + void _finalizeTree() { + // Collect all nodes that need to be permanently removed, i.e. nodes that + // were detached from their parent, but not reattached to another parent. + final Set removals = {}; + for (final SemanticsObject detachmentRoot in _detachments) { + // A detached node may or may not have some of its descendants reattached + // elsewhere. Walk the descendant tree and find all descendants that were + // reattached to a parent. Those descendants need to be removed. + detachmentRoot.visitDepthFirst((SemanticsObject node) { + final SemanticsObject? parent = _attachments[node.id]; + if (parent == null) { + // Was not reparented and is removed permanently from the tree. + removals.add(node); + } else { + assert(node._parent == parent); + assert(node.element.parentNode == parent._childContainerElement); + } + }); + + } + + for (final SemanticsObject removal in removals) { + _semanticsTree.remove(removal.id); + removal.dispose(); + } + + _detachments = []; + _attachments = {}; + + _phase = SemanticsUpdatePhase.postUpdate; + try { + if (_oneTimePostUpdateCallbacks.isNotEmpty) { + for (final ui.VoidCallback callback in _oneTimePostUpdateCallbacks) { + callback(); + } + _oneTimePostUpdateCallbacks = []; + } + } finally { + _phase = SemanticsUpdatePhase.idle; + } + } + + /// Returns the entire semantics tree for testing. + /// + /// Works only in debug mode. + Map? get debugSemanticsTree { + Map? result; + assert(() { + result = _semanticsTree; + return true; + }()); + return result; + } /// Looks up a [SemanticsObject] in the semantics tree by ID, or creates a new /// instance if it does not exist. @@ -2161,23 +2223,45 @@ class EngineSemanticsOwner { return object; } + // Checks the consistency of the semantics node tree against the {ID: node} + // map. The two must be in total agreement. Every node in the map must be + // somewhere in the tree. + (bool, String) _computeNodeMapConsistencyMessage() { + final Map> liveIds = >{}; + + final SemanticsObject? root = _semanticsTree[0]; + if (root != null) { + root.visitDepthFirst((SemanticsObject child) { + liveIds[child.id] = child._childrenInTraversalOrder?.toList() ?? const []; + }); + } + + final bool isConsistent = _semanticsTree.keys.every(liveIds.keys.contains); + final String heading = 'The semantics node map is ${isConsistent ? 'consistent' : 'inconsistent'}'; + final StringBuffer message = StringBuffer('$heading:\n'); + message.writeln(' Nodes in tree:'); + for (final MapEntry> entry in liveIds.entries) { + message.writeln(' ${entry.key}: ${entry.value}'); + } + message.writeln(' Nodes in map: [${_semanticsTree.keys.join(', ')}]'); + + return (isConsistent, message.toString()); + } + /// Updates the semantics tree from data in the [uiUpdate]. void updateSemantics(ui.SemanticsUpdate uiUpdate) { - if (!_semanticsEnabled) { - if (ui_web.debugEmulateFlutterTesterEnvironment) { - // Running Flutter widget tests in a fake environment. Don't enable - // engine semantics. Test semantics trees violate invariants in ways - // production implementation isn't built to handle. For example, tests - // routinely reset semantics node IDs, which is messing up the update - // process. - return; - } else { - // Running a real app. Auto-enable engine semantics. - semanticsHelper.dispose(); // placeholder no longer needed - semanticsEnabled = true; - } + EngineSemantics.instance.didReceiveSemanticsUpdate(); + + if (!EngineSemantics.instance.semanticsEnabled) { + return; } + (bool, String)? preUpdateNodeMapConsistency; + assert(() { + preUpdateNodeMapConsistency = _computeNodeMapConsistencyMessage(); + return true; + }()); + _phase = SemanticsUpdatePhase.updating; final SemanticsUpdate update = uiUpdate as SemanticsUpdate; @@ -2198,33 +2282,31 @@ class EngineSemanticsOwner { object._dirtyFields = 0; } + final SemanticsObject root = _semanticsTree[0]!; if (_rootSemanticsElement == null) { - final SemanticsObject root = _semanticsTree[0]!; _rootSemanticsElement = root.element; - // TODO(mdebbar): There could be multiple views with multiple semantics hosts. - // https://github.com/flutter/flutter/issues/137344 - final DomElement semanticsHost = EnginePlatformDispatcher.instance.implicitView!.dom.semanticsHost; semanticsHost.append(root.element); } _finalizeTree(); - assert(_semanticsTree.containsKey(0)); // must contain root node assert(() { // Validate that the node map only contains live elements, i.e. descendants // of the root node. If a node is not reachable from the root, it should // have been removed from the map. - final List liveIds = []; - final SemanticsObject root = _semanticsTree[0]!; - root.visitDepthFirst((SemanticsObject child) { - liveIds.add(child.id); - }); - assert( - _semanticsTree.keys.every(liveIds.contains), - 'The semantics node map is inconsistent:\n' - ' Nodes in tree: [${liveIds.join(', ')}]\n' - ' Nodes in map : [${_semanticsTree.keys.join(', ')}]' - ); + final (bool isConsistent, String description) = _computeNodeMapConsistencyMessage(); + if (!isConsistent) { + // Use StateError because AssertionError escapes line breaks, but this + // error message is very detailed and it needs line breaks for + // legibility. + throw StateError(''' +Semantics node map was inconsistent after update: + +BEFORE: ${preUpdateNodeMapConsistency?.$2} + +AFTER: $description +'''); + } // Validate that each node in the final tree is self-consistent. _semanticsTree.forEach((int? id, SemanticsObject object) { @@ -2270,6 +2352,29 @@ class EngineSemanticsOwner { return true; }()); } + + /// Removes the semantics tree for this view from the page and collects all + /// resources. + /// + /// The object remains usable after this operation, but because the previous + /// semantics tree is completely removed, partial udpates will not succeed as + /// they rely on the prior state of the tree. There is no distinction between + /// a full update and partial update, so the failure may be cryptic. + void reset() { + final List keys = _semanticsTree.keys.toList(); + final int len = keys.length; + for (int i = 0; i < len; i++) { + _detachObject(keys[i]); + } + _finalizeTree(); + _rootSemanticsElement?.remove(); + _rootSemanticsElement = null; + _semanticsTree.clear(); + _attachments.clear(); + _detachments.clear(); + _phase = SemanticsUpdatePhase.idle; + _oneTimePostUpdateCallbacks.clear(); + } } /// Computes the [longest increasing subsequence](http://en.wikipedia.org/wiki/Longest_increasing_subsequence). diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics_helper.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics_helper.dart index eae0e1bcd0..ae256fb225 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics_helper.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics_helper.dart @@ -138,7 +138,7 @@ class DesktopSemanticsEnabler extends SemanticsEnabler { return true; } - if (EngineSemanticsOwner.instance.semanticsEnabled) { + if (EngineSemantics.instance.semanticsEnabled) { // Semantics already enabled, forward to framework as normal. return true; } @@ -167,7 +167,7 @@ class DesktopSemanticsEnabler extends SemanticsEnabler { return true; } - EngineSemanticsOwner.instance.semanticsEnabled = true; + EngineSemantics.instance.semanticsEnabled = true; dispose(); return false; } @@ -267,7 +267,7 @@ class MobileSemanticsEnabler extends SemanticsEnabler { return true; } - if (EngineSemanticsOwner.instance.semanticsEnabled) { + if (EngineSemantics.instance.semanticsEnabled) { // Semantics already enabled, forward to framework as normal. return true; } @@ -357,7 +357,7 @@ class MobileSemanticsEnabler extends SemanticsEnabler { _schedulePlaceholderRemoval = true; semanticsActivationTimer = Timer(_periodToConsumeEvents, () { dispose(); - EngineSemanticsOwner.instance.semanticsEnabled = true; + EngineSemantics.instance.semanticsEnabled = true; }); return false; } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart index 243e09cab6..c3195c1d41 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart @@ -296,7 +296,7 @@ class TextField extends PrimaryRoleManager { _initializeEditableElement(); activeEditableElement.addEventListener('focus', createDomEventListener((DomEvent event) { - if (semanticsObject.owner.gestureMode != GestureMode.browserGestures) { + if (EngineSemantics.instance.gestureMode != GestureMode.browserGestures) { return; } @@ -305,7 +305,7 @@ class TextField extends PrimaryRoleManager { })); activeEditableElement.addEventListener('blur', createDomEventListener((DomEvent event) { - if (semanticsObject.owner.gestureMode != GestureMode.browserGestures) { + if (EngineSemantics.instance.gestureMode != GestureMode.browserGestures) { return; } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text_editing/text_editing.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text_editing/text_editing.dart index 5e283f44a1..a9a645de70 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/text_editing/text_editing.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text_editing/text_editing.dart @@ -2308,7 +2308,7 @@ class HybridTextEditing { /// Supplies the DOM element used for editing. late final DefaultTextEditingStrategy strategy = debugTextEditingStrategyOverride ?? - (EngineSemanticsOwner.instance.semanticsEnabled + (EngineSemantics.instance.semanticsEnabled ? SemanticsTextEditingStrategy.ensureInitialized(this) : createDefaultTextEditingStrategy(this)); diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/view_embedder/dom_manager.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/view_embedder/dom_manager.dart index 9b39c34c6c..06a65a8873 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/view_embedder/dom_manager.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/view_embedder/dom_manager.dart @@ -43,7 +43,7 @@ import 'style_manager.dart'; /// +-