[skwasm] Implement platform view clipping. (flutter/engine#54201)

This implements platform view clipping for the Skwasm renderer.

This fixes https://github.com/flutter/flutter/issues/133466
This commit is contained in:
Jackson Gardner
2024-08-01 15:12:14 -07:00
committed by GitHub
parent bb477b53cf
commit 2b915b5444
13 changed files with 421 additions and 32 deletions

View File

@@ -281,7 +281,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
@@ -299,7 +299,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

View File

@@ -7,6 +7,7 @@ import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../scene_painting.dart';
import '../vector_math.dart';
import 'canvaskit_api.dart';
import 'native_memory.dart';
@@ -15,7 +16,7 @@ import 'path_metrics.dart';
/// An implementation of [ui.Path] which is backed by an `SkPath`.
///
/// The `SkPath` is required for `CkCanvas` methods which take a path.
class CkPath implements ui.Path {
class CkPath implements ScenePath {
factory CkPath() {
final SkPath skPath = SkPath();
skPath.setFillType(toSkFillType(ui.PathFillType.nonZero));
@@ -314,7 +315,8 @@ class CkPath implements ui.Path {
return CkPath.fromSkPath(newPath, _fillType);
}
String? toSvgString() {
@override
String toSvgString() {
return skiaObject.toSVGString();
}

View File

@@ -43,7 +43,7 @@ class ClipPathLayer
class ClipPathOperation implements LayerOperation {
ClipPathOperation(this.path, this.clip);
final ui.Path path;
final ScenePath path;
final ui.Clip clip;
@override
@@ -68,8 +68,7 @@ class ClipPathOperation implements LayerOperation {
@override
PlatformViewStyling createPlatformViewStyling() {
// TODO(jacksongardner): implement clip styling for platform views
return const PlatformViewStyling();
return PlatformViewStyling(clip: PlatformViewPathClip(path));
}
}
@@ -104,8 +103,7 @@ class ClipRectOperation implements LayerOperation {
@override
PlatformViewStyling createPlatformViewStyling() {
// TODO(jacksongardner): implement clip styling for platform views
return const PlatformViewStyling();
return PlatformViewStyling(clip: PlatformViewRectClip(rect));
}
}
@@ -140,8 +138,7 @@ class ClipRRectOperation implements LayerOperation {
@override
PlatformViewStyling createPlatformViewStyling() {
// TODO(jacksongardner): implement clip styling for platform views
return const PlatformViewStyling();
return PlatformViewStyling(clip: PlatformViewRRectClip(rrect));
}
}
@@ -501,13 +498,15 @@ class PlatformViewPosition {
class PlatformViewStyling {
const PlatformViewStyling({
this.position = const PlatformViewPosition.zero(),
this.clip = const PlatformViewNoClip(),
this.opacity = 1.0
});
bool get isDefault => position.isZero && (opacity == 1.0);
bool get isDefault => position.isZero && (opacity == 1.0) && clip is PlatformViewNoClip;
final PlatformViewPosition position;
final double opacity;
final PlatformViewClip clip;
static PlatformViewStyling combine(PlatformViewStyling outer, PlatformViewStyling inner) {
// Attempt to reuse one of the existing immutable objects.
@@ -519,6 +518,7 @@ class PlatformViewStyling {
}
return PlatformViewStyling(
position: PlatformViewPosition.combine(outer.position, inner.position),
clip: PlatformViewClip.combine(outer.clip, inner.clip.positioned(outer.position)),
opacity: outer.opacity * inner.opacity,
);
}
@@ -531,15 +531,208 @@ class PlatformViewStyling {
if (other is! PlatformViewStyling) {
return false;
}
return (position == other.position) && (opacity == other.opacity);
return (position == other.position) && (opacity == other.opacity) && (clip == other.clip);
}
@override
int get hashCode {
return Object.hash(position, opacity);
return Object.hash(position, opacity, clip);
}
}
sealed class PlatformViewClip {
PlatformViewClip positioned(PlatformViewPosition position);
ui.Rect get boundingRect;
bool covers(ui.Rect rect);
ScenePath get toPath;
static PlatformViewClip combine(PlatformViewClip outer, PlatformViewClip inner) {
if (outer is PlatformViewNoClip) {
return inner;
}
if (inner is PlatformViewNoClip) {
return outer;
}
if (outer.covers(inner.boundingRect)) {
return outer;
}
if (inner.covers(outer.boundingRect)) {
return inner;
}
final ScenePath path = ui.Path() as ScenePath;
path.addPath(outer.toPath, ui.Offset.zero);
path.addPath(inner.toPath, ui.Offset.zero);
return PlatformViewPathClip(path);
}
}
class PlatformViewNoClip implements PlatformViewClip {
const PlatformViewNoClip();
@override
PlatformViewClip positioned(PlatformViewPosition positioned) {
return this;
}
@override
ScenePath get toPath => ui.Path() as ScenePath;
@override
ui.Rect get boundingRect => ui.Rect.zero;
@override
bool covers(ui.Rect rect) {
return false;
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == PlatformViewNoClip);
}
@override
int get hashCode => runtimeType.hashCode;
}
class PlatformViewRectClip implements PlatformViewClip {
PlatformViewRectClip(this.rect);
final ui.Rect rect;
@override
PlatformViewClip positioned(PlatformViewPosition position) {
if (position.isZero) {
return this;
}
final ui.Offset? offset = position.offset;
if (offset != null) {
return PlatformViewRectClip(rect.shift(offset));
} else {
return PlatformViewPathClip(toPath.transform(position.transform!.toFloat64()) as ScenePath);
}
}
@override
ScenePath get toPath => (ui.Path() as ScenePath)..addRect(rect);
@override
ui.Rect get boundingRect => rect;
@override
bool covers(ui.Rect other) {
return rect.left <= other.left &&
rect.right >= other.right &&
rect.top <= other.top &&
rect.bottom >= other.bottom;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is PlatformViewRectClip && rect == other.rect;
}
@override
int get hashCode => Object.hash(runtimeType, rect);
}
class PlatformViewRRectClip implements PlatformViewClip {
PlatformViewRRectClip(this.rrect);
final ui.RRect rrect;
@override
PlatformViewClip positioned(PlatformViewPosition position) {
if (position.isZero) {
return this;
}
final ui.Offset? offset = position.offset;
if (offset != null) {
return PlatformViewRRectClip(rrect.shift(offset));
} else {
return PlatformViewPathClip(toPath.transform(position.transform!.toFloat64()) as ScenePath);
}
}
@override
ScenePath get toPath => (ui.Path() as ScenePath)..addRRect(rrect);
@override
ui.Rect get boundingRect => throw UnimplementedError();
@override
bool covers(ui.Rect other) {
final ui.Rect rect = rrect.safeInnerRect;
return rect.left <= other.left &&
rect.right >= other.right &&
rect.top <= other.top &&
rect.bottom >= other.bottom;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is PlatformViewRRectClip && rrect == other.rrect;
}
@override
int get hashCode => Object.hash(runtimeType, rrect);
}
class PlatformViewPathClip implements PlatformViewClip {
PlatformViewPathClip(this.path);
final ScenePath path;
@override
PlatformViewClip positioned(PlatformViewPosition position) {
if (position.isZero) {
return this;
}
final ui.Offset? offset = position.offset;
if (offset != null) {
return PlatformViewPathClip(path.shift(offset) as ScenePath);
} else {
return PlatformViewPathClip(path.transform(position.transform!.toFloat64()) as ScenePath);
}
}
@override
ScenePath get toPath => path;
@override
ui.Rect get boundingRect => path.getBounds();
@override
bool covers(ui.Rect rect) {
// There is no way of determining if an arbitrary path fully covers a rectangle
// so we always conservatively return false here.
return false;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is PlatformViewPathClip && path == other.path;
}
@override
int get hashCode => Object.hash(runtimeType, path);
}
class LayerBuilder {
factory LayerBuilder.rootLayer() {
return LayerBuilder._(null, EngineRootLayer(), null);

View File

@@ -144,7 +144,7 @@ class EngineSceneBuilder implements ui.SceneBuilder {
ui.ClipPathEngineLayer? oldLayer
}) => pushLayer<ClipPathLayer>(
ClipPathLayer(),
ClipPathOperation(path, clipBehavior),
ClipPathOperation(path as ScenePath, clipBehavior),
);
@override

View File

@@ -23,3 +23,9 @@ abstract class SceneImageFilter implements ui.ImageFilter {
// has been processed by the filter.
ui.Rect filterBounds(ui.Rect inputBounds);
}
abstract class ScenePath implements ui.Path {
// In order to properly clip platform views with paths, we need to be able to get a
// string representation of them.
String toSvgString();
}

View File

@@ -187,6 +187,12 @@ class EngineSceneView {
}
}
for (final SliceContainer? container in reusableContainers) {
if (container != null) {
sceneElement.removeChild(container.container);
}
}
containers = newContainers;
DomElement? currentElement = sceneElement.firstElementChild;
@@ -199,13 +205,6 @@ class EngineSceneView {
sceneElement.insertBefore(container.container, currentElement);
}
}
// Remove any other unused containers
while (currentElement != null) {
final DomElement? sibling = currentElement.nextElementSibling;
sceneElement.removeChild(currentElement);
currentElement = sibling;
}
}
}
@@ -277,16 +276,25 @@ final class PictureSliceContainer extends SliceContainer {
}
final class PlatformViewContainer extends SliceContainer {
PlatformViewContainer(this.viewId) : container = createPlatformViewSlot(viewId);
PlatformViewContainer(this.viewId) :
container = createDomElement('flt-clip'),
slot = createPlatformViewSlot(viewId) {
container.appendChild(slot);
}
final int viewId;
PlatformViewStyling? _styling;
ui.Rect? _bounds;
bool _dirty = false;
ui.Path? _clipPath;
String? _clipPathString;
@override
final DomElement container;
final DomElement slot;
set styling(PlatformViewStyling styling) {
if (_styling != styling) {
_styling = styling;
@@ -301,13 +309,54 @@ final class PlatformViewContainer extends SliceContainer {
}
}
set clipPath(ScenePath? path) {
if (_clipPath == path) {
return;
}
_clipPath = path;
_clipPathString = path?.toSvgString();
}
String cssStringForClip(PlatformViewClip clip, double devicePixelRatio) {
switch (clip) {
case PlatformViewNoClip():
clipPath = null;
return '';
case PlatformViewRectClip():
clipPath = null;
final double top = clip.rect.top / devicePixelRatio;
final double right = clip.rect.right / devicePixelRatio;
final double bottom = clip.rect.bottom / devicePixelRatio;
final double left = clip.rect.left / devicePixelRatio;
return 'rect(${top}px ${right}px ${bottom}px ${left}px)';
case PlatformViewRRectClip():
clipPath = null;
final double top = clip.rrect.top / devicePixelRatio;
final double right = clip.rrect.right / devicePixelRatio;
final double bottom = clip.rrect.bottom / devicePixelRatio;
final double left = clip.rrect.left / devicePixelRatio;
final double tlRadiusX = clip.rrect.tlRadiusX / devicePixelRatio;
final double tlRadiusY = clip.rrect.tlRadiusY / devicePixelRatio;
final double trRadiusX = clip.rrect.trRadiusX / devicePixelRatio;
final double trRadiusY = clip.rrect.trRadiusY / devicePixelRatio;
final double brRadiusX = clip.rrect.brRadiusX / devicePixelRatio;
final double brRadiusY = clip.rrect.brRadiusY / devicePixelRatio;
final double blRadiusX = clip.rrect.blRadiusX / devicePixelRatio;
final double blRadiusY = clip.rrect.blRadiusY / devicePixelRatio;
return 'rect(${top}px ${right}px ${bottom}px ${left}px round ${tlRadiusX}px ${trRadiusX}px ${brRadiusX}px ${blRadiusX}px / ${tlRadiusY}px ${trRadiusY}px ${brRadiusY}px ${blRadiusY}px)';
case PlatformViewPathClip():
clipPath = clip.path;
return "path('$_clipPathString')";
}
}
@override
void updateContents() {
assert(_styling != null);
assert(_bounds != null);
if (_dirty) {
final DomCSSStyleDeclaration style = container.style;
final DomCSSStyleDeclaration style = slot.style;
style.position = 'absolute';
style.width = '${_bounds!.width}px';
style.height = '${_bounds!.height}px';
@@ -329,7 +378,14 @@ final class PlatformViewContainer extends SliceContainer {
style.transform = float64ListToCssTransform(scaleMatrix.storage);
style.transformOrigin = '0 0 0';
style.opacity = _styling!.opacity != 1.0 ? '${_styling!.opacity}' : '';
// TODO(jacksongardner): Implement clip styling for platform views
final DomCSSStyleDeclaration containerStyle = container.style;
containerStyle.position = 'absolute';
containerStyle.width = '100%';
containerStyle.height = '100%';
final String clipPathString = cssStringForClip(_styling!.clip, devicePixelRatio);
containerStyle.clipPath = clipPathString;
_dirty = false;
}

View File

@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:ffi';
import 'dart:typed_data';
@@ -19,7 +20,7 @@ enum PathArcSize {
large,
}
class SkwasmPath extends SkwasmObjectWrapper<RawPath> implements ui.Path {
class SkwasmPath extends SkwasmObjectWrapper<RawPath> implements ScenePath {
factory SkwasmPath() {
return SkwasmPath.fromHandle(pathCreate());
}
@@ -252,4 +253,15 @@ class SkwasmPath extends SkwasmObjectWrapper<RawPath> implements ui.Path {
ui.PathMetrics computeMetrics({bool forceClosed = false}) {
return SkwasmPathMetrics(path: this, forceClosed: forceClosed);
}
@override
String toSvgString() {
final SkStringHandle skString = pathGetSvgString(handle);
final Pointer<Int8> buffer = skStringGetData(skString);
final int length = skStringGetLength(skString);
final List<int> characters = List<int>.generate(length, (int i) => buffer[i]);
final String svgString = utf8.decode(characters);
skStringFree(skString);
return svgString;
}
}

View File

@@ -201,3 +201,6 @@ external void pathGetBounds(PathHandle path, RawRect outRect);
symbol: 'path_combine',
isLeaf: true)
external PathHandle pathCombine(int operation, PathHandle path1, PathHandle path2);
@Native<SkStringHandle Function(PathHandle)>(symbol: 'path_getSvgString', isLeaf: true)
external SkStringHandle pathGetSvgString(PathHandle path);

View File

@@ -20,6 +20,9 @@ external SkStringHandle skStringAllocate(int size);
@Native<Pointer<Int8> Function(SkStringHandle)>(symbol: 'skString_getData', isLeaf: true)
external Pointer<Int8> skStringGetData(SkStringHandle handle);
@Native<Int Function(SkStringHandle)>(symbol: 'skString_getLength', isLeaf: true)
external int skStringGetLength(SkStringHandle handle);
@Native<Void Function(SkStringHandle)>(symbol: 'skString_free', isLeaf: true)
external void skStringFree(SkStringHandle handle);

View File

@@ -5,7 +5,9 @@
#include "export.h"
#include "helpers.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkString.h"
#include "third_party/skia/include/pathops/SkPathOps.h"
#include "third_party/skia/include/utils/SkParsePath.h"
using namespace Skwasm;
@@ -194,3 +196,8 @@ SKWASM_EXPORT SkPath* path_combine(SkPathOp operation,
return nullptr;
}
}
SKWASM_EXPORT SkString* path_getSvgString(SkPath* path) {
SkString* string = new SkString(SkParsePath::ToSVGString(*path));
return string;
}

View File

@@ -14,6 +14,10 @@ SKWASM_EXPORT char* skString_getData(SkString* string) {
return string->data();
}
SKWASM_EXPORT int skString_getLength(SkString* string) {
return string->size();
}
SKWASM_EXPORT void skString_free(SkString* string) {
return delete string;
}

View File

@@ -128,10 +128,10 @@ void testMain() {
final DomElement sceneElement = sceneView.sceneElement;
final List<DomElement> children = sceneElement.children.toList();
expect(children.length, 1);
final DomElement containerElement = children.first;
expect(
containerElement.tagName, equalsIgnoringCase('flt-canvas-container'));
expect(containerElement.tagName, equalsIgnoringCase('flt-canvas-container'));
final List<DomElement> containerChildren =
containerElement.children.toList();
@@ -161,11 +161,15 @@ void testMain() {
final DomElement sceneElement = sceneView.sceneElement;
final List<DomElement> children = sceneElement.children.toList();
expect(children.length, 1);
final DomElement containerElement = children.first;
expect(
containerElement.tagName, equalsIgnoringCase('flt-platform-view-slot'));
expect(children.length, 1);
final DomElement clipElement = children.first;
expect(clipElement.tagName, equalsIgnoringCase('flt-clip'));
final List<DomElement> clipChildren = clipElement.children.toList();
expect(clipChildren.length, 1);
final DomElement containerElement = clipChildren.first;
final DomCSSStyleDeclaration style = containerElement.style;
expect(style.left, '');
expect(style.top, '');

View File

@@ -34,6 +34,8 @@ Future<void> testMain() async {
(int viewId) {
final DomElement element = createDomHTMLDivElement();
element.style.backgroundColor = 'blue';
element.style.width = '100%';
element.style.height = '100%';
return element;
}
);
@@ -234,6 +236,103 @@ Future<void> testMain() async {
await matchGoldenFile('platformview_opacity.png', region: region);
});
test('platformview cliprect', () async {
await _createPlatformView(1, platformViewType);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawCircle(
const ui.Offset(50, 50),
50,
ui.Paint()
..style = ui.PaintingStyle.fill
..color = const ui.Color(0xFFFF0000)
);
final ui.SceneBuilder sb = ui.SceneBuilder();
sb.pushOffset(50, 50);
sb.pushClipRect(const ui.Rect.fromLTRB(60, 60, 100, 100));
sb.addPicture(const ui.Offset(50, 50), recorder.endRecording());
sb.addPlatformView(
1,
offset: const ui.Offset(75, 75),
width: 50,
height: 50,
);
await renderScene(sb.build());
await matchGoldenFile('platformview_cliprect.png', region: region);
});
test('platformview cliprrect', () async {
await _createPlatformView(1, platformViewType);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawCircle(
const ui.Offset(50, 50),
50,
ui.Paint()
..style = ui.PaintingStyle.fill
..color = const ui.Color(0xFFFF0000)
);
final ui.SceneBuilder sb = ui.SceneBuilder();
sb.pushOffset(50, 50);
sb.pushClipRRect(
const ui.RRect.fromLTRBXY(60, 60, 100, 100, 5, 10),
clipBehavior: ui.Clip.antiAlias
);
sb.addPicture(const ui.Offset(50, 50), recorder.endRecording());
sb.addPlatformView(
1,
offset: const ui.Offset(75, 75),
width: 50,
height: 50,
);
await renderScene(sb.build());
await matchGoldenFile('platformview_cliprrect.png', region: region);
});
test('platformview clippath', () async {
await _createPlatformView(1, platformViewType);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawCircle(
const ui.Offset(50, 50),
50,
ui.Paint()
..style = ui.PaintingStyle.fill
..color = const ui.Color(0xFFFF0000)
);
final ui.SceneBuilder sb = ui.SceneBuilder();
sb.pushOffset(50, 50);
final ui.Path path = ui.Path();
path.moveTo(80, 100);
path.lineTo(60, 75);
path.arcToPoint(const ui.Offset(80, 75), radius: const ui.Radius.elliptical(10, 15));
path.arcToPoint(const ui.Offset(100, 75), radius: const ui.Radius.elliptical(10, 15));
path.close();
sb.pushClipPath(path);
sb.addPicture(const ui.Offset(50, 50), recorder.endRecording());
sb.addPlatformView(
1,
offset: const ui.Offset(75, 75),
width: 50,
height: 50,
);
await renderScene(sb.build());
await matchGoldenFile('platformview_clippath.png', region: region);
});
}
// Sends a platform message to create a Platform View with the given id and viewType.