diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 8f2673ed9c..a7b4b6aed9 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1024,7 +1024,6 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_api.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_canvas.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/color_filter.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views.dart -FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views_diff.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/font_fallbacks.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/fonts.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/image.dart diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine.dart b/engine/src/flutter/lib/web_ui/lib/src/engine.dart index 2bad386d02..2983f3f132 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine.dart @@ -25,7 +25,6 @@ export 'engine/canvaskit/canvaskit_api.dart'; export 'engine/canvaskit/canvaskit_canvas.dart'; export 'engine/canvaskit/color_filter.dart'; export 'engine/canvaskit/embedded_views.dart'; -export 'engine/canvaskit/embedded_views_diff.dart'; export 'engine/canvaskit/font_fallbacks.dart'; export 'engine/canvaskit/fonts.dart'; export 'engine/canvaskit/image.dart'; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views.dart index be7dce499b..0905ca66cd 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:math' as math; + import 'package:ui/ui.dart' as ui; import '../../engine.dart' show platformViewManager; @@ -14,7 +16,6 @@ import '../util.dart'; import '../vector_math.dart'; import '../window.dart'; import 'canvas.dart'; -import 'embedded_views_diff.dart'; import 'initialization.dart'; import 'path.dart'; import 'picture_recorder.dart'; @@ -28,44 +29,41 @@ class HtmlViewEmbedder { HtmlViewEmbedder._(); + /// If `true`, overlay canvases are disabled. + /// + /// This causes all drawing to go to a single canvas, with all of the platform + /// views rendered over top. This may result in incorrect rendering with + /// platform views. + static bool get disableOverlays => + debugDisableOverlays || configuration.canvasKitMaximumSurfaces <= 1; + /// Force the view embedder to disable overlays. /// /// This should never be used outside of tests. - static set debugDisableOverlays(bool disable) { - // Short circuit if the value is the same as what we already have. - if (disable == _debugOverlaysDisabled) { - return; - } - _debugOverlaysDisabled = disable; - final SurfaceFactory? instance = SurfaceFactory.debugUninitializedInstance; - if (instance != null) { - instance.releaseSurfaces(); - instance.removeSurfacesFromDom(); - instance.debugClear(); - } - if (disable) { - // If we are disabling overlays then get the current [SurfaceFactory] - // instance, clear it, and overwrite it with a new instance with only - // one surface for the base surface. - SurfaceFactory.debugSetInstance(SurfaceFactory(1)); - } else { - // If we are re-enabling overlays then replace the current - // [SurfaceFactory]instance with one with - // [configuration.canvasKitMaximumSurfaces] overlays. - SurfaceFactory.debugSetInstance( - SurfaceFactory(configuration.canvasKitMaximumSurfaces)); - } - } + static bool debugDisableOverlays = false; - static bool _debugOverlaysDisabled = false; + /// The set of platform views using the backup surface. + final Set _viewsUsingBackupSurface = {}; - /// Whether or not we have issues a warning to the user about having too many - /// surfaces on screen at once. This is so we only warn once, instead of every - /// frame. - bool _warnedAboutTooManySurfaces = false; + /// Picture recorders which were created during the preroll phase. + /// + /// These picture recorders will be "claimed" in the paint phase by platform + /// views being composited into the scene. + final List _pictureRecordersCreatedDuringPreroll = + []; - /// The context for the current frame. - EmbedderFrameContext _context = EmbedderFrameContext(); + /// The picture recorder shared by all platform views which paint to the + /// backup surface. + CkPictureRecorder? _backupPictureRecorder; + + /// A picture recorder associated with a view id. + /// + /// When we composite in the platform view, we need to create a new canvas + /// for further paint commands to paint to, since the composited view will + /// be on top of the current canvas, and we want further paint commands to + /// be on top of the platform view. + final Map _pictureRecorders = + {}; /// The most recent composition parameters for a given view id. /// @@ -94,6 +92,11 @@ class HtmlViewEmbedder { /// The list of view ids that should be composited, in order. List _compositionOrder = []; + /// The number of platform views in this frame which are visible. + /// + /// These platform views will require overlays. + int _visibleViewCount = 0; + /// The most recent composition order. List _activeCompositionOrder = []; @@ -115,36 +118,43 @@ class HtmlViewEmbedder { /// clipped out and not actually drawn). This means that we may end up /// overallocating canvases. This isn't a problem in practice, however, as /// unused recording canvases are simply deleted at the end of the frame. - Iterable getOverlayCanvases() { - return _context.pictureRecordersCreatedDuringPreroll - .map((CkPictureRecorder r) => r.recordingCanvas!); + List getOverlayCanvases() { + if (disableOverlays) { + return const []; + } + final List overlayCanvases = _pictureRecordersCreatedDuringPreroll + .map((CkPictureRecorder r) => r.recordingCanvas!) + .toList(); + if (_backupPictureRecorder != null) { + overlayCanvases.add(_backupPictureRecorder!.recordingCanvas!); + } + return overlayCanvases; } void prerollCompositeEmbeddedView(int viewId, EmbeddedViewParams params) { - final bool hasAvailableOverlay = - _context.pictureRecordersCreatedDuringPreroll.length < - SurfaceFactory.instance.maximumOverlays; - if (!hasAvailableOverlay && !_warnedAboutTooManySurfaces) { - _warnedAboutTooManySurfaces = true; - printWarning('Flutter was unable to create enough overlay surfaces. ' - 'This is usually caused by too many platform views being ' - 'displayed at once. ' - 'You may experience incorrect rendering.'); - } - // We need an overlay for the first platform view no matter what. The first - // visible platform view doesn't need to create a new one if we already - // created one. - final bool needNewOverlay = (platformViewManager.isVisible(viewId) && - _context.seenFirstVisibleViewInPreroll) || - _context.pictureRecordersCreatedDuringPreroll.isEmpty; - if (platformViewManager.isVisible(viewId)) { - _context.seenFirstVisibleViewInPreroll = true; - } - if (needNewOverlay && hasAvailableOverlay) { - final CkPictureRecorder pictureRecorder = CkPictureRecorder(); - pictureRecorder.beginRecording(ui.Offset.zero & _frameSize); - pictureRecorder.recordingCanvas!.clear(const ui.Color(0x00000000)); - _context.pictureRecordersCreatedDuringPreroll.add(pictureRecorder); + if (!disableOverlays && platformViewManager.isVisible(viewId)) { + // We must decide in the preroll phase if a platform view will use the + // backup overlay, so that draw commands after the platform view will + // correctly paint to the backup surface. + bool needBackupSurface = false; + if (_pictureRecordersCreatedDuringPreroll.length >= + SurfaceFactory.instance.maximumOverlays) { + needBackupSurface = true; + } + if (needBackupSurface) { + if (_backupPictureRecorder == null) { + // Only initialize the picture recorder for the backup surface once. + final CkPictureRecorder pictureRecorder = CkPictureRecorder(); + pictureRecorder.beginRecording(ui.Offset.zero & _frameSize); + pictureRecorder.recordingCanvas!.clear(const ui.Color(0x00000000)); + _backupPictureRecorder = pictureRecorder; + } + } else { + final CkPictureRecorder pictureRecorder = CkPictureRecorder(); + pictureRecorder.beginRecording(ui.Offset.zero & _frameSize); + pictureRecorder.recordingCanvas!.clear(const ui.Color(0x00000000)); + _pictureRecordersCreatedDuringPreroll.add(pictureRecorder); + } } // Do nothing if the params didn't change. @@ -165,33 +175,38 @@ class HtmlViewEmbedder { /// If this returns a [CkCanvas], then that canvas should be the new leaf /// node. Otherwise, keep the same leaf node. CkCanvas? compositeEmbeddedView(int viewId) { - final int overlayIndex = _context.visibleViewCount; + final int overlayIndex = _visibleViewCount; _compositionOrder.add(viewId); - if (platformViewManager.isVisible(viewId) || - _context.pictureRecorders.isEmpty) { - _context.visibleViewCount++; - } - // We need a new overlay if this is a visible view or if we don't have one yet. - final bool needNewOverlay = (platformViewManager.isVisible(viewId) && - _context.seenFirstVisibleView) || - _context.pictureRecorders.isEmpty; if (platformViewManager.isVisible(viewId)) { - _context.seenFirstVisibleView = true; + _visibleViewCount++; } - CkPictureRecorder? recorderToUseForRendering; - if (needNewOverlay) { - if (overlayIndex < _context.pictureRecordersCreatedDuringPreroll.length) { - recorderToUseForRendering = - _context.pictureRecordersCreatedDuringPreroll[overlayIndex]; - _context.pictureRecorders.add(recorderToUseForRendering); + final bool needOverlay = + !disableOverlays && platformViewManager.isVisible(viewId); + if (needOverlay) { + if (overlayIndex < _pictureRecordersCreatedDuringPreroll.length) { + _pictureRecorders[viewId] = + _pictureRecordersCreatedDuringPreroll[overlayIndex]; + } else { + _viewsUsingBackupSurface.add(viewId); + _pictureRecorders[viewId] = _backupPictureRecorder!; } } - if (_viewsToRecomposite.contains(viewId)) { - _compositeWithParams(viewId, _currentCompositionParams[viewId]!); - _viewsToRecomposite.remove(viewId); + // Do nothing if this view doesn't need to be composited. + if (!_viewsToRecomposite.contains(viewId)) { + if (needOverlay) { + return _pictureRecorders[viewId]!.recordingCanvas; + } else { + return null; + } + } + _compositeWithParams(viewId, _currentCompositionParams[viewId]!); + _viewsToRecomposite.remove(viewId); + if (needOverlay) { + return _pictureRecorders[viewId]!.recordingCanvas; + } else { + return null; } - return recorderToUseForRendering?.recordingCanvas; } void _compositeWithParams(int viewId, EmbeddedViewParams params) { @@ -279,7 +294,8 @@ class HtmlViewEmbedder { /// be recomposited. void _cleanUpClipDefs(int viewId) { if (_svgClipDefs.containsKey(viewId)) { - final DomElement clipDefs = _svgPathDefs!.querySelector('#sk_path_defs')!; + final DomElement clipDefs = + _svgPathDefs!.querySelector('#sk_path_defs')!; final List nodesToRemove = []; final Set oldDefs = _svgClipDefs[viewId]!; for (final DomElement child in clipDefs.children) { @@ -299,8 +315,8 @@ class HtmlViewEmbedder { final MutatorsStack mutators = params.mutators; DomElement head = embeddedView; Matrix4 headTransform = params.offset == ui.Offset.zero - ? Matrix4.identity() - : Matrix4.translationValues(params.offset.dx, params.offset.dy, 0); + ? Matrix4.identity() + : Matrix4.translationValues(params.offset.dx, params.offset.dy, 0); double embeddedOpacity = 1.0; _resetAnchor(head); _cleanUpClipDefs(viewId); @@ -335,7 +351,8 @@ class HtmlViewEmbedder { final SVGClipPathElement newClipPath = createSVGClipPathElement(); newClipPath.id = clipId; newClipPath.append( - createSVGPathElement()..setAttribute('d', path.toSvgString()!)); + createSVGPathElement() + ..setAttribute('d', path.toSvgString()!)); pathDefs.append(newClipPath); // Store the id of the node instead of [newClipPath] directly. For @@ -353,7 +370,8 @@ class HtmlViewEmbedder { final SVGClipPathElement newClipPath = createSVGClipPathElement(); newClipPath.id = clipId; newClipPath.append( - createSVGPathElement()..setAttribute('d', path.toSvgString()!)); + createSVGPathElement() + ..setAttribute('d', path.toSvgString()!)); pathDefs.append(newClipPath); // Store the id of the node instead of [newClipPath] directly. For // some reason, calling `newClipPath.remove()` doesn't remove it @@ -381,7 +399,8 @@ class HtmlViewEmbedder { final Matrix4 scaleMatrix = Matrix4.diagonal3Values(inverseScale, inverseScale, 1); headTransform = scaleMatrix.multiplied(headTransform); - head.style.transform = float64ListToCssTransform(headTransform.storage); + head.style.transform = + float64ListToCssTransform(headTransform.storage); } /// Sets the transform origin to the top-left corner of the element. @@ -412,36 +431,54 @@ class HtmlViewEmbedder { } void submitFrame() { - final ViewListDiffResult? diffResult = - (_activeCompositionOrder.isEmpty || _compositionOrder.isEmpty) - ? null - : diffViewList(_activeCompositionOrder, _compositionOrder); - _updateOverlays(diffResult); - assert(_context.pictureRecorders.length == _overlays.length); - int pictureRecorderIndex = 0; + final ViewListDiffResult? diffResult = (_activeCompositionOrder.isEmpty || + _compositionOrder.isEmpty || + disableOverlays) + ? null + : diffViewList( + _activeCompositionOrder + .where((int viewId) => platformViewManager.isVisible(viewId)) + .toList(), + _compositionOrder + .where((int viewId) => platformViewManager.isVisible(viewId)) + .toList()); + final Map? insertBeforeMap = _updateOverlays(diffResult); - for (int i = 0; i < _compositionOrder.length; i++) { - final int viewId = _compositionOrder[i]; - if (_overlays[viewId] != null) { - final SurfaceFrame frame = _overlays[viewId]!.acquireFrame(_frameSize); - final CkCanvas canvas = frame.skiaCanvas; - canvas.drawPicture( - _context.pictureRecorders[pictureRecorderIndex].endRecording(), - ); - pictureRecorderIndex++; - frame.submit(); + bool _didPaintBackupSurface = false; + if (!disableOverlays) { + for (int i = 0; i < _compositionOrder.length; i++) { + final int viewId = _compositionOrder[i]; + if (platformViewManager.isInvisible(viewId)) { + continue; + } + if (_viewsUsingBackupSurface.contains(viewId)) { + // Only draw the picture to the backup surface once. + if (!_didPaintBackupSurface) { + final SurfaceFrame backupFrame = + SurfaceFactory.instance.backupSurface.acquireFrame(_frameSize); + backupFrame.skiaCanvas + .drawPicture(_backupPictureRecorder!.endRecording()); + _backupPictureRecorder = null; + backupFrame.submit(); + _didPaintBackupSurface = true; + } + } else { + final SurfaceFrame frame = + _overlays[viewId]!.acquireFrame(_frameSize); + final CkCanvas canvas = frame.skiaCanvas; + canvas.drawPicture( + _pictureRecorders[viewId]!.endRecording(), + ); + frame.submit(); + } } } - for (final CkPictureRecorder recorder - in _context.pictureRecordersCreatedDuringPreroll) { - if (recorder.isRecording) { - recorder.endRecording(); - } - } - // Reset the context. - _context = EmbedderFrameContext(); + _pictureRecordersCreatedDuringPreroll.clear(); + _pictureRecorders.clear(); + _viewsUsingBackupSurface.clear(); if (listEquals(_compositionOrder, _activeCompositionOrder)) { _compositionOrder.clear(); + _visibleViewCount = 0; return; } @@ -451,12 +488,7 @@ class HtmlViewEmbedder { List? debugInvalidViewIds; if (diffResult != null) { - // Dispose of the views that should be removed, except for the ones which - // are going to be added back. Moving rather than removing and re-adding - // the view helps it maintain state. - disposeViews(diffResult.viewsToRemove - .where((int view) => !diffResult.viewsToAdd.contains(view)) - .toSet()); + disposeViews(diffResult.viewsToRemove.toSet()); _activeCompositionOrder.addAll(_compositionOrder); unusedViews.removeAll(_compositionOrder); @@ -491,23 +523,19 @@ class HtmlViewEmbedder { } } } - // It's possible that some platform views which were in the unchanged - // section have newly assigned overlays. If so, add them to the DOM. - for (int i = 0; i < _compositionOrder.length; i++) { - final int view = _compositionOrder[i]; - if (_overlays[view] != null) { - final DomElement overlayElement = _overlays[view]!.htmlElement; - if (!overlayElement.isConnected) { - // This overlay wasn't added to the DOM. - if (i == _compositionOrder.length - 1) { - skiaSceneHost!.append(overlayElement); - } else { - final int nextView = _compositionOrder[i + 1]; - final DomElement nextElement = _viewClipChains[nextView]!.root; - skiaSceneHost!.insertBefore(overlayElement, nextElement); - } - } + insertBeforeMap?.forEach((int viewId, int viewIdToInsertBefore) { + final DomElement overlay = _overlays[viewId]!.htmlElement; + if (viewIdToInsertBefore != -1) { + final DomElement nextSibling = + _viewClipChains[viewIdToInsertBefore]!.root; + skiaSceneHost!.insertBefore(overlay, nextSibling); + } else { + skiaSceneHost!.append(overlay); } + }); + if (_didPaintBackupSurface) { + skiaSceneHost! + .append(SurfaceFactory.instance.backupSurface.htmlElement); } } else { SurfaceFactory.instance.removeSurfacesFromDom(); @@ -531,12 +559,19 @@ class HtmlViewEmbedder { _activeCompositionOrder.add(viewId); unusedViews.remove(viewId); } + if (_didPaintBackupSurface) { + skiaSceneHost! + .append(SurfaceFactory.instance.backupSurface.htmlElement); + } } _compositionOrder.clear(); + _visibleViewCount = 0; disposeViews(unusedViews); + _pictureRecorders.clear(); + if (assertionsEnabled) { if (debugInvalidViewIds != null && debugInvalidViewIds.isNotEmpty) { throw AssertionError( @@ -568,105 +603,128 @@ class HtmlViewEmbedder { } } - // Assigns overlays to the embedded views in the scene. - // - // This method attempts to be efficient by taking advantage of the - // [diffResult] and trying to re-use overlays which have already been - // assigned. - // - // This method accounts for invisible platform views by grouping them - // with the last visible platform view which precedes it. All invisible - // platform views that come after a visible view share the same overlay - // as the preceding visible view. - // - // This is called right before compositing the scene. + // Called right before compositing the scene. // // [_compositionOrder] and [_activeComposition] order should contain the // composition order of the current and previous frame, respectively. // // TODO(hterkelsen): Test this more thoroughly. - void _updateOverlays(ViewListDiffResult? diffResult) { + Map? _updateOverlays(ViewListDiffResult? diffResult) { + if (_viewsUsingBackupSurface.isEmpty) { + SurfaceFactory.instance + .releaseSurface(SurfaceFactory.instance.backupSurface); + } if (diffResult != null && diffResult.viewsToAdd.isEmpty && diffResult.viewsToRemove.isEmpty) { - // The composition order has not changed, continue using the assigned - // overlays. - return; + return null; } - final List> overlayGroups = getOverlayGroups(_compositionOrder); - final Iterable viewsNeedingOverlays = - overlayGroups.map((List group) => group.last); if (diffResult == null) { // Everything is going to be explicitly recomposited anyway. Release all - // the surfaces and assign an overlay to all the surfaces needing one. + // the surfaces and assign an overlay to the first N surfaces where + // N = [SurfaceFactory.instance.maximumOverlays] and assign the rest + // to the backup surface. SurfaceFactory.instance.releaseSurfaces(); _overlays.clear(); - viewsNeedingOverlays.forEach(_initializeOverlay); + final List viewsNeedingOverlays = _compositionOrder + .where((int viewId) => platformViewManager.isVisible(viewId)) + .toList(); + final int numOverlays = math.min( + SurfaceFactory.instance.maximumOverlays, + viewsNeedingOverlays.length, + ); + for (int i = 0; i < numOverlays; i++) { + final int viewId = viewsNeedingOverlays[i]; + assert(!_viewsUsingBackupSurface.contains(viewId)); + _initializeOverlay(viewId); + } + _assertOverlaysInitialized(); + return null; } else { // We want to preserve the overlays in the "unchanged" section of the - // diff result as much as possible. Iterate over all the views needing - // overlays and assign them an overlay if they don't have one already. + // diff result as much as possible. If `addToBeginning` is `false`, then + // release the overlays for the views which were deleted from the + // beginning of the composition order and try to reuse those overlays in + // either the unchanged segment or the newly added views. If + // `addToBeginning` is `true` then release the overlays for the deleted + // views and from the unchanged segment and assign the newly added views + // to them. + diffResult.viewsToRemove.forEach(_releaseOverlay); + final int availableOverlays = + SurfaceFactory.instance.numAvailableOverlays; + if (diffResult.addToBeginning) { + // If we have enough overlays for the newly added views, then just use + // them. Otherwise, we will need to release overlays from the unchanged + // segment of view ids. + if (diffResult.viewsToAdd.length > availableOverlays) { + int viewsToDispose = math.min(SurfaceFactory.instance.maximumOverlays, + diffResult.viewsToAdd.length - availableOverlays); + // The first `maximumSurfaces` views in the previous composition order + // had an overlay. + int index = SurfaceFactory.instance.maximumOverlays - + diffResult.viewsToAdd.length; + while (viewsToDispose > 0) { + // The first [maxOverlays - viewsAdded] active views should have + // overlays. The rest should be removed. + _releaseOverlay(_activeCompositionOrder[index++]); + viewsToDispose--; + } + } - // Use `toList` here since we will modify `_overlays` in the for-loop - // below. - final Iterable viewsWithOverlays = _overlays.keys.toList(); - viewsWithOverlays - .where((int view) => !viewsNeedingOverlays.contains(view)) - .forEach(_releaseOverlay); - viewsNeedingOverlays - .where((int view) => !_overlays.containsKey(view)) - .forEach(_initializeOverlay); + // Now assign an overlay to the newly added views. + final int overlaysToAssign = math.min(diffResult.viewsToAdd.length, + SurfaceFactory.instance.numAvailableOverlays); + for (int i = 0; i < overlaysToAssign; i++) { + _initializeOverlay(diffResult.viewsToAdd[i]); + } + _assertOverlaysInitialized(); + return null; + } else { + // Use the overlays we just released for any platform views at the + // beginning of the list which previously used the backup surface. + int overlaysToAssign = + math.min(_compositionOrder.length, availableOverlays); + int index = 0; + final int lastOriginalIndex = + _activeCompositionOrder.length - diffResult.viewsToRemove.length; + final Map insertBeforeMap = {}; + while (overlaysToAssign > 0 && index < _compositionOrder.length) { + final bool activeView = index < lastOriginalIndex; + final int viewId = _compositionOrder[index]; + if (!_overlays.containsKey(viewId) && + platformViewManager.isVisible(viewId)) { + _initializeOverlay(viewId); + overlaysToAssign--; + if (activeView) { + if (index + 1 < _compositionOrder.length) { + insertBeforeMap[viewId] = _compositionOrder[index + 1]; + } else { + insertBeforeMap[viewId] = -1; + } + } + } + index++; + } + _assertOverlaysInitialized(); + return insertBeforeMap; + } } - assert(_overlays.length == viewsNeedingOverlays.length); } - // Group the platform views into "overlay groups". These are sublists - // of the composition order which can share the same overlay. Every overlay - // group is a list containing a visible view followed by zero or more - // invisible views. - List> getOverlayGroups(List views) { - // Visibility groups are typically a visible view followed by zero or more - // invisible views. However, if the view list begins with one or more - // invisible views, we can group them with the first visible view. - final int maxGroups = SurfaceFactory.instance.maximumOverlays; - if (maxGroups == 0) { - return const >[]; - } - bool foundFirstVisibleView = false; - final List> result = >[]; - List currentGroup = []; - int i = 0; - for (; i < views.length; i++) { - // If we're on the last group, then break and just add all the rest of the - // views to current group. - if (result.length == maxGroups - 1) { - break; - } - final int view = views[i]; - if (platformViewManager.isInvisible(view)) { - currentGroup.add(view); - } else { - if (foundFirstVisibleView) { - // We hit this case if this is the first visible view. - result.add(currentGroup); - currentGroup = [view]; - } else { - foundFirstVisibleView = true; - currentGroup.add(view); - } + void _assertOverlaysInitialized() { + if (assertionsEnabled) { + for (int i = 0; i < _compositionOrder.length; i++) { + final int viewId = _compositionOrder[i]; + assert(_viewsUsingBackupSurface.contains(viewId) || + platformViewManager.isInvisible(viewId) || + _overlays[viewId] != null); } } - if (i < views.length) { - currentGroup.addAll(views.sublist(i)); - } - if (currentGroup.isNotEmpty) { - result.add(currentGroup); - } - return result; } void _initializeOverlay(int viewId) { - assert(!_overlays.containsKey(viewId)); + assert(!_overlays.containsKey(viewId) && + !_viewsUsingBackupSurface.contains(viewId)); // Try reusing a cached overlay created for another platform view. final Surface overlay = SurfaceFactory.instance.getOverlay()!; @@ -678,9 +736,7 @@ class HtmlViewEmbedder { void debugCleanupSvgClipPaths() { final DomElement? parent = _svgPathDefs?.children.single; if (parent != null) { - for (DomNode? child = parent.lastChild; - child != null; - child = parent.lastChild) { + for (DomNode? child = parent.lastChild; child != null; child = parent.lastChild) { parent.removeChild(child); } } @@ -695,7 +751,11 @@ class HtmlViewEmbedder { void debugClear() { final Set allViews = platformViewManager.debugClear(); disposeViews(allViews); - _context = EmbedderFrameContext(); + _backupPictureRecorder?.endRecording(); + _backupPictureRecorder = null; + _viewsUsingBackupSurface.clear(); + _pictureRecordersCreatedDuringPreroll.clear(); + _pictureRecorders.clear(); _currentCompositionParams.clear(); debugCleanupSvgClipPaths(); _currentCompositionParams.clear(); @@ -704,6 +764,7 @@ class HtmlViewEmbedder { _viewsToRecomposite.clear(); _activeCompositionOrder.clear(); _compositionOrder.clear(); + _visibleViewCount = 0; } } @@ -883,28 +944,99 @@ class MutatorsStack extends Iterable { Iterator get iterator => _mutators.reversed.iterator; } -/// The state for the current frame. -class EmbedderFrameContext { - /// Whether or not we have seen a visible platform view in this frame yet. - bool seenFirstVisibleViewInPreroll = false; +/// The results of diffing the current composition order with the active +/// composition order. +class ViewListDiffResult { + /// Views which should be removed from the scene. + final List viewsToRemove; - /// Whether or not we have seen a visible platform view in this frame yet. - bool seenFirstVisibleView = false; + /// Views to add to the scene. + final List viewsToAdd; - /// Picture recorders which were created during the preroll phase. + /// If `true`, [viewsToAdd] should be added at the beginning of the scene. + /// Otherwise, they should be added at the end of the scene. + final bool addToBeginning; + + /// If [addToBeginning] is `true`, then this is the id of the platform view + /// to insert [viewsToAdd] before. /// - /// These picture recorders will be "claimed" in the paint phase by platform - /// views being composited into the scene. - final List pictureRecordersCreatedDuringPreroll = - []; + /// `null` if [addToBeginning] is `false`. + final int? viewToInsertBefore; - /// Picture recorders which were actually used in the paint phase. - /// - /// This is a subset of [_pictureRecordersCreatedDuringPreroll]. - final List pictureRecorders = []; - - /// The number of platform views in this frame which are visible. - /// - /// These platform views will require overlays. - int visibleViewCount = 0; + const ViewListDiffResult( + this.viewsToRemove, this.viewsToAdd, this.addToBeginning, + {this.viewToInsertBefore}); +} + +/// Diff the composition order with the active composition order. It is +/// common for the composition order and active composition order to differ +/// only slightly. +/// +/// Consider a scrolling list of platform views; from frame +/// to frame the composition order will change in one of two ways, depending +/// on which direction the list is scrolling. One or more views will be added +/// to the beginning of the list, and one or more views will be removed from +/// the end of the list, with the order of the unchanged middle views +/// remaining the same. +// TODO(hterkelsen): Refactor to use [longestIncreasingSubsequence] and logic +// similar to `Surface._insertChildDomNodes` to efficiently handle more cases, +// https://github.com/flutter/flutter/issues/89611. +ViewListDiffResult? diffViewList(List active, List next) { + if (active.isEmpty || next.isEmpty) { + return null; + } + // If the [active] and [next] lists are in the expected form described above, + // then either the first or last element of [next] will be in [active]. + int index = active.indexOf(next.first); + if (index != -1) { + // Verify that the active composition order is contained, in order, in the + // next composition order. + for (int i = 0; i + index < active.length; i++) { + if (active[i + index] != next[i]) { + return null; + } + if (i == next.length - 1) { + if (index == 0) { + return ViewListDiffResult(active.sublist(i + 1), const [], true, + viewToInsertBefore: next.first); + } else { + return ViewListDiffResult( + active.sublist(0, index), const [], false); + } + } + } + // Remove all ids from viewsToRemove that also exist in viewsToAdd. + final List viewsToAdd = next.sublist(active.length - index); + final Set viewsToAddSet = viewsToAdd.toSet(); + final List viewsToRemove = active.sublist(0, index).where((int e) => !viewsToAddSet.contains(e)).toList(); + + return ViewListDiffResult( + viewsToRemove, + viewsToAdd, + false, + ); + } + + index = active.lastIndexOf(next.last); + if (index != -1) { + for (int i = 0; index - i >= 0; i++) { + if (next.length <= i || active[index - i] != next[next.length - 1 - i]) { + return null; + } + } + + // Remove all ids from viewsToRemove that also exist in viewsToAdd. + final List viewsToAdd = active.sublist(index + 1); + final Set viewsToAddSet = viewsToAdd.toSet(); + final List viewsToRemove = next.sublist(0, next.length - index - 1).where((int e) => !viewsToAddSet.contains(e)).toList(); + + return ViewListDiffResult( + viewsToAdd, + viewsToRemove, + true, + viewToInsertBefore: active.first, + ); + } + + return null; } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views_diff.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views_diff.dart deleted file mode 100644 index f5cce723f2..0000000000 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views_diff.dart +++ /dev/null @@ -1,161 +0,0 @@ -// 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. - -/// The results of diffing the current composition order with the active -/// composition order. -class ViewListDiffResult { - /// Views which should be removed from the scene. - final List viewsToRemove; - - /// Views to add to the scene. - final List viewsToAdd; - - /// If `true`, [viewsToAdd] should be added at the beginning of the scene. - /// Otherwise, they should be added at the end of the scene. - final bool addToBeginning; - - /// If [addToBeginning] is `true`, then this is the id of the platform view - /// to insert [viewsToAdd] before. - /// - /// `null` if [addToBeginning] is `false`. - final int? viewToInsertBefore; - - const ViewListDiffResult( - this.viewsToRemove, this.viewsToAdd, this.addToBeginning, - {this.viewToInsertBefore}); -} - -/// Diff the composition order with the active composition order. It is -/// common for the composition order and active composition order to differ -/// only slightly. -/// -/// Consider a scrolling list of platform views; from frame -/// to frame the composition order will change in one of two ways, depending -/// on which direction the list is scrolling. One or more views will be added -/// to the beginning of the list, and one or more views will be removed from -/// the end of the list, with the order of the unchanged middle views -/// remaining the same. -// TODO(hterkelsen): Refactor to use [longestIncreasingSubsequence] and logic -// similar to `Surface._insertChildDomNodes` to efficiently handle more cases, -// https://github.com/flutter/flutter/issues/89611. -ViewListDiffResult? diffViewList(List active, List next) { - if (active.isEmpty || next.isEmpty) { - return null; - } - - // This is tried if the first element of the next list is contained in the - // active list at `index`. If the active and next lists are in the expected - // form, then we should be able to iterate from `index` to the end of the - // active list where every element matches in the next list. - ViewListDiffResult? lookForwards(int index) { - for (int i = 0; i + index < active.length; i++) { - if (active[i + index] != next[i]) { - // An element in the next list didn't match. This isn't in the expected - // form we can optimize. - return null; - } - if (i == next.length - 1) { - // The entire next list was contained in the active list. - if (index == 0) { - // If the first index of the next list is also the first index in the - // active list, then the next list is the same as the active list with - // views removed from the end. - return ViewListDiffResult( - active.sublist(i + 1), const [], false); - } else if (i + index == active.length - 1) { - // If this is also the end of the active list, then the next list is - // the same as the active list with some views removed from the - // beginning. - return ViewListDiffResult( - active.sublist(0, index), const [], false); - } else { - return null; - } - } - } - // We reached the end of the active list but have not reached the end of the - // next list. The lists are in the expected form. We should remove the - // elements from `0` to `index` in the active list from the DOM and add the - // elements from `active.length - index` (the entire active list minus the - // number of new elements at the beginning) to the end of the next list to - // the DOM at the end of the list of platform views. - final List viewsToRemove = active.sublist(0, index); - final List viewsToAdd = next.sublist(active.length - index); - - return ViewListDiffResult( - viewsToRemove, - viewsToAdd, - false, - ); - } - - // This is tried if the last element of the next list is contained in the - // active list at `index`. If the lists are in the expected form, we should be - // able to iterate backwards from index to the beginning of the active list - // and have every element match the corresponding element from the next list. - ViewListDiffResult? lookBackwards(int index) { - for (int i = 0; index - i >= 0; i++) { - if (active[index - i] != next[next.length - 1 - i]) { - // An element from the next list didn't match the coresponding element - // from the active list. These lists aren't in the expected form. - return null; - } - if (i == next.length - 1) { - // The entire next list was contained in the active list. - if (index == active.length - 1) { - // If the last element of the next list is also the last element of - // the active list, then the next list is just the active list with - // some elements removed from the beginning. - return ViewListDiffResult( - active.sublist(0, active.length - i - 1), const [], false); - } else if (index == i) { - // If we also reached the beginning of the active list, then the next - // list is the same as the active list with some views removed from - // the end. - return ViewListDiffResult( - active.sublist(index + 1), const [], false); - } else { - return null; - } - } - } - - // We reached the beginning of the active list but have not exhausted the - // entire next list. The lists are in the expected form. We should remove - // the elements from the end of the active list which come after the element - // which matches the last index of the next list (everything after `index`). - // We should add the elements from the next list which we didn't reach while - // iterating above (the first `next.length - index` views). - final List viewsToRemove = active.sublist(index + 1); - final List viewsToAdd = next.sublist(0, next.length - 1 - index); - - return ViewListDiffResult( - viewsToRemove, - viewsToAdd, - true, - viewToInsertBefore: active.first, - ); - } - - // If the [active] and [next] lists are in the expected form described above, - // then either the first or last element of [next] will be in [active]. - final int firstIndex = active.indexOf(next.first); - final int lastIndex = active.lastIndexOf(next.last); - if (firstIndex != -1 && lastIndex != -1) { - // Both the first element and the last element of the next list are in the - // active list. Search in the direction that will result in the least - // amount of deletions. - if (firstIndex <= (active.length - lastIndex)) { - return lookForwards(firstIndex); - } else { - return lookBackwards(lastIndex); - } - } else if (firstIndex != -1) { - return lookForwards(firstIndex); - } else if (lastIndex != -1) { - return lookBackwards(lastIndex); - } else { - return null; - } -} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer_tree.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer_tree.dart index 8e8462a05b..046fb49c84 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer_tree.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer_tree.dart @@ -48,9 +48,11 @@ class LayerTree { void paint(Frame frame, {bool ignoreRasterCache = false}) { final CkNWayCanvas internalNodesCanvas = CkNWayCanvas(); internalNodesCanvas.addCanvas(frame.canvas); - final Iterable overlayCanvases = + final List overlayCanvases = frame.viewEmbedder!.getOverlayCanvases(); - overlayCanvases.forEach(internalNodesCanvas.addCanvas); + for (int i = 0; i < overlayCanvases.length; i++) { + internalNodesCanvas.addCanvas(overlayCanvases[i]); + } // Clear the canvases before painting internalNodesCanvas.clear(const ui.Color(0x00000000)); final PaintContext context = PaintContext( diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/surface_factory.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/surface_factory.dart index 0ea08af2cc..2a5aefecf0 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/surface_factory.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/surface_factory.dart @@ -1,7 +1,6 @@ // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:math' as math show max; import 'package:meta/meta.dart'; @@ -20,23 +19,12 @@ class SurfaceFactory { /// Useful in tests for checking the lifecycle of this class. static SurfaceFactory? get debugUninitializedInstance => _instance; - // Override the current instance with a new one. - // - // This should only be used in tests. - static void debugSetInstance(SurfaceFactory newInstance) { - _instance = newInstance; - } - static SurfaceFactory? _instance; - SurfaceFactory(int maximumSurfaces) - : maximumSurfaces = math.max(maximumSurfaces, 1) { + SurfaceFactory(this.maximumSurfaces) + : assert(maximumSurfaces >= 1, + 'The maximum number of surfaces must be at least 1') { if (assertionsEnabled) { - if (maximumSurfaces < 1) { - printWarning('Attempted to create a $SurfaceFactory with ' - '$maximumSurfaces maximum surfaces. At least 1 surface is required ' - 'for rendering.'); - } registerHotRestartListener(debugClear); } } @@ -46,14 +34,17 @@ class SurfaceFactory { /// all painting commands. final Surface baseSurface = Surface(); + /// The shared backup surface + final Surface backupSurface = Surface(); + /// The maximum number of surfaces which can be live at once. final int maximumSurfaces; /// The maximum number of assignable overlays. /// - /// This is just `maximumSurfaces - 1` (the maximum number of surfaces minus - /// the required base surface). - int get maximumOverlays => maximumSurfaces - 1; + /// This is just `maximumSurfaces - 2` (the maximum number of surfaces minus + /// the base surface and backup surface). + int get maximumOverlays => maximumSurfaces - 2; /// Surfaces created by this factory which are currently in use. final List _liveSurfaces = []; @@ -63,11 +54,11 @@ class SurfaceFactory { final List _cache = []; /// The number of surfaces which have been created by this factory. - int get _surfaceCount => _liveSurfaces.length + _cache.length + 1; + int get _surfaceCount => _liveSurfaces.length + _cache.length + 2; /// The number of available overlay surfaces. /// - /// This does not include the base surface. + /// This does not include the base surface or backup surface. int get numAvailableOverlays => maximumOverlays - _liveSurfaces.length; /// The number of surfaces created by this factory. Used for testing. @@ -79,6 +70,10 @@ class SurfaceFactory { /// Useful in tests. int get debugCacheSize => _cache.length; + /// Whether or not we have already emitted a warning about creating too many + /// surfaces. + bool _warnedAboutTooManySurfaces = false; + /// Gets an overlay surface from the cache or creates a new one if it wouldn't /// exceed the maximum. If there are no available surfaces, returns `null`. Surface? getOverlay() { @@ -95,6 +90,29 @@ class SurfaceFactory { } } + /// Gets a [Surface] which is ready to paint to. + /// + /// If there are available surfaces in the cache, then this will return one of + /// them. If this factory hasn't yet created [maximumSurfaces] surfaces, then a + /// new one will be created. If this factory has already created [maximumSurfaces] + /// surfaces, then this will return a backup surface which will be returned by + /// all subsequent calls to [getSurface] until some surfaces have been + /// released with [releaseSurface]. + Surface getSurface() { + final Surface? surface = getOverlay(); + if (surface != null) { + return surface; + } + if (!_warnedAboutTooManySurfaces) { + _warnedAboutTooManySurfaces = true; + printWarning('Flutter was unable to create enough overlay surfaces. ' + 'This is usually caused by too many platform views being ' + 'displayed at once. ' + 'You may experience incorrect rendering.'); + } + return backupSurface; + } + /// Releases all surfaces so they can be reused in the next frame. /// /// If a released surface is in the DOM, it is not removed. This allows the @@ -112,6 +130,7 @@ class SurfaceFactory { /// the new surfaces. void removeSurfacesFromDom() { _cache.forEach(_removeFromDom); + _removeFromDom(backupSurface); } // Removes [surface] from the DOM. @@ -122,6 +141,11 @@ class SurfaceFactory { /// Signals that a surface is no longer being used. It can be reused. void releaseSurface(Surface surface) { assert(surface != baseSurface, 'Attempting to release the base surface'); + if (surface == backupSurface) { + // If it's the backup surface, just remove it from the DOM. + surface.htmlElement.remove(); + return; + } assert( _liveSurfaces.contains(surface), 'Attempting to release a Surface which ' @@ -133,12 +157,13 @@ class SurfaceFactory { /// Returns [true] if [surface] is currently being used to paint content. /// - /// The base surface always counts as live. + /// The base surface and backup surface always count as live. /// /// If a surface is not live, then it must be in the cache and ready to be /// reused. bool isLive(Surface surface) { if (surface == baseSurface || + surface == backupSurface || _liveSurfaces.contains(surface)) { return true; } @@ -155,6 +180,7 @@ class SurfaceFactory { surface.dispose(); } baseSurface.dispose(); + backupSurface.dispose(); _liveSurfaces.clear(); _cache.clear(); _instance = null; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/dom.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/dom.dart index 3eabd99404..1870e9c9ff 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/dom.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/dom.dart @@ -197,7 +197,7 @@ extension DomNodeExtension on DomNode { } external DomNode removeChild(DomNode child); - external bool get isConnected; + external bool? get isConnected; set text(String? value) => js_util.setProperty(this, 'textContent', value); external DomNode cloneNode(bool? deep); diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/embedded_views_diff_test.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/embedded_views_diff_test.dart deleted file mode 100644 index cb5edda0d1..0000000000 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/embedded_views_diff_test.dart +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:test/bootstrap/browser.dart'; -import 'package:test/test.dart'; -import 'package:ui/src/engine/canvaskit/embedded_views_diff.dart'; - -import 'common.dart'; - -void main() { - internalBootstrapBrowserTest(() => testMain); -} - -void testMain() { - group('diffViewList', () { - setUpCanvasKitTest(); - - test('works in the expected case', () { - ViewListDiffResult? result = diffViewList( - [1, 2, 3, 4, 5], - [3, 4, 5, 6, 7], - ); - expect(result, isNotNull); - expect(result!.viewsToAdd, [6, 7]); - expect(result.viewsToRemove, [1, 2]); - expect(result.addToBeginning, isFalse); - - result = diffViewList( - [3, 4, 5, 6, 7], - [1, 2, 3, 4, 5], - ); - expect(result, isNotNull); - expect(result!.viewsToAdd, [1, 2]); - expect(result.viewsToRemove, [6, 7]); - expect(result.addToBeginning, isTrue); - expect(result.viewToInsertBefore, 3); - - result = diffViewList([3, 4, 5], [2, 3, 4, 5]); - expect(result, isNotNull); - expect(result!.viewsToAdd, [2]); - expect(result.viewsToRemove, []); - expect(result.addToBeginning, isTrue); - expect(result.viewToInsertBefore, 3); - - result = diffViewList([3, 4, 5], [3, 4, 5, 6]); - expect(result, isNotNull); - expect(result!.viewsToAdd, [6]); - expect(result.viewsToRemove, []); - expect(result.addToBeginning, isFalse); - - result = diffViewList([3, 4, 5, 6], [3, 4, 5]); - expect(result, isNotNull); - expect(result!.viewsToAdd, []); - expect(result.viewsToRemove, [6]); - - result = diffViewList([3, 4, 5, 6], [4, 5, 6]); - expect(result, isNotNull); - expect(result!.viewsToAdd, []); - expect(result.viewsToRemove, [3]); - expect(result.addToBeginning, isFalse); - - result = diffViewList([3, 4, 5, 6, 7, 8], [3, 4, 5]); - expect(result, isNotNull); - expect(result!.viewsToAdd, []); - expect(result.viewsToRemove, [6, 7, 8]); - - result = diffViewList([1, 2, 3, 4, 5, 6], [4, 5, 6]); - expect(result, isNotNull); - expect(result!.viewsToAdd, []); - expect(result.viewsToRemove, [1, 2, 3]); - expect(result.addToBeginning, isFalse); - - result = diffViewList([3, 4, 5, 6, 7, 8], [2, 3, 4, 5]); - expect(result, isNotNull); - expect(result!.viewsToAdd, [2]); - expect(result.viewsToRemove, [6, 7, 8]); - expect(result.addToBeginning, isTrue); - expect(result.viewToInsertBefore, 3); - - result = diffViewList([1, 2, 3, 4, 5, 6], [4, 5, 6, 7]); - expect(result, isNotNull); - expect(result!.viewsToAdd, [7]); - expect(result.viewsToRemove, [1, 2, 3]); - expect(result.addToBeginning, isFalse); - - result = diffViewList([1, 2, 3], [4, 5]); - expect(result, isNull); - - result = diffViewList([1, 2, 3, 4], [2, 3, 5, 4]); - expect(result, isNull); - - result = diffViewList([3, 4], [1, 2, 3, 4, 5, 6]); - expect(result, isNull); - - result = diffViewList([1, 2, 3, 4, 5], [2, 3, 4]); - expect(result, isNull); - }); - - test('works for flutter/flutter#101580', () { - ViewListDiffResult? result; - - // Reverse the list - result = diffViewList([1, 2, 3, 4], [4, 3, 2, 1]); - expect(result, isNotNull); - expect(result!.viewsToAdd, [3, 2, 1]); - expect(result.viewsToRemove, [1, 2, 3]); - expect(result.addToBeginning, isFalse); - - // Sort the list - result = diffViewList([3, 4, 1, 2], [1, 2, 3, 4]); - expect(result, isNotNull); - expect(result!.viewsToAdd, [3, 4]); - expect(result.viewsToRemove, [3, 4]); - expect(result.addToBeginning, isFalse); - - // Move last view to the beginning - result = diffViewList([2, 3, 4, 1], [1, 2, 3, 4]); - expect(result, isNotNull); - expect(result!.viewsToAdd, [1]); - expect(result.viewsToRemove, [1]); - expect(result.addToBeginning, isTrue); - expect(result.viewToInsertBefore, 2); - - // Shuffle the list - result = diffViewList([1, 2, 3, 4], [2, 4, 1, 3]); - expect(result, isNull); - }); - }); -} diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/embedded_views_test.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/embedded_views_test.dart index 6c68f4bb19..d9b2cf47ca 100644 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/embedded_views_test.dart +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/embedded_views_test.dart @@ -77,9 +77,7 @@ void testMain() { dispatcher.rasterizer!.draw(sb.build().layerTree); expect( - flutterViewEmbedder.sceneElement! - .querySelectorAll('#sk_path_defs') - .single, + flutterViewEmbedder.sceneElement!.querySelectorAll('#sk_path_defs').single, isNotNull, ); expect( @@ -120,8 +118,8 @@ void testMain() { dispatcher.rasterizer!.draw(sb.build().layerTree); // Transformations happen on the slot element. - final html.Element slotHost = flutterViewEmbedder.sceneElement! - .querySelector('flt-platform-view-slot')!; + final html.Element slotHost = + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot')!; expect( slotHost.style.transform, @@ -145,8 +143,8 @@ void testMain() { sb.addPlatformView(0, offset: const ui.Offset(3, 4), width: 5, height: 6); dispatcher.rasterizer!.draw(sb.build().layerTree); - final html.Element slotHost = flutterViewEmbedder.sceneElement! - .querySelector('flt-platform-view-slot')!; + final html.Element slotHost = + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot')!; final html.CssStyleDeclaration style = slotHost.style; expect(style.transform, 'matrix(1, 0, 0, 1, 3, 4)'); @@ -190,8 +188,8 @@ void testMain() { dispatcher.rasterizer!.draw(sb.build().layerTree); // Transformations happen on the slot element. - html.Element slotHost = flutterViewEmbedder.sceneElement! - .querySelector('flt-platform-view-slot')!; + html.Element slotHost = + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot')!; expect( getTransformChain(slotHost), @@ -211,8 +209,8 @@ void testMain() { dispatcher.rasterizer!.draw(sb.build().layerTree); // Transformations happen on the slot element. - slotHost = flutterViewEmbedder.sceneElement! - .querySelector('flt-platform-view-slot')!; + slotHost = + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot')!; expect( getTransformChain(slotHost), @@ -242,8 +240,8 @@ void testMain() { dispatcher.rasterizer!.draw(sb.build().layerTree); // Transformations happen on the slot element. - final html.Element slotHost = flutterViewEmbedder.sceneElement! - .querySelector('flt-platform-view-slot')!; + final html.Element slotHost = + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot')!; expect( getTransformChain(slotHost), @@ -271,8 +269,8 @@ void testMain() { dispatcher.rasterizer!.draw(sb.build().layerTree); // Transformations happen on the slot element. - final html.Element slotHost = flutterViewEmbedder.sceneElement! - .querySelector('flt-platform-view-slot')!; + final html.Element slotHost = + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot')!; expect( getTransformChain(slotHost), @@ -286,7 +284,6 @@ void testMain() { test('renders overlays on top of platform views', () async { expect(SurfaceFactory.instance.debugCacheSize, 0); - expect(configuration.canvasKitMaximumSurfaces, 8); final CkPicture testPicture = paintPicture(const ui.Rect.fromLTRB(0, 0, 10, 10), (CkCanvas canvas) { canvas.drawCircle(const ui.Offset(5, 5), 5, CkPaint()); @@ -294,7 +291,7 @@ void testMain() { // Initialize all platform views to be used in the test. final List platformViewIds = []; - for (int i = 0; i < 16; i++) { + for (int i = 0; i < configuration.canvasKitMaximumSurfaces * 2; i++) { ui.platformViewRegistry.registerViewFactory( 'test-platform-view', (int viewId) => html.DivElement()..id = 'view-$i', @@ -316,95 +313,43 @@ void testMain() { dispatcher.rasterizer!.draw(sb.build().layerTree); } + int countCanvases() { + return flutterViewEmbedder.sceneElement!.querySelectorAll('canvas').length; + } + // Frame 1: // Render: up to cache size platform views. // Expect: main canvas plus platform view overlays. - renderTestScene(viewCount: 8); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - platformView, - overlay, - ]); + renderTestScene(viewCount: configuration.canvasKitMaximumSurfaces); + expect(countCanvases(), configuration.canvasKitMaximumSurfaces); // Frame 2: // Render: zero platform views. // Expect: main canvas, no overlays. await Future.delayed(Duration.zero); renderTestScene(viewCount: 0); - expectSceneMatches(<_EmbeddedViewMarker>[overlay]); + expect(countCanvases(), 1); // Frame 3: // Render: less than cache size platform views. // Expect: overlays reused. await Future.delayed(Duration.zero); - renderTestScene(viewCount: 6); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - ]); + renderTestScene(viewCount: configuration.canvasKitMaximumSurfaces - 2); + expect(countCanvases(), configuration.canvasKitMaximumSurfaces - 1); // Frame 4: // Render: more platform views than max cache size. // Expect: main canvas, backup overlay, maximum overlays. await Future.delayed(Duration.zero); - renderTestScene(viewCount: 16); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - platformView, - platformView, - platformView, - platformView, - platformView, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); + renderTestScene(viewCount: configuration.canvasKitMaximumSurfaces * 2); + expect(countCanvases(), configuration.canvasKitMaximumSurfaces); // Frame 5: // Render: zero platform views. // Expect: main canvas, no overlays. await Future.delayed(Duration.zero); renderTestScene(viewCount: 0); - expectSceneMatches(<_EmbeddedViewMarker>[overlay]); + expect(countCanvases(), 1); // Frame 6: // Render: deleted platform views. @@ -438,7 +383,6 @@ void testMain() { // Expect: success. Just checking the system is not left in a corrupted state. await createPlatformView(0, 'test-platform-view'); renderTestScene(viewCount: 0); - expectSceneMatches(<_EmbeddedViewMarker>[overlay]); // TODO(yjbanov): skipped due to https://github.com/flutter/flutter/issues/73867 }, skip: isSafari); @@ -472,110 +416,29 @@ void testMain() { dispatcher.rasterizer!.draw(sb.build().layerTree); } + int countCanvases() { + return flutterViewEmbedder.sceneElement!.querySelectorAll('canvas').length; + } + // Frame 1: // Render: Views 1-10 // Expect: main canvas plus platform view overlays; empty cache. renderTestScene([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); - expect(SurfaceFactory.instance.numAvailableOverlays, 0); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); + expect(countCanvases(), configuration.canvasKitMaximumSurfaces); // Frame 2: // Render: Views 2-11 // Expect: main canvas plus platform view overlays; empty cache. await Future.delayed(Duration.zero); renderTestScene([2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); - expect(SurfaceFactory.instance.numAvailableOverlays, 0); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); + expect(countCanvases(), configuration.canvasKitMaximumSurfaces); // Frame 3: // Render: Views 3-12 // Expect: main canvas plus platform view overlays; empty cache. await Future.delayed(Duration.zero); renderTestScene([3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); - - // Frame 4: - // Render: Views 3-12 again (same as last frame) - // Expect: main canvas plus platform view overlays; empty cache. - await Future.delayed(Duration.zero); - renderTestScene([3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - overlay, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); + expect(countCanvases(), configuration.canvasKitMaximumSurfaces); // TODO(yjbanov): skipped due to https://github.com/flutter/flutter/issues/73867 }, skip: isSafari); @@ -594,15 +457,13 @@ void testMain() { sb.pushOffset(0, 0); sb.addPlatformView(0, width: 10, height: 10); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - ]); expect( - flutterViewEmbedder.glassPaneElement! - .querySelector('flt-platform-view'), + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot'), + isNotNull, + ); + expect( + flutterViewEmbedder.glassPaneElement!.querySelector('flt-platform-view'), isNotNull, ); @@ -612,13 +473,12 @@ void testMain() { sb.pushOffset(0, 0); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - ]); - expect( - flutterViewEmbedder.glassPaneElement! - .querySelector('flt-platform-view'), + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot'), + isNull, + ); + expect( + flutterViewEmbedder.glassPaneElement!.querySelector('flt-platform-view'), isNull, ); }); @@ -637,15 +497,13 @@ void testMain() { sb.pushOffset(0, 0); sb.addPlatformView(0, width: 10, height: 10); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - ]); expect( - flutterViewEmbedder.glassPaneElement! - .querySelector('flt-platform-view'), + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot'), + isNotNull, + ); + expect( + flutterViewEmbedder.glassPaneElement!.querySelector('flt-platform-view'), isNotNull, ); @@ -655,15 +513,12 @@ void testMain() { sb.pushOffset(0, 0); sb.addPlatformView(1, width: 10, height: 10); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - ]); expect( - flutterViewEmbedder.glassPaneElement! - .querySelectorAll('flt-platform-view'), + flutterViewEmbedder.sceneElement!.querySelectorAll('flt-platform-view-slot'), + hasLength(1)); + expect( + flutterViewEmbedder.glassPaneElement!.querySelectorAll('flt-platform-view'), hasLength(2)); // Render a frame without a platform view, but also without disposing of @@ -671,16 +526,17 @@ void testMain() { sb = LayerSceneBuilder(); sb.pushOffset(0, 0); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - ]); + expect( + flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot'), + isNull, + ); // The actual contents of the platform view are kept in the dom, until // it's actually disposed of! expect( - flutterViewEmbedder.glassPaneElement! - .querySelectorAll('flt-platform-view'), - hasLength(2)); + flutterViewEmbedder.glassPaneElement!.querySelector('flt-platform-view'), + isNotNull, + ); }); test( @@ -721,6 +577,95 @@ void testMain() { expect(skPathDefs.childNodes, hasLength(1)); }); + test('diffViewList works in the expected case', () { + ViewListDiffResult? result = diffViewList( + [1, 2, 3, 4, 5], + [3, 4, 5, 6, 7], + ); + expect(result, isNotNull); + expect(result!.viewsToAdd, [6, 7]); + expect(result.viewsToRemove, [1, 2]); + expect(result.addToBeginning, isFalse); + + result = diffViewList( + [3, 4, 5, 6, 7], + [1, 2, 3, 4, 5], + ); + expect(result, isNotNull); + expect(result!.viewsToAdd, [1, 2]); + expect(result.viewsToRemove, [6, 7]); + expect(result.addToBeginning, isTrue); + expect(result.viewToInsertBefore, 3); + + result = diffViewList([3, 4, 5], [2, 3, 4, 5]); + expect(result, isNotNull); + expect(result!.viewsToAdd, [2]); + expect(result.viewsToRemove, []); + expect(result.addToBeginning, isTrue); + expect(result.viewToInsertBefore, 3); + + result = diffViewList([3, 4, 5], [3, 4, 5, 6]); + expect(result, isNotNull); + expect(result!.viewsToAdd, [6]); + expect(result.viewsToRemove, []); + expect(result.addToBeginning, isFalse); + + result = diffViewList([3, 4, 5, 6], [3, 4, 5]); + expect(result, isNotNull); + expect(result!.viewsToAdd, []); + expect(result.viewsToRemove, [6]); + expect(result.addToBeginning, isTrue); + expect(result.viewToInsertBefore, 3); + + result = diffViewList([3, 4, 5, 6], [4, 5, 6]); + expect(result, isNotNull); + expect(result!.viewsToAdd, []); + expect(result.viewsToRemove, [3]); + expect(result.addToBeginning, isFalse); + + result = diffViewList([1, 2, 3], [4, 5]); + expect(result, isNull); + + result = diffViewList([1, 2, 3, 4], [2, 3, 5, 4]); + expect(result, isNull); + + result = diffViewList([3, 4], [1, 2, 3, 4, 5, 6]); + expect(result, isNull); + }); + + test('diffViewList works for flutter/flutter#101580', () { + ViewListDiffResult? result; + + // Reverse the list + result = diffViewList([1, 2, 3, 4], [4, 3, 2, 1]); + expect(result, isNotNull); + expect(result!.viewsToAdd, [3, 2, 1]); + expect(result.viewsToRemove, isEmpty); + expect(result.addToBeginning, isFalse); + + // Sort the list + result = diffViewList([3, 4, 1, 2], [1, 2, 3, 4]); + expect(result, isNotNull); + expect(result!.viewsToAdd, [3, 4]); + expect(result.viewsToRemove, isEmpty); + expect(result.addToBeginning, isFalse); + + // Move last view to the beginning + // (The algo explores the diff from left to right, but in this case, it'd + // more efficient to add [1] at the beginning. Maybe we should compute both + // diffs, from left and right, and return the one that results in fewer + // add/remove operations?) + result = diffViewList([2, 3, 4, 1], [1, 2, 3, 4]); + expect(result, isNotNull); + expect(result!.viewsToAdd, [2, 3, 4]); + expect(result.viewsToRemove, isEmpty); + expect(result.addToBeginning, isFalse); + + // Shuffle the list + result = diffViewList([1, 2, 3, 4], [2, 4, 1, 3]); + expect(result, isNull); + }); + test('does not crash when a prerolled platform view is not composited', () async { ui.platformViewRegistry.registerViewFactory( @@ -739,9 +684,10 @@ void testMain() { sb.pop(); // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - ]); + expect( + flutterViewEmbedder.glassPaneShadow! + .querySelectorAll('flt-platform-view-slot'), + isEmpty); }); test('does not crash when overlays are disabled', () async { @@ -761,10 +707,10 @@ void testMain() { sb.pop(); // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - ]); + expect( + flutterViewEmbedder.glassPaneShadow! + .querySelectorAll('flt-platform-view-slot'), + hasLength(1)); HtmlViewEmbedder.debugDisableOverlays = false; }); @@ -774,7 +720,7 @@ void testMain() { SurfaceFactory.instance.debugClear(); expect(SurfaceFactory.instance.maximumSurfaces, 2); - expect(SurfaceFactory.instance.maximumOverlays, 1); + expect(SurfaceFactory.instance.maximumOverlays, 0); ui.platformViewRegistry.registerViewFactory( 'test-platform-view', @@ -793,11 +739,10 @@ void testMain() { // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - ]); + expect( + flutterViewEmbedder.glassPaneShadow! + .querySelectorAll('flt-platform-view-slot'), + hasLength(1)); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -807,12 +752,10 @@ void testMain() { // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - overlay, - ]); + expect( + flutterViewEmbedder.glassPaneShadow! + .querySelectorAll('flt-platform-view-slot'), + hasLength(2)); // Reset configuration debugSetConfiguration(FlutterConfiguration(null)); @@ -839,11 +782,11 @@ void testMain() { sb.pop(); // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - ]); + + expect( + flutterViewEmbedder.glassPaneShadow! + .querySelectorAll('flt-platform-view-slot'), + hasLength(2)); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -851,10 +794,10 @@ void testMain() { sb.pop(); // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - ]); + expect( + flutterViewEmbedder.glassPaneShadow! + .querySelectorAll('flt-platform-view-slot'), + hasLength(1)); HtmlViewEmbedder.debugDisableOverlays = false; }); @@ -881,6 +824,10 @@ void testMain() { final EnginePlatformDispatcher dispatcher = ui.window.platformDispatcher as EnginePlatformDispatcher; + int countCanvases() { + return flutterViewEmbedder.sceneElement!.querySelectorAll('canvas').length; + } + expect(platformViewManager.isInvisible(0), isFalse); expect(platformViewManager.isInvisible(1), isTrue); @@ -889,11 +836,7 @@ void testMain() { sb.addPlatformView(1, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - overlay, - ]); + expect(countCanvases(), 1); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -901,12 +844,7 @@ void testMain() { sb.addPlatformView(1, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - overlay, - ]); + expect(countCanvases(), 2); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -915,14 +853,7 @@ void testMain() { sb.addPlatformView(2, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - overlay, - platformView, - overlay, - ]); + expect(countCanvases(), 3); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -932,15 +863,7 @@ void testMain() { sb.addPlatformView(3, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - overlay, - platformView, - platformView, - overlay, - ]); + expect(countCanvases(), 3); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -951,16 +874,7 @@ void testMain() { sb.addPlatformView(4, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - overlay, - platformView, - platformView, - platformView, - overlay, - ]); + expect(countCanvases(), 3); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -972,17 +886,7 @@ void testMain() { sb.addPlatformView(5, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - overlay, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); + expect(countCanvases(), 3); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -995,18 +899,7 @@ void testMain() { sb.addPlatformView(6, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - overlay, - platformView, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); + expect(countCanvases(), 3); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -1017,78 +910,8 @@ void testMain() { sb.addPlatformView(6, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); - - sb = LayerSceneBuilder(); - sb.pushOffset(0, 0); - sb.addPlatformView(1, width: 10, height: 10); - sb.addPlatformView(2, width: 10, height: 10); - sb.addPlatformView(3, width: 10, height: 10); - sb.addPlatformView(4, width: 10, height: 10); - sb.pop(); - dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); - - sb = LayerSceneBuilder(); - sb.pushOffset(0, 0); - sb.addPlatformView(4, width: 10, height: 10); - sb.addPlatformView(3, width: 10, height: 10); - sb.addPlatformView(2, width: 10, height: 10); - sb.addPlatformView(1, width: 10, height: 10); - sb.pop(); - dispatcher.rasterizer!.draw(sb.build().layerTree); - expectSceneMatches(<_EmbeddedViewMarker>[ - overlay, - platformView, - platformView, - platformView, - platformView, - overlay, - ]); + expect(countCanvases(), 1); }); // TODO(dit): https://github.com/flutter/flutter/issues/60040 }, skip: isIosSafari); } - -// Used to test that the platform views and overlays are in the correct order in -// the scene. -enum _EmbeddedViewMarker { - overlay, - platformView, -} - -_EmbeddedViewMarker get overlay => _EmbeddedViewMarker.overlay; -_EmbeddedViewMarker get platformView => _EmbeddedViewMarker.platformView; - -void expectSceneMatches(List<_EmbeddedViewMarker> markers) { - final List sceneElements = flutterViewEmbedder - .sceneElement!.children - .where((html.Element element) => element.tagName != 'svg') - .toList(); - expect(markers, hasLength(sceneElements.length)); - for (int i = 0; i < markers.length; i++) { - switch (markers[i]) { - case _EmbeddedViewMarker.overlay: - expect(sceneElements[i].tagName, 'FLT-CANVAS-CONTAINER'); - break; - case _EmbeddedViewMarker.platformView: - expect(sceneElements[i].tagName, 'FLT-PLATFORM-VIEW-SLOT'); - break; - } - } -} diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/h5vcc_test.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/h5vcc_test.dart index 141f9df94a..b5b4608e0a 100644 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/h5vcc_test.dart +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/h5vcc_test.dart @@ -53,7 +53,7 @@ void testMain() { }); test('Surface acquireFrame uses getH5vccSkSurface', () { - final Surface surface = SurfaceFactory.instance.getOverlay()!; + final Surface surface = SurfaceFactory.instance.getSurface(); surface.acquireFrame(ui.Size.zero); expect(getH5vccSkSurfaceCalledCount, 1); diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/surface_factory_test.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/surface_factory_test.dart index bdefb5a921..c312aca45a 100644 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/surface_factory_test.dart +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/surface_factory_test.dart @@ -7,6 +7,7 @@ import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; +import '../matchers.dart'; import 'common.dart'; const MethodCodec codec = StandardMethodCodec(); @@ -20,27 +21,32 @@ void testMain() { setUpCanvasKitTest(); test('cannot be created with size less than 1', () { - expect(SurfaceFactory(-1).maximumSurfaces, 1); - expect(SurfaceFactory(0).maximumSurfaces, 1); - expect(SurfaceFactory(1).maximumSurfaces, 1); - expect(SurfaceFactory(2).maximumSurfaces, 2); + expect(() => SurfaceFactory(-1), throwsAssertionError); + expect(() => SurfaceFactory(0), throwsAssertionError); + expect(SurfaceFactory(1), isNotNull); + expect(SurfaceFactory(2), isNotNull); }); - test('getOverlay', () { + test('getSurface', () { final SurfaceFactory factory = SurfaceFactory(3); expect(factory.baseSurface, isNotNull); - - expect(factory.debugSurfaceCount, equals(1)); - - // Get a surface from the factory, it should be unique. - final Surface? newSurface = factory.getOverlay(); - expect(newSurface, isNot(equals(factory.baseSurface))); + expect(factory.backupSurface, isNotNull); + expect(factory.baseSurface, isNot(equals(factory.backupSurface))); expect(factory.debugSurfaceCount, equals(2)); - // Get another surface from the factory. Now we are at maximum capacity. - final Surface? anotherSurface = factory.getOverlay(); + // Get a surface from the factory, it should be unique. + final Surface newSurface = factory.getSurface(); + expect(newSurface, isNot(equals(factory.baseSurface))); + expect(newSurface, isNot(equals(factory.backupSurface))); + + expect(factory.debugSurfaceCount, equals(3)); + + // Get another surface from the factory. Now we are at maximum capacity, + // so it should return the backup surface. + final Surface anotherSurface = factory.getSurface(); expect(anotherSurface, isNot(equals(factory.baseSurface))); + expect(anotherSurface, equals(factory.backupSurface)); expect(factory.debugSurfaceCount, equals(3)); }); @@ -49,12 +55,12 @@ void testMain() { final SurfaceFactory factory = SurfaceFactory(3); // Create a new surface and immediately release it. - final Surface? surface = factory.getOverlay(); - factory.releaseSurface(surface!); + final Surface surface = factory.getSurface(); + factory.releaseSurface(surface); // If we create a new surface, it should be the same as the one we // just created. - final Surface? newSurface = factory.getOverlay(); + final Surface newSurface = factory.getSurface(); expect(newSurface, equals(surface)); }); @@ -62,9 +68,10 @@ void testMain() { final SurfaceFactory factory = SurfaceFactory(3); expect(factory.isLive(factory.baseSurface), isTrue); + expect(factory.isLive(factory.backupSurface), isTrue); - final Surface? surface = factory.getOverlay(); - expect(factory.isLive(surface!), isTrue); + final Surface surface = factory.getSurface(); + expect(factory.isLive(surface), isTrue); factory.releaseSurface(surface); expect(factory.isLive(surface), isFalse); @@ -86,18 +93,23 @@ void testMain() { // Create a few overlay surfaces final List overlays = []; for (int i = 0; i < 3; i++) { - overlays.add(originalFactory.getOverlay()! + overlays.add(originalFactory.getSurface() ..acquireFrame(const ui.Size(10, 10)) ..addToScene()); } - expect(originalFactory.debugSurfaceCount, 4); + expect(originalFactory.debugSurfaceCount, 5); + + originalFactory.backupSurface.acquireFrame(const ui.Size(10, 10)); + originalFactory.backupSurface.addToScene(); + expect(originalFactory.backupSurface.htmlCanvas!.isConnected, isTrue); // Trigger hot restart clean-up logic and check that we indeed clean up. debugEmulateHotRestart(); expect(SurfaceFactory.debugUninitializedInstance, isNull); expectDisposed(originalFactory.baseSurface); + expectDisposed(originalFactory.backupSurface); overlays.forEach(expectDisposed); - expect(originalFactory.debugSurfaceCount, 1); + expect(originalFactory.debugSurfaceCount, 2); }); // TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040 }, skip: isIosSafari); diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/surface_test.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/surface_test.dart index 123fff0151..73a7274fdc 100644 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/surface_test.dart +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/surface_test.dart @@ -21,9 +21,9 @@ void testMain() { }); test('Surface allocates canvases efficiently', () { - final Surface? surface = SurfaceFactory.instance.getOverlay(); + final Surface surface = SurfaceFactory.instance.getSurface(); final CkSurface originalSurface = - surface!.acquireFrame(const ui.Size(9, 19)).skiaSurface; + surface.acquireFrame(const ui.Size(9, 19)).skiaSurface; final DomCanvasElement original = surface.htmlCanvas!; // Expect exact requested dimensions. @@ -102,8 +102,8 @@ void testMain() { test( 'Surface creates new context when WebGL context is restored', () async { - final Surface? surface = SurfaceFactory.instance.getOverlay(); - expect(surface!.debugForceNewContext, isTrue); + final Surface surface = SurfaceFactory.instance.getSurface(); + expect(surface.debugForceNewContext, isTrue); final CkSurface before = surface.acquireFrame(const ui.Size(9, 19)).skiaSurface; expect(surface.debugForceNewContext, isFalse);