From d40fdb6114b740520b2f5a08afedca50e15b1372 Mon Sep 17 00:00:00 2001 From: Harry Terkelsen Date: Wed, 8 Sep 2021 09:45:21 -0700 Subject: [PATCH] [canvaskit] Optimize CanvasKit platform views in special cases (flutter/engine#28087) --- .../src/engine/canvaskit/embedded_views.dart | 341 +++++++++++++++--- .../src/engine/canvaskit/surface_factory.dart | 55 ++- .../test/canvaskit/embedded_views_test.dart | 56 +++ 3 files changed, 380 insertions(+), 72 deletions(-) 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 9e62d9320e..905e62fd37 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 @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'dart:html' as html; +import 'dart:math' as math; import 'package:ui/ui.dart' as ui; @@ -106,7 +107,13 @@ class HtmlViewEmbedder { void prerollCompositeEmbeddedView(int viewId, EmbeddedViewParams params) { if (!disableOverlays) { - _ensureOverlayInitialized(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. + _viewsUsingBackupSurface.remove(viewId); + if (_compositionOrder.length >= SurfaceFactory.instance.maximumOverlays) { + _viewsUsingBackupSurface.add(viewId); + } if (_viewsUsingBackupSurface.contains(viewId)) { if (_backupPictureRecorder == null) { // Only initialize the picture recorder for the backup surface once. @@ -374,6 +381,12 @@ class HtmlViewEmbedder { } void submitFrame() { + final ViewListDiffResult? diffResult = + (_activeCompositionOrder.isEmpty || _compositionOrder.isEmpty) + ? null + : diffViewList(_activeCompositionOrder, _compositionOrder); + final Map? insertBeforeMap = _updateOverlays(diffResult); + bool _didPaintBackupSurface = false; if (!disableOverlays) { for (int i = 0; i < _compositionOrder.length; i++) { @@ -400,46 +413,100 @@ class HtmlViewEmbedder { } } } + _pictureRecorders.clear(); + _viewsUsingBackupSurface.clear(); if (listEquals(_compositionOrder, _activeCompositionOrder)) { _compositionOrder.clear(); return; } - SurfaceFactory.instance.removeSurfacesFromDom(); final Set unusedViews = Set.from(_activeCompositionOrder); _activeCompositionOrder.clear(); List? debugInvalidViewIds; - for (int i = 0; i < _compositionOrder.length; i++) { - final int viewId = _compositionOrder[i]; - if (assertionsEnabled) { - if (!platformViewManager.knowsViewId(viewId)) { - debugInvalidViewIds ??= []; - debugInvalidViewIds.add(viewId); - continue; + if (diffResult != null) { + disposeViews(diffResult.viewsToRemove.toSet()); + _activeCompositionOrder.addAll(_compositionOrder); + unusedViews.removeAll(_compositionOrder); + + html.Element? elementToInsertBefore; + if (diffResult.addToBeginning) { + elementToInsertBefore = + _viewClipChains[diffResult.viewToInsertBefore!]!.root; + } + + for (final int viewId in diffResult.viewsToAdd) { + if (assertionsEnabled) { + if (!platformViewManager.knowsViewId(viewId)) { + debugInvalidViewIds ??= []; + debugInvalidViewIds.add(viewId); + continue; + } + } + if (diffResult.addToBeginning) { + final html.Element platformViewRoot = _viewClipChains[viewId]!.root; + skiaSceneHost!.insertBefore(platformViewRoot, elementToInsertBefore); + final Surface? overlay = _overlays[viewId]; + if (overlay != null) { + skiaSceneHost! + .insertBefore(overlay.htmlElement, elementToInsertBefore); + } + } else { + final html.Element platformViewRoot = _viewClipChains[viewId]!.root; + skiaSceneHost!.append(platformViewRoot); + final Surface? overlay = _overlays[viewId]; + if (overlay != null) { + skiaSceneHost!.append(overlay.htmlElement); + } } } - - unusedViews.remove(viewId); - final html.Element platformViewRoot = _viewClipChains[viewId]!.root; - platformViewRoot.remove(); - skiaSceneHost!.append(platformViewRoot); - if (!disableOverlays) { + insertBeforeMap?.forEach((int viewId, int viewIdToInsertBefore) { final html.Element overlay = _overlays[viewId]!.htmlElement; - overlay.remove(); - skiaSceneHost!.append(overlay); + if (viewIdToInsertBefore != -1) { + final html.Element nextSibling = + _viewClipChains[viewIdToInsertBefore]!.root; + skiaSceneHost!.insertBefore(overlay, nextSibling); + } else { + skiaSceneHost!.append(overlay); + } + }); + if (_didPaintBackupSurface) { + skiaSceneHost! + .append(SurfaceFactory.instance.backupSurface.htmlElement); + } + } else { + SurfaceFactory.instance.removeSurfacesFromDom(); + for (int i = 0; i < _compositionOrder.length; i++) { + final int viewId = _compositionOrder[i]; + + if (assertionsEnabled) { + if (!platformViewManager.knowsViewId(viewId)) { + debugInvalidViewIds ??= []; + debugInvalidViewIds.add(viewId); + continue; + } + } + + final html.Element platformViewRoot = _viewClipChains[viewId]!.root; + final Surface? overlay = _overlays[viewId]; + skiaSceneHost!.append(platformViewRoot); + if (overlay != null) { + skiaSceneHost!.append(overlay.htmlElement); + } + _activeCompositionOrder.add(viewId); + } + if (_didPaintBackupSurface) { + skiaSceneHost! + .append(SurfaceFactory.instance.backupSurface.htmlElement); } - _activeCompositionOrder.add(viewId); - } - if (_didPaintBackupSurface) { - skiaSceneHost!.append(SurfaceFactory.instance.backupSurface.htmlElement); } _compositionOrder.clear(); disposeViews(unusedViews); - _releaseOverlays(); + + _pictureRecorders.clear(); if (assertionsEnabled) { if (debugInvalidViewIds != null && debugInvalidViewIds.isNotEmpty) { @@ -464,52 +531,131 @@ class HtmlViewEmbedder { } } - void _releaseOverlays() { - _pictureRecorders.clear(); - _overlays.clear(); - _viewsUsingBackupSurface.clear(); - SurfaceFactory.instance.releaseSurfaces(); - } - void _releaseOverlay(int viewId) { if (_overlays[viewId] != null) { final Surface overlay = _overlays[viewId]!; - if (overlay == SurfaceFactory.instance.backupSurface) { - assert(_viewsUsingBackupSurface.contains(viewId)); - _viewsUsingBackupSurface.remove(viewId); - _overlays.remove(viewId); - // If no views use the backup surface, then we can release it. This - // happens when the number of live platform views drops below the - // maximum overlay surfaces, so the backup surface is no longer needed. - if (_viewsUsingBackupSurface.isEmpty) { - SurfaceFactory.instance.releaseSurface(overlay); + SurfaceFactory.instance.releaseSurface(overlay); + _overlays.remove(viewId); + } + } + + // Called right before compositing the scene. + // + // [_compositionOrder] and [_activeComposition] order should contain the + // composition order of the current and previous frame, respectively. + Map? _updateOverlays(ViewListDiffResult? diffResult) { + if (_viewsUsingBackupSurface.isEmpty) { + SurfaceFactory.instance + .releaseSurface(SurfaceFactory.instance.backupSurface); + } + if (diffResult != null && + diffResult.viewsToAdd.isEmpty && + diffResult.viewsToRemove.isEmpty) { + return null; + } + 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. + SurfaceFactory.instance.releaseSurfaces(); + _overlays.clear(); + final int numOverlays = math.min( + SurfaceFactory.instance.maximumOverlays, + _compositionOrder.length, + ); + for (int i = 0; i < numOverlays; i++) { + final int viewId = _compositionOrder[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. 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 = 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--; + } } + + // 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 { - SurfaceFactory.instance.releaseSurface(overlay); - _overlays.remove(viewId); + // 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)) { + _initializeOverlay(viewId); + overlaysToAssign--; + if (activeView) { + if (index + 1 < _compositionOrder.length) { + insertBeforeMap[viewId] = _compositionOrder[index + 1]; + } else { + insertBeforeMap[viewId] = -1; + } + } + } + index++; + } + _assertOverlaysInitialized(); + return insertBeforeMap; } } } - void _ensureOverlayInitialized(int viewId) { - // If there's an active overlay for the view ID, continue using it. - Surface? overlay = _overlays[viewId]; - if (overlay != null && !_viewsUsingBackupSurface.contains(viewId)) { - overlay.createOrUpdateSurfaces(_frameSize); - return; + void _assertOverlaysInitialized() { + if (assertionsEnabled) { + for (int i = 0; i < _compositionOrder.length; i++) { + final int viewId = _compositionOrder[i]; + assert(_viewsUsingBackupSurface.contains(viewId) || + _overlays[viewId] != null); + } } + } - // If this view was using the backup surface, try to release the backup - // surface and see if a non-backup surface became available. - if (_viewsUsingBackupSurface.contains(viewId)) { - _releaseOverlay(viewId); - } + void _initializeOverlay(int viewId) { + assert(!_overlays.containsKey(viewId) && + !_viewsUsingBackupSurface.contains(viewId)); // Try reusing a cached overlay created for another platform view. - overlay = SurfaceFactory.instance.getSurface(); - if (overlay == SurfaceFactory.instance.backupSurface) { - _viewsUsingBackupSurface.add(viewId); - } + final Surface overlay = SurfaceFactory.instance.getOverlay()!; overlay.createOrUpdateSurfaces(_frameSize); _overlays[viewId] = overlay; } @@ -718,3 +864,88 @@ class MutatorsStack extends Iterable { @override 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; + + /// 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) { + assert(active.isNotEmpty && next.isNotEmpty, + 'diffViewList called with empty view list'); + // 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); + } + } + } + return ViewListDiffResult( + active.sublist(0, index), + next.sublist(active.length - index), + 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; + } + } + return ViewListDiffResult( + active.sublist(index + 1), + next.sublist(0, next.length - index - 1), + true, + viewToInsertBefore: active.first, + ); + } + + return null; +} 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 a6ec4bb814..a741624572 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 @@ -29,6 +29,12 @@ class SurfaceFactory { /// 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; + /// Surfaces created by this factory which are currently in use. final List _liveSurfaces = []; @@ -39,6 +45,11 @@ class SurfaceFactory { /// The number of surfaces which have been created by this factory. int get _surfaceCount => _liveSurfaces.length + _cache.length + 2; + /// The number of available overlay surfaces. + /// + /// 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. @visibleForTesting int get debugSurfaceCount => _surfaceCount; @@ -52,15 +63,9 @@ class SurfaceFactory { /// surfaces. bool _warnedAboutTooManySurfaces = false; - /// 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() { + /// 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() { if (_cache.isNotEmpty) { final Surface surface = _cache.removeLast(); _liveSurfaces.add(surface); @@ -70,17 +75,33 @@ class SurfaceFactory { _liveSurfaces.add(surface); return surface; } else { - 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; + return null; } } + /// 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 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 e754166b3d..ad67231d02 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 @@ -498,6 +498,62 @@ void testMain() { renderTestScene(); 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); + }); // TODO(dit): https://github.com/flutter/flutter/issues/60040 }, skip: isIosSafari); }