[web] Migrate Flutter Web DOM usage to JS static interop - 4 (flutter/engine#32938)

* [web] Migrate Flutter Web DOM usage to JS static interop - 3.

* [web] Migrate Flutter Web DOM usage to JS static interop - 4.
This commit is contained in:
joshualitt
2022-05-05 08:31:29 -07:00
committed by GitHub
parent 0bdde39716
commit de2d4ad277
6 changed files with 167 additions and 61 deletions

View File

@@ -13,13 +13,13 @@
library canvaskit_api;
import 'dart:async';
import 'dart:html' as html;
import 'dart:js' as js;
import 'dart:typed_data';
import 'package:js/js.dart';
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../profiler.dart';
/// Entrypoint into the CanvasKit API.
@@ -132,7 +132,7 @@ extension CanvasKitExtension on CanvasKit {
external TypefaceFontProviderNamespace get TypefaceFontProvider;
external SkTypefaceFactory get Typeface;
external int GetWebGLContext(
html.CanvasElement canvas, SkWebGLContextOptions options);
DomCanvasElement canvas, SkWebGLContextOptions options);
external SkGrContext MakeGrContext(int glContext);
external SkSurface? MakeOnScreenGLSurface(
SkGrContext grContext,
@@ -140,7 +140,7 @@ extension CanvasKitExtension on CanvasKit {
int height,
ColorSpace colorSpace,
);
external SkSurface MakeSWCanvasSurface(html.CanvasElement canvas);
external SkSurface MakeSWCanvasSurface(DomCanvasElement canvas);
/// Creates an image from decoded pixels represented as a list of bytes.
///
@@ -2332,7 +2332,7 @@ class ProductionCollector implements Collector {
/// emptied out to prevent memory leaks. This may happen, for example, when the
/// same object is deleted more than once.
void collectSkiaObjectsNow() {
html.window.performance.mark('SkObject collection-start');
domWindow.performance.mark('SkObject collection-start');
final int length = _skiaObjectCollectionQueue.length;
dynamic firstError;
StackTrace? firstStackTrace;
@@ -2364,8 +2364,8 @@ class ProductionCollector implements Collector {
}
_skiaObjectCollectionQueue = <SkDeletable>[];
html.window.performance.mark('SkObject collection-end');
html.window.performance.measure('SkObject collection',
domWindow.performance.mark('SkObject collection-end');
domWindow.performance.measure('SkObject collection',
'SkObject collection-start', 'SkObject collection-end');
// It's safe to throw the error here, now that we've processed the queue.
@@ -2539,14 +2539,14 @@ extension SkPartialImageInfoExtension on SkPartialImageInfo {
// TODO(hterkelsen): Rather than this monkey-patch hack, we should
// build CanvasKit ourselves. See:
// https://github.com/flutter/flutter/issues/52588
void patchCanvasKitModule(html.ScriptElement canvasKitScript) {
void patchCanvasKitModule(DomHTMLScriptElement canvasKitScript) {
// First check if `exports` and `module` are already defined. If so, then
// CommonJS is being used, and we shouldn't have any problems.
final js.JsFunction objectConstructor = js.context['Object'] as js.JsFunction;
if (js.context['exports'] == null) {
final js.JsObject exportsAccessor = js.JsObject.jsify(<String, dynamic>{
'get': allowInterop(() {
if (html.document.currentScript == canvasKitScript) {
if (domDocument.currentScript == canvasKitScript) {
return js.JsObject(objectConstructor);
} else {
return js.context['_flutterWebCachedExports'];
@@ -2563,7 +2563,7 @@ void patchCanvasKitModule(html.ScriptElement canvasKitScript) {
if (js.context['module'] == null) {
final js.JsObject moduleAccessor = js.JsObject.jsify(<String, dynamic>{
'get': allowInterop(() {
if (html.document.currentScript == canvasKitScript) {
if (domDocument.currentScript == canvasKitScript) {
return js.JsObject(objectConstructor);
} else {
return js.context['_flutterWebCachedModule'];
@@ -2577,5 +2577,5 @@ void patchCanvasKitModule(html.ScriptElement canvasKitScript) {
objectConstructor.callMethod(
'defineProperty', <dynamic>[js.context, 'module', moduleAccessor]);
}
html.document.head!.append(canvasKitScript);
domDocument.head!.appendChild(canvasKitScript);
}

View File

@@ -509,19 +509,20 @@ class HtmlViewEmbedder {
final Surface? overlay = _overlays[viewId];
if (overlay != null) {
skiaSceneHost!
.insertBefore(overlay.htmlElement, elementToInsertBefore);
.insertBefore(overlay.htmlElement as html.Element, elementToInsertBefore);
}
} else {
final html.Element platformViewRoot = _viewClipChains[viewId]!.root;
skiaSceneHost!.append(platformViewRoot);
final Surface? overlay = _overlays[viewId];
if (overlay != null) {
skiaSceneHost!.append(overlay.htmlElement);
skiaSceneHost!.append(overlay.htmlElement as html.Element);
}
}
}
insertBeforeMap?.forEach((int viewId, int viewIdToInsertBefore) {
final html.Element overlay = _overlays[viewId]!.htmlElement;
final html.Element overlay = _overlays[viewId]!.htmlElement as
html.Element;
if (viewIdToInsertBefore != -1) {
final html.Element nextSibling =
_viewClipChains[viewIdToInsertBefore]!.root;
@@ -532,7 +533,8 @@ class HtmlViewEmbedder {
});
if (_didPaintBackupSurface) {
skiaSceneHost!
.append(SurfaceFactory.instance.backupSurface.htmlElement);
.append(SurfaceFactory.instance.backupSurface.htmlElement as
html.Element);
}
} else {
SurfaceFactory.instance.removeSurfacesFromDom();
@@ -551,14 +553,15 @@ class HtmlViewEmbedder {
final Surface? overlay = _overlays[viewId];
skiaSceneHost!.append(platformViewRoot);
if (overlay != null) {
skiaSceneHost!.append(overlay.htmlElement);
skiaSceneHost!.append(overlay.htmlElement as html.Element);
}
_activeCompositionOrder.add(viewId);
unusedViews.remove(viewId);
}
if (_didPaintBackupSurface) {
skiaSceneHost!
.append(SurfaceFactory.instance.backupSurface.htmlElement);
.append(SurfaceFactory.instance.backupSurface.htmlElement as
html.Element);
}
}

View File

@@ -9,6 +9,7 @@ import 'dart:html' as html;
import '../../engine.dart' show kProfileMode;
import '../browser_detection.dart';
import '../configuration.dart';
import '../dom.dart';
import '../safe_browser_api.dart';
import 'canvaskit_api.dart';
import 'fonts.dart';
@@ -91,15 +92,17 @@ Future<void> _downloadCanvasKitJs({String? canvasKitBase}) {
? canvasKitBase + 'canvaskit.js'
: canvasKitJavaScriptBindingsUrl;
final html.ScriptElement canvasKitScript = html.ScriptElement();
final DomHTMLScriptElement canvasKitScript = createDomHTMLScriptElement();
canvasKitScript.src = canvasKitJavaScriptUrl;
final Completer<void> canvasKitLoadCompleter = Completer<void>();
late StreamSubscription<html.Event> loadSubscription;
loadSubscription = canvasKitScript.onLoad.listen((_) {
loadSubscription.cancel();
late DomEventListener callback;
void loadEventHandler(DomEvent _) {
canvasKitLoadCompleter.complete();
});
canvasKitScript.removeEventListener('load', callback);
}
callback = allowInterop(loadEventHandler);
canvasKitScript.addEventListener('load', callback);
patchCanvasKitModule(canvasKitScript);

View File

@@ -8,7 +8,9 @@ import 'package:ui/ui.dart' as ui;
import '../browser_detection.dart';
import '../configuration.dart';
import '../dom.dart';
import '../platform_dispatcher.dart';
import '../safe_browser_api.dart';
import '../util.dart';
import '../window.dart';
import 'canvas.dart';
@@ -70,7 +72,7 @@ class Surface {
/// We must cache this function because each time we access the tear-off it
/// creates a new object, meaning we won't be able to remove this listener
/// later.
void Function(html.Event)? _cachedContextLostListener;
void Function(DomEvent)? _cachedContextLostListener;
/// A cached copy of the most recently created `webglcontextrestored`
/// listener.
@@ -78,7 +80,7 @@ class Surface {
/// We must cache this function because each time we access the tear-off it
/// creates a new object, meaning we won't be able to remove this listener
/// later.
void Function(html.Event)? _cachedContextRestoredListener;
void Function(DomEvent)? _cachedContextRestoredListener;
SkGrContext? _grContext;
int? _glContext;
@@ -93,10 +95,10 @@ class Surface {
/// Conversely, the canvas that lives inside this element can be swapped, for
/// example, when the screen size changes, or when the WebGL context is lost
/// due to the browser tab becoming dormant.
final html.Element htmlElement = html.Element.tag('flt-canvas-container');
final DomElement htmlElement = createDomElement('flt-canvas-container');
/// The underlying `<canvas>` element used for this surface.
html.CanvasElement? htmlCanvas;
DomCanvasElement? htmlCanvas;
int _pixelWidth = -1;
int _pixelHeight = -1;
@@ -131,7 +133,7 @@ class Surface {
void addToScene() {
if (!_addedToScene) {
skiaSceneHost!.children.insert(0, htmlElement);
skiaSceneHost!.children.insert(0, htmlElement as html.Element);
}
_addedToScene = true;
}
@@ -207,9 +209,9 @@ class Surface {
void _updateLogicalHtmlCanvasSize() {
final double logicalWidth = _pixelWidth / window.devicePixelRatio;
final double logicalHeight = _pixelHeight / window.devicePixelRatio;
htmlCanvas!.style
..width = '${logicalWidth}px'
..height = '${logicalHeight}px';
final DomCSSStyleDeclaration style = htmlCanvas!.style;
style.setProperty('width', '${logicalWidth}px');
style.setProperty('height', '${logicalHeight}px');
}
/// Translate the canvas so the surface covers the visible portion of the
@@ -224,10 +226,10 @@ class Surface {
final int surfaceHeight = _currentSurfaceSize!.height.ceil();
final double offset =
(_pixelHeight - surfaceHeight) / window.devicePixelRatio;
htmlCanvas!.style.transform = 'translate(0, -${offset}px)';
htmlCanvas!.style.setProperty('transform', 'translate(0, -${offset}px)');
}
void _contextRestoredListener(html.Event event) {
void _contextRestoredListener(DomEvent event) {
assert(
_contextLost,
'Received "webglcontextrestored" event but never received '
@@ -239,7 +241,7 @@ class Surface {
event.preventDefault();
}
void _contextLostListener(html.Event event) {
void _contextLostListener(DomEvent event) {
assert(event.target == htmlCanvas,
'Received a context lost event for a disposed canvas');
final SurfaceFactory factory = SurfaceFactory.instance;
@@ -277,7 +279,7 @@ class Surface {
// we ensure that the rendred picture covers the entire browser window.
_pixelWidth = physicalSize.width.ceil();
_pixelHeight = physicalSize.height.ceil();
final html.CanvasElement htmlCanvas = html.CanvasElement(
final DomCanvasElement htmlCanvas = createDomCanvasElement(
width: _pixelWidth,
height: _pixelHeight,
);
@@ -294,7 +296,7 @@ class Surface {
// accessible.
htmlCanvas.setAttribute('aria-hidden', 'true');
htmlCanvas.style.position = 'absolute';
htmlCanvas.style.setProperty('position', 'absolute');
_updateLogicalHtmlCanvasSize();
// When the browser tab using WebGL goes dormant the browser and/or OS may
@@ -303,8 +305,8 @@ class Surface {
// notification. When we receive this notification we force a new context.
//
// See also: https://www.khronos.org/webgl/wiki/HandlingContextLost
_cachedContextRestoredListener = _contextRestoredListener;
_cachedContextLostListener = _contextLostListener;
_cachedContextRestoredListener = allowInterop(_contextRestoredListener);
_cachedContextLostListener = allowInterop(_contextLostListener);
htmlCanvas.addEventListener(
'webglcontextlost',
_cachedContextLostListener,
@@ -377,7 +379,7 @@ class Surface {
static bool _didWarnAboutWebGlInitializationFailure = false;
CkSurface _makeSoftwareCanvasSurface(
html.CanvasElement htmlCanvas, String reason) {
DomCanvasElement htmlCanvas, String reason) {
if (!_didWarnAboutWebGlInitializationFailure) {
printWarning('WARNING: Falling back to CPU-only rendering. $reason.');
_didWarnAboutWebGlInitializationFailure = true;

View File

@@ -21,6 +21,7 @@ class DomWindow {}
extension DomWindowExtension on DomWindow {
external DomDocument get document;
external DomNavigator get navigator;
external DomPerformance get performance;
}
@JS('window')
@@ -44,20 +45,86 @@ class DomDocument {}
extension DomDocumentExtension on DomDocument {
external /* List<Node> */ List<Object?> querySelectorAll(String selectors);
external DomElement createElement(String name, [dynamic options]);
external DomHTMLScriptElement? get currentScript;
}
@JS()
@staticInterop
class DomHTMLDocument extends DomDocument {}
extension DomHTMLDocumentExtension on DomHTMLDocument {
external DomHTMLHeadElement? get head;
}
@JS('document')
external DomHTMLDocument get domDocument;
@JS()
@staticInterop
class DomEventTarget {}
extension DomEventTargetExtension on DomEventTarget {
external void addEventListener(String type, DomEventListener? listener,
[bool? useCapture]);
external void removeEventListener(String type, DomEventListener? listener,
[bool? useCapture]);
}
typedef DomEventListener = void Function(DomEvent event);
@JS()
@staticInterop
class DomEvent {}
extension DomEventExtension on DomEvent {
external DomEventTarget? get target;
external void preventDefault();
external void stopPropagation();
}
@JS()
@staticInterop
class DomNode extends DomEventTarget {}
extension DomNodeExtension on DomNode {
external DomNode appendChild(DomNode node);
external DomElement? get parentElement;
external DomNode? get parentNode;
external DomNode insertBefore(DomNode newNode, DomNode? referenceNode);
void remove() {
if (parentNode != null) {
final DomNode parent = parentNode!;
parent.removeChild(this);
}
}
external DomNode removeChild(DomNode child);
external bool? get isConnected;
}
@JS()
@staticInterop
class DomElement extends DomNode {}
DomElement createDomElement(String tag) =>
domDocument.createElement(tag);
extension DomElementExtension on DomElement {
external /* List<DomElement> */ List<Object?> get children;
external DomCSSStyleDeclaration get style;
external void append(DomNode node);
external void setAttribute(String name, Object value);
}
@JS()
@staticInterop
class DomCSSStyleDeclaration {}
extension DomCSSStyleDeclarationExtension on DomCSSStyleDeclaration {
external String getPropertyValue(String property);
external void setProperty(String propertyName, String value, [String
priority]);
}
@JS()
@staticInterop
class DomHTMLElement extends DomElement {}
@@ -72,6 +139,39 @@ extension DomHTMLMetaElementExtension on DomHTMLMetaElement {
external String get content;
}
@JS()
@staticInterop
class DomHTMLHeadElement extends DomHTMLElement {}
@JS()
@staticInterop
class DomHTMLScriptElement extends DomHTMLElement {}
extension DomHTMLScriptElementExtension on DomHTMLScriptElement {
external set src(String value);
}
DomHTMLScriptElement createDomHTMLScriptElement() =>
domDocument.createElement('script') as DomHTMLScriptElement;
@JS()
@staticInterop
class DomPerformance extends DomEventTarget {}
extension DomPerformanceExtension on DomPerformance {
external DomPerformanceEntry? mark(String markName);
external DomPerformanceMeasure? measure(
String measureName, String? startMark, String? endMark);
}
@JS()
@staticInterop
class DomPerformanceEntry {}
@JS()
@staticInterop
class DomPerformanceMeasure extends DomPerformanceEntry {}
@JS()
@staticInterop
class DomCanvasElement extends DomHTMLElement {}

View File

@@ -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:html' as html;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
@@ -26,23 +24,23 @@ void testMain() {
final Surface surface = SurfaceFactory.instance.getSurface();
final CkSurface originalSurface =
surface.acquireFrame(const ui.Size(9, 19)).skiaSurface;
final html.CanvasElement original = surface.htmlCanvas!;
final DomCanvasElement original = surface.htmlCanvas!;
// Expect exact requested dimensions.
expect(original.width, 9);
expect(original.height, 19);
expect(original.style.width, '9px');
expect(original.style.height, '19px');
expect(original.style.getPropertyValue('width'), '9px');
expect(original.style.getPropertyValue('height'), '19px');
expect(originalSurface.width(), 9);
expect(originalSurface.height(), 19);
// Shrinking reuses the existing canvas straight-up.
final CkSurface shrunkSurface =
surface.acquireFrame(const ui.Size(5, 15)).skiaSurface;
final html.CanvasElement shrunk = surface.htmlCanvas!;
final DomCanvasElement shrunk = surface.htmlCanvas!;
expect(shrunk, same(original));
expect(shrunk.style.width, '9px');
expect(shrunk.style.height, '19px');
expect(shrunk.style.getPropertyValue('width'), '9px');
expect(shrunk.style.getPropertyValue('height'), '19px');
expect(shrunkSurface, isNot(same(original)));
expect(shrunkSurface.width(), 5);
expect(shrunkSurface.height(), 15);
@@ -51,22 +49,22 @@ void testMain() {
// by 40% to accommodate future increases.
final CkSurface firstIncreaseSurface =
surface.acquireFrame(const ui.Size(10, 20)).skiaSurface;
final html.CanvasElement firstIncrease = surface.htmlCanvas!;
final DomCanvasElement firstIncrease = surface.htmlCanvas!;
expect(firstIncrease, isNot(same(original)));
expect(firstIncreaseSurface, isNot(same(shrunkSurface)));
// Expect overallocated dimensions
expect(firstIncrease.width, 14);
expect(firstIncrease.height, 28);
expect(firstIncrease.style.width, '14px');
expect(firstIncrease.style.height, '28px');
expect(firstIncrease.style.getPropertyValue('width'), '14px');
expect(firstIncrease.style.getPropertyValue('height'), '28px');
expect(firstIncreaseSurface.width(), 10);
expect(firstIncreaseSurface.height(), 20);
// Subsequent increases within 40% reuse the old canvas.
final CkSurface secondIncreaseSurface =
surface.acquireFrame(const ui.Size(11, 22)).skiaSurface;
final html.CanvasElement secondIncrease = surface.htmlCanvas!;
final DomCanvasElement secondIncrease = surface.htmlCanvas!;
expect(secondIncrease, same(firstIncrease));
expect(secondIncreaseSurface, isNot(same(firstIncreaseSurface)));
expect(secondIncreaseSurface.width(), 11);
@@ -74,22 +72,22 @@ void testMain() {
// Increases beyond the 40% limit will cause a new allocation.
final CkSurface hugeSurface = surface.acquireFrame(const ui.Size(20, 40)).skiaSurface;
final html.CanvasElement huge = surface.htmlCanvas!;
final DomCanvasElement huge = surface.htmlCanvas!;
expect(huge, isNot(same(secondIncrease)));
expect(hugeSurface, isNot(same(secondIncreaseSurface)));
// Also over-allocated
expect(huge.width, 28);
expect(huge.height, 56);
expect(huge.style.width, '28px');
expect(huge.style.height, '56px');
expect(huge.style.getPropertyValue('width'), '28px');
expect(huge.style.getPropertyValue('height'), '56px');
expect(hugeSurface.width(), 20);
expect(hugeSurface.height(), 40);
// Shrink again. Reuse the last allocated surface.
final CkSurface shrunkSurface2 =
surface.acquireFrame(const ui.Size(5, 15)).skiaSurface;
final html.CanvasElement shrunk2 = surface.htmlCanvas!;
final DomCanvasElement shrunk2 = surface.htmlCanvas!;
expect(shrunk2, same(huge));
expect(shrunkSurface2, isNot(same(hugeSurface)));
expect(shrunkSurface2.width(), 5);
@@ -118,8 +116,8 @@ void testMain() {
expect(afterAcquireFrame, same(before));
// Emulate WebGL context loss.
final html.CanvasElement canvas =
surface.htmlElement.children.single as html.CanvasElement;
final DomCanvasElement canvas =
surface.htmlElement.children.single! as DomCanvasElement;
final dynamic ctx = canvas.getContext('webgl2');
expect(ctx, isNotNull);
final dynamic loseContextExtension =
@@ -156,8 +154,8 @@ void testMain() {
expect(original.width(), 10);
expect(original.height(), 16);
expect(surface.htmlCanvas!.style.width, '10px');
expect(surface.htmlCanvas!.style.height, '16px');
expect(surface.htmlCanvas!.style.getPropertyValue('width'), '10px');
expect(surface.htmlCanvas!.style.getPropertyValue('height'), '16px');
// Increase device-pixel ratio: this makes CSS pixels bigger, so we need
// fewer of them to cover the browser window.
@@ -166,8 +164,8 @@ void testMain() {
surface.acquireFrame(const ui.Size(10, 16)).skiaSurface;
expect(highDpr.width(), 10);
expect(highDpr.height(), 16);
expect(surface.htmlCanvas!.style.width, '5px');
expect(surface.htmlCanvas!.style.height, '8px');
expect(surface.htmlCanvas!.style.getPropertyValue('width'), '5px');
expect(surface.htmlCanvas!.style.getPropertyValue('height'), '8px');
// Decrease device-pixel ratio: this makes CSS pixels smaller, so we need
// more of them to cover the browser window.
@@ -176,8 +174,8 @@ void testMain() {
surface.acquireFrame(const ui.Size(10, 16)).skiaSurface;
expect(lowDpr.width(), 10);
expect(lowDpr.height(), 16);
expect(surface.htmlCanvas!.style.width, '20px');
expect(surface.htmlCanvas!.style.height, '32px');
expect(surface.htmlCanvas!.style.getPropertyValue('width'), '20px');
expect(surface.htmlCanvas!.style.getPropertyValue('height'), '32px');
});
}, skip: isIosSafari);
}