From 3da9e6d12fc83cdc2d1cfd8af9097c0b1d57df74 Mon Sep 17 00:00:00 2001 From: Harry Terkelsen Date: Wed, 22 Jun 2022 10:17:19 -0700 Subject: [PATCH] [canvaskit] Rework embedded view manager (flutter/engine#34081) --- .../ci/licenses_golden/licenses_flutter | 1 + .../flutter/lib/web_ui/lib/src/engine.dart | 1 + .../src/engine/canvaskit/embedded_views.dart | 598 +++++++----------- .../engine/canvaskit/embedded_views_diff.dart | 161 +++++ .../lib/src/engine/canvaskit/layer_tree.dart | 6 +- .../src/engine/canvaskit/surface_factory.dart | 68 +- .../lib/web_ui/lib/src/engine/dom.dart | 2 +- .../canvaskit/embedded_views_diff_test.dart | 130 ++++ .../test/canvaskit/embedded_views_test.dart | 549 ++++++++++------ .../lib/web_ui/test/canvaskit/h5vcc_test.dart | 2 +- .../test/canvaskit/surface_factory_test.dart | 54 +- .../web_ui/test/canvaskit/surface_test.dart | 8 +- 12 files changed, 939 insertions(+), 641 deletions(-) create mode 100644 engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views_diff.dart create mode 100644 engine/src/flutter/lib/web_ui/test/canvaskit/embedded_views_diff_test.dart diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index a7b4b6aed9..8f2673ed9c 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1024,6 +1024,7 @@ 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 2983f3f132..2bad386d02 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine.dart @@ -25,6 +25,7 @@ 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 0905ca66cd..be7dce499b 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,8 +2,6 @@ // 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; @@ -16,6 +14,7 @@ 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'; @@ -29,41 +28,44 @@ 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 bool debugDisableOverlays = false; + 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)); + } + } - /// The set of platform views using the backup surface. - final Set _viewsUsingBackupSurface = {}; + static bool _debugOverlaysDisabled = 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 = - []; + /// 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; - /// 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 context for the current frame. + EmbedderFrameContext _context = EmbedderFrameContext(); /// The most recent composition parameters for a given view id. /// @@ -92,11 +94,6 @@ 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 = []; @@ -118,43 +115,36 @@ 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. - 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; + Iterable getOverlayCanvases() { + return _context.pictureRecordersCreatedDuringPreroll + .map((CkPictureRecorder r) => r.recordingCanvas!); } void prerollCompositeEmbeddedView(int viewId, EmbeddedViewParams params) { - 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); - } + 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); } // Do nothing if the params didn't change. @@ -175,38 +165,33 @@ 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 = _visibleViewCount; + final int overlayIndex = _context.visibleViewCount; _compositionOrder.add(viewId); - if (platformViewManager.isVisible(viewId)) { - _visibleViewCount++; + if (platformViewManager.isVisible(viewId) || + _context.pictureRecorders.isEmpty) { + _context.visibleViewCount++; } - final bool needOverlay = - !disableOverlays && platformViewManager.isVisible(viewId); - if (needOverlay) { - if (overlayIndex < _pictureRecordersCreatedDuringPreroll.length) { - _pictureRecorders[viewId] = - _pictureRecordersCreatedDuringPreroll[overlayIndex]; - } else { - _viewsUsingBackupSurface.add(viewId); - _pictureRecorders[viewId] = _backupPictureRecorder!; + // 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; + } + CkPictureRecorder? recorderToUseForRendering; + if (needNewOverlay) { + if (overlayIndex < _context.pictureRecordersCreatedDuringPreroll.length) { + recorderToUseForRendering = + _context.pictureRecordersCreatedDuringPreroll[overlayIndex]; + _context.pictureRecorders.add(recorderToUseForRendering); } } - // 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; + if (_viewsToRecomposite.contains(viewId)) { + _compositeWithParams(viewId, _currentCompositionParams[viewId]!); + _viewsToRecomposite.remove(viewId); } + return recorderToUseForRendering?.recordingCanvas; } void _compositeWithParams(int viewId, EmbeddedViewParams params) { @@ -294,8 +279,7 @@ 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) { @@ -315,8 +299,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); @@ -351,8 +335,7 @@ 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 @@ -370,8 +353,7 @@ 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 @@ -399,8 +381,7 @@ 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. @@ -431,54 +412,36 @@ class HtmlViewEmbedder { } void submitFrame() { - 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); + final ViewListDiffResult? diffResult = + (_activeCompositionOrder.isEmpty || _compositionOrder.isEmpty) + ? null + : diffViewList(_activeCompositionOrder, _compositionOrder); + _updateOverlays(diffResult); + assert(_context.pictureRecorders.length == _overlays.length); + int pictureRecorderIndex = 0; - 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 (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(); } } - _pictureRecordersCreatedDuringPreroll.clear(); - _pictureRecorders.clear(); - _viewsUsingBackupSurface.clear(); + for (final CkPictureRecorder recorder + in _context.pictureRecordersCreatedDuringPreroll) { + if (recorder.isRecording) { + recorder.endRecording(); + } + } + // Reset the context. + _context = EmbedderFrameContext(); if (listEquals(_compositionOrder, _activeCompositionOrder)) { _compositionOrder.clear(); - _visibleViewCount = 0; return; } @@ -488,7 +451,12 @@ class HtmlViewEmbedder { List? debugInvalidViewIds; if (diffResult != null) { - disposeViews(diffResult.viewsToRemove.toSet()); + // 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()); _activeCompositionOrder.addAll(_compositionOrder); unusedViews.removeAll(_compositionOrder); @@ -523,19 +491,23 @@ class HtmlViewEmbedder { } } } - 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); + // 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); + } + } } - }); - if (_didPaintBackupSurface) { - skiaSceneHost! - .append(SurfaceFactory.instance.backupSurface.htmlElement); } } else { SurfaceFactory.instance.removeSurfacesFromDom(); @@ -559,19 +531,12 @@ 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( @@ -603,128 +568,105 @@ class HtmlViewEmbedder { } } - // Called right before compositing the scene. + // 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. // // [_compositionOrder] and [_activeComposition] order should contain the // composition order of the current and previous frame, respectively. // // TODO(hterkelsen): Test this more thoroughly. - Map? _updateOverlays(ViewListDiffResult? diffResult) { - if (_viewsUsingBackupSurface.isEmpty) { - SurfaceFactory.instance - .releaseSurface(SurfaceFactory.instance.backupSurface); - } + void _updateOverlays(ViewListDiffResult? diffResult) { if (diffResult != null && diffResult.viewsToAdd.isEmpty && diffResult.viewsToRemove.isEmpty) { - return null; + // The composition order has not changed, continue using the assigned + // overlays. + return; } + 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 the first N surfaces where - // N = [SurfaceFactory.instance.maximumOverlays] and assign the rest - // to the backup surface. + // the surfaces and assign an overlay to all the surfaces needing one. SurfaceFactory.instance.releaseSurfaces(); _overlays.clear(); - 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; + viewsNeedingOverlays.forEach(_initializeOverlay); } else { // We want to preserve the overlays in the "unchanged" section of the - // 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--; - } - } + // 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. - // 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; - } + // 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); } + assert(_overlays.length == viewsNeedingOverlays.length); } - 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); + // 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); + } } } + 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) && - !_viewsUsingBackupSurface.contains(viewId)); + assert(!_overlays.containsKey(viewId)); // Try reusing a cached overlay created for another platform view. final Surface overlay = SurfaceFactory.instance.getOverlay()!; @@ -736,7 +678,9 @@ 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); } } @@ -751,11 +695,7 @@ class HtmlViewEmbedder { void debugClear() { final Set allViews = platformViewManager.debugClear(); disposeViews(allViews); - _backupPictureRecorder?.endRecording(); - _backupPictureRecorder = null; - _viewsUsingBackupSurface.clear(); - _pictureRecordersCreatedDuringPreroll.clear(); - _pictureRecorders.clear(); + _context = EmbedderFrameContext(); _currentCompositionParams.clear(); debugCleanupSvgClipPaths(); _currentCompositionParams.clear(); @@ -764,7 +704,6 @@ class HtmlViewEmbedder { _viewsToRecomposite.clear(); _activeCompositionOrder.clear(); _compositionOrder.clear(); - _visibleViewCount = 0; } } @@ -944,99 +883,28 @@ class MutatorsStack extends Iterable { Iterator get iterator => _mutators.reversed.iterator; } -/// 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; +/// 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; - /// Views to add to the scene. - final List viewsToAdd; + /// Whether or not we have seen a visible platform view in this frame yet. + bool seenFirstVisibleView = false; - /// 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. + /// Picture recorders which were created during the preroll phase. /// - /// `null` if [addToBeginning] is `false`. - final int? viewToInsertBefore; + /// These picture recorders will be "claimed" in the paint phase by platform + /// views being composited into the scene. + final List pictureRecordersCreatedDuringPreroll = + []; - 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; + /// 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; } 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 new file mode 100644 index 0000000000..f5cce723f2 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/embedded_views_diff.dart @@ -0,0 +1,161 @@ +// 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 046fb49c84..8e8462a05b 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,11 +48,9 @@ class LayerTree { void paint(Frame frame, {bool ignoreRasterCache = false}) { final CkNWayCanvas internalNodesCanvas = CkNWayCanvas(); internalNodesCanvas.addCanvas(frame.canvas); - final List overlayCanvases = + final Iterable overlayCanvases = frame.viewEmbedder!.getOverlayCanvases(); - for (int i = 0; i < overlayCanvases.length; i++) { - internalNodesCanvas.addCanvas(overlayCanvases[i]); - } + overlayCanvases.forEach(internalNodesCanvas.addCanvas); // 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 2a5aefecf0..0ea08af2cc 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,6 +1,7 @@ // 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'; @@ -19,12 +20,23 @@ 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(this.maximumSurfaces) - : assert(maximumSurfaces >= 1, - 'The maximum number of surfaces must be at least 1') { + SurfaceFactory(int maximumSurfaces) + : maximumSurfaces = math.max(maximumSurfaces, 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); } } @@ -34,17 +46,14 @@ 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 - 2` (the maximum number of surfaces minus - /// the base surface and backup surface). - int get maximumOverlays => maximumSurfaces - 2; + /// This is just `maximumSurfaces - 1` (the maximum number of surfaces minus + /// the required base surface). + int get maximumOverlays => maximumSurfaces - 1; /// Surfaces created by this factory which are currently in use. final List _liveSurfaces = []; @@ -54,11 +63,11 @@ class SurfaceFactory { final List _cache = []; /// The number of surfaces which have been created by this factory. - int get _surfaceCount => _liveSurfaces.length + _cache.length + 2; + int get _surfaceCount => _liveSurfaces.length + _cache.length + 1; /// The number of available overlay surfaces. /// - /// This does not include the base surface or backup surface. + /// This does not include the base surface. int get numAvailableOverlays => maximumOverlays - _liveSurfaces.length; /// The number of surfaces created by this factory. Used for testing. @@ -70,10 +79,6 @@ 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() { @@ -90,29 +95,6 @@ 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 @@ -130,7 +112,6 @@ class SurfaceFactory { /// the new surfaces. void removeSurfacesFromDom() { _cache.forEach(_removeFromDom); - _removeFromDom(backupSurface); } // Removes [surface] from the DOM. @@ -141,11 +122,6 @@ 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 ' @@ -157,13 +133,12 @@ class SurfaceFactory { /// Returns [true] if [surface] is currently being used to paint content. /// - /// The base surface and backup surface always count as live. + /// The base surface always counts 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; } @@ -180,7 +155,6 @@ 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 1870e9c9ff..3eabd99404 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 new file mode 100644 index 0000000000..cb5edda0d1 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/embedded_views_diff_test.dart @@ -0,0 +1,130 @@ +// 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 d9b2cf47ca..6c68f4bb19 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,7 +77,9 @@ 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( @@ -118,8 +120,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, @@ -143,8 +145,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)'); @@ -188,8 +190,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), @@ -209,8 +211,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), @@ -240,8 +242,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), @@ -269,8 +271,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), @@ -284,6 +286,7 @@ 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()); @@ -291,7 +294,7 @@ void testMain() { // Initialize all platform views to be used in the test. final List platformViewIds = []; - for (int i = 0; i < configuration.canvasKitMaximumSurfaces * 2; i++) { + for (int i = 0; i < 16; i++) { ui.platformViewRegistry.registerViewFactory( 'test-platform-view', (int viewId) => html.DivElement()..id = 'view-$i', @@ -313,43 +316,95 @@ 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: configuration.canvasKitMaximumSurfaces); - expect(countCanvases(), configuration.canvasKitMaximumSurfaces); + renderTestScene(viewCount: 8); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + overlay, + platformView, + overlay, + platformView, + overlay, + platformView, + overlay, + platformView, + overlay, + platformView, + overlay, + platformView, + platformView, + overlay, + ]); // Frame 2: // Render: zero platform views. // Expect: main canvas, no overlays. await Future.delayed(Duration.zero); renderTestScene(viewCount: 0); - expect(countCanvases(), 1); + expectSceneMatches(<_EmbeddedViewMarker>[overlay]); // Frame 3: // Render: less than cache size platform views. // Expect: overlays reused. await Future.delayed(Duration.zero); - renderTestScene(viewCount: configuration.canvasKitMaximumSurfaces - 2); - expect(countCanvases(), configuration.canvasKitMaximumSurfaces - 1); + renderTestScene(viewCount: 6); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + overlay, + platformView, + overlay, + platformView, + overlay, + platformView, + overlay, + platformView, + overlay, + platformView, + overlay, + ]); // Frame 4: // Render: more platform views than max cache size. // Expect: main canvas, backup overlay, maximum overlays. await Future.delayed(Duration.zero); - renderTestScene(viewCount: configuration.canvasKitMaximumSurfaces * 2); - expect(countCanvases(), configuration.canvasKitMaximumSurfaces); + 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, + ]); // Frame 5: // Render: zero platform views. // Expect: main canvas, no overlays. await Future.delayed(Duration.zero); renderTestScene(viewCount: 0); - expect(countCanvases(), 1); + expectSceneMatches(<_EmbeddedViewMarker>[overlay]); // Frame 6: // Render: deleted platform views. @@ -383,6 +438,7 @@ 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); @@ -416,29 +472,110 @@ 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(countCanvases(), configuration.canvasKitMaximumSurfaces); + 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, + ]); // 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(countCanvases(), configuration.canvasKitMaximumSurfaces); + 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, + ]); // 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]); - expect(countCanvases(), configuration.canvasKitMaximumSurfaces); + 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, + ]); // TODO(yjbanov): skipped due to https://github.com/flutter/flutter/issues/73867 }, skip: isSafari); @@ -457,13 +594,15 @@ 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.sceneElement!.querySelector('flt-platform-view-slot'), - isNotNull, - ); - expect( - flutterViewEmbedder.glassPaneElement!.querySelector('flt-platform-view'), + flutterViewEmbedder.glassPaneElement! + .querySelector('flt-platform-view'), isNotNull, ); @@ -473,12 +612,13 @@ void testMain() { sb.pushOffset(0, 0); dispatcher.rasterizer!.draw(sb.build().layerTree); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + ]); + expect( - flutterViewEmbedder.sceneElement!.querySelector('flt-platform-view-slot'), - isNull, - ); - expect( - flutterViewEmbedder.glassPaneElement!.querySelector('flt-platform-view'), + flutterViewEmbedder.glassPaneElement! + .querySelector('flt-platform-view'), isNull, ); }); @@ -497,13 +637,15 @@ 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.sceneElement!.querySelector('flt-platform-view-slot'), - isNotNull, - ); - expect( - flutterViewEmbedder.glassPaneElement!.querySelector('flt-platform-view'), + flutterViewEmbedder.glassPaneElement! + .querySelector('flt-platform-view'), isNotNull, ); @@ -513,12 +655,15 @@ 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.sceneElement!.querySelectorAll('flt-platform-view-slot'), - hasLength(1)); - expect( - flutterViewEmbedder.glassPaneElement!.querySelectorAll('flt-platform-view'), + flutterViewEmbedder.glassPaneElement! + .querySelectorAll('flt-platform-view'), hasLength(2)); // Render a frame without a platform view, but also without disposing of @@ -526,17 +671,16 @@ 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!.querySelector('flt-platform-view'), - isNotNull, - ); + flutterViewEmbedder.glassPaneElement! + .querySelectorAll('flt-platform-view'), + hasLength(2)); }); test( @@ -577,95 +721,6 @@ 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( @@ -684,10 +739,9 @@ void testMain() { sb.pop(); // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expect( - flutterViewEmbedder.glassPaneShadow! - .querySelectorAll('flt-platform-view-slot'), - isEmpty); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + ]); }); test('does not crash when overlays are disabled', () async { @@ -707,10 +761,10 @@ void testMain() { sb.pop(); // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expect( - flutterViewEmbedder.glassPaneShadow! - .querySelectorAll('flt-platform-view-slot'), - hasLength(1)); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + ]); HtmlViewEmbedder.debugDisableOverlays = false; }); @@ -720,7 +774,7 @@ void testMain() { SurfaceFactory.instance.debugClear(); expect(SurfaceFactory.instance.maximumSurfaces, 2); - expect(SurfaceFactory.instance.maximumOverlays, 0); + expect(SurfaceFactory.instance.maximumOverlays, 1); ui.platformViewRegistry.registerViewFactory( 'test-platform-view', @@ -739,10 +793,11 @@ void testMain() { // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expect( - flutterViewEmbedder.glassPaneShadow! - .querySelectorAll('flt-platform-view-slot'), - hasLength(1)); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + overlay, + ]); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -752,10 +807,12 @@ void testMain() { // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expect( - flutterViewEmbedder.glassPaneShadow! - .querySelectorAll('flt-platform-view-slot'), - hasLength(2)); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + platformView, + overlay, + ]); // Reset configuration debugSetConfiguration(FlutterConfiguration(null)); @@ -782,11 +839,11 @@ void testMain() { sb.pop(); // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - - expect( - flutterViewEmbedder.glassPaneShadow! - .querySelectorAll('flt-platform-view-slot'), - hasLength(2)); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + platformView, + ]); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -794,10 +851,10 @@ void testMain() { sb.pop(); // The below line should not throw an error. dispatcher.rasterizer!.draw(sb.build().layerTree); - expect( - flutterViewEmbedder.glassPaneShadow! - .querySelectorAll('flt-platform-view-slot'), - hasLength(1)); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + ]); HtmlViewEmbedder.debugDisableOverlays = false; }); @@ -824,10 +881,6 @@ 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); @@ -836,7 +889,11 @@ void testMain() { sb.addPlatformView(1, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expect(countCanvases(), 1); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + overlay, + ]); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -844,7 +901,12 @@ void testMain() { sb.addPlatformView(1, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expect(countCanvases(), 2); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + platformView, + overlay, + ]); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -853,7 +915,14 @@ void testMain() { sb.addPlatformView(2, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expect(countCanvases(), 3); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + platformView, + overlay, + platformView, + overlay, + ]); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -863,7 +932,15 @@ void testMain() { sb.addPlatformView(3, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expect(countCanvases(), 3); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + platformView, + overlay, + platformView, + platformView, + overlay, + ]); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -874,7 +951,16 @@ void testMain() { sb.addPlatformView(4, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expect(countCanvases(), 3); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + platformView, + overlay, + platformView, + platformView, + platformView, + overlay, + ]); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -886,7 +972,17 @@ void testMain() { sb.addPlatformView(5, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expect(countCanvases(), 3); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + platformView, + overlay, + platformView, + platformView, + platformView, + platformView, + overlay, + ]); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -899,7 +995,18 @@ void testMain() { sb.addPlatformView(6, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expect(countCanvases(), 3); + expectSceneMatches(<_EmbeddedViewMarker>[ + overlay, + platformView, + platformView, + overlay, + platformView, + platformView, + platformView, + platformView, + platformView, + overlay, + ]); sb = LayerSceneBuilder(); sb.pushOffset(0, 0); @@ -910,8 +1017,78 @@ void testMain() { sb.addPlatformView(6, width: 10, height: 10); sb.pop(); dispatcher.rasterizer!.draw(sb.build().layerTree); - expect(countCanvases(), 1); + 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, + ]); }); // 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 b5b4608e0a..141f9df94a 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.getSurface(); + final Surface surface = SurfaceFactory.instance.getOverlay()!; 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 c312aca45a..bdefb5a921 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,7 +7,6 @@ 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(); @@ -21,32 +20,27 @@ void testMain() { setUpCanvasKitTest(); test('cannot be created with size less than 1', () { - expect(() => SurfaceFactory(-1), throwsAssertionError); - expect(() => SurfaceFactory(0), throwsAssertionError); - expect(SurfaceFactory(1), isNotNull); - expect(SurfaceFactory(2), isNotNull); + expect(SurfaceFactory(-1).maximumSurfaces, 1); + expect(SurfaceFactory(0).maximumSurfaces, 1); + expect(SurfaceFactory(1).maximumSurfaces, 1); + expect(SurfaceFactory(2).maximumSurfaces, 2); }); - test('getSurface', () { + test('getOverlay', () { final SurfaceFactory factory = SurfaceFactory(3); expect(factory.baseSurface, isNotNull); - expect(factory.backupSurface, isNotNull); - expect(factory.baseSurface, isNot(equals(factory.backupSurface))); + + 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.debugSurfaceCount, equals(2)); - // 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(); + // Get another surface from the factory. Now we are at maximum capacity. + final Surface? anotherSurface = factory.getOverlay(); expect(anotherSurface, isNot(equals(factory.baseSurface))); - expect(anotherSurface, equals(factory.backupSurface)); expect(factory.debugSurfaceCount, equals(3)); }); @@ -55,12 +49,12 @@ void testMain() { final SurfaceFactory factory = SurfaceFactory(3); // Create a new surface and immediately release it. - final Surface surface = factory.getSurface(); - factory.releaseSurface(surface); + final Surface? surface = factory.getOverlay(); + factory.releaseSurface(surface!); // If we create a new surface, it should be the same as the one we // just created. - final Surface newSurface = factory.getSurface(); + final Surface? newSurface = factory.getOverlay(); expect(newSurface, equals(surface)); }); @@ -68,10 +62,9 @@ void testMain() { final SurfaceFactory factory = SurfaceFactory(3); expect(factory.isLive(factory.baseSurface), isTrue); - expect(factory.isLive(factory.backupSurface), isTrue); - final Surface surface = factory.getSurface(); - expect(factory.isLive(surface), isTrue); + final Surface? surface = factory.getOverlay(); + expect(factory.isLive(surface!), isTrue); factory.releaseSurface(surface); expect(factory.isLive(surface), isFalse); @@ -93,23 +86,18 @@ void testMain() { // Create a few overlay surfaces final List overlays = []; for (int i = 0; i < 3; i++) { - overlays.add(originalFactory.getSurface() + overlays.add(originalFactory.getOverlay()! ..acquireFrame(const ui.Size(10, 10)) ..addToScene()); } - expect(originalFactory.debugSurfaceCount, 5); - - originalFactory.backupSurface.acquireFrame(const ui.Size(10, 10)); - originalFactory.backupSurface.addToScene(); - expect(originalFactory.backupSurface.htmlCanvas!.isConnected, isTrue); + expect(originalFactory.debugSurfaceCount, 4); // 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, 2); + expect(originalFactory.debugSurfaceCount, 1); }); // 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 73a7274fdc..123fff0151 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.getSurface(); + final Surface? surface = SurfaceFactory.instance.getOverlay(); 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.getSurface(); - expect(surface.debugForceNewContext, isTrue); + final Surface? surface = SurfaceFactory.instance.getOverlay(); + expect(surface!.debugForceNewContext, isTrue); final CkSurface before = surface.acquireFrame(const ui.Size(9, 19)).skiaSurface; expect(surface.debugForceNewContext, isFalse);