text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// 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; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import '../browser_detection.dart'; import '../dom.dart'; import '../engine_canvas.dart'; import '../svg.dart'; import '../text/canvas_paragraph.dart'; import '../util.dart'; import '../vector_math.dart'; import 'bitmap_canvas.dart'; import 'painting.dart'; import 'path/path.dart'; import 'path/path_to_svg.dart'; import 'shaders/image_shader.dart'; import 'shaders/shader.dart'; /// A canvas that renders to DOM elements and CSS properties. class DomCanvas extends EngineCanvas with SaveElementStackTracking { DomCanvas(this.rootElement); @override final DomElement rootElement; /// Prepare to reuse this canvas by clearing it's current contents. @override void clear() { super.clear(); removeAllChildren(rootElement); } @override void clipRect(ui.Rect rect, ui.ClipOp clipOp) { throw UnimplementedError(); } @override void clipRRect(ui.RRect rrect) { throw UnimplementedError(); } @override void clipPath(ui.Path path) { throw UnimplementedError(); } @override void drawColor(ui.Color color, ui.BlendMode blendMode) { // TODO(yjbanov): implement blendMode final DomElement box = createDomElement('draw-color'); box.style ..position = 'absolute' ..top = '0' ..right = '0' ..bottom = '0' ..left = '0' ..backgroundColor = color.toCssString(); currentElement.append(box); } @override void drawLine(ui.Offset p1, ui.Offset p2, SurfacePaintData paint) { throw UnimplementedError(); } @override void drawPaint(SurfacePaintData paint) { throw UnimplementedError(); } @override void drawRect(ui.Rect rect, SurfacePaintData paint) { rect = adjustRectForDom(rect, paint); currentElement.append( buildDrawRectElement(rect, paint, 'draw-rect', currentTransform)); } @override void drawRRect(ui.RRect rrect, SurfacePaintData paint) { final ui.Rect outerRect = adjustRectForDom(rrect.outerRect, paint); final DomElement element = buildDrawRectElement( outerRect, paint, 'draw-rrect', currentTransform); applyRRectBorderRadius(element.style, rrect); currentElement.append(element); } @override void drawDRRect(ui.RRect outer, ui.RRect inner, SurfacePaintData paint) { throw UnimplementedError(); } @override void drawOval(ui.Rect rect, SurfacePaintData paint) { throw UnimplementedError(); } @override void drawCircle(ui.Offset c, double radius, SurfacePaintData paint) { throw UnimplementedError(); } @override void drawPath(ui.Path path, SurfacePaintData paint) { throw UnimplementedError(); } @override void drawShadow(ui.Path path, ui.Color color, double elevation, bool transparentOccluder) { throw UnimplementedError(); } @override void drawImage(ui.Image image, ui.Offset p, SurfacePaintData paint) { throw UnimplementedError(); } @override void drawImageRect( ui.Image image, ui.Rect src, ui.Rect dst, SurfacePaintData paint) { throw UnimplementedError(); } @override void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) { final DomElement paragraphElement = drawParagraphElement( paragraph as CanvasParagraph, offset, transform: currentTransform); currentElement.append(paragraphElement); } @override void drawVertices( ui.Vertices vertices, ui.BlendMode blendMode, SurfacePaintData paint) { throw UnimplementedError(); } @override void drawPoints( ui.PointMode pointMode, Float32List points, SurfacePaintData paint) { throw UnimplementedError(); } @override void endOfPaint() { // No reuse of elements yet to handle here. Noop. } } /// Converts a shadow color specified by the framework to the color that should /// actually be applied when rendering the element. /// /// Returns a color for box-shadow based on blur filter at sigma. ui.Color blurColor(ui.Color color, double sigma) { final double strength = math.min(math.sqrt(sigma) / (math.pi * 2.0), 1.0); final int reducedAlpha = ((1.0 - strength) * color.alpha).round(); return ui.Color((reducedAlpha & 0xff) << 24 | (color.value & 0x00ffffff)); } /// When drawing a shape (rect, rrect, circle, etc) in DOM/CSS, the [rect] given /// by Flutter needs to be adjusted to what DOM/CSS expect. /// /// This method takes Flutter's [rect] and produces a new rect that can be used /// to generate the correct CSS properties to match Flutter's expectations. /// /// /// Here's what Flutter's given [rect] and [paint.strokeWidth] represent: /// /// top-left ↓ /// β”Œβ”€β”€β†“β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” /// β†’β†’β†’β†’x x │←← /// β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ | /// β”‚ β”‚ β”‚ β”‚ | /// β”‚ β”‚ β”‚ β”‚ | height /// β”‚ β”‚ β”‚ β”‚ | /// β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ | /// β”‚ x x │←← /// β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ /// stroke-width ↑----↑ ↑ /// ↑-------------------↑ width /// /// /// /// In the DOM/CSS, here's how the coordinates should look like: /// /// top-left ↓ /// β†’β†’x─────────────────────────┐ /// β”‚ β”‚ /// β”‚ x───────────────x │←← /// β”‚ β”‚ β”‚ β”‚ | /// β”‚ β”‚ β”‚ β”‚ | height /// β”‚ β”‚ β”‚ β”‚ | /// β”‚ x───────────────x │←← /// β”‚ β”‚ /// β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ /// border-width ↑----↑ ↑ /// ↑---------------↑ width /// /// As shown in the drawing above, the width/height don't start at the top-left /// coordinates. Instead, they start from the inner top-left (inside the border). ui.Rect adjustRectForDom(ui.Rect rect, SurfacePaintData paint) { double left = math.min(rect.left, rect.right); double top = math.min(rect.top, rect.bottom); double width = rect.width.abs(); double height = rect.height.abs(); final bool isStroke = paint.style == ui.PaintingStyle.stroke; final double strokeWidth = paint.strokeWidth ?? 0.0; if (isStroke && strokeWidth > 0.0) { left -= strokeWidth / 2.0; top -= strokeWidth / 2.0; // width and height shouldn't go below zero. width = math.max(0, width - strokeWidth); height = math.max(0, height - strokeWidth); } if (left != rect.left || top != rect.top || width != rect.width || height != rect.height) { return ui.Rect.fromLTWH(left, top, width, height); } return rect; } DomHTMLElement buildDrawRectElement( ui.Rect rect, SurfacePaintData paint, String tagName, Matrix4 transform) { assert(rect.left <= rect.right); assert(rect.top <= rect.bottom); final DomHTMLElement rectangle = domDocument.createElement(tagName) as DomHTMLElement; assert(() { rectangle.setAttribute('flt-rect', '$rect'); rectangle.setAttribute('flt-paint', '$paint'); return true; }()); String effectiveTransform; final bool isStroke = paint.style == ui.PaintingStyle.stroke; final double strokeWidth = paint.strokeWidth ?? 0.0; if (transform.isIdentity()) { effectiveTransform = 'translate(${rect.left}px, ${rect.top}px)'; } else { // Clone to avoid mutating `transform`. final Matrix4 translated = transform.clone()..translate(rect.left, rect.top); effectiveTransform = matrix4ToCssTransform(translated); } final DomCSSStyleDeclaration style = rectangle.style; style ..position = 'absolute' ..transformOrigin = '0 0 0' ..transform = effectiveTransform; String cssColor = colorValueToCssString(paint.color); if (paint.maskFilter != null) { final double sigma = paint.maskFilter!.webOnlySigma; if (browserEngine == BrowserEngine.webkit && !isStroke) { // A bug in webkit leaves artifacts when this element is animated // with filter: blur, we use boxShadow instead. style.boxShadow = '0px 0px ${sigma * 2.0}px $cssColor'; cssColor = blurColor(ui.Color(paint.color), sigma).toCssString(); } else { style.filter = 'blur(${sigma}px)'; } } style ..width = '${rect.width}px' ..height = '${rect.height}px'; if (isStroke) { style.border = '${_borderStrokeToCssUnit(strokeWidth)} solid $cssColor'; } else { style ..backgroundColor = cssColor ..backgroundImage = _getBackgroundImageCssValue(paint.shader, rect); } return rectangle; } String _getBackgroundImageCssValue(ui.Shader? shader, ui.Rect bounds) { final String url = _getBackgroundImageUrl(shader, bounds); return (url != '') ? "url('$url'": ''; } String _getBackgroundImageUrl(ui.Shader? shader, ui.Rect bounds) { if(shader != null) { if(shader is EngineImageShader) { return shader.image.imgElement.src ?? ''; } if(shader is EngineGradient) { return shader.createImageBitmap(bounds, 1, true) as String; } } return ''; } void applyRRectBorderRadius(DomCSSStyleDeclaration style, ui.RRect rrect) { if (rrect.tlRadiusX == rrect.trRadiusX && rrect.tlRadiusX == rrect.blRadiusX && rrect.tlRadiusX == rrect.brRadiusX && rrect.tlRadiusX == rrect.tlRadiusY && rrect.trRadiusX == rrect.trRadiusY && rrect.blRadiusX == rrect.blRadiusY && rrect.brRadiusX == rrect.brRadiusY) { style.borderRadius = _borderStrokeToCssUnit(rrect.blRadiusX); return; } // Non-uniform. Apply each corner radius. style.borderTopLeftRadius = '${_borderStrokeToCssUnit(rrect.tlRadiusX)} ' '${_borderStrokeToCssUnit(rrect.tlRadiusY)}'; style.borderTopRightRadius = '${_borderStrokeToCssUnit(rrect.trRadiusX)} ' '${_borderStrokeToCssUnit(rrect.trRadiusY)}'; style.borderBottomLeftRadius = '${_borderStrokeToCssUnit(rrect.blRadiusX)} ' '${_borderStrokeToCssUnit(rrect.blRadiusY)}'; style.borderBottomRightRadius = '${_borderStrokeToCssUnit(rrect.brRadiusX)} ' '${_borderStrokeToCssUnit(rrect.brRadiusY)}'; } String _borderStrokeToCssUnit(double value) { if (value == 0) { // TODO(ferhat): hairline nees to take into account both dpi and density. value = 1.0; } return '${value.toStringAsFixed(3)}px'; } SVGSVGElement pathToSvgElement(SurfacePath path, SurfacePaintData paint) { // In Firefox some SVG typed attributes are returned as null without a // setter. So we use strings here. final SVGSVGElement root = createSVGSVGElement() ..setAttribute('overflow', 'visible'); final SVGPathElement svgPath = createSVGPathElement(); root.append(svgPath); if (paint.style == ui.PaintingStyle.stroke || (paint.style != ui.PaintingStyle.fill && paint.strokeWidth != 0 && paint.strokeWidth != null)) { svgPath.setAttribute('stroke', colorValueToCssString(paint.color)); svgPath.setAttribute('stroke-width', '${paint.strokeWidth ?? 1.0}'); if (paint.strokeCap != null) { svgPath.setAttribute('stroke-linecap', '${stringForStrokeCap(paint.strokeCap)}'); } svgPath.setAttribute('fill', 'none'); } else { svgPath.setAttribute('fill', colorValueToCssString(paint.color)); } if (path.fillType == ui.PathFillType.evenOdd) { svgPath.setAttribute('fill-rule', 'evenodd'); } svgPath.setAttribute('d', pathToSvg(path.pathRef)); return root; }
engine/lib/web_ui/lib/src/engine/html/dom_canvas.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/dom_canvas.dart", "repo_id": "engine", "token_count": 4594 }
254
// 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; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import '../dom.dart'; import '../engine_canvas.dart'; import '../frame_reference.dart'; import '../picture.dart'; import '../util.dart'; import '../vector_math.dart'; import 'bitmap_canvas.dart'; import 'debug_canvas_reuse_overlay.dart'; import 'dom_canvas.dart'; import 'path/path_metrics.dart'; import 'surface.dart'; import 'surface_stats.dart'; // TODO(yjbanov): this is currently very naive. We probably want to cache // fewer large canvases than small canvases. We could also // improve cache hit count if we did not require exact canvas // size match, but instead could choose a canvas that's big // enough. The optimal heuristic will need to be figured out. // For example, we probably don't want to pick a full-screen // canvas to draw a 10x10 picture. Let's revisit this after // Harry's layer merging refactor. /// The maximum number canvases cached. const int _kCanvasCacheSize = 30; /// Canvases available for reuse, capped at [_kCanvasCacheSize]. List<BitmapCanvas> get recycledCanvases => _recycledCanvases; final List<BitmapCanvas> _recycledCanvases = <BitmapCanvas>[]; /// Reduces recycled canvas list by 50% to reduce bitmap canvas memory use. void reduceCanvasMemoryUsage() { final int canvasCount = _recycledCanvases.length; for (int i = 0; i < canvasCount; i++) { _recycledCanvases[i].dispose(); } _recycledCanvases.clear(); } /// A request to repaint a canvas. /// /// Paint requests are prioritized such that the larger pictures go first. This /// makes canvas allocation more efficient by letting large pictures claim /// larger recycled canvases. Otherwise, small pictures would claim the large /// canvases forcing us to allocate new large canvases. class PaintRequest { PaintRequest({ required this.canvasSize, required this.paintCallback, }); final ui.Size canvasSize; final ui.VoidCallback paintCallback; } /// Repaint requests produced by [PersistedPicture]s that actually paint on the /// canvas. Painting is delayed until the layer tree is updated to maximize /// the number of reusable canvases. List<PaintRequest> paintQueue = <PaintRequest>[]; void _recycleCanvas(EngineCanvas? canvas) { // If a canvas is in the paint queue it maybe be recycled. To // prevent subsequent dispose recycling again check. if (canvas != null && _recycledCanvases.contains(canvas)) { return; } if (canvas is BitmapCanvas) { canvas.setElementCache(null); if (canvas.isReusable()) { _recycledCanvases.add(canvas); if (_recycledCanvases.length > _kCanvasCacheSize) { final BitmapCanvas removedCanvas = _recycledCanvases.removeAt(0); removedCanvas.dispose(); if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.disposedCount++; } } if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.inRecycleCount = _recycledCanvases.length; } } else { canvas.dispose(); } } } /// A surface that uses a combination of `<canvas>`, `<div>` and `<p>` elements /// to draw shapes and text. class PersistedPicture extends PersistedLeafSurface { PersistedPicture(this.dx, this.dy, this.picture, this.hints) : localPaintBounds = picture.recordingCanvas!.pictureBounds; EngineCanvas? _canvas; /// Returns the canvas used by this picture layer. EngineCanvas? get canvas => _canvas; final double dx; final double dy; final EnginePicture picture; final ui.Rect? localPaintBounds; final int hints; double _density = 1.0; /// Cull rect changes and density changes due to transforms should /// call applyPaint for picture when retain() or update() is called after /// preroll is complete. bool _requiresRepaint = false; /// Cache for reusing elements such as images across picture updates. CrossFrameCache<DomHTMLElement>? _elementCache = CrossFrameCache<DomHTMLElement>(); @override DomElement createElement() { final DomElement element = defaultCreateElement('flt-picture'); // The DOM elements used to render pictures are used purely to put pixels on // the screen. They have no semantic information. If an assistive technology // attempts to scan picture content it will look like garbage and confuse // users. UI semantics are exported as a separate DOM tree rendered parallel // to pictures. // // Why are layer and scene elements not hidden from ARIA? Because those // elements may contain platform views, and platform views must be // accessible. element.setAttribute('aria-hidden', 'true'); return element; } @override void preroll(PrerollSurfaceContext prerollContext) { if (prerollContext.activeShaderMaskCount != 0 || prerollContext.activeColorFilterCount != 0) { picture.recordingCanvas?.renderStrategy.isInsideSvgFilterTree = true; } super.preroll(prerollContext); } @override void recomputeTransformAndClip() { transform = parent!.transform; if (dx != 0.0 || dy != 0.0) { transform = transform!.clone(); transform!.translate(dx, dy); } final double paintWidth = localPaintBounds!.width; final double paintHeight = localPaintBounds!.height; final double newDensity = localPaintBounds == null || paintWidth == 0 || paintHeight == 0 ? 1.0 : _computePixelDensity(transform, paintWidth, paintHeight); if (newDensity != _density) { _density = newDensity; _requiresRepaint = true; } _computeExactCullRects(); } /// The rectangle that contains all visible pixels drawn by [picture] inside /// the current layer hierarchy in local coordinates. /// /// This value is a conservative estimate, i.e. it must be big enough to /// contain everything that's visible, but it may be bigger than necessary. /// Therefore it should not be used for clipping. It is meant to be used for /// optimizing canvas allocation. ui.Rect? get optimalLocalCullRect => _optimalLocalCullRect; ui.Rect? _optimalLocalCullRect; /// Same as [optimalLocalCullRect] but in screen coordinate system. ui.Rect? get debugExactGlobalCullRect => _exactGlobalCullRect; ui.Rect? _exactGlobalCullRect; ui.Rect? _exactLocalCullRect; /// Computes the canvas paint bounds based on the estimated paint bounds and /// the scaling produced by transformations. /// /// Return `true` if the local cull rect changed, indicating that a repaint /// may be required. Returns `false` otherwise. Global cull rect changes do /// not necessarily incur repaints. For example, if the layer sub-tree was /// translated from one frame to another we may not need to repaint, just /// translate the canvas. void _computeExactCullRects() { assert(transform != null); assert(localPaintBounds != null); if (parent!.projectedClip == null) { // Compute and cache chain of clipping bounds on parent of picture since // parent may include multiple pictures so it can be reused by all // child pictures. ui.Rect? bounds; PersistedSurface? parentSurface = parent; final Matrix4 clipTransform = Matrix4.identity(); while (parentSurface != null) { final ui.Rect? localClipBounds = parentSurface.localClipBounds; if (localClipBounds != null) { if (bounds == null) { bounds = clipTransform.transformRect(localClipBounds); } else { bounds = bounds.intersect(clipTransform.transformRect(localClipBounds)); } } final Matrix4? localInverse = parentSurface.localTransformInverse; if (localInverse != null && !localInverse.isIdentity()) { clipTransform.multiply(localInverse); } parentSurface = parentSurface.parent; } if (bounds != null && (bounds.width <= 0 || bounds.height <= 0)) { bounds = ui.Rect.zero; } // Cache projected clip on parent. parent!.projectedClip = bounds; } // Intersect localPaintBounds with parent projected clip to calculate // and cache [_exactLocalCullRect]. if (parent!.projectedClip == null) { _exactLocalCullRect = localPaintBounds; } else { _exactLocalCullRect = localPaintBounds!.intersect(parent!.projectedClip!); } if (_exactLocalCullRect!.width <= 0 || _exactLocalCullRect!.height <= 0) { _exactLocalCullRect = ui.Rect.zero; _exactGlobalCullRect = ui.Rect.zero; } else { assert(() { _exactGlobalCullRect = transform!.transformRect(_exactLocalCullRect!); return true; }()); } } void _computeOptimalCullRect(PersistedPicture? oldSurface) { assert(_exactLocalCullRect != null); if (oldSurface == null || !oldSurface.picture.recordingCanvas!.didDraw) { // First useful paint. _optimalLocalCullRect = _exactLocalCullRect; _requiresRepaint = true; return; } assert(oldSurface._optimalLocalCullRect != null); final bool surfaceBeingRetained = identical(oldSurface, this); final ui.Rect? oldOptimalLocalCullRect = surfaceBeingRetained ? _optimalLocalCullRect : oldSurface._optimalLocalCullRect; if (_exactLocalCullRect == ui.Rect.zero) { // The clip collapsed into a zero-sized rectangle. If it was already zero, // no need to signal cull rect change. _optimalLocalCullRect = ui.Rect.zero; if (oldOptimalLocalCullRect != ui.Rect.zero) { _requiresRepaint = true; } return; } if (rectContainsOther(oldOptimalLocalCullRect!, _exactLocalCullRect!)) { // The cull rect we computed in the past contains the newly computed cull // rect. This can happen, for example, when the picture is being shrunk by // a clip when it is scrolled out of the screen. In this case we do not // repaint the picture. We just let it be shrunk by the outer clip. _optimalLocalCullRect = oldOptimalLocalCullRect; return; } // The new cull rect contains area not covered by a previous rect. Perhaps // the clip is growing, moving around the picture, or both. In this case // a part of the picture may not have been painted. We will need to // request a new canvas and paint the picture on it. However, this is also // a strong signal that the clip will continue growing as typically // Flutter uses animated transitions. So instead of allocating the canvas // the size of the currently visible area, we try to allocate a canvas of // a bigger size. This will prevent any further repaints as future frames // will hit the above case where the new cull rect is fully contained // within the cull rect we compute now. // Compute the delta, by which each of the side of the clip rect has "moved" // since the last time we updated the cull rect. final double leftwardDelta = oldOptimalLocalCullRect.left - _exactLocalCullRect!.left; final double upwardDelta = oldOptimalLocalCullRect.top - _exactLocalCullRect!.top; final double rightwardDelta = _exactLocalCullRect!.right - oldOptimalLocalCullRect.right; final double bottomwardDelta = _exactLocalCullRect!.bottom - oldOptimalLocalCullRect.bottom; // Compute the new optimal rect to paint into. final ui.Rect newLocalCullRect = ui.Rect.fromLTRB( _exactLocalCullRect!.left - _predictTrend(leftwardDelta, _exactLocalCullRect!.width), _exactLocalCullRect!.top - _predictTrend(upwardDelta, _exactLocalCullRect!.height), _exactLocalCullRect!.right + _predictTrend(rightwardDelta, _exactLocalCullRect!.width), _exactLocalCullRect!.bottom + _predictTrend(bottomwardDelta, _exactLocalCullRect!.height), ).intersect(localPaintBounds!); _requiresRepaint = _optimalLocalCullRect != newLocalCullRect; _optimalLocalCullRect = newLocalCullRect; } /// Predicts the delta a particular side of a clip rect will move given the /// [delta] it moved by last, and the respective [extent] (width or height) /// of the clip. static double _predictTrend(double delta, double extent) { if (delta <= 0.0) { // Shrinking. Give it 10% of the extent in case the trend is reversed. return extent * 0.1; } else { // Growing. Predict 10 more frames of similar deltas. Give it at least // 50% of the extent (protect from extremely slow growth trend such as // slow scrolling). Give no more than the full extent (protects from // fast scrolling that could lead to overallocation). return math.min( math.max(extent * 0.5, delta * 10.0), extent, ); } } /// Number of bitmap pixel painted by this picture. /// /// If the implementation does not paint onto a bitmap canvas, it should /// return zero. int get bitmapPixelCount { if (_canvas is! BitmapCanvas) { return 0; } final BitmapCanvas bitmapCanvas = _canvas! as BitmapCanvas; return bitmapCanvas.bitmapPixelCount; } void _applyPaint(PersistedPicture? oldSurface) { final EngineCanvas? oldCanvas = oldSurface?._canvas; _requiresRepaint = false; if (!picture.recordingCanvas!.didDraw || _optimalLocalCullRect!.isEmpty) { // The picture is empty, or it has been completely clipped out. Skip // painting. This removes all the setup work and scaffolding objects // that won't be useful for anything anyway. _recycleCanvas(oldCanvas); if (oldSurface != null) { // Make sure it doesn't get reused/recycled again. oldSurface._canvas = null; } if (rootElement != null) { removeAllChildren(rootElement!); } if (_canvas != null && _canvas != oldCanvas) { _recycleCanvas(_canvas); } _canvas = null; return; } if (debugExplainSurfaceStats) { surfaceStatsFor(this).paintCount++; } assert(_optimalLocalCullRect != null); applyPaint(oldCanvas); } @override double matchForUpdate(PersistedPicture existingSurface) { if (existingSurface.picture == picture) { // Picture is the same, return perfect score. return 0.0; } if (!existingSurface.picture.recordingCanvas!.didDraw) { // The previous surface didn't draw anything and therefore has no // resources to reuse. return 1.0; } final bool didRequireBitmap = existingSurface .picture.recordingCanvas!.renderStrategy.hasArbitraryPaint; final bool requiresBitmap = picture.recordingCanvas!.renderStrategy.hasArbitraryPaint; if (didRequireBitmap != requiresBitmap) { // Switching canvas types is always expensive. return 1.0; } else if (!requiresBitmap) { // Currently DomCanvas is always expensive to repaint, as we always throw // out all the DOM we rendered before. This may change in the future, at // which point we may return other values here. return 1.0; } else { final BitmapCanvas? oldCanvas = existingSurface._canvas as BitmapCanvas?; if (oldCanvas == null) { // We did not allocate a canvas last time. This can happen when the // picture is completely clipped out of the view. return 1.0; } else if (!oldCanvas.doesFitBounds(_exactLocalCullRect!, _density)) { // The canvas needs to be resized before painting. return 1.0; } else { final int newPixelCount = BitmapCanvas.widthToPhysical(_exactLocalCullRect!.width) * BitmapCanvas.heightToPhysical(_exactLocalCullRect!.height); final int oldPixelCount = oldCanvas.widthInBitmapPixels * oldCanvas.heightInBitmapPixels; if (oldPixelCount == 0) { return 1.0; } final double pixelCountRatio = newPixelCount / oldPixelCount; assert(0 <= pixelCountRatio && pixelCountRatio <= 1.0, 'Invalid pixel count ratio $pixelCountRatio'); return 1.0 - pixelCountRatio; } } } void applyPaint(EngineCanvas? oldCanvas) { if (picture.recordingCanvas!.renderStrategy.hasArbitraryPaint) { _applyBitmapPaint(oldCanvas); } else { _applyDomPaint(oldCanvas); } } void _applyDomPaint(EngineCanvas? oldCanvas) { _recycleCanvas(_canvas); final DomCanvas domCanvas = DomCanvas(rootElement!); _canvas = domCanvas; removeAllChildren(rootElement!); picture.recordingCanvas!.apply(domCanvas, _optimalLocalCullRect!); } void _applyBitmapPaint(EngineCanvas? oldCanvas) { if (oldCanvas is BitmapCanvas && oldCanvas.doesFitBounds(_optimalLocalCullRect!, _density) && oldCanvas.isReusable()) { final BitmapCanvas reusedCanvas = oldCanvas; if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.keptCount++; } // Re-use old bitmap canvas. reusedCanvas.bounds = _optimalLocalCullRect!; _canvas = reusedCanvas; reusedCanvas.setElementCache(_elementCache); reusedCanvas.clear(); picture.recordingCanvas!.apply(reusedCanvas, _optimalLocalCullRect!); } else { // We can't use the old canvas because the size has changed, so we put // it in a cache for later reuse. _recycleCanvas(oldCanvas); if (_canvas is BitmapCanvas) { (_canvas! as BitmapCanvas).setElementCache(null); } _canvas = null; // We cannot paint immediately because not all canvases that we may be // able to reuse have been released yet. So instead we enqueue this // picture to be painted after the update cycle is done syncing the layer // tree then reuse canvases that were freed up. paintQueue.add(PaintRequest( canvasSize: _optimalLocalCullRect!.size, paintCallback: () { final BitmapCanvas bitmapCanvas = _findOrCreateCanvas(_optimalLocalCullRect!); _canvas = bitmapCanvas; bitmapCanvas.setElementCache(_elementCache); if (debugExplainSurfaceStats) { surfaceStatsFor(this).paintPixelCount += bitmapCanvas.bitmapPixelCount; } removeAllChildren(rootElement!); rootElement!.append(bitmapCanvas.rootElement); bitmapCanvas.clear(); picture.recordingCanvas!.apply(bitmapCanvas, _optimalLocalCullRect!); }, )); } } /// Attempts to reuse a canvas from the [_recycledCanvases]. Allocates a new /// one if unable to reuse. /// /// The best recycled canvas is one that: /// /// - Fits the requested [canvasSize]. This is a hard requirement. Otherwise /// we risk clipping the picture. /// - Is the smallest among all possible reusable canvases. This makes canvas /// reuse more efficient. /// - Contains no more than twice the number of requested pixels. This makes /// sure we do not use too much memory for small canvases. BitmapCanvas _findOrCreateCanvas(ui.Rect bounds) { final ui.Size canvasSize = bounds.size; BitmapCanvas? bestRecycledCanvas; double lastPixelCount = double.infinity; for (int i = 0; i < _recycledCanvases.length; i++) { final BitmapCanvas candidate = _recycledCanvases[i]; if (!candidate.isReusable()) { continue; } final ui.Size candidateSize = candidate.size; final double candidatePixelCount = candidateSize.width * candidateSize.height; final bool fits = candidate.doesFitBounds(bounds, _density); final bool isSmaller = candidatePixelCount < lastPixelCount; if (fits && isSmaller) { // [isTooSmall] is used to make sure that a small picture doesn't // reuse and hold onto memory of a large canvas. final double requestedPixelCount = bounds.width * bounds.height; final bool isTooSmall = isSmaller && requestedPixelCount > 1 && (candidatePixelCount / requestedPixelCount) > 4; if (!isTooSmall) { bestRecycledCanvas = candidate; lastPixelCount = candidatePixelCount; final bool fitsExactly = candidateSize.width == canvasSize.width && candidateSize.height == canvasSize.height; if (fitsExactly) { // No need to keep looking any more. break; } } } } if (bestRecycledCanvas != null) { if (debugExplainSurfaceStats) { surfaceStatsFor(this).reuseCanvasCount++; } _recycledCanvases.remove(bestRecycledCanvas); if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.inRecycleCount = _recycledCanvases.length; } if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.reusedCount++; } bestRecycledCanvas.bounds = bounds; bestRecycledCanvas.setElementCache(_elementCache); return bestRecycledCanvas; } if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.createdCount++; } final BitmapCanvas canvas = BitmapCanvas( bounds, picture.recordingCanvas!.renderStrategy, density: _density); canvas.setElementCache(_elementCache); if (debugExplainSurfaceStats) { surfaceStatsFor(this) ..allocateBitmapCanvasCount += 1 ..allocatedBitmapSizeInPixels = canvas.widthInBitmapPixels * canvas.heightInBitmapPixels; } return canvas; } void _applyTranslate() { rootElement!.style.transform = 'translate(${dx}px, ${dy}px)'; } @override void apply() { _applyTranslate(); _applyPaint(null); } @override void build() { _computeOptimalCullRect(null); _requiresRepaint = true; super.build(); } @override void update(PersistedPicture oldSurface) { super.update(oldSurface); // Transfer element cache over. _elementCache = oldSurface._elementCache; if (oldSurface != this) { oldSurface._elementCache = null; } if (dx != oldSurface.dx || dy != oldSurface.dy) { _applyTranslate(); } _computeOptimalCullRect(oldSurface); if (identical(picture, oldSurface.picture)) { final bool densityChanged = _canvas is BitmapCanvas && _density != (_canvas! as BitmapCanvas).density; // The picture is the same. Attempt to avoid repaint. if (_requiresRepaint || densityChanged) { // Cull rect changed such that a repaint is still necessary. _applyPaint(oldSurface); } else { // Cull rect did not change, or changed such in a way that does not // require a repaint (e.g. it shrunk). _canvas = oldSurface._canvas; } } else { // We have a new picture. Repaint. _applyPaint(oldSurface); } } @override void retain() { super.retain(); _computeOptimalCullRect(this); if (_requiresRepaint) { _applyPaint(this); } } @override void discard() { _recycleCanvas(_canvas); _canvas = null; super.discard(); } @override void debugPrintChildren(StringBuffer buffer, int indent) { super.debugPrintChildren(buffer, indent); if (rootElement != null && rootElement!.firstChild != null) { final DomElement firstChild = rootElement!.firstChild! as DomElement; final String canvasTag = firstChild.tagName.toLowerCase(); final int canvasHash = firstChild.hashCode; buffer.writeln('${' ' * (indent + 1)}<$canvasTag @$canvasHash />'); } else if (rootElement != null) { buffer.writeln( '${' ' * (indent + 1)}<${rootElement!.tagName.toLowerCase()} @$hashCode />'); } else { buffer.writeln('${' ' * (indent + 1)}<recycled-canvas />'); } } @override void debugValidate(List<String> validationErrors) { super.debugValidate(validationErrors); if (picture.recordingCanvas!.didDraw) { if (!_optimalLocalCullRect!.isEmpty && canvas == null) { validationErrors .add('$runtimeType has non-trivial picture but it has null canvas'); } if (_optimalLocalCullRect == null) { validationErrors.add('$runtimeType has null _optimalLocalCullRect'); } if (_exactGlobalCullRect == null) { validationErrors.add('$runtimeType has null _exactGlobalCullRect'); } if (_exactLocalCullRect == null) { validationErrors.add('$runtimeType has null _exactLocalCullRect'); } } } } /// Given size of a rectangle and transform, computes pixel density /// (scale factor). double _computePixelDensity(Matrix4? transform, double width, double height) { if (transform == null || transform.isIdentityOrTranslation()) { return 1.0; } final Float32List m = transform.storage; // Apply perspective transform to all 4 corners. Can't use left,top, bottom, // right since for example rotating 45 degrees would yield inaccurate size. double minX = m[12] * m[15]; double minY = m[13] * m[15]; double maxX = minX; double maxY = minY; double x = width; double y = height; double wp = 1.0 / ((m[3] * x) + (m[7] * y) + m[15]); double xp = ((m[0] * x) + (m[4] * y) + m[12]) * wp; double yp = ((m[1] * x) + (m[5] * y) + m[13]) * wp; minX = math.min(minX, xp); maxX = math.max(maxX, xp); minY = math.min(minY, yp); maxY = math.max(maxY, yp); x = 0; wp = 1.0 / ((m[3] * x) + (m[7] * y) + m[15]); xp = ((m[0] * x) + (m[4] * y) + m[12]) * wp; yp = ((m[1] * x) + (m[5] * y) + m[13]) * wp; minX = math.min(minX, xp); maxX = math.max(maxX, xp); minY = math.min(minY, yp); maxY = math.max(maxY, yp); x = width; y = 0; wp = 1.0 / ((m[3] * x) + (m[7] * y) + m[15]); xp = ((m[0] * x) + (m[4] * y) + m[12]) * wp; yp = ((m[1] * x) + (m[5] * y) + m[13]) * wp; minX = math.min(minX, xp); maxX = math.max(maxX, xp); minY = math.min(minY, yp); maxY = math.max(maxY, yp); final double scaleX = (maxX - minX) / width; final double scaleY = (maxY - minY) / height; double scale = math.min(scaleX, scaleY); // kEpsilon guards against divide by zero below. if (scale < kEpsilon || scale == 1) { // Handle local paint bounds scaled to 0, typical when using // transform animations and nothing is drawn. return 1.0; } if (scale > 1) { // Normalize scale to multiples of 2: 1x, 2x, 4x, 6x, 8x. // This is to prevent frequent rescaling of canvas during animations. // // On a fullscreen high dpi device dpi*density*resolution will demand // too much memory, so clamp at 4. scale = math.min(4.0, (scale / 2.0).ceil() * 2.0); // Guard against webkit absolute limit. const double kPixelLimit = 1024 * 1024 * 4; if ((width * height * scale * scale) > kPixelLimit && scale > 2) { scale = (kPixelLimit * 0.8) / (width * height); } } else { scale = math.max(2.0 / (2.0 / scale).floor(), 0.0001); } return scale; }
engine/lib/web_ui/lib/src/engine/html/picture.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/picture.dart", "repo_id": "engine", "token_count": 10183 }
255
// 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:typed_data'; import 'package:ui/ui.dart' as ui; import '../dom.dart'; import '../util.dart'; import '../vector_math.dart'; import 'surface.dart'; /// A surface that transforms its children using CSS transform. class PersistedTransform extends PersistedContainerSurface implements ui.TransformEngineLayer { PersistedTransform(PersistedTransform? super.oldLayer, this._matrixStorage); /// The storage representing the transform of this surface. final Float32List _matrixStorage; /// The matrix representing the transform of this surface. Matrix4 get matrix4 => _matrix4 ??= Matrix4.fromFloat32List(_matrixStorage); Matrix4? _matrix4; @override void recomputeTransformAndClip() { transform = parent!.transform!.multiplied(matrix4); projectedClip = null; } /// Cached inverse of transform on this node. Unlike [transform], this /// Matrix only contains local transform (not chain multiplied since root). Matrix4? _localTransformInverse; @override Matrix4? get localTransformInverse { _localTransformInverse ??= Matrix4.tryInvert(matrix4); return _localTransformInverse; } @override DomElement createElement() { final DomElement element = domDocument.createElement('flt-transform'); setElementStyle(element, 'position', 'absolute'); setElementStyle(element, 'transform-origin', '0 0 0'); return element; } @override void apply() { rootElement!.style.transform = float64ListToCssTransform(_matrixStorage); } @override void update(PersistedTransform oldSurface) { super.update(oldSurface); if (identical(oldSurface._matrixStorage, _matrixStorage)) { // The matrix storage is identical, so we can copy the matrices from the // old surface to avoid recomputing them. _matrix4 = oldSurface._matrix4; _localTransformInverse = oldSurface._localTransformInverse; return; } bool matrixChanged = false; for (int i = 0; i < _matrixStorage.length; i++) { if (_matrixStorage[i] != oldSurface._matrixStorage[i]) { matrixChanged = true; break; } } if (matrixChanged) { apply(); } else { // The matrix storage hasn't changed, so we can copy the matrices from the // old surface to avoid recomputing them. _matrix4 = oldSurface._matrix4; _localTransformInverse = oldSurface._localTransformInverse; } } }
engine/lib/web_ui/lib/src/engine/html/transform.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/transform.dart", "repo_id": "engine", "token_count": 846 }
256
// 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. const int kMaxCodePoint = 0x10ffff; const int kPrefixDigit0 = 48; const int kPrefixRadix = 10; const int kFontIndexDigit0 = 65 + 32; // 'a'..'z' const int kFontIndexRadix = 26; const int kRangeSizeDigit0 = 65 + 32; // 'a'..'z' const int kRangeSizeRadix = 26; const int kRangeValueDigit0 = 65; // 'A'..'Z' const int kRangeValueRadix = 26;
engine/lib/web_ui/lib/src/engine/noto_font_encoding.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/noto_font_encoding.dart", "repo_id": "engine", "token_count": 179 }
257
// 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:async'; import 'dart:math' as math; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/src/engine/skwasm/skwasm_stub.dart' if (dart.library.ffi) 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; final Renderer _renderer = Renderer._internal(); Renderer get renderer => _renderer; /// This class is an abstraction over the rendering backend for the web engine. /// Which backend is selected is based off of the `--web-renderer` command-line /// argument passed to the flutter tool. It provides many of the rendering /// primitives of the dart:ui library, as well as other backend-specific pieces /// of functionality needed by the rest of the generic web engine code. abstract class Renderer { factory Renderer._internal() { if (FlutterConfiguration.flutterWebUseSkwasm) { return SkwasmRenderer(); } else { bool useCanvasKit; if (FlutterConfiguration.flutterWebAutoDetect) { if (configuration.requestedRendererType != null) { useCanvasKit = configuration.requestedRendererType == 'canvaskit'; } else { // If requestedRendererType is not specified, use CanvasKit for desktop and // html for mobile. useCanvasKit = isDesktop; } } else { useCanvasKit = FlutterConfiguration.useSkia; } return useCanvasKit ? CanvasKitRenderer() : HtmlRenderer(); } } String get rendererTag; FlutterFontCollection get fontCollection; FutureOr<void> initialize(); ui.Paint createPaint(); ui.Vertices createVertices( ui.VertexMode mode, List<ui.Offset> positions, { List<ui.Offset>? textureCoordinates, List<ui.Color>? colors, List<int>? indices, }); ui.Vertices createVerticesRaw( ui.VertexMode mode, Float32List positions, { Float32List? textureCoordinates, Int32List? colors, Uint16List? indices, }); ui.PictureRecorder createPictureRecorder(); ui.Canvas createCanvas(ui.PictureRecorder recorder, [ui.Rect? cullRect]); ui.SceneBuilder createSceneBuilder(); ui.Gradient createLinearGradient( ui.Offset from, ui.Offset to, List<ui.Color> colors, [ List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix4, ]); ui.Gradient createRadialGradient( ui.Offset center, double radius, List<ui.Color> colors, [ List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix4, ]); ui.Gradient createConicalGradient( ui.Offset focal, double focalRadius, ui.Offset center, double radius, List<ui.Color> colors, [ List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix, ]); ui.Gradient createSweepGradient( ui.Offset center, List<ui.Color> colors, [ List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, double startAngle = 0.0, double endAngle = math.pi * 2, Float32List? matrix4, ]); ui.ImageFilter createBlurImageFilter({ double sigmaX = 0.0, double sigmaY = 0.0, ui.TileMode tileMode = ui.TileMode.clamp}); ui.ImageFilter createDilateImageFilter({ double radiusX = 0.0, double radiusY = 0.0}); ui.ImageFilter createErodeImageFilter({ double radiusX = 0.0, double radiusY = 0.0}); ui.ImageFilter createMatrixImageFilter( Float64List matrix4, { ui.FilterQuality filterQuality = ui.FilterQuality.low }); ui.ImageFilter composeImageFilters({required ui.ImageFilter outer, required ui.ImageFilter inner}); Future<ui.Codec> instantiateImageCodec( Uint8List list, { int? targetWidth, int? targetHeight, bool allowUpscaling = true, }); Future<ui.Codec> instantiateImageCodecFromUrl( Uri uri, { ui_web.ImageCodecChunkCallback? chunkCallback, }); FutureOr<ui.Image> createImageFromImageBitmap(DomImageBitmap imageSource); void decodeImageFromPixels( Uint8List pixels, int width, int height, ui.PixelFormat format, ui.ImageDecoderCallback callback, { int? rowBytes, int? targetWidth, int? targetHeight, bool allowUpscaling = true }); ui.ImageShader createImageShader( ui.Image image, ui.TileMode tmx, ui.TileMode tmy, Float64List matrix4, ui.FilterQuality? filterQuality, ); void clearFragmentProgramCache(); Future<ui.FragmentProgram> createFragmentProgram(String assetKey); ui.Path createPath(); ui.Path copyPath(ui.Path src); ui.Path combinePaths(ui.PathOperation op, ui.Path path1, ui.Path path2); ui.LineMetrics createLineMetrics({ required bool hardBreak, required double ascent, required double descent, required double unscaledAscent, required double height, required double width, required double left, required double baseline, required int lineNumber, }); ui.TextStyle createTextStyle({ required ui.Color? color, required ui.TextDecoration? decoration, required ui.Color? decorationColor, required ui.TextDecorationStyle? decorationStyle, required double? decorationThickness, required ui.FontWeight? fontWeight, required ui.FontStyle? fontStyle, required ui.TextBaseline? textBaseline, required String? fontFamily, required List<String>? fontFamilyFallback, required double? fontSize, required double? letterSpacing, required double? wordSpacing, required double? height, required ui.TextLeadingDistribution? leadingDistribution, required ui.Locale? locale, required ui.Paint? background, required ui.Paint? foreground, required List<ui.Shadow>? shadows, required List<ui.FontFeature>? fontFeatures, required List<ui.FontVariation>? fontVariations, }); ui.ParagraphStyle createParagraphStyle({ ui.TextAlign? textAlign, ui.TextDirection? textDirection, int? maxLines, String? fontFamily, double? fontSize, double? height, ui.TextHeightBehavior? textHeightBehavior, ui.FontWeight? fontWeight, ui.FontStyle? fontStyle, ui.StrutStyle? strutStyle, String? ellipsis, ui.Locale? locale, }); ui.StrutStyle createStrutStyle({ String? fontFamily, List<String>? fontFamilyFallback, double? fontSize, double? height, ui.TextLeadingDistribution? leadingDistribution, double? leading, ui.FontWeight? fontWeight, ui.FontStyle? fontStyle, bool? forceStrutHeight, }); ui.ParagraphBuilder createParagraphBuilder(ui.ParagraphStyle style); Future<void> renderScene(ui.Scene scene, ui.FlutterView view); }
engine/lib/web_ui/lib/src/engine/renderer.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/renderer.dart", "repo_id": "engine", "token_count": 2529 }
258
// 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 '../platform_views/slots.dart'; import 'label_and_value.dart'; import 'semantics.dart'; /// Manages the semantic element corresponding to a platform view. /// /// The element in the semantics tree exists only to supply the ARIA traversal /// order. The actual content of the platform view is managed by /// [PlatformViewManager]. /// /// The traversal order is established using "aria-owns", by pointing to the /// element that hosts the view contents. As of this writing, Safari on macOS /// and on iOS does not support "aria-owns". All other browsers on all operating /// systems support it. /// /// See also: /// * https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns /// * https://bugs.webkit.org/show_bug.cgi?id=223798 class PlatformViewRoleManager extends PrimaryRoleManager { PlatformViewRoleManager(SemanticsObject semanticsObject) : super.withBasics( PrimaryRole.platformView, semanticsObject, labelRepresentation: LeafLabelRepresentation.ariaLabel, ); @override void update() { super.update(); if (semanticsObject.isPlatformView) { if (semanticsObject.isPlatformViewIdDirty) { setAttribute( 'aria-owns', getPlatformViewDomId(semanticsObject.platformViewId), ); } } else { removeAttribute('aria-owns'); } } @override bool focusAsRouteDefault() { // It's unclear how it's possible to auto-focus on something inside a // platform view without knowing what's in it. If the framework adds API for // focusing on platform view internals, this method will be able to do more, // but for now there's nothing to focus on. return false; } }
engine/lib/web_ui/lib/src/engine/semantics/platform_view.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/semantics/platform_view.dart", "repo_id": "engine", "token_count": 610 }
259
// 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:_wasm'; import 'dart:js_interop'; @pragma('wasm:prefer-inline') @pragma('dart2js:tryInline') JSAny dartToJsWrapper(Object object) => WasmAnyRef.fromObject(object).externalize().toJS; @pragma('wasm:prefer-inline') @pragma('dart2js:tryInline') Object jsWrapperToDart(JSAny jsWrapper) => externRefForJSAny(jsWrapper).internalize()!.toObject();
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/dart_js_conversion.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/dart_js_conversion.dart", "repo_id": "engine", "token_count": 194 }
260
// 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. @DefaultAsset('skwasm') library skwasm_impl; import 'dart:ffi'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; final class RawPaint extends Opaque {} typedef PaintHandle = Pointer<RawPaint>; @Native<PaintHandle Function()>(symbol: 'paint_create', isLeaf: true) external PaintHandle paintCreate(); @Native<Void Function(PaintHandle)>(symbol: 'paint_dispose', isLeaf: true) external void paintDispose(PaintHandle paint); @Native<Void Function(PaintHandle, Int)>(symbol: 'paint_setBlendMode', isLeaf: true) external void paintSetBlendMode(PaintHandle paint, int blendMode); @Native<Void Function(PaintHandle, Int)>(symbol: 'paint_setStyle', isLeaf: true) external void paintSetStyle(PaintHandle paint, int paintStyle); @Native<Int Function(PaintHandle)>(symbol: 'paint_getStyle', isLeaf: true) external int paintGetStyle(PaintHandle paint); @Native<Void Function(PaintHandle, Float)>(symbol: 'paint_setStrokeWidth', isLeaf: true) external void paintSetStrokeWidth(PaintHandle paint, double strokeWidth); @Native<Float Function(PaintHandle)>(symbol: 'paint_getStrokeWidth', isLeaf: true) external double paintGetStrokeWidth(PaintHandle paint); @Native<Void Function(PaintHandle, Int)>(symbol: 'paint_setStrokeCap', isLeaf: true) external void paintSetStrokeCap(PaintHandle paint, int cap); @Native<Int Function(PaintHandle)>(symbol: 'paint_getStrokeCap', isLeaf: true) external int paintGetStrokeCap(PaintHandle paint); @Native<Void Function(PaintHandle, Int)>(symbol: 'paint_setStrokeJoin', isLeaf: true) external void paintSetStrokeJoin(PaintHandle paint, int join); @Native<Int Function(PaintHandle)>(symbol: 'paint_getStrokeJoin', isLeaf: true) external int paintGetStrokeJoin(PaintHandle paint); @Native<Void Function(PaintHandle, Bool)>(symbol: 'paint_setAntiAlias', isLeaf: true) external void paintSetAntiAlias(PaintHandle paint, bool antiAlias); @Native<Bool Function(PaintHandle)>(symbol: 'paint_getAntiAlias', isLeaf: true) external bool paintGetAntiAlias(PaintHandle paint); @Native<Void Function(PaintHandle, Uint32)>(symbol: 'paint_setColorInt', isLeaf: true) external void paintSetColorInt(PaintHandle paint, int color); @Native<Uint32 Function(PaintHandle)>(symbol: 'paint_getColorInt', isLeaf: true) external int paintGetColorInt(PaintHandle paint); @Native<Void Function(PaintHandle, Float)>(symbol: 'paint_setMiterLimit', isLeaf: true) external void paintSetMiterLimit(PaintHandle paint, double miterLimit); @Native<Float Function(PaintHandle)>(symbol: 'paint_getMiterLimit', isLeaf: true) external double paintGetMiterLimit(PaintHandle paint); @Native<Void Function(PaintHandle, ShaderHandle)>(symbol: 'paint_setShader', isLeaf: true) external void paintSetShader(PaintHandle handle, ShaderHandle shader); @Native<Void Function(PaintHandle, ImageFilterHandle)>(symbol: 'paint_setImageFilter', isLeaf: true) external void paintSetImageFilter(PaintHandle handle, ImageFilterHandle filter); @Native<Void Function(PaintHandle, ColorFilterHandle)>(symbol: 'paint_setColorFilter', isLeaf: true) external void paintSetColorFilter(PaintHandle handle, ColorFilterHandle filter); @Native<Void Function(PaintHandle, MaskFilterHandle)>(symbol: 'paint_setMaskFilter', isLeaf: true) external void paintSetMaskFilter(PaintHandle handle, MaskFilterHandle filter);
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_paint.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_paint.dart", "repo_id": "engine", "token_count": 1139 }
261
// 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:async'; import 'dart:js_interop'; import 'dart:math' as math; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; class SkwasmRenderer implements Renderer { late SkwasmSurface surface; EngineSceneView? _sceneView; @override final SkwasmFontCollection fontCollection = SkwasmFontCollection(); @override ui.Path combinePaths(ui.PathOperation op, ui.Path path1, ui.Path path2) { return SkwasmPath.combine(op, path1 as SkwasmPath, path2 as SkwasmPath); } @override ui.Path copyPath(ui.Path src) { return SkwasmPath.from(src as SkwasmPath); } @override ui.Canvas createCanvas(ui.PictureRecorder recorder, [ui.Rect? cullRect]) { return SkwasmCanvas(recorder as SkwasmPictureRecorder, cullRect ?? ui.Rect.largest); } @override ui.Gradient createConicalGradient( ui.Offset focal, double focalRadius, ui.Offset center, double radius, List<ui.Color> colors, [ List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix]) => SkwasmGradient.conical( focal: focal, focalRadius: focalRadius, center: center, centerRadius: radius, colors: colors, colorStops: colorStops, tileMode: tileMode, matrix4: matrix, ); @override ui.ImageFilter createBlurImageFilter({ double sigmaX = 0.0, double sigmaY = 0.0, ui.TileMode tileMode = ui.TileMode.clamp }) => SkwasmImageFilter.blur( sigmaX: sigmaX, sigmaY: sigmaY, tileMode: tileMode ); @override ui.ImageFilter createDilateImageFilter({ double radiusX = 0.0, double radiusY = 0.0 }) => SkwasmImageFilter.dilate( radiusX: radiusX, radiusY: radiusY, ); @override ui.ImageFilter createErodeImageFilter({ double radiusX = 0.0, double radiusY = 0.0 }) => SkwasmImageFilter.erode( radiusX: radiusX, radiusY: radiusY, ); @override ui.ImageFilter composeImageFilters({ required ui.ImageFilter outer, required ui.ImageFilter inner }) => SkwasmImageFilter.compose( SkwasmImageFilter.fromUiFilter(outer), SkwasmImageFilter.fromUiFilter(inner), ); @override ui.ImageFilter createMatrixImageFilter( Float64List matrix4, { ui.FilterQuality filterQuality = ui.FilterQuality.low }) => SkwasmImageFilter.matrix( matrix4, filterQuality: filterQuality ); @override ui.ImageShader createImageShader( ui.Image image, ui.TileMode tmx, ui.TileMode tmy, Float64List matrix4, ui.FilterQuality? filterQuality ) => SkwasmImageShader.imageShader( image as SkwasmImage, tmx, tmy, matrix4, filterQuality ); @override ui.Gradient createLinearGradient( ui.Offset from, ui.Offset to, List<ui.Color> colors, [ List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix4 ]) => SkwasmGradient.linear( from: from, to: to, colors: colors, colorStops: colorStops, tileMode: tileMode, matrix4: matrix4, ); @override ui.Paint createPaint() => SkwasmPaint(); @override ui.ParagraphBuilder createParagraphBuilder(ui.ParagraphStyle style) => SkwasmParagraphBuilder(style as SkwasmParagraphStyle, fontCollection); @override ui.ParagraphStyle createParagraphStyle({ ui.TextAlign? textAlign, ui.TextDirection? textDirection, int? maxLines, String? fontFamily, double? fontSize, double? height, ui.TextHeightBehavior? textHeightBehavior, ui.FontWeight? fontWeight, ui.FontStyle? fontStyle, ui.StrutStyle? strutStyle, String? ellipsis, ui.Locale? locale }) => SkwasmParagraphStyle( textAlign: textAlign, textDirection: textDirection, maxLines: maxLines, fontFamily: fontFamily, fontSize: fontSize, height: height, textHeightBehavior: textHeightBehavior, fontWeight: fontWeight, fontStyle: fontStyle, strutStyle: strutStyle, ellipsis: ellipsis, locale: locale, ); @override ui.Path createPath() => SkwasmPath(); @override ui.PictureRecorder createPictureRecorder() => SkwasmPictureRecorder(); @override ui.Gradient createRadialGradient( ui.Offset center, double radius, List<ui.Color> colors, [ List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix4 ]) => SkwasmGradient.radial( center: center, radius: radius, colors: colors, colorStops: colorStops, tileMode: tileMode, matrix4: matrix4 ); @override ui.SceneBuilder createSceneBuilder() => EngineSceneBuilder(); @override ui.StrutStyle createStrutStyle({ String? fontFamily, List<String>? fontFamilyFallback, double? fontSize, double? height, ui.TextLeadingDistribution? leadingDistribution, double? leading, ui.FontWeight? fontWeight, ui.FontStyle? fontStyle, bool? forceStrutHeight }) => SkwasmStrutStyle( fontFamily: fontFamily, fontFamilyFallback: fontFamilyFallback, fontSize: fontSize, height: height, leadingDistribution: leadingDistribution, leading: leading, fontWeight: fontWeight, fontStyle: fontStyle, forceStrutHeight: forceStrutHeight, ); @override ui.Gradient createSweepGradient( ui.Offset center, List<ui.Color> colors, [ List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, double startAngle = 0.0, double endAngle = math.pi * 2, Float32List? matrix4 ]) => SkwasmGradient.sweep( center: center, colors: colors, colorStops: colorStops, tileMode: tileMode, startAngle: startAngle, endAngle: endAngle, matrix4: matrix4 ); @override ui.TextStyle createTextStyle({ ui.Color? color, ui.TextDecoration? decoration, ui.Color? decorationColor, ui.TextDecorationStyle? decorationStyle, double? decorationThickness, ui.FontWeight? fontWeight, ui.FontStyle? fontStyle, ui.TextBaseline? textBaseline, String? fontFamily, List<String>? fontFamilyFallback, double? fontSize, double? letterSpacing, double? wordSpacing, double? height, ui.TextLeadingDistribution? leadingDistribution, ui.Locale? locale, ui.Paint? background, ui.Paint? foreground, List<ui.Shadow>? shadows, List<ui.FontFeature>? fontFeatures, List<ui.FontVariation>? fontVariations }) => SkwasmTextStyle( color: color, decoration: decoration, decorationColor: decorationColor, decorationStyle: decorationStyle, decorationThickness: decorationThickness, fontWeight: fontWeight, fontStyle: fontStyle, textBaseline: textBaseline, fontFamily: fontFamily, fontFamilyFallback: fontFamilyFallback, fontSize: fontSize, letterSpacing: letterSpacing, wordSpacing: wordSpacing, height: height, leadingDistribution: leadingDistribution, locale: locale, background: background, foreground: foreground, shadows: shadows, fontFeatures: fontFeatures, fontVariations: fontVariations, ); @override ui.Vertices createVertices( ui.VertexMode mode, List<ui.Offset> positions, { List<ui.Offset>? textureCoordinates, List<ui.Color>? colors, List<int>? indices }) => SkwasmVertices( mode, positions, textureCoordinates: textureCoordinates, colors: colors, indices: indices ); @override ui.Vertices createVerticesRaw( ui.VertexMode mode, Float32List positions, { Float32List? textureCoordinates, Int32List? colors, Uint16List? indices }) => SkwasmVertices.raw( mode, positions, textureCoordinates: textureCoordinates, colors: colors, indices: indices ); @override void decodeImageFromPixels( Uint8List pixels, int width, int height, ui.PixelFormat format, ui.ImageDecoderCallback callback, { int? rowBytes, int? targetWidth, int? targetHeight, bool allowUpscaling = true }) { final SkwasmImage pixelImage = SkwasmImage.fromPixels( pixels, width, height, format ); final ui.Image scaledImage = scaleImageIfNeeded( pixelImage, targetWidth: targetWidth, targetHeight: targetHeight, allowUpscaling: allowUpscaling, ); callback(scaledImage); } @override FutureOr<void> initialize() { surface = SkwasmSurface(); } @override Future<ui.Codec> instantiateImageCodec( Uint8List list, { int? targetWidth, int? targetHeight, bool allowUpscaling = true }) async { final String? contentType = detectContentType(list); if (contentType == null) { throw Exception('Could not determine content type of image from data'); } final SkwasmImageDecoder baseDecoder = SkwasmImageDecoder( contentType: contentType, dataSource: list.toJS, debugSource: 'encoded image bytes', ); await baseDecoder.initialize(); if (targetWidth == null && targetHeight == null) { return baseDecoder; } return ResizingCodec( baseDecoder, targetWidth: targetWidth, targetHeight: targetHeight, allowUpscaling: allowUpscaling ); } @override Future<ui.Codec> instantiateImageCodecFromUrl( Uri uri, { ui_web.ImageCodecChunkCallback? chunkCallback }) async { final DomResponse response = await rawHttpGet(uri.toString()); final String? contentType = response.headers.get('Content-Type'); if (contentType == null) { throw Exception('Could not determine content type of image at url $uri'); } final SkwasmImageDecoder decoder = SkwasmImageDecoder( contentType: contentType, dataSource: response.body as JSObject, debugSource: uri.toString(), ); await decoder.initialize(); return decoder; } // TODO(harryterkelsen): Add multiview support, // https://github.com/flutter/flutter/issues/137073. @override Future<void> renderScene(ui.Scene scene, ui.FlutterView view) { final FrameTimingRecorder? recorder = FrameTimingRecorder.frameTimingsEnabled ? FrameTimingRecorder() : null; recorder?.recordBuildFinish(); view as EngineFlutterView; assert(view is EngineFlutterWindow, 'Skwasm does not support multi-view mode yet'); final EngineSceneView sceneView = _getSceneViewForView(view); return sceneView.renderScene(scene as EngineScene, recorder); } EngineSceneView _getSceneViewForView(EngineFlutterView view) { // TODO(mdebbar): Support multi-view mode. if (_sceneView == null) { _sceneView = EngineSceneView(SkwasmPictureRenderer(surface), view); final EngineFlutterView implicitView = EnginePlatformDispatcher.instance.implicitView!; implicitView.dom.setScene(_sceneView!.sceneElement); } return _sceneView!; } @override String get rendererTag => 'skwasm'; static final Map<String, Future<ui.FragmentProgram>> _programs = <String, Future<ui.FragmentProgram>>{}; @override void clearFragmentProgramCache() { _programs.clear(); } @override Future<ui.FragmentProgram> createFragmentProgram(String assetKey) { if (_programs.containsKey(assetKey)) { return _programs[assetKey]!; } return _programs[assetKey] = ui_web.assetManager.load(assetKey).then((ByteData data) { return SkwasmFragmentProgram.fromBytes(assetKey, data.buffer.asUint8List()); }); } @override ui.LineMetrics createLineMetrics({ required bool hardBreak, required double ascent, required double descent, required double unscaledAscent, required double height, required double width, required double left, required double baseline, required int lineNumber }) => SkwasmLineMetrics( hardBreak: hardBreak, ascent: ascent, descent: descent, unscaledAscent: unscaledAscent, height: height, width: width, left: left, baseline: baseline, lineNumber: lineNumber ); @override ui.Image createImageFromImageBitmap(DomImageBitmap imageSource) { return SkwasmImage(imageCreateFromTextureSource( imageSource as JSObject, imageSource.width.toDartInt, imageSource.height.toDartInt, surface.handle, )); } } class SkwasmPictureRenderer implements PictureRenderer { SkwasmPictureRenderer(this.surface); SkwasmSurface surface; @override FutureOr<RenderResult> renderPictures(List<ScenePicture> pictures) => surface.renderPictures(pictures.cast<SkwasmPicture>()); @override ScenePicture clipPicture(ScenePicture picture, ui.Rect clip) { final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder, clip); canvas.clipRect(clip); canvas.drawPicture(picture); return recorder.endRecording() as ScenePicture; } }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/renderer.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/renderer.dart", "repo_id": "engine", "token_count": 5037 }
262
// 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 '../../engine.dart' show registerHotRestartListener; import '../dom.dart'; import '../platform_dispatcher.dart'; import '../view_embedder/dom_manager.dart'; // TODO(yjbanov): this is a hack we use to compute ideographic baseline; this // number is the ratio ideographic/alphabetic for font Ahem, // which matches the Flutter number. It may be completely wrong // for any other font. We'll need to eventually fix this. That // said Flutter doesn't seem to use ideographic baseline for // anything as of this writing. const double baselineRatioHack = 1.1662499904632568; /// Hosts ruler DOM elements in a hidden container under [DomManager.renderingHost]. class RulerHost { RulerHost() { _rulerHost.style ..position = 'fixed' ..visibility = 'hidden' ..overflow = 'hidden' ..top = '0' ..left = '0' ..width = '0' ..height = '0'; // TODO(mdebbar): There could be multiple views with multiple rendering hosts. // https://github.com/flutter/flutter/issues/137344 final DomNode renderingHost = EnginePlatformDispatcher.instance.implicitView!.dom.renderingHost; renderingHost.appendChild(_rulerHost); registerHotRestartListener(dispose); } /// Hosts a cache of rulers that measure text. /// /// This element exists purely for organizational purposes. Otherwise the /// rulers would be attached to the `<body>` element polluting the element /// tree and making it hard to navigate. It does not serve any functional /// purpose. final DomElement _rulerHost = createDomElement('flt-ruler-host'); /// Releases the resources used by this [RulerHost]. /// /// After this is called, this object is no longer usable. void dispose() { _rulerHost.remove(); } /// Adds an element used for measuring text as a child of [_rulerHost]. void addElement(DomHTMLElement element) { _rulerHost.append(element); } } // These global variables are used to memoize calls to [measureSubstring]. They // are used to remember the last arguments passed to it, and the last return // value. // They are being initialized so that the compiler knows they'll never be null. int _lastStart = -1; int _lastEnd = -1; String _lastText = ''; String _lastCssFont = ''; double _lastWidth = -1; /// Measures the width of the substring of [text] starting from the index /// [start] (inclusive) to [end] (exclusive). /// /// This method assumes that the correct font has already been set on /// [canvasContext]. double measureSubstring( DomCanvasRenderingContext2D canvasContext, String text, int start, int end, { double? letterSpacing, }) { assert(0 <= start); assert(start <= end); assert(end <= text.length); if (start == end) { return 0; } final String cssFont = canvasContext.font; double width; // TODO(mdebbar): Explore caching all widths in a map, not only the last one. if (start == _lastStart && end == _lastEnd && text == _lastText && cssFont == _lastCssFont) { // Reuse the previously calculated width if all factors that affect width // are unchanged. The only exception is letter-spacing. We always add // letter-spacing to the width later below. width = _lastWidth; } else { final String sub = start == 0 && end == text.length ? text : text.substring(start, end); width = canvasContext.measureText(sub).width!; } _lastStart = start; _lastEnd = end; _lastText = text; _lastCssFont = cssFont; _lastWidth = width; // Now add letter spacing to the width. letterSpacing ??= 0.0; if (letterSpacing != 0.0) { width += letterSpacing * (end - start); } // What we are doing here is we are rounding to the nearest 2nd decimal // point. So 39.999423 becomes 40, and 11.243982 becomes 11.24. // The reason we are doing this is because we noticed that canvas API has a // Β±0.001 error margin. return _roundWidth(width); } double _roundWidth(double width) { return (width * 100).round() / 100; }
engine/lib/web_ui/lib/src/engine/text/measurement.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/text/measurement.dart", "repo_id": "engine", "token_count": 1397 }
263
// 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; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import 'util.dart'; class Matrix4 { /// Constructs a new mat4. factory Matrix4( double arg0, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6, double arg7, double arg8, double arg9, double arg10, double arg11, double arg12, double arg13, double arg14, double arg15) => Matrix4.zero() ..setValues(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15); /// Zero matrix. Matrix4.zero() : _m4storage = Float32List(16); /// Identity matrix. Matrix4.identity() : _m4storage = Float32List(16) { _m4storage[15] = 1.0; _m4storage[0] = 1.0; _m4storage[5] = 1.0; _m4storage[10] = 1.0; } /// Copies values from [other]. factory Matrix4.copy(Matrix4 other) => Matrix4.zero()..setFrom(other); /// Constructs a matrix that is the inverse of [other]. factory Matrix4.inverted(Matrix4 other) { final Matrix4 r = Matrix4.zero(); final double determinant = r.copyInverse(other); if (determinant == 0.0) { throw ArgumentError.value(other, 'other', 'Matrix cannot be inverted'); } return r; } /// Rotation of [radians_] around X. factory Matrix4.rotationX(double radians) => Matrix4.zero() .._m4storage[15] = 1.0 ..setRotationX(radians); /// Rotation of [radians_] around Y. factory Matrix4.rotationY(double radians) => Matrix4.zero() .._m4storage[15] = 1.0 ..setRotationY(radians); /// Rotation of [radians_] around Z. factory Matrix4.rotationZ(double radians) => Matrix4.zero() .._m4storage[15] = 1.0 ..setRotationZ(radians); /// Translation matrix. factory Matrix4.translation(Vector3 translation) => Matrix4.identity() ..setTranslation(translation); /// Translation matrix. factory Matrix4.translationValues(double x, double y, double z) => Matrix4.identity() ..setTranslationRaw(x, y, z); /// Scale matrix. factory Matrix4.diagonal3Values(double x, double y, double z) => Matrix4.zero() .._m4storage[15] = 1.0 .._m4storage[10] = z .._m4storage[5] = y .._m4storage[0] = x; /// Constructs Matrix4 with given [Float32List] as [storage]. Matrix4.fromFloat32List(this._m4storage); /// Constructs Matrix4 with a [storage] that views given [buffer] starting at /// [offset]. [offset] has to be multiple of [Float32List.bytesPerElement]. Matrix4.fromBuffer(ByteBuffer buffer, int offset) : _m4storage = Float32List.view(buffer, offset, 16); final Float32List _m4storage; /// The components of the matrix. Float32List get storage => _m4storage; /// Returns a matrix that is the inverse of [other] if [other] is invertible, /// otherwise `null`. static Matrix4? tryInvert(Matrix4 other) { final Matrix4 r = Matrix4.zero(); final double determinant = r.copyInverse(other); if (determinant == 0.0) { return null; } return r; } /// Return index in storage for [row], [col] value. int index(int row, int col) => (col * 4) + row; /// Value at [row], [col]. double entry(int row, int col) { assert((row >= 0) && (row < dimension)); assert((col >= 0) && (col < dimension)); return _m4storage[index(row, col)]; } /// Set value at [row], [col] to be [v]. void setEntry(int row, int col, double v) { assert((row >= 0) && (row < dimension)); assert((col >= 0) && (col < dimension)); _m4storage[index(row, col)] = v; } /// Sets the matrix with specified values. void setValues( double arg0, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6, double arg7, double arg8, double arg9, double arg10, double arg11, double arg12, double arg13, double arg14, double arg15) { _m4storage[15] = arg15; _m4storage[14] = arg14; _m4storage[13] = arg13; _m4storage[12] = arg12; _m4storage[11] = arg11; _m4storage[10] = arg10; _m4storage[9] = arg9; _m4storage[8] = arg8; _m4storage[7] = arg7; _m4storage[6] = arg6; _m4storage[5] = arg5; _m4storage[4] = arg4; _m4storage[3] = arg3; _m4storage[2] = arg2; _m4storage[1] = arg1; _m4storage[0] = arg0; } /// Sets the entire matrix to the matrix in [arg]. void setFrom(Matrix4 arg) { final Float32List argStorage = arg._m4storage; _m4storage[15] = argStorage[15]; _m4storage[14] = argStorage[14]; _m4storage[13] = argStorage[13]; _m4storage[12] = argStorage[12]; _m4storage[11] = argStorage[11]; _m4storage[10] = argStorage[10]; _m4storage[9] = argStorage[9]; _m4storage[8] = argStorage[8]; _m4storage[7] = argStorage[7]; _m4storage[6] = argStorage[6]; _m4storage[5] = argStorage[5]; _m4storage[4] = argStorage[4]; _m4storage[3] = argStorage[3]; _m4storage[2] = argStorage[2]; _m4storage[1] = argStorage[1]; _m4storage[0] = argStorage[0]; } /// Dimension of the matrix. int get dimension => 4; /// Access the element of the matrix at the index [i]. double operator [](int i) => _m4storage[i]; /// Set the element of the matrix at the index [i]. void operator []=(int i, double v) { _m4storage[i] = v; } /// Clone matrix. Matrix4 clone() => Matrix4.copy(this); /// Copy into [arg]. Matrix4 copyInto(Matrix4 arg) { final Float32List argStorage = arg._m4storage; // Start reading from the last element to eliminate range checks // in subsequent reads. argStorage[15] = _m4storage[15]; argStorage[0] = _m4storage[0]; argStorage[1] = _m4storage[1]; argStorage[2] = _m4storage[2]; argStorage[3] = _m4storage[3]; argStorage[4] = _m4storage[4]; argStorage[5] = _m4storage[5]; argStorage[6] = _m4storage[6]; argStorage[7] = _m4storage[7]; argStorage[8] = _m4storage[8]; argStorage[9] = _m4storage[9]; argStorage[10] = _m4storage[10]; argStorage[11] = _m4storage[11]; argStorage[12] = _m4storage[12]; argStorage[13] = _m4storage[13]; argStorage[14] = _m4storage[14]; return arg; } /// Translate this matrix by x, y, and z. void translate(double x, [double y = 0.0, double z = 0.0]) { const double tw = 1.0; final double t1 = _m4storage[0] * x + _m4storage[4] * y + _m4storage[8] * z + _m4storage[12] * tw; final double t2 = _m4storage[1] * x + _m4storage[5] * y + _m4storage[9] * z + _m4storage[13] * tw; final double t3 = _m4storage[2] * x + _m4storage[6] * y + _m4storage[10] * z + _m4storage[14] * tw; final double t4 = _m4storage[3] * x + _m4storage[7] * y + _m4storage[11] * z + _m4storage[15] * tw; _m4storage[12] = t1; _m4storage[13] = t2; _m4storage[14] = t3; _m4storage[15] = t4; } /// Scale this matrix by a [Vector3], [Vector4], or x,y,z void scale(double x, [double? y, double? z]) { final double sx = x; final double sy = y ?? x; final double sz = z ?? x; const double sw = 1.0; _m4storage[15] *= sw; _m4storage[0] *= sx; _m4storage[1] *= sx; _m4storage[2] *= sx; _m4storage[3] *= sx; _m4storage[4] *= sy; _m4storage[5] *= sy; _m4storage[6] *= sy; _m4storage[7] *= sy; _m4storage[8] *= sz; _m4storage[9] *= sz; _m4storage[10] *= sz; _m4storage[11] *= sz; _m4storage[12] *= sw; _m4storage[13] *= sw; _m4storage[14] *= sw; } /// Create a copy of [this] scaled by a [Vector3], [Vector4] or [x],[y], and /// [z]. Matrix4 scaled(double x, [double? y, double? z]) => clone()..scale(x, y, z); /// Zeros [this]. void setZero() { _m4storage[15] = 0.0; _m4storage[0] = 0.0; _m4storage[1] = 0.0; _m4storage[2] = 0.0; _m4storage[3] = 0.0; _m4storage[4] = 0.0; _m4storage[5] = 0.0; _m4storage[6] = 0.0; _m4storage[7] = 0.0; _m4storage[8] = 0.0; _m4storage[9] = 0.0; _m4storage[10] = 0.0; _m4storage[11] = 0.0; _m4storage[12] = 0.0; _m4storage[13] = 0.0; _m4storage[14] = 0.0; } /// Makes [this] into the identity matrix. void setIdentity() { _m4storage[15] = 1.0; _m4storage[0] = 1.0; _m4storage[1] = 0.0; _m4storage[2] = 0.0; _m4storage[3] = 0.0; _m4storage[4] = 0.0; _m4storage[5] = 1.0; _m4storage[6] = 0.0; _m4storage[7] = 0.0; _m4storage[8] = 0.0; _m4storage[9] = 0.0; _m4storage[10] = 1.0; _m4storage[11] = 0.0; _m4storage[12] = 0.0; _m4storage[13] = 0.0; _m4storage[14] = 0.0; } /// Returns the tranpose of this. Matrix4 transposed() => clone()..transpose(); void transpose() { double temp; temp = _m4storage[4]; _m4storage[4] = _m4storage[1]; _m4storage[1] = temp; temp = _m4storage[8]; _m4storage[8] = _m4storage[2]; _m4storage[2] = temp; temp = _m4storage[12]; _m4storage[12] = _m4storage[3]; _m4storage[3] = temp; temp = _m4storage[9]; _m4storage[9] = _m4storage[6]; _m4storage[6] = temp; temp = _m4storage[13]; _m4storage[13] = _m4storage[7]; _m4storage[7] = temp; temp = _m4storage[14]; _m4storage[14] = _m4storage[11]; _m4storage[11] = temp; } /// Returns the determinant of this matrix. double determinant() { final Float32List m = _m4storage; final double det2_01_01 = m[0] * m[5] - m[1] * m[4]; final double det2_01_02 = m[0] * m[6] - m[2] * m[4]; final double det2_01_03 = m[0] * m[7] - m[3] * m[4]; final double det2_01_12 = m[1] * m[6] - m[2] * m[5]; final double det2_01_13 = m[1] * m[7] - m[3] * m[5]; final double det2_01_23 = m[2] * m[7] - m[3] * m[6]; final double det3_201_012 = m[8] * det2_01_12 - m[9] * det2_01_02 + m[10] * det2_01_01; final double det3_201_013 = m[8] * det2_01_13 - m[9] * det2_01_03 + m[11] * det2_01_01; final double det3_201_023 = m[8] * det2_01_23 - m[10] * det2_01_03 + m[11] * det2_01_02; final double det3_201_123 = m[9] * det2_01_23 - m[10] * det2_01_13 + m[11] * det2_01_12; return -det3_201_123 * m[12] + det3_201_023 * m[13] - det3_201_013 * m[14] + det3_201_012 * m[15]; } /// Transform [arg] of type [Vector3] using the perspective transformation /// defined by [this]. Vector3 perspectiveTransform({ required double x, required double y, required double z, }) { final double transformedX = (_m4storage[0] * x) + (_m4storage[4] * y) + (_m4storage[8] * z) + _m4storage[12]; final double transformedY = (_m4storage[1] * x) + (_m4storage[5] * y) + (_m4storage[9] * z) + _m4storage[13]; final double transformedZ = (_m4storage[2] * x) + (_m4storage[6] * y) + (_m4storage[10] * z) + _m4storage[14]; final double w = 1.0 / ((_m4storage[3] * x) + (_m4storage[7] * y) + (_m4storage[11] * z) + _m4storage[15]); return ( x: transformedX * w, y: transformedY * w, z: transformedZ * w, ); } bool isIdentity() => _m4storage[0] == 1.0 && // col 1 _m4storage[1] == 0.0 && _m4storage[2] == 0.0 && _m4storage[3] == 0.0 && _m4storage[4] == 0.0 && // col 2 _m4storage[5] == 1.0 && _m4storage[6] == 0.0 && _m4storage[7] == 0.0 && _m4storage[8] == 0.0 && // col 3 _m4storage[9] == 0.0 && _m4storage[10] == 1.0 && _m4storage[11] == 0.0 && _m4storage[12] == 0.0 && // col 4 _m4storage[13] == 0.0 && _m4storage[14] == 0.0 && _m4storage[15] == 1.0; /// Whether transform is identity or simple translation using m[12,13,14]. /// /// We check for [15] first since that will eliminate bounds checks for rest. bool isIdentityOrTranslation() => _m4storage[15] == 1.0 && _m4storage[0] == 1.0 && // col 1 _m4storage[1] == 0.0 && _m4storage[2] == 0.0 && _m4storage[3] == 0.0 && _m4storage[4] == 0.0 && // col 2 _m4storage[5] == 1.0 && _m4storage[6] == 0.0 && _m4storage[7] == 0.0 && _m4storage[8] == 0.0 && // col 3 _m4storage[9] == 0.0 && _m4storage[10] == 1.0 && _m4storage[11] == 0.0; /// Returns the translation vector from this homogeneous transformation matrix. Vector3 getTranslation() { return ( x: _m4storage[12], y: _m4storage[13], z: _m4storage[14], ); } void rotate(Vector3 axis, double angle) { final double len = axis.length; final double x = axis.x / len; final double y = axis.y / len; final double z = axis.z / len; final double c = math.cos(angle); final double s = math.sin(angle); final double C = 1.0 - c; final double m11 = x * x * C + c; final double m12 = x * y * C - z * s; final double m13 = x * z * C + y * s; final double m21 = y * x * C + z * s; final double m22 = y * y * C + c; final double m23 = y * z * C - x * s; final double m31 = z * x * C - y * s; final double m32 = z * y * C + x * s; final double m33 = z * z * C + c; final double t1 = _m4storage[0] * m11 + _m4storage[4] * m21 + _m4storage[8] * m31; final double t2 = _m4storage[1] * m11 + _m4storage[5] * m21 + _m4storage[9] * m31; final double t3 = _m4storage[2] * m11 + _m4storage[6] * m21 + _m4storage[10] * m31; final double t4 = _m4storage[3] * m11 + _m4storage[7] * m21 + _m4storage[11] * m31; final double t5 = _m4storage[0] * m12 + _m4storage[4] * m22 + _m4storage[8] * m32; final double t6 = _m4storage[1] * m12 + _m4storage[5] * m22 + _m4storage[9] * m32; final double t7 = _m4storage[2] * m12 + _m4storage[6] * m22 + _m4storage[10] * m32; final double t8 = _m4storage[3] * m12 + _m4storage[7] * m22 + _m4storage[11] * m32; final double t9 = _m4storage[0] * m13 + _m4storage[4] * m23 + _m4storage[8] * m33; final double t10 = _m4storage[1] * m13 + _m4storage[5] * m23 + _m4storage[9] * m33; final double t11 = _m4storage[2] * m13 + _m4storage[6] * m23 + _m4storage[10] * m33; final double t12 = _m4storage[3] * m13 + _m4storage[7] * m23 + _m4storage[11] * m33; _m4storage[0] = t1; _m4storage[1] = t2; _m4storage[2] = t3; _m4storage[3] = t4; _m4storage[4] = t5; _m4storage[5] = t6; _m4storage[6] = t7; _m4storage[7] = t8; _m4storage[8] = t9; _m4storage[9] = t10; _m4storage[10] = t11; _m4storage[11] = t12; } void rotateZ(double angle) { final double cosAngle = math.cos(angle); final double sinAngle = math.sin(angle); final double t1 = _m4storage[0] * cosAngle + _m4storage[4] * sinAngle; final double t2 = _m4storage[1] * cosAngle + _m4storage[5] * sinAngle; final double t3 = _m4storage[2] * cosAngle + _m4storage[6] * sinAngle; final double t4 = _m4storage[3] * cosAngle + _m4storage[7] * sinAngle; final double t5 = _m4storage[0] * -sinAngle + _m4storage[4] * cosAngle; final double t6 = _m4storage[1] * -sinAngle + _m4storage[5] * cosAngle; final double t7 = _m4storage[2] * -sinAngle + _m4storage[6] * cosAngle; final double t8 = _m4storage[3] * -sinAngle + _m4storage[7] * cosAngle; _m4storage[0] = t1; _m4storage[1] = t2; _m4storage[2] = t3; _m4storage[3] = t4; _m4storage[4] = t5; _m4storage[5] = t6; _m4storage[6] = t7; _m4storage[7] = t8; } /// Sets the translation vector in this homogeneous transformation matrix. void setTranslation(Vector3 t) { _m4storage[14] = t.z; _m4storage[13] = t.y; _m4storage[12] = t.x; } /// Sets the translation vector in this homogeneous transformation matrix. void setTranslationRaw(double x, double y, double z) { _m4storage[14] = z; _m4storage[13] = y; _m4storage[12] = x; } /// Transposes just the upper 3x3 rotation matrix. void transposeRotation() { double temp; temp = _m4storage[1]; _m4storage[1] = _m4storage[4]; _m4storage[4] = temp; temp = _m4storage[2]; _m4storage[2] = _m4storage[8]; _m4storage[8] = temp; temp = _m4storage[4]; _m4storage[4] = _m4storage[1]; _m4storage[1] = temp; temp = _m4storage[6]; _m4storage[6] = _m4storage[9]; _m4storage[9] = temp; temp = _m4storage[8]; _m4storage[8] = _m4storage[2]; _m4storage[2] = temp; temp = _m4storage[9]; _m4storage[9] = _m4storage[6]; _m4storage[6] = temp; } /// Invert [this]. double invert() => copyInverse(this); /// Set this matrix to be the inverse of [arg] double copyInverse(Matrix4 arg) { final Float32List argStorage = arg._m4storage; final double a00 = argStorage[0]; final double a01 = argStorage[1]; final double a02 = argStorage[2]; final double a03 = argStorage[3]; final double a10 = argStorage[4]; final double a11 = argStorage[5]; final double a12 = argStorage[6]; final double a13 = argStorage[7]; final double a20 = argStorage[8]; final double a21 = argStorage[9]; final double a22 = argStorage[10]; final double a23 = argStorage[11]; final double a30 = argStorage[12]; final double a31 = argStorage[13]; final double a32 = argStorage[14]; final double a33 = argStorage[15]; final double b00 = a00 * a11 - a01 * a10; final double b01 = a00 * a12 - a02 * a10; final double b02 = a00 * a13 - a03 * a10; final double b03 = a01 * a12 - a02 * a11; final double b04 = a01 * a13 - a03 * a11; final double b05 = a02 * a13 - a03 * a12; final double b06 = a20 * a31 - a21 * a30; final double b07 = a20 * a32 - a22 * a30; final double b08 = a20 * a33 - a23 * a30; final double b09 = a21 * a32 - a22 * a31; final double b10 = a21 * a33 - a23 * a31; final double b11 = a22 * a33 - a23 * a32; final double det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (det == 0.0) { setFrom(arg); return 0.0; } final double invDet = 1.0 / det; _m4storage[0] = (a11 * b11 - a12 * b10 + a13 * b09) * invDet; _m4storage[1] = (-a01 * b11 + a02 * b10 - a03 * b09) * invDet; _m4storage[2] = (a31 * b05 - a32 * b04 + a33 * b03) * invDet; _m4storage[3] = (-a21 * b05 + a22 * b04 - a23 * b03) * invDet; _m4storage[4] = (-a10 * b11 + a12 * b08 - a13 * b07) * invDet; _m4storage[5] = (a00 * b11 - a02 * b08 + a03 * b07) * invDet; _m4storage[6] = (-a30 * b05 + a32 * b02 - a33 * b01) * invDet; _m4storage[7] = (a20 * b05 - a22 * b02 + a23 * b01) * invDet; _m4storage[8] = (a10 * b10 - a11 * b08 + a13 * b06) * invDet; _m4storage[9] = (-a00 * b10 + a01 * b08 - a03 * b06) * invDet; _m4storage[10] = (a30 * b04 - a31 * b02 + a33 * b00) * invDet; _m4storage[11] = (-a20 * b04 + a21 * b02 - a23 * b00) * invDet; _m4storage[12] = (-a10 * b09 + a11 * b07 - a12 * b06) * invDet; _m4storage[13] = (a00 * b09 - a01 * b07 + a02 * b06) * invDet; _m4storage[14] = (-a30 * b03 + a31 * b01 - a32 * b00) * invDet; _m4storage[15] = (a20 * b03 - a21 * b01 + a22 * b00) * invDet; return det; } double invertRotation() { final double det = determinant(); if (det == 0.0) { return 0.0; } final double invDet = 1.0 / det; double ix; double iy; double iz; double jx; double jy; double jz; double kx; double ky; double kz; ix = invDet * (_m4storage[5] * _m4storage[10] - _m4storage[6] * _m4storage[9]); iy = invDet * (_m4storage[2] * _m4storage[9] - _m4storage[1] * _m4storage[10]); iz = invDet * (_m4storage[1] * _m4storage[6] - _m4storage[2] * _m4storage[5]); jx = invDet * (_m4storage[6] * _m4storage[8] - _m4storage[4] * _m4storage[10]); jy = invDet * (_m4storage[0] * _m4storage[10] - _m4storage[2] * _m4storage[8]); jz = invDet * (_m4storage[2] * _m4storage[4] - _m4storage[0] * _m4storage[6]); kx = invDet * (_m4storage[4] * _m4storage[9] - _m4storage[5] * _m4storage[8]); ky = invDet * (_m4storage[1] * _m4storage[8] - _m4storage[0] * _m4storage[9]); kz = invDet * (_m4storage[0] * _m4storage[5] - _m4storage[1] * _m4storage[4]); _m4storage[0] = ix; _m4storage[1] = iy; _m4storage[2] = iz; _m4storage[4] = jx; _m4storage[5] = jy; _m4storage[6] = jz; _m4storage[8] = kx; _m4storage[9] = ky; _m4storage[10] = kz; return det; } /// Sets the upper 3x3 to a rotation of [radians] around X void setRotationX(double radians) { final double c = math.cos(radians); final double s = math.sin(radians); _m4storage[0] = 1.0; _m4storage[1] = 0.0; _m4storage[2] = 0.0; _m4storage[4] = 0.0; _m4storage[5] = c; _m4storage[6] = s; _m4storage[8] = 0.0; _m4storage[9] = -s; _m4storage[10] = c; _m4storage[3] = 0.0; _m4storage[7] = 0.0; _m4storage[11] = 0.0; } /// Sets the upper 3x3 to a rotation of [radians] around Y void setRotationY(double radians) { final double c = math.cos(radians); final double s = math.sin(radians); _m4storage[0] = c; _m4storage[1] = 0.0; _m4storage[2] = -s; _m4storage[4] = 0.0; _m4storage[5] = 1.0; _m4storage[6] = 0.0; _m4storage[8] = s; _m4storage[9] = 0.0; _m4storage[10] = c; _m4storage[3] = 0.0; _m4storage[7] = 0.0; _m4storage[11] = 0.0; } /// Sets the upper 3x3 to a rotation of [radians] around Z void setRotationZ(double radians) { final double c = math.cos(radians); final double s = math.sin(radians); _m4storage[0] = c; _m4storage[1] = s; _m4storage[2] = 0.0; _m4storage[4] = -s; _m4storage[5] = c; _m4storage[6] = 0.0; _m4storage[8] = 0.0; _m4storage[9] = 0.0; _m4storage[10] = 1.0; _m4storage[3] = 0.0; _m4storage[7] = 0.0; _m4storage[11] = 0.0; } /// Multiply [this] by [arg]. void multiply(Matrix4 arg) { final double m33 = _m4storage[15]; final double m00 = _m4storage[0]; final double m01 = _m4storage[4]; final double m02 = _m4storage[8]; final double m03 = _m4storage[12]; final double m10 = _m4storage[1]; final double m11 = _m4storage[5]; final double m12 = _m4storage[9]; final double m13 = _m4storage[13]; final double m20 = _m4storage[2]; final double m21 = _m4storage[6]; final double m22 = _m4storage[10]; final double m23 = _m4storage[14]; final double m30 = _m4storage[3]; final double m31 = _m4storage[7]; final double m32 = _m4storage[11]; final Float32List argStorage = arg._m4storage; final double n33 = argStorage[15]; final double n00 = argStorage[0]; final double n01 = argStorage[4]; final double n02 = argStorage[8]; final double n03 = argStorage[12]; final double n10 = argStorage[1]; final double n11 = argStorage[5]; final double n12 = argStorage[9]; final double n13 = argStorage[13]; final double n20 = argStorage[2]; final double n21 = argStorage[6]; final double n22 = argStorage[10]; final double n23 = argStorage[14]; final double n30 = argStorage[3]; final double n31 = argStorage[7]; final double n32 = argStorage[11]; _m4storage[0] = (m00 * n00) + (m01 * n10) + (m02 * n20) + (m03 * n30); _m4storage[4] = (m00 * n01) + (m01 * n11) + (m02 * n21) + (m03 * n31); _m4storage[8] = (m00 * n02) + (m01 * n12) + (m02 * n22) + (m03 * n32); _m4storage[12] = (m00 * n03) + (m01 * n13) + (m02 * n23) + (m03 * n33); _m4storage[1] = (m10 * n00) + (m11 * n10) + (m12 * n20) + (m13 * n30); _m4storage[5] = (m10 * n01) + (m11 * n11) + (m12 * n21) + (m13 * n31); _m4storage[9] = (m10 * n02) + (m11 * n12) + (m12 * n22) + (m13 * n32); _m4storage[13] = (m10 * n03) + (m11 * n13) + (m12 * n23) + (m13 * n33); _m4storage[2] = (m20 * n00) + (m21 * n10) + (m22 * n20) + (m23 * n30); _m4storage[6] = (m20 * n01) + (m21 * n11) + (m22 * n21) + (m23 * n31); _m4storage[10] = (m20 * n02) + (m21 * n12) + (m22 * n22) + (m23 * n32); _m4storage[14] = (m20 * n03) + (m21 * n13) + (m22 * n23) + (m23 * n33); _m4storage[3] = (m30 * n00) + (m31 * n10) + (m32 * n20) + (m33 * n30); _m4storage[7] = (m30 * n01) + (m31 * n11) + (m32 * n21) + (m33 * n31); _m4storage[11] = (m30 * n02) + (m31 * n12) + (m32 * n22) + (m33 * n32); _m4storage[15] = (m30 * n03) + (m31 * n13) + (m32 * n23) + (m33 * n33); } /// Multiply a copy of [this] with [arg]. Matrix4 multiplied(Matrix4 arg) => clone()..multiply(arg); /// Multiply a transposed [this] with [arg]. void transposeMultiply(Matrix4 arg) { final double m33 = _m4storage[15]; final double m00 = _m4storage[0]; final double m01 = _m4storage[1]; final double m02 = _m4storage[2]; final double m03 = _m4storage[3]; final double m10 = _m4storage[4]; final double m11 = _m4storage[5]; final double m12 = _m4storage[6]; final double m13 = _m4storage[7]; final double m20 = _m4storage[8]; final double m21 = _m4storage[9]; final double m22 = _m4storage[10]; final double m23 = _m4storage[11]; final double m30 = _m4storage[12]; final double m31 = _m4storage[13]; final double m32 = _m4storage[14]; final Float32List argStorage = arg._m4storage; _m4storage[0] = (m00 * argStorage[0]) + (m01 * argStorage[1]) + (m02 * argStorage[2]) + (m03 * argStorage[3]); _m4storage[4] = (m00 * argStorage[4]) + (m01 * argStorage[5]) + (m02 * argStorage[6]) + (m03 * argStorage[7]); _m4storage[8] = (m00 * argStorage[8]) + (m01 * argStorage[9]) + (m02 * argStorage[10]) + (m03 * argStorage[11]); _m4storage[12] = (m00 * argStorage[12]) + (m01 * argStorage[13]) + (m02 * argStorage[14]) + (m03 * argStorage[15]); _m4storage[1] = (m10 * argStorage[0]) + (m11 * argStorage[1]) + (m12 * argStorage[2]) + (m13 * argStorage[3]); _m4storage[5] = (m10 * argStorage[4]) + (m11 * argStorage[5]) + (m12 * argStorage[6]) + (m13 * argStorage[7]); _m4storage[9] = (m10 * argStorage[8]) + (m11 * argStorage[9]) + (m12 * argStorage[10]) + (m13 * argStorage[11]); _m4storage[13] = (m10 * argStorage[12]) + (m11 * argStorage[13]) + (m12 * argStorage[14]) + (m13 * argStorage[15]); _m4storage[2] = (m20 * argStorage[0]) + (m21 * argStorage[1]) + (m22 * argStorage[2]) + (m23 * argStorage[3]); _m4storage[6] = (m20 * argStorage[4]) + (m21 * argStorage[5]) + (m22 * argStorage[6]) + (m23 * argStorage[7]); _m4storage[10] = (m20 * argStorage[8]) + (m21 * argStorage[9]) + (m22 * argStorage[10]) + (m23 * argStorage[11]); _m4storage[14] = (m20 * argStorage[12]) + (m21 * argStorage[13]) + (m22 * argStorage[14]) + (m23 * argStorage[15]); _m4storage[3] = (m30 * argStorage[0]) + (m31 * argStorage[1]) + (m32 * argStorage[2]) + (m33 * argStorage[3]); _m4storage[7] = (m30 * argStorage[4]) + (m31 * argStorage[5]) + (m32 * argStorage[6]) + (m33 * argStorage[7]); _m4storage[11] = (m30 * argStorage[8]) + (m31 * argStorage[9]) + (m32 * argStorage[10]) + (m33 * argStorage[11]); _m4storage[15] = (m30 * argStorage[12]) + (m31 * argStorage[13]) + (m32 * argStorage[14]) + (m33 * argStorage[15]); } /// Multiply [this] with a transposed [arg]. void multiplyTranspose(Matrix4 arg) { final double m00 = _m4storage[0]; final double m01 = _m4storage[4]; final double m02 = _m4storage[8]; final double m03 = _m4storage[12]; final double m10 = _m4storage[1]; final double m11 = _m4storage[5]; final double m12 = _m4storage[9]; final double m13 = _m4storage[13]; final double m20 = _m4storage[2]; final double m21 = _m4storage[6]; final double m22 = _m4storage[10]; final double m23 = _m4storage[14]; final double m30 = _m4storage[3]; final double m31 = _m4storage[7]; final double m32 = _m4storage[11]; final double m33 = _m4storage[15]; final Float32List argStorage = arg._m4storage; _m4storage[0] = (m00 * argStorage[0]) + (m01 * argStorage[4]) + (m02 * argStorage[8]) + (m03 * argStorage[12]); _m4storage[4] = (m00 * argStorage[1]) + (m01 * argStorage[5]) + (m02 * argStorage[9]) + (m03 * argStorage[13]); _m4storage[8] = (m00 * argStorage[2]) + (m01 * argStorage[6]) + (m02 * argStorage[10]) + (m03 * argStorage[14]); _m4storage[12] = (m00 * argStorage[3]) + (m01 * argStorage[7]) + (m02 * argStorage[11]) + (m03 * argStorage[15]); _m4storage[1] = (m10 * argStorage[0]) + (m11 * argStorage[4]) + (m12 * argStorage[8]) + (m13 * argStorage[12]); _m4storage[5] = (m10 * argStorage[1]) + (m11 * argStorage[5]) + (m12 * argStorage[9]) + (m13 * argStorage[13]); _m4storage[9] = (m10 * argStorage[2]) + (m11 * argStorage[6]) + (m12 * argStorage[10]) + (m13 * argStorage[14]); _m4storage[13] = (m10 * argStorage[3]) + (m11 * argStorage[7]) + (m12 * argStorage[11]) + (m13 * argStorage[15]); _m4storage[2] = (m20 * argStorage[0]) + (m21 * argStorage[4]) + (m22 * argStorage[8]) + (m23 * argStorage[12]); _m4storage[6] = (m20 * argStorage[1]) + (m21 * argStorage[5]) + (m22 * argStorage[9]) + (m23 * argStorage[13]); _m4storage[10] = (m20 * argStorage[2]) + (m21 * argStorage[6]) + (m22 * argStorage[10]) + (m23 * argStorage[14]); _m4storage[14] = (m20 * argStorage[3]) + (m21 * argStorage[7]) + (m22 * argStorage[11]) + (m23 * argStorage[15]); _m4storage[3] = (m30 * argStorage[0]) + (m31 * argStorage[4]) + (m32 * argStorage[8]) + (m33 * argStorage[12]); _m4storage[7] = (m30 * argStorage[1]) + (m31 * argStorage[5]) + (m32 * argStorage[9]) + (m33 * argStorage[13]); _m4storage[11] = (m30 * argStorage[2]) + (m31 * argStorage[6]) + (m32 * argStorage[10]) + (m33 * argStorage[14]); _m4storage[15] = (m30 * argStorage[3]) + (m31 * argStorage[7]) + (m32 * argStorage[11]) + (m33 * argStorage[15]); } /// Transforms a 3-component vector in-place. void transform3(Float32List vector) { final double x = (_m4storage[0] * vector[0]) + (_m4storage[4] * vector[1]) + (_m4storage[8] * vector[2]) + _m4storage[12]; final double y = (_m4storage[1] * vector[0]) + (_m4storage[5] * vector[1]) + (_m4storage[9] * vector[2]) + _m4storage[13]; final double z = (_m4storage[2] * vector[0]) + (_m4storage[6] * vector[1]) + (_m4storage[10] * vector[2]) + _m4storage[14]; vector[0] = x; vector[1] = y; vector[2] = z; } /// Transforms a 2-component vector in-place. /// /// This transformation forgets the final Z component. If you need the /// Z component, see [transform3]. void transform2(Float32List vector) { final double x = vector[0]; final double y = vector[1]; vector[0] = (_m4storage[0] * x) + (_m4storage[4] * y) + _m4storage[12]; vector[1] = (_m4storage[1] * x) + (_m4storage[5] * y) + _m4storage[13]; } /// Transforms the input rect and calculates the bounding box of the rect /// after the transform. ui.Rect transformRect(ui.Rect rect) => transformRectWithMatrix(this, rect); /// Copies [this] into [array] starting at [offset]. void copyIntoArray(List<num> array, [int offset = 0]) { final int i = offset; array[i + 15] = _m4storage[15]; array[i + 14] = _m4storage[14]; array[i + 13] = _m4storage[13]; array[i + 12] = _m4storage[12]; array[i + 11] = _m4storage[11]; array[i + 10] = _m4storage[10]; array[i + 9] = _m4storage[9]; array[i + 8] = _m4storage[8]; array[i + 7] = _m4storage[7]; array[i + 6] = _m4storage[6]; array[i + 5] = _m4storage[5]; array[i + 4] = _m4storage[4]; array[i + 3] = _m4storage[3]; array[i + 2] = _m4storage[2]; array[i + 1] = _m4storage[1]; array[i + 0] = _m4storage[0]; } /// Copies elements from [array] into [this] starting at [offset]. void copyFromArray(List<double> array, [int offset = 0]) { final int i = offset; _m4storage[15] = array[i + 15]; _m4storage[14] = array[i + 14]; _m4storage[13] = array[i + 13]; _m4storage[12] = array[i + 12]; _m4storage[11] = array[i + 11]; _m4storage[10] = array[i + 10]; _m4storage[9] = array[i + 9]; _m4storage[8] = array[i + 8]; _m4storage[7] = array[i + 7]; _m4storage[6] = array[i + 6]; _m4storage[5] = array[i + 5]; _m4storage[4] = array[i + 4]; _m4storage[3] = array[i + 3]; _m4storage[2] = array[i + 2]; _m4storage[1] = array[i + 1]; _m4storage[0] = array[i + 0]; } /// Converts this matrix to a [Float64List]. /// /// Generally we try to stick with 32-bit floats inside the engine code /// because it's faster (see [toMatrix32]). However, this method is handy /// in tests that use the public `dart:ui` surface. /// /// This method is not optimized, but also is not meant to be fast, only /// convenient. Float64List toFloat64() { return Float64List.fromList(_m4storage); } @override String toString() { String result = super.toString(); assert(() { String fmt(int index) { return storage[index].toStringAsFixed(2); } result = '[${fmt(0)}, ${fmt(4)}, ${fmt(8)}, ${fmt(12)}]\n' '[${fmt(1)}, ${fmt(5)}, ${fmt(9)}, ${fmt(13)}]\n' '[${fmt(2)}, ${fmt(6)}, ${fmt(10)}, ${fmt(14)}]\n' '[${fmt(3)}, ${fmt(7)}, ${fmt(11)}, ${fmt(15)}]'; return true; }()); return result; } } const Vector3 kUnitX = (x: 1.0, y: 0.0, z: 0.0); const Vector3 kUnitY = (x: 0.0, y: 1.0, z: 0.0); const Vector3 kUnitZ = (x: 0.0, y: 0.0, z: 1.0); /// 3D column vector. typedef Vector3 = ({double x, double y, double z}); extension Vector3Extension on Vector3 { /// Length. double get length => math.sqrt(length2); /// Length squared. double get length2 { return (x * x) + (y * y) + (z * z); } } /// Converts a matrix represented using [Float64List] to one represented using /// [Float32List]. /// /// 32-bit precision is sufficient because Flutter Engine itself (as well as /// Skia) use 32-bit precision under the hood anyway. /// /// 32-bit matrices require 2x less memory and in V8 they are allocated on the /// JavaScript heap, thus avoiding a malloc. /// /// See also: /// * https://bugs.chromium.org/p/v8/issues/detail?id=9199 /// * https://bugs.chromium.org/p/v8/issues/detail?id=2022 Float32List toMatrix32(Float64List matrix64) { final Float32List matrix32 = Float32List(16); matrix32[15] = matrix64[15]; matrix32[14] = matrix64[14]; matrix32[13] = matrix64[13]; matrix32[12] = matrix64[12]; matrix32[11] = matrix64[11]; matrix32[10] = matrix64[10]; matrix32[9] = matrix64[9]; matrix32[8] = matrix64[8]; matrix32[7] = matrix64[7]; matrix32[6] = matrix64[6]; matrix32[5] = matrix64[5]; matrix32[4] = matrix64[4]; matrix32[3] = matrix64[3]; matrix32[2] = matrix64[2]; matrix32[1] = matrix64[1]; matrix32[0] = matrix64[0]; return matrix32; } /// Converts a matrix represented using [Float32List] to one represented using /// [Float64List]. /// /// 32-bit precision is sufficient because Flutter Engine itself (as well as /// Skia) use 32-bit precision under the hood anyway. /// /// 32-bit matrices require 2x less memory and in V8 they are allocated on the /// JavaScript heap, thus avoiding a malloc. /// /// See also: /// * https://bugs.chromium.org/p/v8/issues/detail?id=9199 /// * https://bugs.chromium.org/p/v8/issues/detail?id=2022 Float64List toMatrix64(Float32List matrix32) { final Float64List matrix64 = Float64List(16); matrix64[15] = matrix32[15]; matrix64[14] = matrix32[14]; matrix64[13] = matrix32[13]; matrix64[12] = matrix32[12]; matrix64[11] = matrix32[11]; matrix64[10] = matrix32[10]; matrix64[9] = matrix32[9]; matrix64[8] = matrix32[8]; matrix64[7] = matrix32[7]; matrix64[6] = matrix32[6]; matrix64[5] = matrix32[5]; matrix64[4] = matrix32[4]; matrix64[3] = matrix32[3]; matrix64[2] = matrix32[2]; matrix64[1] = matrix32[1]; matrix64[0] = matrix32[0]; return matrix64; } // Stores matrix in a form that allows zero allocation transforms. // TODO(yjbanov): re-evaluate the need for this class. It may be an // over-optimization. It is only used by `GradientLinear` in the // HTML renderer. However that class creates a whole new WebGL // context to render the gradient, then copies the resulting // bitmap back into the destination canvas. This is multiple // orders of magnitude more computation and data copying. Saving // an allocation of one point is unlikely to save anything, but // is guaranteed to add complexity (e.g. it's stateful). class FastMatrix32 { FastMatrix32(this.matrix); final Float32List matrix; double transformedX = 0; double transformedY = 0; /// Transforms the point defined by [x] and [y] using the [matrix] and stores /// the results in [transformedX] and [transformedY]. void transform(double x, double y) { transformedX = matrix[12] + (matrix[0] * x) + (matrix[4] * y); transformedY = matrix[13] + (matrix[1] * x) + (matrix[5] * y); } String debugToString() => '${matrix[0].toStringAsFixed(3)}, ${matrix[4].toStringAsFixed(3)}, ${matrix[8].toStringAsFixed(3)}, ${matrix[12].toStringAsFixed(3)}\n' '${matrix[1].toStringAsFixed(3)}, ${matrix[5].toStringAsFixed(3)}, ${matrix[9].toStringAsFixed(3)}, ${matrix[13].toStringAsFixed(3)}\n' '${matrix[2].toStringAsFixed(3)}, ${matrix[6].toStringAsFixed(3)}, ${matrix[10].toStringAsFixed(3)}, ${matrix[14].toStringAsFixed(3)}\n' '${matrix[3].toStringAsFixed(3)}, ${matrix[7].toStringAsFixed(3)}, ${matrix[11].toStringAsFixed(3)}, ${matrix[15].toStringAsFixed(3)}\n'; }
engine/lib/web_ui/lib/src/engine/vector_math.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/vector_math.dart", "repo_id": "engine", "token_count": 18343 }
264
// 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. /// This library defines the web equivalent of the native dart:ui. /// /// All types in this library are public. library ui; import 'dart:async'; import 'dart:collection' as collection; import 'dart:convert'; import 'dart:math' as math; import 'dart:typed_data'; import 'src/engine.dart' as engine; import 'ui_web/src/ui_web.dart' as ui_web; part 'annotations.dart'; part 'canvas.dart'; part 'channel_buffers.dart'; part 'compositing.dart'; part 'geometry.dart'; part 'hash_codes.dart'; part 'initialization.dart'; part 'key.dart'; part 'lerp.dart'; part 'math.dart'; part 'natives.dart'; part 'painting.dart'; part 'path.dart'; part 'path_metrics.dart'; part 'platform_dispatcher.dart'; part 'platform_isolate.dart'; part 'pointer.dart'; part 'semantics.dart'; part 'text.dart'; part 'tile_mode.dart'; part 'window.dart';
engine/lib/web_ui/lib/ui.dart/0
{ "file_path": "engine/lib/web_ui/lib/ui.dart", "repo_id": "engine", "token_count": 358 }
265
// 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. #include "export.h" #include "helpers.h" #include "third_party/skia/include/core/SkContourMeasure.h" #include "third_party/skia/include/core/SkPath.h" using namespace Skwasm; SKWASM_EXPORT SkContourMeasureIter* contourMeasureIter_create(SkPath* path, bool forceClosed, SkScalar resScale) { return new SkContourMeasureIter(*path, forceClosed, resScale); } SKWASM_EXPORT SkContourMeasure* contourMeasureIter_next( SkContourMeasureIter* iter) { auto next = iter->next(); if (next) { next->ref(); } return next.get(); } SKWASM_EXPORT void contourMeasureIter_dispose(SkContourMeasureIter* iter) { delete iter; } SKWASM_EXPORT void contourMeasure_dispose(SkContourMeasure* measure) { measure->unref(); } SKWASM_EXPORT SkScalar contourMeasure_length(SkContourMeasure* measure) { return measure->length(); } SKWASM_EXPORT bool contourMeasure_isClosed(SkContourMeasure* measure) { return measure->isClosed(); } SKWASM_EXPORT bool contourMeasure_getPosTan(SkContourMeasure* measure, SkScalar distance, SkPoint* outPosition, SkVector* outTangent) { return measure->getPosTan(distance, outPosition, outTangent); } SKWASM_EXPORT SkPath* contourMeasure_getSegment(SkContourMeasure* measure, SkScalar startD, SkScalar stopD, bool startWithMoveTo) { SkPath* outPath = new SkPath(); if (!measure->getSegment(startD, stopD, outPath, startWithMoveTo)) { delete outPath; return nullptr; } return outPath; }
engine/lib/web_ui/skwasm/contour_measure.cpp/0
{ "file_path": "engine/lib/web_ui/skwasm/contour_measure.cpp", "repo_id": "engine", "token_count": 837 }
266
// 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. #include "../export.h" #include "third_party/skia/modules/skparagraph/include/Paragraph.h" using namespace skia::textlayout; SKWASM_EXPORT LineMetrics* lineMetrics_create(bool hardBreak, double ascent, double descent, double unscaledAscent, double height, double width, double left, double baseline, size_t lineNumber) { auto metrics = new LineMetrics(); metrics->fHardBreak = hardBreak; metrics->fAscent = ascent; metrics->fDescent = descent; metrics->fUnscaledAscent = unscaledAscent; metrics->fHeight = height; metrics->fWidth = width; metrics->fLeft = left; metrics->fBaseline = baseline; metrics->fLineNumber = lineNumber; return metrics; } SKWASM_EXPORT void lineMetrics_dispose(LineMetrics* metrics) { delete metrics; } SKWASM_EXPORT bool lineMetrics_getHardBreak(LineMetrics* metrics) { return metrics->fHardBreak; } SKWASM_EXPORT SkScalar lineMetrics_getAscent(LineMetrics* metrics) { return metrics->fAscent; } SKWASM_EXPORT SkScalar lineMetrics_getDescent(LineMetrics* metrics) { return metrics->fDescent; } SKWASM_EXPORT SkScalar lineMetrics_getUnscaledAscent(LineMetrics* metrics) { return metrics->fUnscaledAscent; } SKWASM_EXPORT SkScalar lineMetrics_getHeight(LineMetrics* metrics) { return metrics->fHeight; } SKWASM_EXPORT SkScalar lineMetrics_getWidth(LineMetrics* metrics) { return metrics->fWidth; } SKWASM_EXPORT SkScalar lineMetrics_getLeft(LineMetrics* metrics) { return metrics->fLeft; } SKWASM_EXPORT SkScalar lineMetrics_getBaseline(LineMetrics* metrics) { return metrics->fBaseline; } SKWASM_EXPORT int lineMetrics_getLineNumber(LineMetrics* metrics) { return metrics->fLineNumber; } SKWASM_EXPORT size_t lineMetrics_getStartIndex(LineMetrics* metrics) { return metrics->fStartIndex; } SKWASM_EXPORT size_t lineMetrics_getEndIndex(LineMetrics* metrics) { return metrics->fEndIndex; }
engine/lib/web_ui/skwasm/text/line_metrics.cpp/0
{ "file_path": "engine/lib/web_ui/skwasm/text/line_metrics.cpp", "repo_id": "engine", "token_count": 1070 }
267
// 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.dart'; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } class DummyDisplayCanvas extends DisplayCanvas { @override void dispose() {} final DomElement _element = createDomElement('div'); @override DomElement get hostElement => _element; @override void initialize() {} @override bool get isConnected => throw UnimplementedError(); } void testMain() { group('$DisplayCanvasFactory', () { setUpCanvasKitTest(withImplicitView: true); test('getCanvas', () { final DisplayCanvasFactory<DisplayCanvas> factory = DisplayCanvasFactory<DisplayCanvas>( createCanvas: () => DummyDisplayCanvas()); expect(factory.baseCanvas, isNotNull); expect(factory.debugSurfaceCount, equals(1)); // Get a canvas from the factory, it should be unique. final DisplayCanvas newCanvas = factory.getCanvas(); expect(newCanvas, isNot(equals(factory.baseCanvas))); expect(factory.debugSurfaceCount, equals(2)); // Get another canvas from the factory. Now we are at maximum capacity. final DisplayCanvas anotherCanvas = factory.getCanvas(); expect(anotherCanvas, isNot(equals(factory.baseCanvas))); expect(factory.debugSurfaceCount, equals(3)); }); test('releaseCanvas', () { final DisplayCanvasFactory<DisplayCanvas> factory = DisplayCanvasFactory<DisplayCanvas>( createCanvas: () => DummyDisplayCanvas()); // Create a new canvas and immediately release it. final DisplayCanvas canvas = factory.getCanvas(); factory.releaseCanvas(canvas); // If we create a new canvas, it should be the same as the one we // just created. final DisplayCanvas newCanvas = factory.getCanvas(); expect(newCanvas, equals(canvas)); }); test('isLive', () { final DisplayCanvasFactory<DisplayCanvas> factory = DisplayCanvasFactory<DisplayCanvas>( createCanvas: () => DummyDisplayCanvas()); expect(factory.isLive(factory.baseCanvas), isTrue); final DisplayCanvas canvas = factory.getCanvas(); expect(factory.isLive(canvas), isTrue); factory.releaseCanvas(canvas); expect(factory.isLive(canvas), isFalse); }); test('hot restart', () { void expectDisposed(DisplayCanvas canvas) { expect(canvas.isConnected, isFalse); } final EngineFlutterView implicitView = EnginePlatformDispatcher.instance.implicitView!; final DisplayCanvasFactory<DisplayCanvas> originalFactory = CanvasKitRenderer.instance .debugGetRasterizerForView(implicitView)! .displayFactory; // Cause the surface and its canvas to be attached to the page implicitView.dom.sceneHost .prepend(originalFactory.baseCanvas.hostElement); expect(originalFactory.baseCanvas.isConnected, isTrue); // Create a few overlay canvases final List<DisplayCanvas> overlays = <DisplayCanvas>[]; for (int i = 0; i < 3; i++) { final DisplayCanvas canvas = originalFactory.getCanvas(); implicitView.dom.sceneHost.prepend(canvas.hostElement); overlays.add(canvas); } expect(originalFactory.debugSurfaceCount, 4); // Trigger hot restart clean-up logic and check that we indeed clean up. debugEmulateHotRestart(); expectDisposed(originalFactory.baseCanvas); overlays.forEach(expectDisposed); expect(originalFactory.debugSurfaceCount, 1); }); }); }
engine/lib/web_ui/test/canvaskit/display_canvas_factory_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/display_canvas_factory_test.dart", "repo_id": "engine", "token_count": 1394 }
268
// 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.dart'; import '../common/matchers.dart'; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('CkPaint', () { setUpCanvasKitTest(); test('lifecycle', () { final CkPaint paint = CkPaint(); expect(paint.skiaObject, isNotNull); expect(paint.debugRef.isDisposed, isFalse); paint.dispose(); expect(paint.debugRef.isDisposed, isTrue); expect( reason: 'Cannot dispose more than once', () => paint.dispose(), throwsA(isAssertionError), ); }); }); }
engine/lib/web_ui/test/canvaskit/painting_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/painting_test.dart", "repo_id": "engine", "token_count": 331 }
269
// 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:convert'; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; class FakeAssetManager implements ui_web.AssetManager { FakeAssetManager(); @override String get assetsDir => 'assets'; @override String getAssetUrl(String asset) => asset; @override Future<ByteData> load(String assetKey) async { final ByteData? assetData = await _currentScope?.getAssetData(assetKey); if (assetData == null) { throw HttpFetchNoPayloadError(assetKey, status: 404); } return assetData; } @override Future<HttpFetchResponse> loadAsset(String asset) async { final ByteData? assetData = await _currentScope?.getAssetData(asset); if (assetData != null) { return MockHttpFetchResponse( url: asset, status: 200, payload: MockHttpFetchPayload( byteBuffer: assetData.buffer, ), ); } else { return MockHttpFetchResponse( url: asset, status: 404, ); } } FakeAssetScope pushAssetScope() { final FakeAssetScope scope = FakeAssetScope._(_currentScope); _currentScope = scope; return scope; } void popAssetScope(FakeAssetScope scope) { assert(_currentScope == scope); _currentScope = scope._parent; } FakeAssetScope? _currentScope; } class FakeAssetScope { FakeAssetScope._(this._parent); final FakeAssetScope? _parent; final Map<String, Future<ByteData> Function()> _assetFetcherMap = <String, Future<ByteData> Function()>{}; void setAsset(String assetKey, ByteData assetData) { _assetFetcherMap[assetKey] = () async => assetData; } void setAssetPassthrough(String assetKey) { _assetFetcherMap[assetKey] = () async { return ByteData.view(await httpFetchByteBuffer(assetKey)); }; } Future<ByteData>? getAssetData(String assetKey) { final Future<ByteData> Function()? fetcher = _assetFetcherMap[assetKey]; if (fetcher != null) { return fetcher(); } if (_parent != null) { return _parent.getAssetData(assetKey); } return null; } } FakeAssetManager fakeAssetManager = FakeAssetManager(); ByteData stringAsUtf8Data(String string) { return ByteData.sublistView(utf8.encode(string)); } const String ahemFontFamily = 'Ahem'; const String ahemFontUrl = '/assets/fonts/ahem.ttf'; const String robotoFontFamily = 'Roboto'; const String robotoTestFontUrl = '/assets/fonts/Roboto-Regular.ttf'; const String robotoVariableFontFamily = 'RobotoVariable'; const String robotoVariableFontUrl = '/assets/fonts/RobotoSlab-VariableFont_wght.ttf'; /// The list of test fonts, in the form of font family name - font file url pairs. /// This list does not include embedded test fonts, which need to be loaded and /// registered separately in [FontCollection.debugDownloadTestFonts]. const Map<String, String> testFontUrls = <String, String>{ ahemFontFamily: ahemFontUrl, robotoFontFamily: robotoTestFontUrl, robotoVariableFontFamily: robotoVariableFontUrl, }; FakeAssetScope configureDebugFontsAssetScope(FakeAssetManager manager) { final FakeAssetScope scope = manager.pushAssetScope(); scope.setAsset('AssetManifest.json', stringAsUtf8Data('{}')); scope.setAsset('FontManifest.json', stringAsUtf8Data(''' [ { "family":"$robotoFontFamily", "fonts":[{"asset":"$robotoTestFontUrl"}] }, { "family":"$ahemFontFamily", "fonts":[{"asset":"$ahemFontUrl"}] }, { "family":"$robotoVariableFontFamily", "fonts":[{"asset":"$robotoVariableFontUrl"}] } ]''')); scope.setAssetPassthrough(robotoTestFontUrl); scope.setAssetPassthrough(ahemFontUrl); scope.setAssetPassthrough(robotoVariableFontUrl); return scope; }
engine/lib/web_ui/test/common/fake_asset_manager.dart/0
{ "file_path": "engine/lib/web_ui/test/common/fake_asset_manager.dart", "repo_id": "engine", "token_count": 1402 }
270
// 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.dart'; import 'package:ui/ui.dart' as ui; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('EngineFlutterDisplay', () { test('overrides and restores devicePixelRatio', () { final EngineFlutterDisplay display = EngineFlutterDisplay( id: 0, size: const ui.Size(100.0, 100.0), refreshRate: 60.0, ); final double originalDevicePixelRatio = display.devicePixelRatio; display.debugOverrideDevicePixelRatio(99.3); expect(display.devicePixelRatio, 99.3); display.debugOverrideDevicePixelRatio(null); expect(display.devicePixelRatio, originalDevicePixelRatio); }); }); }
engine/lib/web_ui/test/engine/display_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/display_test.dart", "repo_id": "engine", "token_count": 339 }
271
// 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/util.dart'; typedef TestCacheEntry = ({String key, int value}); void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { test('$LruCache starts out empty', () { final LruCache<String, int> cache = LruCache<String, int>(10); expect(cache.length, 0); }); test('$LruCache adds up to a maximum number of items in most recently used first order', () { final LruCache<String, int> cache = LruCache<String, int>(3); cache.cache('a', 1); expect(cache.debugItemQueue.toList(), <TestCacheEntry>[ (key: 'a', value: 1), ]); expect(cache['a'], 1); expect(cache['b'], isNull); cache.cache('b', 2); expect(cache.debugItemQueue.toList(), <TestCacheEntry>[ (key: 'b', value: 2), (key: 'a', value: 1), ]); expect(cache['a'], 1); expect(cache['b'], 2); cache.cache('c', 3); expect(cache.debugItemQueue.toList(), <TestCacheEntry>[ (key: 'c', value: 3), (key: 'b', value: 2), (key: 'a', value: 1), ]); cache.cache('d', 4); expect(cache.debugItemQueue.toList(), <TestCacheEntry>[ (key: 'd', value: 4), (key: 'c', value: 3), (key: 'b', value: 2), ]); cache.cache('e', 5); expect(cache.debugItemQueue.toList(), <TestCacheEntry>[ (key: 'e', value: 5), (key: 'd', value: 4), (key: 'c', value: 3), ]); }); test('$LruCache promotes entry to most recently used position', () { final LruCache<String, int> cache = LruCache<String, int>(3); cache.cache('a', 1); cache.cache('b', 2); cache.cache('c', 3); expect(cache.debugItemQueue.toList(), <TestCacheEntry>[ (key: 'c', value: 3), (key: 'b', value: 2), (key: 'a', value: 1), ]); cache.cache('b', 2); expect(cache.debugItemQueue.toList(), <TestCacheEntry>[ (key: 'b', value: 2), (key: 'c', value: 3), (key: 'a', value: 1), ]); }); test('$LruCache updates and promotes entry to most recently used position', () { final LruCache<String, int> cache = LruCache<String, int>(3); cache.cache('a', 1); cache.cache('b', 2); cache.cache('c', 3); expect(cache.debugItemQueue.toList(), <TestCacheEntry>[ (key: 'c', value: 3), (key: 'b', value: 2), (key: 'a', value: 1), ]); expect(cache['b'], 2); cache.cache('b', 42); expect(cache.debugItemQueue.toList(), <TestCacheEntry>[ (key: 'b', value: 42), (key: 'c', value: 3), (key: 'a', value: 1), ]); expect(cache['b'], 42); }); }
engine/lib/web_ui/test/engine/lru_cache_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/lru_cache_test.dart", "repo_id": "engine", "token_count": 1185 }
272
// 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:async'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart' hide window; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../common/matchers.dart'; import 'history_test.dart'; Map<String, dynamic> _tagStateWithSerialCount(dynamic state, int serialCount) { return <String, dynamic> { 'serialCount': serialCount, 'state': state, }; } void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { late EngineFlutterWindow myWindow; final EnginePlatformDispatcher dispatcher = EnginePlatformDispatcher.instance; setUp(() { myWindow = EngineFlutterView.implicit(dispatcher, createDomHTMLDivElement()); dispatcher.viewManager.registerView(myWindow); }); tearDown(() async { dispatcher.viewManager.unregisterView(myWindow.viewId); await myWindow.resetHistory(); myWindow.dispose(); }); // For now, web always has an implicit view provided by the web engine. test('EnginePlatformDispatcher.instance.implicitView should be non-null', () async { expect(EnginePlatformDispatcher.instance.implicitView, isNotNull); expect(EnginePlatformDispatcher.instance.implicitView?.viewId, 0); expect(myWindow.viewId, 0); }); test('window.defaultRouteName should work with a custom url strategy', () async { const String path = '/initial'; const Object state = <dynamic, dynamic>{'origin': true}; final _SampleUrlStrategy customStrategy = _SampleUrlStrategy(path, state); await myWindow.debugInitializeHistory(customStrategy, useSingle: true); expect(myWindow.defaultRouteName, '/initial'); // Also make sure that the custom url strategy was actually used. expect(customStrategy.wasUsed, isTrue); }); test('window.defaultRouteName should not change', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/initial'), ); await myWindow.debugInitializeHistory(strategy, useSingle: true); expect(myWindow.defaultRouteName, '/initial'); // Changing the URL in the address bar later shouldn't affect [window.defaultRouteName]. strategy.replaceState(null, '', '/newpath'); expect(myWindow.defaultRouteName, '/initial'); }); // window.defaultRouteName is now permanently decoupled from the history, // even in subsequent tests, because the PlatformDispatcher caches it. test('window.defaultRouteName should reset after navigation platform message', () async { await myWindow.debugInitializeHistory(TestUrlStrategy.fromEntry( // The URL here does not set the PlatformDispatcher's defaultRouteName, // since it got cached as soon as we read it above. const TestHistoryEntry('initial state', null, '/not-really-inital/THIS_IS_IGNORED'), ), useSingle: true); // Reading it multiple times should return the same value. expect(myWindow.defaultRouteName, '/initial'); expect(myWindow.defaultRouteName, '/initial'); final Completer<void> callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeUpdated', <String, dynamic>{'routeName': '/bar'}, )), (_) { callback.complete(); }, ); await callback.future; // After a navigation platform message, the PlatformDispatcher's // defaultRouteName resets to "/". expect(myWindow.defaultRouteName, '/'); }); // window.defaultRouteName is now '/'. test('can switch history mode', () async { Completer<void> callback; await myWindow.debugInitializeHistory(TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/initial'), ), useSingle: false); expect(myWindow.browserHistory, isA<MultiEntriesBrowserHistory>()); Future<void> check<T>(String method, Object? arguments) async { callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(MethodCall(method, arguments)), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory, isA<T>()); } // These may be initialized as `null` // See https://github.com/flutter/flutter/issues/83158#issuecomment-847483010 await check<SingleEntryBrowserHistory>('selectSingleEntryHistory', null); // -> single await check<MultiEntriesBrowserHistory>('selectMultiEntryHistory', null); // -> multi await check<SingleEntryBrowserHistory>('selectSingleEntryHistory', <String, dynamic>{}); // -> single await check<MultiEntriesBrowserHistory>('selectMultiEntryHistory', <String, dynamic>{}); // -> multi await check<SingleEntryBrowserHistory>('routeUpdated', <String, dynamic>{'routeName': '/bar'}); // -> single await check<SingleEntryBrowserHistory>('routeInformationUpdated', <String, dynamic>{'location': '/bar'}); // does not change mode await check<MultiEntriesBrowserHistory>('selectMultiEntryHistory', <String, dynamic>{}); // -> multi await check<MultiEntriesBrowserHistory>('routeInformationUpdated', <String, dynamic>{'location': '/bar'}); // does not change mode }); test('handleNavigationMessage throws for route update methods called with null arguments', () async { expect(() async { await myWindow.handleNavigationMessage( const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeUpdated', )) ); }, throwsAssertionError); expect(() async { await myWindow.handleNavigationMessage( const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeInformationUpdated', )) ); }, throwsAssertionError); }); test('handleNavigationMessage execute request in order.', () async { // Start with multi entries. await myWindow.debugInitializeHistory(TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/initial'), ), useSingle: false); expect(myWindow.browserHistory, isA<MultiEntriesBrowserHistory>()); final List<String> executionOrder = <String>[]; await myWindow.handleNavigationMessage( const JSONMethodCodec().encodeMethodCall(const MethodCall( 'selectSingleEntryHistory', )) ).then<void>((bool data) { executionOrder.add('1'); }); await myWindow.handleNavigationMessage( const JSONMethodCodec().encodeMethodCall(const MethodCall( 'selectMultiEntryHistory', )) ).then<void>((bool data) { executionOrder.add('2'); }); await myWindow.handleNavigationMessage( const JSONMethodCodec().encodeMethodCall(const MethodCall( 'selectSingleEntryHistory', )) ).then<void>((bool data) { executionOrder.add('3'); }); await myWindow.handleNavigationMessage( const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeInformationUpdated', <String, dynamic>{ 'location': '/baz', 'state': null, }, // boom )) ).then<void>((bool data) { executionOrder.add('4'); }); // The routeInformationUpdated should finish after the browser history // has been set to single entry. expect(executionOrder.length, 4); expect(executionOrder[0], '1'); expect(executionOrder[1], '2'); expect(executionOrder[2], '3'); expect(executionOrder[3], '4'); }); test('should not throw when using nav1 and nav2 together', () async { await myWindow.debugInitializeHistory(TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/initial'), ), useSingle: false); expect(myWindow.browserHistory, isA<MultiEntriesBrowserHistory>()); // routeUpdated resets the history type Completer<void> callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeUpdated', <String, dynamic>{'routeName': '/bar'}, )), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory, isA<SingleEntryBrowserHistory>()); expect(myWindow.browserHistory.urlStrategy!.getPath(), '/bar'); // routeInformationUpdated does not callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeInformationUpdated', <String, dynamic>{ 'location': '/baz', 'state': null, }, )), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory, isA<SingleEntryBrowserHistory>()); expect(myWindow.browserHistory.urlStrategy!.getPath(), '/baz'); // they can be interleaved safely await myWindow.handleNavigationMessage( const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeUpdated', <String, dynamic>{'routeName': '/foo'}, )) ); expect(myWindow.browserHistory, isA<SingleEntryBrowserHistory>()); expect(myWindow.browserHistory.urlStrategy!.getPath(), '/foo'); }); test('should not throw when state is complex json object', () async { // Regression test https://github.com/flutter/flutter/issues/87823. await myWindow.debugInitializeHistory(TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/initial'), ), useSingle: false); expect(myWindow.browserHistory, isA<MultiEntriesBrowserHistory>()); // routeInformationUpdated does not final Completer<void> callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeInformationUpdated', <String, dynamic>{ 'location': '/baz', 'state': <String, dynamic>{ 'state1': true, 'state2': 1, 'state3': 'string', 'state4': <String, dynamic> { 'substate1': 1.0, 'substate2': 'string2', } }, }, )), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory, isA<MultiEntriesBrowserHistory>()); expect(myWindow.browserHistory.urlStrategy!.getPath(), '/baz'); final dynamic wrappedState = myWindow.browserHistory.urlStrategy!.getState(); final dynamic actualState = wrappedState['state']; expect(actualState['state1'], true); expect(actualState['state2'], 1); expect(actualState['state3'], 'string'); expect(actualState['state4']['substate1'], 1.0); expect(actualState['state4']['substate2'], 'string2'); }); test('routeInformationUpdated can handle uri', () async { await myWindow.debugInitializeHistory(TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/initial'), ), useSingle: false); expect(myWindow.browserHistory, isA<MultiEntriesBrowserHistory>()); // routeInformationUpdated does not final Completer<void> callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeInformationUpdated', <String, dynamic>{ 'uri': 'http://myhostname.com/baz?abc=def#fragment', }, )), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory, isA<MultiEntriesBrowserHistory>()); expect(myWindow.browserHistory.urlStrategy!.getPath(), '/baz?abc=def#fragment'); }); test('can replace in MultiEntriesBrowserHistory', () async { await myWindow.debugInitializeHistory(TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/initial'), ), useSingle: false); expect(myWindow.browserHistory, isA<MultiEntriesBrowserHistory>()); Completer<void> callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeInformationUpdated', <String, dynamic>{ 'location': '/baz', 'state': '/state', }, )), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory.urlStrategy!.getPath(), '/baz'); expect(myWindow.browserHistory.urlStrategy!.getState(), _tagStateWithSerialCount('/state', 1)); callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeInformationUpdated', <String, dynamic>{ 'location': '/baz', 'state': '/state1', 'replace': true }, )), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory.urlStrategy!.getPath(), '/baz'); expect(myWindow.browserHistory.urlStrategy!.getState(), _tagStateWithSerialCount('/state1', 1)); callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeInformationUpdated', <String, dynamic>{ 'location': '/foo', 'state': '/foostate1', }, )), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory.urlStrategy!.getPath(), '/foo'); expect(myWindow.browserHistory.urlStrategy!.getState(), _tagStateWithSerialCount('/foostate1', 2)); await myWindow.browserHistory.back(); expect(myWindow.browserHistory.urlStrategy!.getPath(), '/baz'); expect(myWindow.browserHistory.urlStrategy!.getState(), _tagStateWithSerialCount('/state1', 1)); }); test('initialize browser history with default url strategy (single)', () async { // On purpose, we don't initialize history on the window. We want to let the // window to self-initialize when it receives a navigation message. // Without initializing history, the default route name should be // initialized to "/" in tests. expect(myWindow.defaultRouteName, '/'); final Completer<void> callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeUpdated', <String, dynamic>{'routeName': '/bar'}, )), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory, isA<SingleEntryBrowserHistory>()); // The url strategy should've been set to the default, and the path // should've been correctly set to "/bar". expect(myWindow.browserHistory.urlStrategy, isNot(isNull)); expect(myWindow.browserHistory.urlStrategy!.getPath(), '/bar'); }, skip: isSafari); // https://github.com/flutter/flutter/issues/50836 test('initialize browser history with default url strategy (multiple)', () async { // On purpose, we don't initialize history on the window. We want to let the // window to self-initialize when it receives a navigation message. // Without initializing history, the default route name should be // initialized to "/" in tests. expect(myWindow.defaultRouteName, '/'); final Completer<void> callback = Completer<void>(); myWindow.sendPlatformMessage( 'flutter/navigation', const JSONMethodCodec().encodeMethodCall(const MethodCall( 'routeInformationUpdated', <String, dynamic>{ 'location': '/baz', 'state': null, }, )), (_) { callback.complete(); }, ); await callback.future; expect(myWindow.browserHistory, isA<MultiEntriesBrowserHistory>()); // The url strategy should've been set to the default, and the path // should've been correctly set to "/baz". expect(myWindow.browserHistory.urlStrategy, isNot(isNull)); expect(myWindow.browserHistory.urlStrategy!.getPath(), '/baz'); }, skip: isSafari); // https://github.com/flutter/flutter/issues/50836 test('can disable location strategy', () async { // Disable URL strategy. expect( () { ui_web.urlStrategy = null; }, returnsNormally, ); // History should be initialized. expect(myWindow.browserHistory, isNotNull); // But without a URL strategy. expect(myWindow.browserHistory.urlStrategy, isNull); // Current path is always "/" in this case. expect(myWindow.browserHistory.currentPath, '/'); // Perform some navigation operations. await routeInformationUpdated('/foo/bar', null); // Path should not be updated because URL strategy is disabled. expect(myWindow.browserHistory.currentPath, '/'); }); test('cannot set url strategy after it was initialized', () async { final TestUrlStrategy testStrategy = TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/'), ); await myWindow.debugInitializeHistory(testStrategy, useSingle: true); expect( () { ui_web.urlStrategy = null; }, throwsA(isAssertionError), ); }); test('cannot set url strategy more than once', () async { // First time is okay. expect( () { ui_web.urlStrategy = null; }, returnsNormally, ); // Second time is not allowed. expect( () { ui_web.urlStrategy = null; }, throwsA(isAssertionError), ); }); // Regression test for https://github.com/flutter/flutter/issues/77817 test('window.locale(s) are not nullable', () { // If the getters were nullable, these expressions would result in compiler errors. ui.PlatformDispatcher.instance.locale.countryCode; ui.PlatformDispatcher.instance.locales.first.countryCode; }); } class _SampleUrlStrategy implements ui_web.UrlStrategy { _SampleUrlStrategy(this._path, this._state); final String _path; final Object? _state; bool wasUsed = false; @override String getPath() => _path; @override Object? getState() => _state; @override ui.VoidCallback addPopStateListener(DartDomEventListener listener) { wasUsed = true; return () {}; } @override String prepareExternalUrl(String value) => ''; @override void pushState(Object? newState, String title, String url) { wasUsed = true; } @override void replaceState(Object? newState, String title, String url) { wasUsed = true; } @override Future<void> go(int delta) async { wasUsed = true; } }
engine/lib/web_ui/test/engine/routing_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/routing_test.dart", "repo_id": "engine", "token_count": 6644 }
273
// 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:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { final Float32List points = Float32List(PathIterator.kMaxBufferSize); group('PathIterator', () { test('Should return done verb for empty path', () { final SurfacePath path = SurfacePath(); final PathIterator iter = PathIterator(path.pathRef, false); expect(iter.peek(), SPath.kDoneVerb); expect(iter.next(points), SPath.kDoneVerb); }); test('Should return done when moveTo is last instruction', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); final PathIterator iter = PathIterator(path.pathRef, false); expect(iter.peek(), SPath.kMoveVerb); expect(iter.next(points), SPath.kDoneVerb); }); test('Should return lineTo', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); path.lineTo(20, 20); final PathIterator iter = PathIterator(path.pathRef, false); expect(iter.peek(), SPath.kMoveVerb); expect(iter.next(points), SPath.kMoveVerb); expect(points[0], 10); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 20); expect(iter.next(points), SPath.kDoneVerb); }); test('Should return extra lineTo if iteration is closed', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); path.lineTo(20, 20); final PathIterator iter = PathIterator(path.pathRef, true); expect(iter.peek(), SPath.kMoveVerb); expect(iter.next(points), SPath.kMoveVerb); expect(points[0], 10); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 20); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 10); expect(iter.next(points), SPath.kCloseVerb); expect(iter.next(points), SPath.kDoneVerb); }); test('Should not return extra lineTo if last point is starting point', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); path.lineTo(20, 20); path.lineTo(10, 10); final PathIterator iter = PathIterator(path.pathRef, true); expect(iter.peek(), SPath.kMoveVerb); expect(iter.next(points), SPath.kMoveVerb); expect(points[0], 10); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 20); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 10); expect(iter.next(points), SPath.kCloseVerb); expect(iter.next(points), SPath.kDoneVerb); }); test('peek should return lineTo if iteration is closed', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); path.lineTo(20, 20); final PathIterator iter = PathIterator(path.pathRef, true); expect(iter.next(points), SPath.kMoveVerb); expect(iter.next(points), SPath.kLineVerb); expect(iter.peek(), SPath.kLineVerb); }); }); }
engine/lib/web_ui/test/engine/surface/path/path_iterator_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/surface/path/path_iterator_test.dart", "repo_id": "engine", "token_count": 1264 }
274
// 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. @TestOn('browser') library; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine/dom.dart'; import 'package:ui/src/engine/view_embedder/embedding_strategy/custom_element_embedding_strategy.dart'; void main() { internalBootstrapBrowserTest(() => doTests); } void doTests() { late CustomElementEmbeddingStrategy strategy; late DomElement target; group('initialize', () { setUp(() { target = createDomElement('this-is-the-target'); domDocument.body!.append(target); strategy = CustomElementEmbeddingStrategy(target); }); tearDown(() { target.remove(); }); test('Prepares target environment', () { expect(target.getAttribute('flt-embedding'), 'custom-element', reason: 'Should identify itself as a specific key=value into the target element.'); }); }); group('attachViewRoot', () { setUp(() { target = createDomElement('this-is-the-target'); domDocument.body!.append(target); strategy = CustomElementEmbeddingStrategy(target); }); tearDown(() { target.remove(); }); test('Should attach glasspane into embedder target (body)', () async { final DomElement glassPane = createDomElement('some-tag-for-tests'); final DomCSSStyleDeclaration style = glassPane.style; expect(glassPane.isConnected, isFalse); expect(style.position, '', reason: 'Should not have any specific position.'); expect(style.width, '', reason: 'Should not have any size set.'); strategy.attachViewRoot(glassPane); // Assert injection into <body> expect(glassPane.isConnected, isTrue, reason: 'Should inject glassPane into the document.'); expect(glassPane.parent, target, reason: 'Should inject glassPane into the target element'); final DomCSSStyleDeclaration styleAfter = glassPane.style; // Assert required styling to cover the viewport expect(styleAfter.position, 'relative', reason: 'Should be relatively positioned.'); expect(styleAfter.display, 'block', reason: 'Should be display:block.'); expect(styleAfter.width, '100%', reason: 'Should take 100% of the available width'); expect(styleAfter.height, '100%', reason: 'Should take 100% of the available height'); expect(styleAfter.overflow, 'hidden', reason: 'Should hide the occasional oversized canvas elements.'); }); }); }
engine/lib/web_ui/test/engine/view_embedder/embedding_strategy/custom_element_embedding_strategy_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/view_embedder/embedding_strategy/custom_element_embedding_strategy_test.dart", "repo_id": "engine", "token_count": 950 }
275
// 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.dart'; import 'package:ui/ui.dart'; import '../common/test_initialization.dart'; import 'paragraph/helper.dart'; import 'screenshot.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); /// Regression test for https://github.com/flutter/flutter/issues/64734. test('Clips using difference', () async { const Offset shift = Offset(8, 8); const Rect region = Rect.fromLTRB(0, 0, 400, 300); final RecordingCanvas canvas = RecordingCanvas(region); final Rect titleRect = const Rect.fromLTWH(20, 0, 50, 20).shift(shift); final SurfacePaint paint = SurfacePaint() ..style = PaintingStyle.stroke ..color = const Color(0xff000000) ..strokeWidth = 1; canvas.save(); try { final Rect borderRect = Rect.fromLTRB(0, 10, region.width, region.height).shift(shift); canvas.clipRect(titleRect, ClipOp.difference); canvas.drawRect(borderRect, paint); } finally { canvas.restore(); } canvas.drawRect(titleRect, paint); await canvasScreenshot(canvas, 'clip_op_difference', region: const Rect.fromLTRB(0, 0, 420, 360)); }); /// Regression test for https://github.com/flutter/flutter/issues/86345 test('Clips with zero width or height', () async { const Rect region = Rect.fromLTRB(0, 0, 400, 300); final RecordingCanvas canvas = RecordingCanvas(region); final SurfacePaint paint = SurfacePaint() ..style = PaintingStyle.fill ..color = const Color(0xff00ff00); final SurfacePaint borderPaint = SurfacePaint() ..style = PaintingStyle.stroke ..color = const Color(0xffff0000) ..strokeWidth = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { final double x = 10 + i * 70; final double y = 10 + j * 70; canvas.save(); // Clip. canvas.clipRect( Rect.fromLTWH(x, y, i * 25, j * 25), ClipOp.intersect, ); // Draw the blue (clipped) rect. canvas.drawRect( Rect.fromLTWH(x, y, 50, 50), paint, ); final Paragraph p = plain( EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 34), '23', textStyle: EngineTextStyle.only(color: const Color(0xff0000ff)), ); p.layout(const ParagraphConstraints(width: double.infinity)); canvas.drawParagraph(p, Offset(x, y)); canvas.restore(); // Draw the red border. canvas.drawRect( Rect.fromLTWH(x, y, 50, 50), borderPaint, ); } } await canvasScreenshot(canvas, 'clip_zero_width_height', region: region); }); }
engine/lib/web_ui/test/html/clip_op_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/clip_op_golden_test.dart", "repo_id": "engine", "token_count": 1240 }
276
// 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.dart'; import 'package:ui/ui.dart'; import '../screenshot.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { late RecordingCanvas rc; const Rect canvasRect = Rect.fromLTWH(0, 0, 500, 100); const Rect region = Rect.fromLTWH(8, 8, 500, 100); // Compensate for old golden tester padding final SurfacePaint niceRRectPaint = SurfacePaint() ..color = const Color.fromRGBO(250, 186, 218, 1.0) // #fabada ..style = PaintingStyle.fill; // Some values to see how the algo behaves as radius get absurdly large const List<double> rRectRadii = <double>[0, 10, 20, 80, 8000]; const Radius someFixedRadius = Radius.circular(10); setUp(() { rc = RecordingCanvas(const Rect.fromLTWH(0, 0, 500, 100)); rc.translate(10, 10); // Center }); test('round square with big (equal) radius ends up as a circle', () async { for (int i = 0; i < 5; i++) { rc.drawRRect( RRect.fromRectAndRadius(Rect.fromLTWH(100 * i.toDouble(), 0, 80, 80), Radius.circular(rRectRadii[i])), niceRRectPaint); } await canvasScreenshot(rc, 'canvas_rrect_round_square', canvasRect: canvasRect, region: region); }); /// Regression test for https://github.com/flutter/flutter/issues/62631 test('round square with flipped left/right coordinates', () async { rc.translate(35, 320); rc.drawRRect( RRect.fromRectAndRadius( const Rect.fromLTRB(-30, -100, 30, -300), const Radius.circular(30)), niceRRectPaint); rc.drawPath(Path()..moveTo(0, 0)..lineTo(20, 0), niceRRectPaint); await canvasScreenshot(rc, 'canvas_rrect_flipped', canvasRect: canvasRect, region: const Rect.fromLTWH(0, 0, 100, 200)); }); test('round rect with big radius scale down smaller radius', () async { for (int i = 0; i < 5; i++) { final Radius growingRadius = Radius.circular(rRectRadii[i]); final RRect rrect = RRect.fromRectAndCorners( Rect.fromLTWH(100 * i.toDouble(), 0, 80, 80), bottomRight: someFixedRadius, topRight: growingRadius, bottomLeft: growingRadius); rc.drawRRect(rrect, niceRRectPaint); } await canvasScreenshot(rc, 'canvas_rrect_overlapping_radius', canvasRect: canvasRect, region: region); }); test('diff round rect with big radius scale down smaller radius', () async { for (int i = 0; i < 5; i++) { final Radius growingRadius = Radius.circular(rRectRadii[i]); final RRect outerRRect = RRect.fromRectAndCorners( Rect.fromLTWH(100 * i.toDouble(), 0, 80, 80), bottomRight: someFixedRadius, topRight: growingRadius, bottomLeft: growingRadius); // Inner is half of outer, but offset a little so it looks nicer final RRect innerRRect = RRect.fromRectAndCorners( Rect.fromLTWH(100 * i.toDouble() + 5, 5, 40, 40), bottomRight: someFixedRadius / 2, topRight: growingRadius / 2, bottomLeft: growingRadius / 2); rc.drawDRRect(outerRRect, innerRRect, niceRRectPaint); } await canvasScreenshot(rc, 'canvas_drrect_overlapping_radius', canvasRect: canvasRect, region: region); }); }
engine/lib/web_ui/test/html/drawing/canvas_rrect_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/drawing/canvas_rrect_golden_test.dart", "repo_id": "engine", "token_count": 1335 }
277
// 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:async'; import 'package:test/bootstrap/browser.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' hide window; import '../../common/test_initialization.dart'; import 'text_goldens.dart'; const String threeLines = 'First\nSecond\nThird'; const String veryLong = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { final EngineGoldenTester goldenTester = await EngineGoldenTester.initialize( viewportSize: const Size(800, 800), ); setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); testEachCanvas('maxLines clipping', (EngineCanvas canvas) { Offset offset = Offset.zero; CanvasParagraph p; // All three lines are rendered. p = paragraph(threeLines); canvas.drawParagraph(p, offset); offset = offset.translate(0, p.height + 10); // Only the first two lines are rendered. p = paragraph(threeLines, paragraphStyle: ParagraphStyle(maxLines: 2)); canvas.drawParagraph(p, offset); offset = offset.translate(0, p.height + 10); // The whole text is rendered. p = paragraph(veryLong, maxWidth: 200); canvas.drawParagraph(p, offset); offset = offset.translate(0, p.height + 10); // Only the first two lines are rendered. p = paragraph(veryLong, paragraphStyle: ParagraphStyle(maxLines: 2), maxWidth: 200); canvas.drawParagraph(p, offset); offset = offset.translate(0, p.height + 10); return goldenTester.diffCanvasScreenshot(canvas, 'text_max_lines'); }); }
engine/lib/web_ui/test/html/paragraph/text_overflow_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/paragraph/text_overflow_golden_test.dart", "repo_id": "engine", "token_count": 653 }
278
// 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.dart'; import 'package:ui/ui.dart'; import 'package:web_engine_tester/golden_tester.dart'; import '../common/test_initialization.dart'; const Color _kShadowColor = Color.fromARGB(255, 0, 0, 0); void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const Rect region = Rect.fromLTWH(0, 0, 550, 300); late SurfaceSceneBuilder builder; setUpUnitTests( emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); setUp(() { builder = SurfaceSceneBuilder(); }); void paintShapeOutline() { final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(Rect.largest); canvas.drawRect( const Rect.fromLTRB(0.0, 0.0, 20.0, 20.0), SurfacePaint() ..color = const Color.fromARGB(255, 0, 0, 255) ..style = PaintingStyle.stroke ..strokeWidth = 1.0, ); builder.addPicture(Offset.zero, recorder.endRecording()); } void paintShadowBounds(SurfacePath path, double elevation) { final Rect shadowBounds = computePenumbraBounds(path.getBounds(), elevation); final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(Rect.largest); canvas.drawRect( shadowBounds, SurfacePaint() ..color = const Color.fromARGB(255, 0, 255, 0) ..style = PaintingStyle.stroke ..strokeWidth = 1.0, ); builder.addPicture(Offset.zero, recorder.endRecording()); } void paintBitmapCanvasShadow( double elevation, Offset offset, bool transparentOccluder) { final SurfacePath path = SurfacePath() ..addRect(const Rect.fromLTRB(0, 0, 20, 20)); builder.pushOffset(offset.dx, offset.dy); final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(Rect.largest); canvas .debugEnforceArbitraryPaint(); // make sure DOM canvas doesn't take over canvas.drawShadow( path, _kShadowColor, elevation, transparentOccluder, ); builder.addPicture(Offset.zero, recorder.endRecording()); paintShapeOutline(); paintShadowBounds(path, elevation); builder.pop(); // offset } void paintBitmapCanvasComplexPathShadow(double elevation, Offset offset) { final SurfacePath path = SurfacePath() ..moveTo(10, 0) ..lineTo(20, 10) ..lineTo(10, 20) ..lineTo(0, 10) ..close(); builder.pushOffset(offset.dx, offset.dy); final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(Rect.largest); canvas .debugEnforceArbitraryPaint(); // make sure DOM canvas doesn't take over canvas.drawShadow( path, _kShadowColor, elevation, false, ); canvas.drawPath( path, SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = const Color.fromARGB(255, 0, 0, 255), ); builder.addPicture(Offset.zero, recorder.endRecording()); paintShadowBounds(path, elevation); builder.pop(); // offset } test( 'renders shadows correctly', () async { // Physical shape clips. We want to see that clipping in the screenshot. debugShowClipLayers = false; builder.pushOffset(10, 20); for (int i = 0; i < 10; i++) { paintBitmapCanvasShadow(i.toDouble(), Offset(50.0 * i, 60), false); } for (int i = 0; i < 10; i++) { paintBitmapCanvasShadow(i.toDouble(), Offset(50.0 * i, 120), true); } for (int i = 0; i < 10; i++) { paintBitmapCanvasComplexPathShadow( i.toDouble(), Offset(50.0 * i, 180)); } builder.pop(); final DomElement sceneElement = builder.build().webOnlyRootElement!; domDocument.body!.append(sceneElement); await matchGoldenFile( 'shadows.png', region: region, ); }, testOn: 'chrome', ); /// For dart testing having `no tests ran` in a file is considered an error /// and result in exit code 1. /// See: https://github.com/dart-lang/test/pull/1173 /// /// Since screenshot tests run one by one and exit code is checked immediately /// after that a test file that only runs in chrome will break the other /// browsers. This method is added as a bandaid solution. test('dummy tests to pass on other browsers', () async { expect(2 + 2, 4); }); }
engine/lib/web_ui/test/html/shadow_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/shadow_golden_test.dart", "repo_id": "engine", "token_count": 1779 }
279
# UI Tests These tests are intended to be renderer-agnostic. These tests should not use APIs which only exist in either the HTML or CanvasKit renderers. In practice, this means these tests should only use `dart:ui` APIs or `dart:_engine` APIs which are not renderer-specific. ## Notes These tests should call `setUpUnitTests()` at the top level to initialize the renderer they are expected to run.
engine/lib/web_ui/test/ui/README.md/0
{ "file_path": "engine/lib/web_ui/test/ui/README.md", "repo_id": "engine", "token_count": 111 }
280
// 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/ui.dart' as ui; import '../common/test_initialization.dart'; import 'utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); test('toString()', () { final ui.Paint paint = ui.Paint(); paint.blendMode = ui.BlendMode.darken; paint.style = ui.PaintingStyle.fill; paint.strokeWidth = 1.2; paint.strokeCap = ui.StrokeCap.square; paint.strokeJoin = ui.StrokeJoin.bevel; paint.isAntiAlias = true; paint.color = const ui.Color(0xaabbccdd); paint.invertColors = true; paint.shader = ui.Gradient.linear( const ui.Offset(0.1, 0.2), const ui.Offset(1.5, 1.6), const <ui.Color>[ ui.Color(0xaabbccdd), ui.Color(0xbbccddee), ], <double>[0.3, 0.4], ui.TileMode.decal, ); paint.maskFilter = const ui.MaskFilter.blur(ui.BlurStyle.normal, 1.7); paint.filterQuality = ui.FilterQuality.high; paint.colorFilter = const ui.ColorFilter.linearToSrgbGamma(); paint.strokeMiterLimit = 1.8; paint.imageFilter = ui.ImageFilter.blur( sigmaX: 1.9, sigmaY: 2.1, tileMode: ui.TileMode.mirror, ); if (!isSkwasm) { expect( paint.toString(), 'Paint(' 'Color(0xaabbccdd); ' 'BlendMode.darken; ' 'colorFilter: ColorFilter.linearToSrgbGamma(); ' 'maskFilter: MaskFilter.blur(BlurStyle.normal, 1.7); ' 'filterQuality: FilterQuality.high; ' 'shader: Gradient(); ' 'imageFilter: ImageFilter.blur(1.9, 2.1, mirror); ' 'invert: true' ')', ); } else { // TODO(yjbanov): https://github.com/flutter/flutter/issues/141639 expect(paint.toString(), 'Paint()'); } }); }
engine/lib/web_ui/test/ui/paint_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/paint_test.dart", "repo_id": "engine", "token_count": 941 }
281
// 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:async'; import 'package:ui/src/engine.dart'; import 'package:ui/src/engine/skwasm/skwasm_stub.dart' if (dart.library.ffi) 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui.dart'; import '../common/rendering.dart'; Picture drawPicture(void Function(Canvas) drawCommands) { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); drawCommands(canvas); return recorder.endRecording(); } /// Draws the [Picture]. This is in preparation for a golden test. Future<void> drawPictureUsingCurrentRenderer(Picture picture) async { final SceneBuilder sb = SceneBuilder(); sb.pushOffset(0, 0); sb.addPicture(Offset.zero, picture); await renderScene(sb.build()); } /// Convenience getter for the implicit view. FlutterView get implicitView => EnginePlatformDispatcher.instance.implicitView!; /// Returns [true] if this test is running in the CanvasKit renderer. bool get isCanvasKit => renderer is CanvasKitRenderer; /// Returns [true] if this test is running in the HTML renderer. bool get isHtml => renderer is HtmlRenderer; bool get isSkwasm => renderer is SkwasmRenderer;
engine/lib/web_ui/test/ui/utils.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/utils.dart", "repo_id": "engine", "token_count": 424 }
282
// 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. #ifndef FLUTTER_RUNTIME_DART_SNAPSHOT_H_ #define FLUTTER_RUNTIME_DART_SNAPSHOT_H_ #include <memory> #include <string> #include "flutter/common/settings.h" #include "flutter/fml/macros.h" #include "flutter/fml/memory/ref_counted.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief A read-only Dart heap snapshot, or, read-executable mapping of /// AOT compiled Dart code. /// /// To make Dart code startup more performant, the Flutter tools on /// the host snapshot the state of the Dart heap at specific points /// and package the same with the Flutter application. When the Dart /// VM on the target is configured to run AOT compiled Dart code, /// the tools also compile the developer's Flutter application code /// to target specific machine code (instructions). This class deals /// with the mapping of both these buffers at runtime on the target. /// /// A Flutter application typically needs two instances of this /// class at runtime to run Dart code. One instance is for the VM /// and is called the "core snapshot". The other is the isolate /// and called the "isolate snapshot". Different root isolates can /// be launched with different isolate snapshots. /// /// These snapshots are typically memory-mapped at runtime, or, /// referenced directly as symbols present in Mach or ELF binaries. /// /// In the case of the core snapshot, the snapshot is collected when /// the VM shuts down. The isolate snapshot is collected when the /// isolate group shuts down. /// class DartSnapshot : public fml::RefCountedThreadSafe<DartSnapshot> { public: //---------------------------------------------------------------------------- /// The symbol name of the heap data of the core snapshot in a dynamic library /// or currently loaded process. /// static const char* kVMDataSymbol; //---------------------------------------------------------------------------- /// The symbol name of the instructions data of the core snapshot in a dynamic /// library or currently loaded process. /// static const char* kVMInstructionsSymbol; //---------------------------------------------------------------------------- /// The symbol name of the heap data of the isolate snapshot in a dynamic /// library or currently loaded process. /// static const char* kIsolateDataSymbol; //---------------------------------------------------------------------------- /// The symbol name of the instructions data of the isolate snapshot in a /// dynamic library or currently loaded process. /// static const char* kIsolateInstructionsSymbol; //---------------------------------------------------------------------------- /// @brief From the fields present in the given settings object, infer /// the core snapshot. /// /// @attention Depending on the runtime mode of the Flutter application and /// the target that Flutter is running on, a complex fallback /// mechanism is in place to infer the locations of each snapshot /// buffer. If the caller wants to explicitly specify the buffers /// of the core snapshot, the `Settings::vm_snapshot_data` and /// `Settings::vm_snapshots_instr` mapping fields may be used. /// This specification takes precedence over all fallback search /// paths. /// /// @param[in] settings The settings to infer the core snapshot from. /// /// @return A valid core snapshot or nullptr. /// static fml::RefPtr<const DartSnapshot> VMSnapshotFromSettings( const Settings& settings); //---------------------------------------------------------------------------- /// @brief From the fields present in the given settings object, infer /// the isolate snapshot. /// /// @attention Depending on the runtime mode of the Flutter application and /// the target that Flutter is running on, a complex fallback /// mechanism is in place to infer the locations of each snapshot /// buffer. If the caller wants to explicitly specify the buffers /// of the isolate snapshot, the `Settings::isolate_snapshot_data` /// and `Settings::isolate_snapshots_instr` mapping fields may be /// used. This specification takes precedence over all fallback /// search paths. /// /// @param[in] settings The settings to infer the isolate snapshot from. /// /// @return A valid isolate snapshot or nullptr. /// static fml::RefPtr<const DartSnapshot> IsolateSnapshotFromSettings( const Settings& settings); //---------------------------------------------------------------------------- /// @brief Create an isolate snapshot from existing fml::Mappings. /// /// @param[in] snapshot_data The mapping for the heap snapshot. /// @param[in] snapshot_instructions The mapping for the instructions /// snapshot. /// /// @return A valid isolate snapshot or nullptr. static fml::RefPtr<DartSnapshot> IsolateSnapshotFromMappings( const std::shared_ptr<const fml::Mapping>& snapshot_data, const std::shared_ptr<const fml::Mapping>& snapshot_instructions); //---------------------------------------------------------------------------- /// @brief Create an isolate snapshot specialized for launching the /// service isolate. Returns nullptr if no such snapshot is /// available. /// /// @return A valid isolate snapshot or nullptr. static fml::RefPtr<DartSnapshot> VMServiceIsolateSnapshotFromSettings( const Settings& settings); //---------------------------------------------------------------------------- /// @brief Determines if this snapshot contains a heap component. Since /// the instructions component is optional, the method does not /// check for its presence. Use `IsValidForAOT` to determine if /// both the heap and instructions components of the snapshot are /// present. /// /// @return Returns if the snapshot contains a heap component. /// bool IsValid() const; //---------------------------------------------------------------------------- /// @brief Determines if this snapshot contains both the heap and /// instructions components. This is only useful when determining /// if the snapshot may be used to run AOT code. The instructions /// component will be absent in JIT modes. /// /// @return Returns if the snapshot contains both a heap and instructions /// component. /// bool IsValidForAOT() const; //---------------------------------------------------------------------------- /// @brief Get a pointer to the read-only mapping to the heap snapshot. /// /// @return The data mapping. /// const uint8_t* GetDataMapping() const; //---------------------------------------------------------------------------- /// @brief Get a pointer to the read-execute mapping to the instructions /// snapshot. /// /// @return The instructions mapping. /// const uint8_t* GetInstructionsMapping() const; //---------------------------------------------------------------------------- /// @brief Returns whether both the data and instructions mappings are /// safe to use with madvise(DONTNEED). bool IsDontNeedSafe() const; bool IsNullSafetyEnabled( const fml::Mapping* application_kernel_mapping) const; private: std::shared_ptr<const fml::Mapping> data_; std::shared_ptr<const fml::Mapping> instructions_; DartSnapshot(std::shared_ptr<const fml::Mapping> data, std::shared_ptr<const fml::Mapping> instructions); ~DartSnapshot(); FML_FRIEND_REF_COUNTED_THREAD_SAFE(DartSnapshot); FML_FRIEND_MAKE_REF_COUNTED(DartSnapshot); FML_DISALLOW_COPY_AND_ASSIGN(DartSnapshot); }; } // namespace flutter #endif // FLUTTER_RUNTIME_DART_SNAPSHOT_H_
engine/runtime/dart_snapshot.h/0
{ "file_path": "engine/runtime/dart_snapshot.h", "repo_id": "engine", "token_count": 2620 }
283
// 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:async'; import 'dart:isolate'; import 'dart:ui'; import 'split_lib_test.dart' deferred as splitlib; void main() {} @pragma('vm:entry-point') void sayHi() { print('Hi'); } @pragma('vm:entry-point') void throwExceptionNow() { throw 'Hello'; } @pragma('vm:entry-point') void canRegisterNativeCallback() async { print('In function canRegisterNativeCallback'); notifyNative(); print('Called native method from canRegisterNativeCallback'); } Future<void>? splitLoadFuture = null; @pragma('vm:entry-point') void canCallDeferredLibrary() { print('In function canCallDeferredLibrary'); splitLoadFuture = splitlib.loadLibrary() .then((_) { print('Deferred load complete'); notifySuccess(splitlib.splitAdd(10, 23) == 33); }) .catchError((_) { print('Deferred load error'); notifySuccess(false); }); notifyNative(); } @pragma('vm:external-name', 'NotifyNative') external void notifyNative(); @pragma('vm:entry-point') void testIsolateShutdown() { } @pragma('vm:external-name', 'NotifyNative') external void notifyResult(bool success); @pragma('vm:external-name', 'PassMessage') external void passMessage(String message); void secondaryIsolateMain(String message) { print('Secondary isolate got message: ' + message); passMessage('Hello from code is secondary isolate.'); notifyNative(); } @pragma('vm:entry-point') void testCanLaunchSecondaryIsolate() { final onExit = RawReceivePort((_) { notifyNative(); }); Isolate.spawn(secondaryIsolateMain, 'Hello from root isolate.', onExit: onExit.sendPort); } @pragma('vm:entry-point') void testIsolateStartupFailure() async { Future mainTest(dynamic _) async { Future testSuccessfullIsolateLaunch() async { final onMessage = ReceivePort(); final onExit = ReceivePort(); final messages = StreamIterator<dynamic>(onMessage); final exits = StreamIterator<dynamic>(onExit); await Isolate.spawn((SendPort port) => port.send('good'), onMessage.sendPort, onExit: onExit.sendPort); if (!await messages.moveNext()) { throw 'Failed to receive message'; } if (messages.current != 'good') { throw 'Failed to receive correct message'; } if (!await exits.moveNext()) { throw 'Failed to receive onExit'; } messages.cancel(); exits.cancel(); } Future testUnsuccessfullIsolateLaunch() async { IsolateSpawnException? error; try { await Isolate.spawn((_) {}, null); } on IsolateSpawnException catch (e) { error = e; } if (error == null) { throw 'Expected isolate spawn to fail.'; } } await testSuccessfullIsolateLaunch(); makeNextIsolateSpawnFail(); await testUnsuccessfullIsolateLaunch(); notifyNative(); } // The root isolate will not run an eventloop, so we have to run the actual // test in an isolate. Isolate.spawn(mainTest, null); } @pragma('vm:external-name', 'MakeNextIsolateSpawnFail') external void makeNextIsolateSpawnFail(); @pragma('vm:entry-point') void testCanReceiveArguments(List<String> args) { notifyResult(args.length == 1 && args[0] == 'arg1'); } @pragma('vm:entry-point') void trampoline() { notifyNative(); } @pragma('vm:external-name', 'NotifySuccess') external void notifySuccess(bool success); @pragma('vm:entry-point') void testCanConvertEmptyList(List<int> args){ notifySuccess(args.length == 0); } @pragma('vm:entry-point') void testCanConvertListOfStrings(List<String> args){ notifySuccess(args.length == 4 && args[0] == 'tinker' && args[1] == 'tailor' && args[2] == 'soldier' && args[3] == 'sailor'); } @pragma('vm:entry-point') void testCanConvertListOfDoubles(List<double> args){ notifySuccess(args.length == 4 && args[0] == 1.0 && args[1] == 2.0 && args[2] == 3.0 && args[3] == 4.0); } @pragma('vm:entry-point') void testCanConvertListOfInts(List<int> args){ notifySuccess(args.length == 4 && args[0] == 1 && args[1] == 2 && args[2] == 3 && args[3] == 4); } bool didCallRegistrantBeforeEntrypoint = false; // Test the Dart plugin registrant. @pragma('vm:entry-point') class _PluginRegistrant { @pragma('vm:entry-point') static void register() { if (didCallRegistrantBeforeEntrypoint) { throw '_registerPlugins is being called twice'; } didCallRegistrantBeforeEntrypoint = true; } } @pragma('vm:entry-point') void mainForPluginRegistrantTest() { if (didCallRegistrantBeforeEntrypoint) { passMessage('_PluginRegistrant.register() was called'); } else { passMessage('_PluginRegistrant.register() was not called'); } } @pragma('vm:entry-point') void mainForPlatformIsolates() { passMessage('Platform isolate is ready'); } @pragma('vm:entry-point') void emptyMain(args) {} @pragma('vm:entry-point') Function createEntryPointForPlatIsoSendAndRecvTest() { final port = RawReceivePort(); port.handler = (message) { port.close(); (message as SendPort).send('Hello from root isolate!'); }; final SendPort sendPort = port.sendPort; return () { final replyPort = RawReceivePort(); replyPort.handler = (message) { replyPort.close(); passMessage('Platform isolate received: $message'); }; sendPort.send(replyPort.sendPort); }; } @pragma('vm:entry-point') void mainForPlatformIsolatesThrowError() { throw 'Error from platform isolate'; }
engine/runtime/fixtures/runtime_test.dart/0
{ "file_path": "engine/runtime/fixtures/runtime_test.dart", "repo_id": "engine", "token_count": 2195 }
284
// 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. #define RAPIDJSON_HAS_STDSTRING 1 #include "flutter/runtime/service_protocol.h" #include <cstring> #include <sstream> #include <string> #include <utility> #include <vector> #include "flutter/fml/posix_wrappers.h" #include "flutter/fml/synchronization/waitable_event.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "third_party/dart/runtime/include/dart_tools_api.h" namespace flutter { const std::string_view ServiceProtocol::kScreenshotExtensionName = "_flutter.screenshot"; const std::string_view ServiceProtocol::kScreenshotSkpExtensionName = "_flutter.screenshotSkp"; const std::string_view ServiceProtocol::kRunInViewExtensionName = "_flutter.runInView"; const std::string_view ServiceProtocol::kFlushUIThreadTasksExtensionName = "_flutter.flushUIThreadTasks"; const std::string_view ServiceProtocol::kSetAssetBundlePathExtensionName = "_flutter.setAssetBundlePath"; const std::string_view ServiceProtocol::kGetDisplayRefreshRateExtensionName = "_flutter.getDisplayRefreshRate"; const std::string_view ServiceProtocol::kGetSkSLsExtensionName = "_flutter.getSkSLs"; const std::string_view ServiceProtocol::kEstimateRasterCacheMemoryExtensionName = "_flutter.estimateRasterCacheMemory"; const std::string_view ServiceProtocol::kRenderFrameWithRasterStatsExtensionName = "_flutter.renderFrameWithRasterStats"; const std::string_view ServiceProtocol::kReloadAssetFonts = "_flutter.reloadAssetFonts"; static constexpr std::string_view kViewIdPrefx = "_flutterView/"; static constexpr std::string_view kListViewsExtensionName = "_flutter.listViews"; ServiceProtocol::ServiceProtocol() : endpoints_({ // Private kListViewsExtensionName, // Public kScreenshotExtensionName, kScreenshotSkpExtensionName, kRunInViewExtensionName, kFlushUIThreadTasksExtensionName, kSetAssetBundlePathExtensionName, kGetDisplayRefreshRateExtensionName, kGetSkSLsExtensionName, kEstimateRasterCacheMemoryExtensionName, kRenderFrameWithRasterStatsExtensionName, kReloadAssetFonts, }), handlers_mutex_(fml::SharedMutex::Create()) {} ServiceProtocol::~ServiceProtocol() { ToggleHooks(false); } void ServiceProtocol::AddHandler(Handler* handler, const Handler::Description& description) { fml::UniqueLock lock(*handlers_mutex_); handlers_.emplace(handler, description); } void ServiceProtocol::RemoveHandler(Handler* handler) { fml::UniqueLock lock(*handlers_mutex_); handlers_.erase(handler); } void ServiceProtocol::SetHandlerDescription( Handler* handler, const Handler::Description& description) { fml::SharedLock lock(*handlers_mutex_); auto it = handlers_.find(handler); if (it != handlers_.end()) { it->second.Store(description); } } void ServiceProtocol::ToggleHooks(bool set) { for (const auto& endpoint : endpoints_) { Dart_RegisterIsolateServiceRequestCallback( endpoint.data(), // method &ServiceProtocol::HandleMessage, // callback set ? this : nullptr // user data ); } } static void WriteServerErrorResponse(rapidjson::Document* document, const char* message) { document->SetObject(); document->AddMember("code", -32000, document->GetAllocator()); rapidjson::Value message_value; message_value.SetString(message, document->GetAllocator()); document->AddMember("message", message_value, document->GetAllocator()); } bool ServiceProtocol::HandleMessage(const char* method, const char** param_keys, const char** param_values, intptr_t num_params, void* user_data, const char** json_object) { Handler::ServiceProtocolMap params; for (intptr_t i = 0; i < num_params; i++) { params[std::string_view{param_keys[i]}] = std::string_view{param_values[i]}; } #ifndef NDEBUG FML_DLOG(INFO) << "Service protcol method: " << method; FML_DLOG(INFO) << "Arguments: " << params.size(); for (intptr_t i = 0; i < num_params; i++) { FML_DLOG(INFO) << " " << i + 1 << ": " << param_keys[i] << " = " << param_values[i]; } #endif // NDEBUG rapidjson::Document document; bool result = HandleMessage(std::string_view{method}, // params, // static_cast<ServiceProtocol*>(user_data), // &document // ); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); document.Accept(writer); *json_object = fml::strdup(buffer.GetString()); #ifndef NDEBUG FML_DLOG(INFO) << "Response: " << *json_object; FML_DLOG(INFO) << "RPC Result: " << result; #endif // NDEBUG return result; } bool ServiceProtocol::HandleMessage(std::string_view method, const Handler::ServiceProtocolMap& params, ServiceProtocol* service_protocol, rapidjson::Document* response) { if (service_protocol == nullptr) { WriteServerErrorResponse(response, "Service protocol unavailable."); return false; } return service_protocol->HandleMessage(method, params, response); } [[nodiscard]] static bool HandleMessageOnHandler( ServiceProtocol::Handler* handler, std::string_view method, const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* document) { FML_DCHECK(handler); fml::AutoResetWaitableEvent latch; bool result = false; fml::TaskRunner::RunNowOrPostTask( handler->GetServiceProtocolHandlerTaskRunner(method), [&latch, // &result, // &handler, // &method, // &params, // &document // ]() { result = handler->HandleServiceProtocolMessage(method, params, document); latch.Signal(); }); latch.Wait(); return result; } bool ServiceProtocol::HandleMessage(std::string_view method, const Handler::ServiceProtocolMap& params, rapidjson::Document* response) const { if (method == kListViewsExtensionName) { // So far, this is the only built-in method that does not forward to the // dynamic set of handlers. return HandleListViewsMethod(response); } fml::SharedLock lock(*handlers_mutex_); if (handlers_.empty()) { WriteServerErrorResponse(response, "There are no running service protocol handlers."); return false; } // Find the handler by its "viewId" in the params. auto view_id_param_found = params.find(std::string_view{"viewId"}); if (view_id_param_found != params.end()) { auto* handler = reinterpret_cast<Handler*>(std::stoull( view_id_param_found->second.data() + kViewIdPrefx.size(), nullptr, 16)); auto handler_found = handlers_.find(handler); if (handler_found != handlers_.end()) { return HandleMessageOnHandler(handler, method, params, response); } } // Handle legacy calls that do not specify a handler in their args. // TODO(chinmaygarde): Deprecate these calls in the tools and remove these // fallbacks. if (method == kScreenshotExtensionName || method == kScreenshotSkpExtensionName || method == kFlushUIThreadTasksExtensionName) { return HandleMessageOnHandler(handlers_.begin()->first, method, params, response); } WriteServerErrorResponse( response, "Service protocol could not handle or find a handler for the " "requested method."); return false; } static std::string CreateFlutterViewID(intptr_t handler) { std::stringstream stream; stream << kViewIdPrefx << "0x" << std::hex << handler; return stream.str(); } static std::string CreateIsolateID(int64_t isolate) { std::stringstream stream; stream << "isolates/" << isolate; return stream.str(); } void ServiceProtocol::Handler::Description::Write( Handler* handler, rapidjson::Value& view, rapidjson::MemoryPoolAllocator<>& allocator) const { view.SetObject(); view.AddMember("type", "FlutterView", allocator); view.AddMember("id", CreateFlutterViewID(reinterpret_cast<intptr_t>(handler)), allocator); if (isolate_port != 0) { rapidjson::Value isolate(rapidjson::Type::kObjectType); { isolate.AddMember("type", "@Isolate", allocator); isolate.AddMember("fixedId", true, allocator); isolate.AddMember("id", CreateIsolateID(isolate_port), allocator); isolate.AddMember("name", isolate_name, allocator); isolate.AddMember("number", isolate_port, allocator); } view.AddMember("isolate", isolate, allocator); } } bool ServiceProtocol::HandleListViewsMethod( rapidjson::Document* response) const { fml::SharedLock lock(*handlers_mutex_); std::vector<std::pair<intptr_t, Handler::Description>> descriptions; descriptions.reserve(handlers_.size()); for (const auto& handler : handlers_) { descriptions.emplace_back(reinterpret_cast<intptr_t>(handler.first), handler.second.Load()); } auto& allocator = response->GetAllocator(); // Construct the response objects. response->SetObject(); response->AddMember("type", "FlutterViewList", allocator); rapidjson::Value viewsList(rapidjson::Type::kArrayType); for (const auto& description : descriptions) { rapidjson::Value view(rapidjson::Type::kObjectType); description.second.Write(reinterpret_cast<Handler*>(description.first), view, allocator); viewsList.PushBack(view, allocator); } response->AddMember("views", viewsList, allocator); return true; } } // namespace flutter
engine/runtime/service_protocol.cc/0
{ "file_path": "engine/runtime/service_protocol.cc", "repo_id": "engine", "token_count": 4044 }
285
// 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. #ifndef FLUTTER_SHELL_COMMON_CONTEXT_OPTIONS_H_ #define FLUTTER_SHELL_COMMON_CONTEXT_OPTIONS_H_ #include <optional> #include "flutter/fml/macros.h" #include "third_party/skia/include/gpu/GrContextOptions.h" namespace flutter { enum class ContextType { /// The context is used to render to a texture or renderbuffer. kRender, /// The context will only be used to transfer resources to and from device /// memory. No rendering will be performed using this context. kResource, }; //------------------------------------------------------------------------------ /// @brief Initializes GrContextOptions with values suitable for Flutter. /// The options can be further tweaked before a GrContext is created /// from these options. /// /// @param[in] type The type of context that will be created using these /// options. /// @param[in] type The client rendering API that will be wrapped using a /// context with these options. This argument is only required /// if the context is going to be used with a particular /// client rendering API. /// /// @return The default graphics context options. /// GrContextOptions MakeDefaultContextOptions( ContextType type, std::optional<GrBackendApi> api = std::nullopt); } // namespace flutter #endif // FLUTTER_SHELL_COMMON_CONTEXT_OPTIONS_H_
engine/shell/common/context_options.h/0
{ "file_path": "engine/shell/common/context_options.h", "repo_id": "engine", "token_count": 512 }
286
// 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. #include "flutter/shell/common/resource_cache_limit_calculator.h" #include "gtest/gtest.h" namespace flutter { namespace testing { class TestResourceCacheLimitItem : public ResourceCacheLimitItem { public: explicit TestResourceCacheLimitItem(size_t resource_cache_limit) : resource_cache_limit_(resource_cache_limit), weak_factory_(this) {} size_t GetResourceCacheLimit() override { return resource_cache_limit_; } fml::WeakPtr<TestResourceCacheLimitItem> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } private: size_t resource_cache_limit_; fml::WeakPtrFactory<TestResourceCacheLimitItem> weak_factory_; }; TEST(ResourceCacheLimitCalculatorTest, GetResourceCacheMaxBytes) { ResourceCacheLimitCalculator calculator(800U); auto item1 = std::make_unique<TestResourceCacheLimitItem>(100.0); calculator.AddResourceCacheLimitItem(item1->GetWeakPtr()); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(100U)); auto item2 = std::make_unique<TestResourceCacheLimitItem>(200.0); calculator.AddResourceCacheLimitItem(item2->GetWeakPtr()); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(300U)); auto item3 = std::make_unique<TestResourceCacheLimitItem>(300.0); calculator.AddResourceCacheLimitItem(item3->GetWeakPtr()); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(600U)); auto item4 = std::make_unique<TestResourceCacheLimitItem>(400.0); calculator.AddResourceCacheLimitItem(item4->GetWeakPtr()); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(800U)); item3.reset(); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(700U)); item2.reset(); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(500U)); } } // namespace testing } // namespace flutter
engine/shell/common/resource_cache_limit_calculator_unittests.cc/0
{ "file_path": "engine/shell/common/resource_cache_limit_calculator_unittests.cc", "repo_id": "engine", "token_count": 641 }
287
// 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. #include "flutter/shell/common/shell_test_platform_view.h" #ifdef SHELL_ENABLE_GL #include "flutter/shell/common/shell_test_platform_view_gl.h" #endif // SHELL_ENABLE_GL #ifdef SHELL_ENABLE_VULKAN #include "flutter/shell/common/shell_test_platform_view_vulkan.h" #endif // SHELL_ENABLE_VULKAN #ifdef SHELL_ENABLE_METAL #include "flutter/shell/common/shell_test_platform_view_metal.h" #endif // SHELL_ENABLE_METAL #include "flutter/shell/common/vsync_waiter_fallback.h" namespace flutter { namespace testing { std::unique_ptr<ShellTestPlatformView> ShellTestPlatformView::Create( PlatformView::Delegate& delegate, const TaskRunners& task_runners, const std::shared_ptr<ShellTestVsyncClock>& vsync_clock, const CreateVsyncWaiter& create_vsync_waiter, BackendType backend, const std::shared_ptr<ShellTestExternalViewEmbedder>& shell_test_external_view_embedder, const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch) { // TODO(gw280): https://github.com/flutter/flutter/issues/50298 // Make this fully runtime configurable switch (backend) { case BackendType::kDefaultBackend: #ifdef SHELL_ENABLE_GL case BackendType::kGLBackend: return std::make_unique<ShellTestPlatformViewGL>( delegate, task_runners, vsync_clock, create_vsync_waiter, shell_test_external_view_embedder); #endif // SHELL_ENABLE_GL #ifdef SHELL_ENABLE_VULKAN case BackendType::kVulkanBackend: return std::make_unique<ShellTestPlatformViewVulkan>( delegate, task_runners, vsync_clock, create_vsync_waiter, shell_test_external_view_embedder); #endif // SHELL_ENABLE_VULKAN #ifdef SHELL_ENABLE_METAL case BackendType::kMetalBackend: return std::make_unique<ShellTestPlatformViewMetal>( delegate, task_runners, vsync_clock, create_vsync_waiter, shell_test_external_view_embedder, is_gpu_disabled_sync_switch); #endif // SHELL_ENABLE_METAL default: FML_LOG(FATAL) << "No backends supported for ShellTestPlatformView"; return nullptr; } } ShellTestPlatformViewBuilder::ShellTestPlatformViewBuilder(Config config) : config_(std::move(config)) {} std::unique_ptr<PlatformView> ShellTestPlatformViewBuilder::operator()( Shell& shell) { const TaskRunners& task_runners = shell.GetTaskRunners(); const auto vsync_clock = std::make_shared<ShellTestVsyncClock>(); CreateVsyncWaiter create_vsync_waiter = [&task_runners, vsync_clock, simulate_vsync = config_.simulate_vsync]() { if (simulate_vsync) { return static_cast<std::unique_ptr<VsyncWaiter>>( std::make_unique<ShellTestVsyncWaiter>(task_runners, vsync_clock)); } else { return static_cast<std::unique_ptr<VsyncWaiter>>( std::make_unique<VsyncWaiterFallback>(task_runners, true)); } }; return ShellTestPlatformView::Create( shell, // task_runners, // vsync_clock, // create_vsync_waiter, // config_.rendering_backend, // config_.shell_test_external_view_embedder, // shell.GetIsGpuDisabledSyncSwitch() // ); } } // namespace testing } // namespace flutter
engine/shell/common/shell_test_platform_view.cc/0
{ "file_path": "engine/shell/common/shell_test_platform_view.cc", "repo_id": "engine", "token_count": 1495 }
288
// 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. #ifndef FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_SKIA_H_ #define FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_SKIA_H_ #include "flutter/shell/common/snapshot_controller.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { class SnapshotControllerSkia : public SnapshotController { public: explicit SnapshotControllerSkia(const SnapshotController::Delegate& delegate) : SnapshotController(delegate) {} sk_sp<DlImage> MakeRasterSnapshot(sk_sp<DisplayList> display_list, SkISize size) override; virtual sk_sp<SkImage> ConvertToRasterImage(sk_sp<SkImage> image) override; private: sk_sp<DlImage> DoMakeRasterSnapshot( SkISize size, std::function<void(SkCanvas*)> draw_callback); FML_DISALLOW_COPY_AND_ASSIGN(SnapshotControllerSkia); }; } // namespace flutter #endif // FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_SKIA_H_
engine/shell/common/snapshot_controller_skia.h/0
{ "file_path": "engine/shell/common/snapshot_controller_skia.h", "repo_id": "engine", "token_count": 414 }
289
// 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. #define FML_USED_ON_EMBEDDER #include "flutter/shell/common/shell_test.h" #include "flutter/flow/layers/layer_tree.h" #include "flutter/flow/layers/transform_layer.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/mapping.h" #include "flutter/runtime/dart_vm.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { void ShellTestVsyncClock::SimulateVSync() { std::scoped_lock lock(mutex_); if (vsync_issued_ >= vsync_promised_.size()) { vsync_promised_.emplace_back(); } FML_CHECK(vsync_issued_ < vsync_promised_.size()); vsync_promised_[vsync_issued_].set_value(vsync_issued_); vsync_issued_ += 1; } std::future<int> ShellTestVsyncClock::NextVSync() { std::scoped_lock lock(mutex_); vsync_promised_.emplace_back(); return vsync_promised_.back().get_future(); } void ShellTestVsyncWaiter::AwaitVSync() { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); auto vsync_future = clock_->NextVSync(); auto async_wait = std::async([&vsync_future, this]() { vsync_future.wait(); // Post the `FireCallback` to the Platform thread so earlier Platform tasks // (specifically, the `VSyncFlush` call) will be finished before // `FireCallback` is executed. This is only needed for our unit tests. // // Without this, the repeated VSYNC signals in `VSyncFlush` may start both // the current frame in the UI thread and the next frame in the secondary // callback (both of them are waiting for VSYNCs). That breaks the unit // test's assumption that each frame's VSYNC must be issued by different // `VSyncFlush` call (which resets the `will_draw_new_frame` bit). // // For example, HandlesActualIphoneXsInputEvents will fail without this. task_runners_.GetPlatformTaskRunner()->PostTask([this]() { FireCallback(fml::TimePoint::Now(), fml::TimePoint::Now()); }); }); } void ConstantFiringVsyncWaiter::AwaitVSync() { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); auto async_wait = std::async([this]() { task_runners_.GetPlatformTaskRunner()->PostTask( [this]() { FireCallback(kFrameBeginTime, kFrameTargetTime); }); }); } TestRefreshRateReporter::TestRefreshRateReporter(double refresh_rate) : refresh_rate_(refresh_rate) {} void TestRefreshRateReporter::UpdateRefreshRate(double refresh_rate) { refresh_rate_ = refresh_rate; } double TestRefreshRateReporter::GetRefreshRate() const { return refresh_rate_; } } // namespace testing } // namespace flutter
engine/shell/common/vsync_waiters_test.cc/0
{ "file_path": "engine/shell/common/vsync_waiters_test.cc", "repo_id": "engine", "token_count": 940 }
290
// 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. #ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_SKIA_H_ #define FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_SKIA_H_ #include "flutter/common/graphics/msaa_sample_count.h" #include "flutter/flow/surface.h" #include "flutter/fml/macros.h" #include "flutter/shell/gpu/gpu_surface_metal_delegate.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { class SK_API_AVAILABLE_CA_METAL_LAYER GPUSurfaceMetalSkia : public Surface { public: GPUSurfaceMetalSkia(GPUSurfaceMetalDelegate* delegate, sk_sp<GrDirectContext> context, MsaaSampleCount msaa_samples, bool render_to_surface = true); // |Surface| ~GPUSurfaceMetalSkia(); // |Surface| bool IsValid() override; private: const GPUSurfaceMetalDelegate* delegate_; const MTLRenderTargetType render_target_type_; sk_sp<GrDirectContext> context_; GrDirectContext* precompiled_sksl_context_ = nullptr; MsaaSampleCount msaa_samples_ = MsaaSampleCount::kNone; // TODO(38466): Refactor GPU surface APIs take into account the fact that an // external view embedder may want to render to the root surface. This is a // hack to make avoid allocating resources for the root surface when an // external view embedder is present. bool render_to_surface_ = true; bool disable_partial_repaint_ = false; // Accumulated damage for each framebuffer; Key is address of underlying // MTLTexture for each drawable std::map<uintptr_t, SkIRect> damage_; // |Surface| std::unique_ptr<SurfaceFrame> AcquireFrame(const SkISize& size) override; // |Surface| SkMatrix GetRootTransformation() const override; // |Surface| GrDirectContext* GetContext() override; // |Surface| std::unique_ptr<GLContextResult> MakeRenderContextCurrent() override; // |Surface| bool AllowsDrawingWhenGpuDisabled() const override; std::unique_ptr<SurfaceFrame> AcquireFrameFromCAMetalLayer( const SkISize& frame_info); std::unique_ptr<SurfaceFrame> AcquireFrameFromMTLTexture( const SkISize& frame_info); void PrecompileKnownSkSLsIfNecessary(); FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceMetalSkia); }; } // namespace flutter #endif // FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_SKIA_H_
engine/shell/gpu/gpu_surface_metal_skia.h/0
{ "file_path": "engine/shell/gpu/gpu_surface_metal_skia.h", "repo_id": "engine", "token_count": 868 }
291
# Android Platform Embedder Android embedder for Flutter, including Java [`io.flutter`](io/flutter/) sources and Android specific engine-side C++. This code provides the glue between the Flutter engine and the Android platform, and is responsible for: - Initializing the Flutter engine. - Providing a platform view for the Flutter engine to render into. - Dispatching events to the Flutter engine. > [!CAUTION] > This is a best effort attempt to document the Android embedder. It is not > guaranteed to be up to date or complete. If you find a discrepancy, please > [send a pull request](https://github.com/flutter/engine/compare)! See also: - [`../../tools/android_lint/bin/main.dart`](../../../tools/android_lint/bin/main.dart) - [Android Platform Views](https://github.com/flutter/flutter/wiki/Android-Platform-Views) - [Hosting native Android views in your Flutter app with Platform Views](https://docs.flutter.dev/platform-integration/android/platform-views) - [Testing Android Changes in the Devicelab on an Emulator](https://github.com/flutter/flutter/wiki/Testing-Android-Changes-in-the-Devicelab-on-an-Emulator) - [Texture Layer Hybrid Composition](https://github.com/flutter/flutter/wiki/Texture-Layer-Hybrid-Composition) ## Testing There are two classes of tests for the Android embedder: unit tests that tend to test _contracts_ within the embedder, and integration tests that test the engine and embedder together, typically coupled with a Flutter app (that's how our users interact with the engine and embedder). ### Unit tests Unit tests for the Android embedder are located in: - [`test`](test): Java unit tests. - C++ files that end in `_unittests.cc` in [`shell/platform/android`](./). The easiest way (though not the quickest) is to use `run_tests.py`: ```shell # Assuming you're at the root of the engine repo where `run_tests.py` is located. ./testing/run_tests.py --type java # Confusingly, these are C++ tests for Android. ./testing/run_tests.py --type android # If you're using android_debug_unopt_arm64 builds: ./testing/run_tests.py --type android --android-variant android_debug_unopt_arm64 ./testing/run_tests.py --type java --android-variant android_debug_unopt_arm64 ``` You may also be able to run the tests directly from Android Studio. ### Integration tests Integration tests for the Android embedder mostly exist outside of the engine for dubious historical reasons. To run these tests, you'll need to have a Flutter checkout and a working Android emulator or device: ```shell # Build an up-to-date Flutter engine for Android. cd $ENGINE/src # Or, use your favorite arguments and build variant. ninja -j1000 -C ../out/android_debug_unopt_arm64 android_jar # Run the tests. Here is *1* example: cd $FLUTTER/dev/integration_tests/external_textures flutter drive \ --local-engine-host=$ENGINE/out/host_debug_unopt_arm64 \ --local-engine=$ENGINE/out/android_debug_unopt_arm64 ``` Another good source of (unfortunately, manual) testing is `flutter/packages`: ```shell cd $PACKAGES/packages/video_player/video_player_android/example flutter run \ --local-engine-host=$ENGINE/out/host_debug_unopt_arm64 \ --local-engine=$ENGINE/out/android_debug_unopt_arm64 ``` > [!NOTE] > External texture rendering on Android is based on the device API level. For > example to test the OpenGLES branch (which uses `SurfaceTexture`), you'll > typically need an older device or emulator with an API version 29 or lower. > > You can also (locally) "force" the engine to use `SurfaceTextures`: > > ```diff > // shell/platform/android/io/flutter/embedding/engine/renderer/FlutterRenderer.java > - @VisibleForTesting static boolean debugForceSurfaceProducerGlTextures = false; > + @VisibleForTesting static boolean debugForceSurfaceProducerGlTextures = true; > ``` > > ... and rebuild the engine. See [our wiki](https://github.com/flutter/flutter/wiki/Testing-the-engine#java---android-embedding) also. ## Developing How to edit and contribute to the Android embedder. > [!TIP] > This guide assumes you already have a working Engine development environment: > > - [Setting up the Engine development environment](https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment) > - [Compiling for Android](https://github.com/flutter/flutter/wiki/Compiling-the-engine#compiling-for-android-from-macos-or-linux) > > You should also have a working Android development environment: > > - [Android Studio](https://developer.android.com/studio) > - [Install Flutter > Test Drive](https://docs.flutter.dev/get-started/test-drive?tab=androidstudio) > > _It is also recommended (but not required) to install > [Visual Studio Code](https://code.visualstudio.com/)._ Depending on what you are trying to do, you may need to edit the Java code in [`io.flutter`](io/flutter/) or the C++ code in [`shell/platform/android`](./), sometimes both. Let's start with the C++ code, as it is more similar to developing for other platforms or platform-agnostic parts of the engine. ### Editing C++ code The C++ code for the Android embedder is located in [`shell/platform/android`](./) and subdirectories. Some notable files include: - [`context/android_context.h`](./context/android_context.h): Holds state that is shared across Android surfaces. - [`jni/platform_view_android_jni.h`](./jni/platform_view_android_jni.h): Allows calling Java code running in the JVM. - [`AndroidManifest.xml`](./AndroidManifest.xml): Used by [`android_lint`](../../../tools/android_lint/). - [`BUILD.gn`](./BUILD.gn): Used by GN to build the C++-side embedder tests and the `flutter.jar` file for the engine. - [`ndk_helpers.h`](./ndk_helpers.h): Helper functions for dynamically loading and calling Android NDK (C/C++) functions. - [`platform_view_android.h`](./platform_view_android.h): The main entry point for the Android embedder. See [VSCode with C/C++ Intellisense](https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment#vscode-with-cc-intellisense-cc) for how to use the [`clangd`](https://marketplace.visualstudio.com/items?itemName=llvm-vs-code-extensions.vscode-clangd) extension to get C++ code completion: ![Example](https://github.com/flutter/flutter/assets/168174/8a75dd27-66e1-4c4f-88af-667a73b909b6) > [!NOTE] > `--compile-commands-dir` must point to an Android build output: > > ```jsonc > { > /* ... */ > "clangd.path": "buildtools/mac-arm64/clang/bin/clangd", > "clangd.arguments": ["--compile-commands-dir=out/android_debug_unopt_arm64"] > /* ... */ > } > ``` > > ... but remember to change it back when editing other parts of the engine. ### Editing Java code The Java code for the Android embedder is located in [`io/flutter/`](io/flutter/) and subdirectories. The tests are located in [`test/io/flutter/`](test/io/flutter/), and the test runner in [`test_runner`](test_runner/). Some notable files include: - [`io/flutter/embedding/android/FlutterActivity.java`](io/flutter/embedding/android/FlutterActivity.java): An activity that displays a full-screen Flutter UI. - [`io/flutter/embedding/engine/FlutterJNI.java`](io/flutter/embedding/engine/FlutterJNI.java): The Java interface for the C++ engine. - [`io/flutter/view/TextureRegistry.java`](io/flutter/view/TextureRegistry.java): Registry of backend textures used by a Flutter View. It is non-trivial to get a working IDE setup for editing Java code in the Flutter engine. Some developers have had success [using VSCode as an IDE for the Android Embedding](https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment#using-vscode-as-an-ide-for-the-android-embedding-java), but the following instructions are for if that doesn't work, or you want to use Android Studio: 1. Open `shell/platform/android` in Android Studio. 1. Configure the following: - [`Preferences | Build, Execution, Deployment | Gradle-Android Compiler`](jetbrains://AndroidStudio/settings?name=Build%2C+Execution%2C+Deployment--Gradle-Android+Compiler) Command-line Options: ```txt -Pbuild_dir="/tmp/build_dir" -Pflutter_jar="$ENGINE/src/out/android_debug_unopt_arm64/flutter.jar" ``` - [`Preferences | Build, Execution, Deployment | Build Tools | Gradle`](jetbrains://AndroidStudio/settings?name=Build%2C+Execution%2C+Deployment--Build+Tools--Gradle) Distribution of `Local Installation` with: ```txt $ENGINE/src/third_party/gradle ``` Gradle SDK using Android Studio (path depends on your machine): ```txt /Applications/Android Studio.app/Contents/jbr/Contents/Home ``` 1. Sync Gradle. ![Example](https://github.com/flutter/flutter/assets/168174/02fe0e6f-f0c4-47b2-8dae-9aa0b9520503) At this point you should be able to open Java files in Android Studio and get code completion in the `io/flutter` and `test/io/flutter` folders. For example, `FlutterJNI.java`: ![Example](https://github.com/flutter/flutter/assets/168174/387550d4-eab7-4097-9da3-7713a6ec4da7) To get code coverage displayed in line: go to the test class you wish to run and 1. Right click > Modify Run Configuration..., 2. In the window that pops up click Modify options > Specify classes and packages (under "code coverage"). 3. In the new box that appears at the bottom of the window, click the + > Add package, and then add `io.flutter.*`.
engine/shell/platform/android/README.md/0
{ "file_path": "engine/shell/platform/android/README.md", "repo_id": "engine", "token_count": 3004 }
292
// 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. #include "flutter/shell/platform/android/android_image_generator.h" #include <memory> #include <utility> #include <android/bitmap.h> #include <android/hardware_buffer.h> #include "flutter/fml/platform/android/jni_util.h" #include "third_party/skia/include/codec/SkCodecAnimation.h" namespace flutter { static fml::jni::ScopedJavaGlobalRef<jclass>* g_flutter_jni_class = nullptr; static jmethodID g_decode_image_method = nullptr; AndroidImageGenerator::~AndroidImageGenerator() = default; AndroidImageGenerator::AndroidImageGenerator(sk_sp<SkData> data) : data_(std::move(data)), image_info_(SkImageInfo::MakeUnknown(-1, -1)) {} const SkImageInfo& AndroidImageGenerator::GetInfo() { header_decoded_latch_.Wait(); return image_info_; } unsigned int AndroidImageGenerator::GetFrameCount() const { return 1; } unsigned int AndroidImageGenerator::GetPlayCount() const { return 1; } const ImageGenerator::FrameInfo AndroidImageGenerator::GetFrameInfo( unsigned int frame_index) { return {.required_frame = std::nullopt, .duration = 0, .disposal_method = SkCodecAnimation::DisposalMethod::kKeep}; } SkISize AndroidImageGenerator::GetScaledDimensions(float desired_scale) { return GetInfo().dimensions(); } bool AndroidImageGenerator::GetPixels(const SkImageInfo& info, void* pixels, size_t row_bytes, unsigned int frame_index, std::optional<unsigned int> prior_frame) { fully_decoded_latch_.Wait(); if (!software_decoded_data_) { return false; } if (kRGBA_8888_SkColorType != info.colorType()) { return false; } switch (info.alphaType()) { case kOpaque_SkAlphaType: if (kOpaque_SkAlphaType != GetInfo().alphaType()) { return false; } break; case kPremul_SkAlphaType: break; default: return false; } // TODO(bdero): Override `GetImage()` to use `SkImage::FromAHardwareBuffer` on // API level 30+ once it's updated to do symbol lookups and not get // preprocessed out in Skia. This will allow for avoiding this copy in // cases where the result image doesn't need to be resized. memcpy(pixels, software_decoded_data_->data(), software_decoded_data_->size()); return true; } void AndroidImageGenerator::DecodeImage() { DoDecodeImage(); header_decoded_latch_.Signal(); fully_decoded_latch_.Signal(); } void AndroidImageGenerator::DoDecodeImage() { FML_DCHECK(g_flutter_jni_class); FML_DCHECK(g_decode_image_method); // Call FlutterJNI.decodeImage JNIEnv* env = fml::jni::AttachCurrentThread(); // This task is run on the IO thread. Create a frame to ensure that all // local JNI references used here are freed. fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env); jobject direct_buffer = env->NewDirectByteBuffer(const_cast<void*>(data_->data()), data_->size()); auto bitmap = std::make_unique<fml::jni::ScopedJavaGlobalRef<jobject>>( env, env->CallStaticObjectMethod(g_flutter_jni_class->obj(), g_decode_image_method, direct_buffer, reinterpret_cast<jlong>(this))); FML_CHECK(fml::jni::CheckException(env)); if (bitmap->is_null()) { return; } AndroidBitmapInfo info; [[maybe_unused]] int status; if ((status = AndroidBitmap_getInfo(env, bitmap->obj(), &info)) < 0) { FML_DLOG(ERROR) << "Failed to get bitmap info, status=" << status; return; } FML_DCHECK(info.format == ANDROID_BITMAP_FORMAT_RGBA_8888); // Lock the android buffer in a shared pointer void* pixel_lock; if ((status = AndroidBitmap_lockPixels(env, bitmap->obj(), &pixel_lock)) < 0) { FML_DLOG(ERROR) << "Failed to lock pixels, error=" << status; return; } SkData::ReleaseProc on_release = [](const void* ptr, void* context) -> void { fml::jni::ScopedJavaGlobalRef<jobject>* bitmap = reinterpret_cast<fml::jni::ScopedJavaGlobalRef<jobject>*>(context); auto env = fml::jni::AttachCurrentThread(); AndroidBitmap_unlockPixels(env, bitmap->obj()); delete bitmap; }; software_decoded_data_ = SkData::MakeWithProc( pixel_lock, info.width * info.height * sizeof(uint32_t), on_release, bitmap.release()); } bool AndroidImageGenerator::Register(JNIEnv* env) { g_flutter_jni_class = new fml::jni::ScopedJavaGlobalRef<jclass>( env, env->FindClass("io/flutter/embedding/engine/FlutterJNI")); FML_DCHECK(!g_flutter_jni_class->is_null()); g_decode_image_method = env->GetStaticMethodID( g_flutter_jni_class->obj(), "decodeImage", "(Ljava/nio/ByteBuffer;J)Landroid/graphics/Bitmap;"); FML_DCHECK(g_decode_image_method); static const JNINativeMethod header_decoded_method = { .name = "nativeImageHeaderCallback", .signature = "(JII)V", .fnPtr = reinterpret_cast<void*>( &AndroidImageGenerator::NativeImageHeaderCallback), }; if (env->RegisterNatives(g_flutter_jni_class->obj(), &header_decoded_method, 1) != 0) { FML_LOG(ERROR) << "Failed to register FlutterJNI.nativeImageHeaderCallback method"; return false; } return true; } std::shared_ptr<ImageGenerator> AndroidImageGenerator::MakeFromData( sk_sp<SkData> data, const fml::RefPtr<fml::TaskRunner>& task_runner) { std::shared_ptr<AndroidImageGenerator> generator( new AndroidImageGenerator(std::move(data))); fml::TaskRunner::RunNowOrPostTask( task_runner, [generator]() { generator->DecodeImage(); }); if (generator->IsValidImageData()) { return generator; } return nullptr; } void AndroidImageGenerator::NativeImageHeaderCallback(JNIEnv* env, jclass jcaller, jlong generator_address, int width, int height) { AndroidImageGenerator* generator = reinterpret_cast<AndroidImageGenerator*>(generator_address); generator->image_info_ = SkImageInfo::Make( width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType); generator->header_decoded_latch_.Signal(); } bool AndroidImageGenerator::IsValidImageData() { // The generator kicks off an IO task to decode everything, and calls to // "GetInfo()" block until either the header has been decoded or decoding has // failed, whichever is sooner. The decoder is initialized with a width and // height of -1 and will update the dimensions if the image is able to be // decoded. return GetInfo().height() != -1; } } // namespace flutter
engine/shell/platform/android/android_image_generator.cc/0
{ "file_path": "engine/shell/platform/android/android_image_generator.cc", "repo_id": "engine", "token_count": 2787 }
293
// This file only exists to provide IDE support to Android Studio. // // See ./README.md for details. buildscript { repositories { google() mavenCentral() } dependencies { classpath "com.android.tools.build:gradle:7.4.2" } } repositories { google() mavenCentral() } apply plugin: "com.android.library" android { compileSdkVersion 34 defaultConfig { minSdkVersion 21 } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs './' java.include './io.flutter/**' test { java.srcDir './test' java.include './test/io.flutter/**' } } } testOptions { unitTests { includeAndroidResources = true } } dependencies { implementation fileTree(include: ["*.jar"], dir: "../../../../third_party/android_embedding_dependencies/lib/") // These dependencies should be kept in line with those in the ./test_runner/build.gradle implementation "androidx.test:core:1.4.0" implementation "com.google.android.play:core:1.8.0" implementation "com.ibm.icu:icu4j:69.1" implementation "org.robolectric:robolectric:4.11.1" implementation "junit:junit:4.13.2" implementation "androidx.test.ext:junit:1.1.4-alpha07" def mockitoVersion = "4.7.0" implementation "org.mockito:mockito-core:$mockitoVersion" implementation "org.mockito:mockito-inline:$mockitoVersion" implementation "org.mockito:mockito-android:$mockitoVersion" } }
engine/shell/platform/android/build.gradle/0
{ "file_path": "engine/shell/platform/android/build.gradle", "repo_id": "engine", "token_count": 748 }
294
// 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. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_H_ #include "flutter/common/graphics/texture.h" #include "flutter/fml/logging.h" #include "flutter/shell/platform/android/image_lru.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" #include "flutter/shell/platform/android/platform_view_android_jni_impl.h" #include <android/hardware_buffer.h> #include <android/hardware_buffer_jni.h> namespace flutter { // External texture peered to a sequence of android.hardware.HardwareBuffers. // class ImageExternalTexture : public flutter::Texture { public: explicit ImageExternalTexture( int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& image_texture_entry, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade); virtual ~ImageExternalTexture() = default; // |flutter::Texture|. void Paint(PaintContext& context, const SkRect& bounds, bool freeze, const DlImageSampling sampling) override; // |flutter::Texture|. void MarkNewFrameAvailable() override; // |flutter::Texture| void OnTextureUnregistered() override; // |flutter::ContextListener| void OnGrContextCreated() override; // |flutter::ContextListener| void OnGrContextDestroyed() override; protected: virtual void Attach(PaintContext& context) = 0; virtual void Detach() = 0; virtual void ProcessFrame(PaintContext& context, const SkRect& bounds) = 0; JavaLocalRef AcquireLatestImage(); void CloseImage(const fml::jni::JavaRef<jobject>& image); JavaLocalRef HardwareBufferFor(const fml::jni::JavaRef<jobject>& image); void CloseHardwareBuffer(const fml::jni::JavaRef<jobject>& hardware_buffer); AHardwareBuffer* AHardwareBufferFor( const fml::jni::JavaRef<jobject>& hardware_buffer); fml::jni::ScopedJavaGlobalRef<jobject> image_texture_entry_; std::shared_ptr<PlatformViewAndroidJNI> jni_facade_; enum class AttachmentState { kUninitialized, kAttached, kDetached }; AttachmentState state_ = AttachmentState::kUninitialized; sk_sp<flutter::DlImage> dl_image_; ImageLRU image_lru_ = ImageLRU(); FML_DISALLOW_COPY_AND_ASSIGN(ImageExternalTexture); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_H_
engine/shell/platform/android/image_external_texture.h/0
{ "file_path": "engine/shell/platform/android/image_external_texture.h", "repo_id": "engine", "token_count": 870 }
295
// 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. package io.flutter.app; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import androidx.fragment.app.FragmentActivity; import io.flutter.app.FlutterActivityDelegate.ViewFactory; import io.flutter.plugin.common.PluginRegistry; import io.flutter.view.FlutterNativeView; import io.flutter.view.FlutterView; /** * Deprecated class for activities that use Flutter who also require the use of the Android v4 * Support library's {@link FragmentActivity}. * * <p>Applications that don't have this need will likely want to use {@link FlutterActivity} * instead. * * <p><strong>Important!</strong> Flutter does not bundle the necessary Android v4 Support library * classes for this class to work at runtime. It is the responsibility of the app developer using * this class to ensure that they link against the v4 support library .jar file when creating their * app to ensure that {@link FragmentActivity} is available at runtime. * * @see <a target="_new" * href="https://developer.android.com/training/testing/set-up-project">https://developer.android.com/training/testing/set-up-project</a> * @deprecated this class is replaced by {@link * io.flutter.embedding.android.FlutterFragmentActivity}. */ @Deprecated public class FlutterFragmentActivity extends FragmentActivity implements FlutterView.Provider, PluginRegistry, ViewFactory { private final FlutterActivityDelegate delegate = new FlutterActivityDelegate(this, this); // These aliases ensure that the methods we forward to the delegate adhere // to relevant interfaces versus just existing in FlutterActivityDelegate. private final FlutterActivityEvents eventDelegate = delegate; private final FlutterView.Provider viewProvider = delegate; private final PluginRegistry pluginRegistry = delegate; /** * Returns the Flutter view used by this activity; will be null before {@link #onCreate(Bundle)} * is called. */ @Override public FlutterView getFlutterView() { return viewProvider.getFlutterView(); } /** * Hook for subclasses to customize the creation of the {@code FlutterView}. * * <p>The default implementation returns {@code null}, which will cause the activity to use a * newly instantiated full-screen view. */ @Override public FlutterView createFlutterView(Context context) { return null; } @Override public FlutterNativeView createFlutterNativeView() { return null; } @Override public boolean retainFlutterNativeView() { return false; } @Override public final boolean hasPlugin(String key) { return pluginRegistry.hasPlugin(key); } @Override public final <T> T valuePublishedByPlugin(String pluginKey) { return pluginRegistry.valuePublishedByPlugin(pluginKey); } @Override public final Registrar registrarFor(String pluginKey) { return pluginRegistry.registrarFor(pluginKey); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); eventDelegate.onCreate(savedInstanceState); } @Override protected void onDestroy() { eventDelegate.onDestroy(); super.onDestroy(); } @Override public void onBackPressed() { if (!eventDelegate.onBackPressed()) { super.onBackPressed(); } } @Override protected void onStart() { super.onStart(); eventDelegate.onStart(); } @Override protected void onStop() { eventDelegate.onStop(); super.onStop(); } @Override protected void onPause() { super.onPause(); eventDelegate.onPause(); } @Override protected void onPostResume() { super.onPostResume(); eventDelegate.onPostResume(); } @Override public void onRequestPermissionsResult( int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); eventDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (!eventDelegate.onActivityResult(requestCode, resultCode, data)) { super.onActivityResult(requestCode, resultCode, data); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); eventDelegate.onNewIntent(intent); } @Override @SuppressWarnings("MissingSuperCall") public void onUserLeaveHint() { eventDelegate.onUserLeaveHint(); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); eventDelegate.onWindowFocusChanged(hasFocus); } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); eventDelegate.onTrimMemory(level); } @Override public void onLowMemory() { eventDelegate.onLowMemory(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); eventDelegate.onConfigurationChanged(newConfig); } }
engine/shell/platform/android/io/flutter/app/FlutterFragmentActivity.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/app/FlutterFragmentActivity.java", "repo_id": "engine", "token_count": 1586 }
296
// 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. package io.flutter.embedding.android; import static io.flutter.Build.API_LEVELS; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.database.ContentObserver; import android.graphics.Insets; import android.graphics.Rect; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.provider.Settings; import android.text.format.DateFormat; import android.util.AttributeSet; import android.util.SparseArray; import android.view.DisplayCutout; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.PointerIcon; import android.view.Surface; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewStructure; import android.view.WindowInsets; import android.view.WindowManager; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeProvider; import android.view.autofill.AutofillValue; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.textservice.SpellCheckerInfo; import android.view.textservice.TextServicesManager; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.VisibleForTesting; import androidx.core.content.ContextCompat; import androidx.core.util.Consumer; import androidx.window.java.layout.WindowInfoTrackerCallbackAdapter; import androidx.window.layout.DisplayFeature; import androidx.window.layout.FoldingFeature; import androidx.window.layout.FoldingFeature.OcclusionType; import androidx.window.layout.FoldingFeature.State; import androidx.window.layout.WindowInfoTracker; import androidx.window.layout.WindowLayoutInfo; import io.flutter.Log; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.renderer.FlutterRenderer; import io.flutter.embedding.engine.renderer.FlutterRenderer.DisplayFeatureState; import io.flutter.embedding.engine.renderer.FlutterRenderer.DisplayFeatureType; import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener; import io.flutter.embedding.engine.renderer.RenderSurface; import io.flutter.embedding.engine.systemchannels.SettingsChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.editing.SpellCheckPlugin; import io.flutter.plugin.editing.TextInputPlugin; import io.flutter.plugin.localization.LocalizationPlugin; import io.flutter.plugin.mouse.MouseCursorPlugin; import io.flutter.plugin.platform.PlatformViewsController; import io.flutter.util.ViewUtils; import io.flutter.view.AccessibilityBridge; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Displays a Flutter UI on an Android device. * * <p>A {@code FlutterView}'s UI is painted by a corresponding {@link * io.flutter.embedding.engine.FlutterEngine}. * * <p>A {@code FlutterView} can operate in 2 different {@link * io.flutter.embedding.android.RenderMode}s: * * <ol> * <li>{@link io.flutter.embedding.android.RenderMode#surface}, which paints a Flutter UI to a * {@link android.view.SurfaceView}. This mode has the best performance, but a {@code * FlutterView} in this mode cannot be positioned between 2 other Android {@code View}s in the * z-index, nor can it be animated/transformed. Unless the special capabilities of a {@link * android.graphics.SurfaceTexture} are required, developers should strongly prefer this * render mode. * <li>{@link io.flutter.embedding.android.RenderMode#texture}, which paints a Flutter UI to a * {@link android.graphics.SurfaceTexture}. This mode is not as performant as {@link * io.flutter.embedding.android.RenderMode#surface}, but a {@code FlutterView} in this mode * can be animated and transformed, as well as positioned in the z-index between 2+ other * Android {@code Views}. Unless the special capabilities of a {@link * android.graphics.SurfaceTexture} are required, developers should strongly prefer the {@link * io.flutter.embedding.android.RenderMode#surface} render mode. * </ol> * * See <a>https://source.android.com/devices/graphics/arch-tv#surface_or_texture</a> for more * information comparing {@link android.view.SurfaceView} and {@link android.view.TextureView}. */ public class FlutterView extends FrameLayout implements MouseCursorPlugin.MouseCursorViewDelegate, KeyboardManager.ViewDelegate { private static final String TAG = "FlutterView"; // Internal view hierarchy references. @Nullable private FlutterSurfaceView flutterSurfaceView; @Nullable private FlutterTextureView flutterTextureView; @Nullable private FlutterImageView flutterImageView; @Nullable @VisibleForTesting /* package */ RenderSurface renderSurface; @Nullable private RenderSurface previousRenderSurface; private final Set<FlutterUiDisplayListener> flutterUiDisplayListeners = new HashSet<>(); private boolean isFlutterUiDisplayed; // Connections to a Flutter execution context. @Nullable private FlutterEngine flutterEngine; @NonNull private final Set<FlutterEngineAttachmentListener> flutterEngineAttachmentListeners = new HashSet<>(); // Components that process various types of Android View input and events, // possibly storing intermediate state, and communicating those events to Flutter. // // These components essentially add some additional behavioral logic on top of // existing, stateless system channels, e.g., MouseCursorChannel, TextInputChannel, etc. @Nullable private MouseCursorPlugin mouseCursorPlugin; @Nullable private TextInputPlugin textInputPlugin; @Nullable private SpellCheckPlugin spellCheckPlugin; @Nullable private LocalizationPlugin localizationPlugin; @Nullable private KeyboardManager keyboardManager; @Nullable private AndroidTouchProcessor androidTouchProcessor; @Nullable private AccessibilityBridge accessibilityBridge; @Nullable private TextServicesManager textServicesManager; // Provides access to foldable/hinge information @Nullable private WindowInfoRepositoryCallbackAdapterWrapper windowInfoRepo; // Directly implemented View behavior that communicates with Flutter. private final FlutterRenderer.ViewportMetrics viewportMetrics = new FlutterRenderer.ViewportMetrics(); private final AccessibilityBridge.OnAccessibilityChangeListener onAccessibilityChangeListener = new AccessibilityBridge.OnAccessibilityChangeListener() { @Override public void onAccessibilityChanged( boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) { resetWillNotDraw(isAccessibilityEnabled, isTouchExplorationEnabled); } }; private final ContentObserver systemSettingsObserver = new ContentObserver(new Handler(Looper.getMainLooper())) { @Override public void onChange(boolean selfChange) { super.onChange(selfChange); if (flutterEngine == null) { return; } Log.v(TAG, "System settings changed. Sending user settings to Flutter."); sendUserSettingsToFlutter(); } @Override public boolean deliverSelfNotifications() { // The Flutter app may change system settings. return true; } }; private final FlutterUiDisplayListener flutterUiDisplayListener = new FlutterUiDisplayListener() { @Override public void onFlutterUiDisplayed() { isFlutterUiDisplayed = true; for (FlutterUiDisplayListener listener : flutterUiDisplayListeners) { listener.onFlutterUiDisplayed(); } } @Override public void onFlutterUiNoLongerDisplayed() { isFlutterUiDisplayed = false; for (FlutterUiDisplayListener listener : flutterUiDisplayListeners) { listener.onFlutterUiNoLongerDisplayed(); } } }; private final Consumer<WindowLayoutInfo> windowInfoListener = new Consumer<WindowLayoutInfo>() { @Override public void accept(WindowLayoutInfo layoutInfo) { setWindowInfoListenerDisplayFeatures(layoutInfo); } }; /** * Constructs a {@code FlutterView} programmatically, without any XML attributes. * * <p> * * <ul> * <li>A {@link FlutterSurfaceView} is used to render the Flutter UI. * <li>{@code transparencyMode} defaults to {@link TransparencyMode#opaque}. * </ul> * * {@code FlutterView} requires an {@code Activity} instead of a generic {@code Context} to be * compatible with {@link PlatformViewsController}. */ public FlutterView(@NonNull Context context) { this(context, null, new FlutterSurfaceView(context)); } /** * Deprecated - use {@link #FlutterView(Context, FlutterSurfaceView)} or {@link * #FlutterView(Context, FlutterTextureView)} or {@link #FlutterView(Context, FlutterImageView)} * instead. */ @Deprecated public FlutterView(@NonNull Context context, @NonNull RenderMode renderMode) { super(context, null); if (renderMode == RenderMode.surface) { flutterSurfaceView = new FlutterSurfaceView(context); renderSurface = flutterSurfaceView; } else if (renderMode == RenderMode.texture) { flutterTextureView = new FlutterTextureView(context); renderSurface = flutterTextureView; } else { throw new IllegalArgumentException( "RenderMode not supported with this constructor: " + renderMode); } init(); } /** * Deprecated - use {@link #FlutterView(Context, FlutterSurfaceView)} or {@link * #FlutterView(Context, FlutterTextureView)} instead, and configure the incoming {@code * FlutterSurfaceView} or {@code FlutterTextureView} for transparency as desired. * * <p>Constructs a {@code FlutterView} programmatically, without any XML attributes, uses a {@link * FlutterSurfaceView} to render the Flutter UI, and allows selection of a {@code * transparencyMode}. * * <p>{@code FlutterView} requires an {@code Activity} instead of a generic {@code Context} to be * compatible with {@link PlatformViewsController}. */ @Deprecated public FlutterView(@NonNull Context context, @NonNull TransparencyMode transparencyMode) { this( context, null, new FlutterSurfaceView(context, transparencyMode == TransparencyMode.transparent)); } /** * Constructs a {@code FlutterView} programmatically, without any XML attributes, uses the given * {@link FlutterSurfaceView} to render the Flutter UI, and allows selection of a {@code * transparencyMode}. * * <p>{@code FlutterView} requires an {@code Activity} instead of a generic {@code Context} to be * compatible with {@link PlatformViewsController}. */ public FlutterView(@NonNull Context context, @NonNull FlutterSurfaceView flutterSurfaceView) { this(context, null, flutterSurfaceView); } /** * Constructs a {@code FlutterView} programmatically, without any XML attributes, uses the given * {@link FlutterTextureView} to render the Flutter UI, and allows selection of a {@code * transparencyMode}. * * <p>{@code FlutterView} requires an {@code Activity} instead of a generic {@code Context} to be * compatible with {@link PlatformViewsController}. */ public FlutterView(@NonNull Context context, @NonNull FlutterTextureView flutterTextureView) { this(context, null, flutterTextureView); } /** * Constructs a {@code FlutterView} programmatically, without any XML attributes, uses the given * {@link FlutterImageView} to render the Flutter UI. * * <p>{@code FlutterView} requires an {@code Activity} instead of a generic {@code Context} to be * compatible with {@link PlatformViewsController}. */ public FlutterView(@NonNull Context context, @NonNull FlutterImageView flutterImageView) { this(context, null, flutterImageView); } /** * Constructs a {@code FlutterView} in an XML-inflation-compliant manner. * * <p>{@code FlutterView} requires an {@code Activity} instead of a generic {@code Context} to be * compatible with {@link PlatformViewsController}. */ // TODO(mattcarroll): expose renderMode in XML when build system supports R.attr public FlutterView(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, new FlutterSurfaceView(context)); } /** * Deprecated - use {@link #FlutterView(Context, FlutterSurfaceView)} or {@link * #FlutterView(Context, FlutterTextureView)} instead, and configure the incoming {@code * FlutterSurfaceView} or {@code FlutterTextureView} for transparency as desired. */ @Deprecated public FlutterView( @NonNull Context context, @NonNull RenderMode renderMode, @NonNull TransparencyMode transparencyMode) { super(context, null); if (renderMode == RenderMode.surface) { flutterSurfaceView = new FlutterSurfaceView(context, transparencyMode == TransparencyMode.transparent); renderSurface = flutterSurfaceView; } else if (renderMode == RenderMode.texture) { flutterTextureView = new FlutterTextureView(context); renderSurface = flutterTextureView; } else { throw new IllegalArgumentException( "RenderMode not supported with this constructor: " + renderMode); } init(); } private FlutterView( @NonNull Context context, @Nullable AttributeSet attrs, @NonNull FlutterSurfaceView flutterSurfaceView) { super(context, attrs); this.flutterSurfaceView = flutterSurfaceView; this.renderSurface = flutterSurfaceView; init(); } private FlutterView( @NonNull Context context, @Nullable AttributeSet attrs, @NonNull FlutterTextureView flutterTextureView) { super(context, attrs); this.flutterTextureView = flutterTextureView; this.renderSurface = flutterTextureView; init(); } private FlutterView( @NonNull Context context, @Nullable AttributeSet attrs, @NonNull FlutterImageView flutterImageView) { super(context, attrs); this.flutterImageView = flutterImageView; this.renderSurface = flutterImageView; init(); } private void init() { Log.v(TAG, "Initializing FlutterView"); if (flutterSurfaceView != null) { Log.v(TAG, "Internally using a FlutterSurfaceView."); addView(flutterSurfaceView); } else if (flutterTextureView != null) { Log.v(TAG, "Internally using a FlutterTextureView."); addView(flutterTextureView); } else { Log.v(TAG, "Internally using a FlutterImageView."); addView(flutterImageView); } // FlutterView needs to be focusable so that the InputMethodManager can interact with it. setFocusable(true); setFocusableInTouchMode(true); if (Build.VERSION.SDK_INT >= API_LEVELS.API_26) { setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_YES); } } /** * Returns true if an attached {@link io.flutter.embedding.engine.FlutterEngine} has rendered at * least 1 frame to this {@code FlutterView}. * * <p>Returns false if no {@link io.flutter.embedding.engine.FlutterEngine} is attached. * * <p>This flag is specific to a given {@link io.flutter.embedding.engine.FlutterEngine}. The * following hypothetical timeline demonstrates how this flag changes over time. * * <ol> * <li>{@code flutterEngineA} is attached to this {@code FlutterView}: returns false * <li>{@code flutterEngineA} renders its first frame to this {@code FlutterView}: returns true * <li>{@code flutterEngineA} is detached from this {@code FlutterView}: returns false * <li>{@code flutterEngineB} is attached to this {@code FlutterView}: returns false * <li>{@code flutterEngineB} renders its first frame to this {@code FlutterView}: returns true * </ol> */ public boolean hasRenderedFirstFrame() { return isFlutterUiDisplayed; } /** * Adds the given {@code listener} to this {@code FlutterView}, to be notified upon Flutter's * first rendered frame. */ public void addOnFirstFrameRenderedListener(@NonNull FlutterUiDisplayListener listener) { flutterUiDisplayListeners.add(listener); } /** * Removes the given {@code listener}, which was previously added with {@link * #addOnFirstFrameRenderedListener(FlutterUiDisplayListener)}. */ public void removeOnFirstFrameRenderedListener(@NonNull FlutterUiDisplayListener listener) { flutterUiDisplayListeners.remove(listener); } // ------- Start: Process View configuration that Flutter cares about. ------ /** * Sends relevant configuration data from Android to Flutter when the Android {@link * Configuration} changes. * * <p>The Android {@link Configuration} might change as a result of device orientation change, * device language change, device text scale factor change, etc. */ @Override protected void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); // We've observed on Android Q that going to the background, changing // orientation, and bringing the app back to foreground results in a sequence // of detatch from flutterEngine, onConfigurationChanged, followed by attach // to flutterEngine. // No-op here so that we avoid NPE; these channels will get notified once // the activity or fragment tell the view to attach to the Flutter engine // again (e.g. in onStart). if (flutterEngine != null) { Log.v(TAG, "Configuration changed. Sending locales and user settings to Flutter."); localizationPlugin.sendLocalesToFlutter(newConfig); sendUserSettingsToFlutter(); ViewUtils.calculateMaximumDisplayMetrics(getContext(), flutterEngine); } } /** * Invoked when this {@code FlutterView} changes size, including upon initial measure. * * <p>The initial measure reports an {@code oldWidth} and {@code oldHeight} of zero. * * <p>Flutter cares about the width and height of the view that displays it on the host platform. * Therefore, when this method is invoked, the new width and height are communicated to Flutter as * the "physical size" of the view that displays Flutter's UI. */ @Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { super.onSizeChanged(width, height, oldWidth, oldHeight); Log.v( TAG, "Size changed. Sending Flutter new viewport metrics. FlutterView was " + oldWidth + " x " + oldHeight + ", it is now " + width + " x " + height); viewportMetrics.width = width; viewportMetrics.height = height; sendViewportMetricsToFlutter(); } @VisibleForTesting() protected WindowInfoRepositoryCallbackAdapterWrapper createWindowInfoRepo() { try { return new WindowInfoRepositoryCallbackAdapterWrapper( new WindowInfoTrackerCallbackAdapter( WindowInfoTracker.Companion.getOrCreate(getContext()))); } catch (NoClassDefFoundError noClassDefFoundError) { // Testing environment uses gn/javac, which does not work with aar files. This is why aar // are converted to jar files, losing resources and other android-specific files. // androidx.window does contain resources, which causes it to fail during testing, since the // class androidx.window.R is not found. // This method is mocked in the tests involving androidx.window, but this catch block is // needed for other tests, which would otherwise fail during onAttachedToWindow(). return null; } } /** * Invoked when this is attached to the window. * * <p>We register for {@link androidx.window.layout.WindowInfoTracker} updates. */ @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); this.windowInfoRepo = createWindowInfoRepo(); Activity activity = ViewUtils.getActivity(getContext()); if (windowInfoRepo != null && activity != null) { windowInfoRepo.addWindowLayoutInfoListener( activity, ContextCompat.getMainExecutor(getContext()), windowInfoListener); } } /** * Invoked when this is detached from the window. * * <p>We unregister from {@link androidx.window.layout.WindowInfoTracker} updates. */ @Override protected void onDetachedFromWindow() { if (windowInfoRepo != null) { windowInfoRepo.removeWindowLayoutInfoListener(windowInfoListener); } this.windowInfoRepo = null; super.onDetachedFromWindow(); } /** * Refresh {@link androidx.window.layout.WindowInfoTracker} and {@link android.view.DisplayCutout} * display features. Fold, hinge and cutout areas are populated here. */ @TargetApi(API_LEVELS.API_28) protected void setWindowInfoListenerDisplayFeatures(WindowLayoutInfo layoutInfo) { List<DisplayFeature> displayFeatures = layoutInfo.getDisplayFeatures(); List<FlutterRenderer.DisplayFeature> result = new ArrayList<>(); // Data from WindowInfoTracker display features. Fold and hinge areas are // populated here. for (DisplayFeature displayFeature : displayFeatures) { Log.v( TAG, "WindowInfoTracker Display Feature reported with bounds = " + displayFeature.getBounds().toString() + " and type = " + displayFeature.getClass().getSimpleName()); if (displayFeature instanceof FoldingFeature) { DisplayFeatureType type; DisplayFeatureState state; final FoldingFeature feature = (FoldingFeature) displayFeature; if (feature.getOcclusionType() == OcclusionType.FULL) { type = DisplayFeatureType.HINGE; } else { type = DisplayFeatureType.FOLD; } if (feature.getState() == State.FLAT) { state = DisplayFeatureState.POSTURE_FLAT; } else if (feature.getState() == State.HALF_OPENED) { state = DisplayFeatureState.POSTURE_HALF_OPENED; } else { state = DisplayFeatureState.UNKNOWN; } result.add(new FlutterRenderer.DisplayFeature(displayFeature.getBounds(), type, state)); } else { result.add( new FlutterRenderer.DisplayFeature( displayFeature.getBounds(), DisplayFeatureType.UNKNOWN, DisplayFeatureState.UNKNOWN)); } } // Data from the DisplayCutout bounds. Cutouts for cameras and other sensors are // populated here. DisplayCutout was introduced in API 28. if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { WindowInsets insets = getRootWindowInsets(); if (insets != null) { DisplayCutout cutout = insets.getDisplayCutout(); if (cutout != null) { for (Rect bounds : cutout.getBoundingRects()) { Log.v(TAG, "DisplayCutout area reported with bounds = " + bounds.toString()); result.add(new FlutterRenderer.DisplayFeature(bounds, DisplayFeatureType.CUTOUT)); } } } } viewportMetrics.displayFeatures = result; sendViewportMetricsToFlutter(); } // TODO(garyq): Add support for notch cutout API: https://github.com/flutter/flutter/issues/56592 // Decide if we want to zero the padding of the sides. When in Landscape orientation, // android may decide to place the software navigation bars on the side. When the nav // bar is hidden, the reported insets should be removed to prevent extra useless space // on the sides. private enum ZeroSides { NONE, LEFT, RIGHT, BOTH } private ZeroSides calculateShouldZeroSides() { // We get both orientation and rotation because rotation is all 4 // rotations relative to default rotation while orientation is portrait // or landscape. By combining both, we can obtain a more precise measure // of the rotation. Context context = getContext(); int orientation = context.getResources().getConfiguration().orientation; int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay() .getRotation(); if (orientation == Configuration.ORIENTATION_LANDSCAPE) { if (rotation == Surface.ROTATION_90) { return ZeroSides.RIGHT; } else if (rotation == Surface.ROTATION_270) { // In android API >= 23, the nav bar always appears on the "bottom" (USB) side. return Build.VERSION.SDK_INT >= API_LEVELS.API_23 ? ZeroSides.LEFT : ZeroSides.RIGHT; } // Ambiguous orientation due to landscape left/right default. Zero both sides. else if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) { return ZeroSides.BOTH; } } // Square orientation deprecated in API 16, we will not check for it and return false // to be safe and not remove any unique padding for the devices that do use it. return ZeroSides.NONE; } // TODO(garyq): The keyboard detection may interact strangely with // https://github.com/flutter/flutter/issues/22061 // Uses inset heights and screen heights as a heuristic to determine if the insets should // be padded. When the on-screen keyboard is detected, we want to include the full inset // but when the inset is just the hidden nav bar, we want to provide a zero inset so the space // can be used. // // This method is replaced by Android API 30 (R/11) getInsets() method which can take the // android.view.WindowInsets.Type.ime() flag to find the keyboard inset. private int guessBottomKeyboardInset(WindowInsets insets) { int screenHeight = getRootView().getHeight(); // Magic number due to this being a heuristic. This should be replaced, but we have not // found a clean way to do it yet (Sept. 2018) final double keyboardHeightRatioHeuristic = 0.18; if (insets.getSystemWindowInsetBottom() < screenHeight * keyboardHeightRatioHeuristic) { // Is not a keyboard, so return zero as inset. return 0; } else { // Is a keyboard, so return the full inset. return insets.getSystemWindowInsetBottom(); } } /** * Invoked when Android's desired window insets change, i.e., padding. * * <p>Flutter does not use a standard {@code View} hierarchy and therefore Flutter is unaware of * these insets. Therefore, this method calculates the viewport metrics that Flutter should use * and then sends those metrics to Flutter. * * <p>This callback is not present in API &lt; 20, which means lower API devices will see the * wider than expected padding when the status and navigation bars are hidden. */ @Override // The annotations to suppress "InlinedApi" and "NewApi" lints prevent lint warnings // caused by usage of Android Q APIs. These calls are safe because they are // guarded. @SuppressLint({"InlinedApi", "NewApi"}) @NonNull public final WindowInsets onApplyWindowInsets(@NonNull WindowInsets insets) { WindowInsets newInsets = super.onApplyWindowInsets(insets); // getSystemGestureInsets() was introduced in API 29 and immediately deprecated in 30. if (Build.VERSION.SDK_INT == API_LEVELS.API_29) { Insets systemGestureInsets = insets.getSystemGestureInsets(); viewportMetrics.systemGestureInsetTop = systemGestureInsets.top; viewportMetrics.systemGestureInsetRight = systemGestureInsets.right; viewportMetrics.systemGestureInsetBottom = systemGestureInsets.bottom; viewportMetrics.systemGestureInsetLeft = systemGestureInsets.left; } boolean statusBarVisible = (SYSTEM_UI_FLAG_FULLSCREEN & getWindowSystemUiVisibility()) == 0; boolean navigationBarVisible = (SYSTEM_UI_FLAG_HIDE_NAVIGATION & getWindowSystemUiVisibility()) == 0; if (Build.VERSION.SDK_INT >= API_LEVELS.API_30) { int mask = 0; if (navigationBarVisible) { mask = mask | android.view.WindowInsets.Type.navigationBars(); } if (statusBarVisible) { mask = mask | android.view.WindowInsets.Type.statusBars(); } Insets uiInsets = insets.getInsets(mask); viewportMetrics.viewPaddingTop = uiInsets.top; viewportMetrics.viewPaddingRight = uiInsets.right; viewportMetrics.viewPaddingBottom = uiInsets.bottom; viewportMetrics.viewPaddingLeft = uiInsets.left; Insets imeInsets = insets.getInsets(android.view.WindowInsets.Type.ime()); viewportMetrics.viewInsetTop = imeInsets.top; viewportMetrics.viewInsetRight = imeInsets.right; viewportMetrics.viewInsetBottom = imeInsets.bottom; // Typically, only bottom is non-zero viewportMetrics.viewInsetLeft = imeInsets.left; Insets systemGestureInsets = insets.getInsets(android.view.WindowInsets.Type.systemGestures()); viewportMetrics.systemGestureInsetTop = systemGestureInsets.top; viewportMetrics.systemGestureInsetRight = systemGestureInsets.right; viewportMetrics.systemGestureInsetBottom = systemGestureInsets.bottom; viewportMetrics.systemGestureInsetLeft = systemGestureInsets.left; // TODO(garyq): Expose the full rects of the display cutout. // Take the max of the display cutout insets and existing padding to merge them DisplayCutout cutout = insets.getDisplayCutout(); if (cutout != null) { Insets waterfallInsets = cutout.getWaterfallInsets(); viewportMetrics.viewPaddingTop = Math.max( Math.max(viewportMetrics.viewPaddingTop, waterfallInsets.top), cutout.getSafeInsetTop()); viewportMetrics.viewPaddingRight = Math.max( Math.max(viewportMetrics.viewPaddingRight, waterfallInsets.right), cutout.getSafeInsetRight()); viewportMetrics.viewPaddingBottom = Math.max( Math.max(viewportMetrics.viewPaddingBottom, waterfallInsets.bottom), cutout.getSafeInsetBottom()); viewportMetrics.viewPaddingLeft = Math.max( Math.max(viewportMetrics.viewPaddingLeft, waterfallInsets.left), cutout.getSafeInsetLeft()); } } else { // We zero the left and/or right sides to prevent the padding the // navigation bar would have caused. ZeroSides zeroSides = ZeroSides.NONE; if (!navigationBarVisible) { zeroSides = calculateShouldZeroSides(); } // Status bar (top), navigation bar (bottom) and left/right system insets should // partially obscure the content (padding). viewportMetrics.viewPaddingTop = statusBarVisible ? insets.getSystemWindowInsetTop() : 0; viewportMetrics.viewPaddingRight = zeroSides == ZeroSides.RIGHT || zeroSides == ZeroSides.BOTH ? 0 : insets.getSystemWindowInsetRight(); viewportMetrics.viewPaddingBottom = navigationBarVisible && guessBottomKeyboardInset(insets) == 0 ? insets.getSystemWindowInsetBottom() : 0; viewportMetrics.viewPaddingLeft = zeroSides == ZeroSides.LEFT || zeroSides == ZeroSides.BOTH ? 0 : insets.getSystemWindowInsetLeft(); // Bottom system inset (keyboard) should adjust scrollable bottom edge (inset). viewportMetrics.viewInsetTop = 0; viewportMetrics.viewInsetRight = 0; viewportMetrics.viewInsetBottom = guessBottomKeyboardInset(insets); viewportMetrics.viewInsetLeft = 0; } Log.v( TAG, "Updating window insets (onApplyWindowInsets()):\n" + "Status bar insets: Top: " + viewportMetrics.viewPaddingTop + ", Left: " + viewportMetrics.viewPaddingLeft + ", Right: " + viewportMetrics.viewPaddingRight + "\n" + "Keyboard insets: Bottom: " + viewportMetrics.viewInsetBottom + ", Left: " + viewportMetrics.viewInsetLeft + ", Right: " + viewportMetrics.viewInsetRight + "System Gesture Insets - Left: " + viewportMetrics.systemGestureInsetLeft + ", Top: " + viewportMetrics.systemGestureInsetTop + ", Right: " + viewportMetrics.systemGestureInsetRight + ", Bottom: " + viewportMetrics.viewInsetBottom); sendViewportMetricsToFlutter(); return newInsets; } // ------- End: Process View configuration that Flutter cares about. -------- // -------- Start: Process UI I/O that Flutter cares about. ------- /** * Creates an {@link InputConnection} to work with a {@link * android.view.inputmethod.InputMethodManager}. * * <p>Any {@code View} that can take focus or process text input must implement this method by * returning a non-null {@code InputConnection}. Flutter may render one or many focusable and * text-input widgets, therefore {@code FlutterView} must support an {@code InputConnection}. * * <p>The {@code InputConnection} returned from this method comes from a {@link TextInputPlugin}, * which is owned by this {@code FlutterView}. A {@link TextInputPlugin} exists to encapsulate the * nuances of input communication, rather than spread that logic throughout this {@code * FlutterView}. */ @Override @Nullable public InputConnection onCreateInputConnection(@NonNull EditorInfo outAttrs) { if (!isAttachedToFlutterEngine()) { return super.onCreateInputConnection(outAttrs); } return textInputPlugin.createInputConnection(this, keyboardManager, outAttrs); } /** * Allows a {@code View} that is not currently the input connection target to invoke commands on * the {@link android.view.inputmethod.InputMethodManager}, which is otherwise disallowed. * * <p>Returns true to allow non-input-connection-targets to invoke methods on {@code * InputMethodManager}, or false to exclusively allow the input connection target to invoke such * methods. */ @Override public boolean checkInputConnectionProxy(View view) { return flutterEngine != null ? flutterEngine.getPlatformViewsController().checkInputConnectionProxy(view) : super.checkInputConnectionProxy(view); } /** * Invoked when a hardware key is pressed or released. * * <p>This method is typically invoked in response to the press of a physical keyboard key or a * D-pad button. It is generally not invoked when a virtual software keyboard is used, though a * software keyboard may choose to invoke this method in some situations. * * <p>{@link KeyEvent}s are sent from Android to Flutter. {@link KeyboardManager} may do some * additional work with the given {@link KeyEvent}, e.g., combine this {@code keyCode} with the * previous {@code keyCode} to generate a unicode combined character. */ @Override public boolean dispatchKeyEvent(@NonNull KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { // Tell Android to start tracking this event. getKeyDispatcherState().startTracking(event, this); } else if (event.getAction() == KeyEvent.ACTION_UP) { // Stop tracking the event. getKeyDispatcherState().handleUpEvent(event); } // If the key processor doesn't handle it, then send it on to the // superclass. The key processor will typically handle all events except // those where it has re-dispatched the event after receiving a reply from // the framework that the framework did not handle it. return (isAttachedToFlutterEngine() && keyboardManager.handleEvent(event)) || super.dispatchKeyEvent(event); } /** * Invoked by Android when a user touch event occurs. * * <p>Flutter handles all of its own gesture detection and processing, therefore this method * forwards all {@link MotionEvent} data from Android to Flutter. */ @Override public boolean onTouchEvent(@NonNull MotionEvent event) { if (!isAttachedToFlutterEngine()) { return super.onTouchEvent(event); } requestUnbufferedDispatch(event); return androidTouchProcessor.onTouchEvent(event); } /** * Invoked by Android when a generic motion event occurs, e.g., joystick movement, mouse hover, * track pad touches, scroll wheel movements, etc. * * <p>Flutter handles all of its own gesture detection and processing, therefore this method * forwards all {@link MotionEvent} data from Android to Flutter. */ @Override public boolean onGenericMotionEvent(@NonNull MotionEvent event) { boolean handled = isAttachedToFlutterEngine() && androidTouchProcessor.onGenericMotionEvent(event, getContext()); return handled ? true : super.onGenericMotionEvent(event); } /** * Invoked by Android when a hover-compliant input system causes a hover event. * * <p>An example of hover events is a stylus sitting near an Android screen. As the stylus moves * from outside a {@code View} to hover over a {@code View}, or move around within a {@code View}, * or moves from over a {@code View} to outside a {@code View}, a corresponding {@link * MotionEvent} is reported via this method. * * <p>Hover events can be used for accessibility touch exploration and therefore are processed * here for accessibility purposes. */ @Override public boolean onHoverEvent(@NonNull MotionEvent event) { if (!isAttachedToFlutterEngine()) { return super.onHoverEvent(event); } boolean handled = accessibilityBridge.onAccessibilityHoverEvent(event); if (!handled) { // TODO(ianh): Expose hover events to the platform, // implementing ADD, REMOVE, etc. } return handled; } // -------- End: Process UI I/O that Flutter cares about. --------- // -------- Start: Accessibility ------- @Override @Nullable public AccessibilityNodeProvider getAccessibilityNodeProvider() { if (accessibilityBridge != null && accessibilityBridge.isAccessibilityEnabled()) { return accessibilityBridge; } else { // TODO(goderbauer): when a11y is off this should return a one-off snapshot of // the a11y // tree. return null; } } /** * Prior to Android Q, it's impossible to add real views as descendants of virtual nodes. This * breaks accessibility when an Android view is embedded in a Flutter app. * * <p>This method overrides a hidden method in {@code ViewGroup} to workaround this limitation. * This solution is derivated from Jetpack Compose, and can be found in the Android source code as * well. * * <p>This workaround finds the descendant {@code View} that matches the provided accessibility * id. * * @param accessibilityId The view accessibility id. * @return The view matching the accessibility id if any. */ @SuppressLint("SoonBlockedPrivateApi") @Nullable public View findViewByAccessibilityIdTraversal(int accessibilityId) { if (Build.VERSION.SDK_INT < API_LEVELS.API_29) { return findViewByAccessibilityIdRootedAtCurrentView(accessibilityId, this); } // Android Q or later doesn't call this method. // // However, since this is implementation detail, a future version of Android might call // this method again, fallback to calling the This member is not intended for public use, and is // only visible for testing. method as expected by ViewGroup. Method findViewByAccessibilityIdTraversalMethod; try { findViewByAccessibilityIdTraversalMethod = View.class.getDeclaredMethod("findViewByAccessibilityIdTraversal", int.class); } catch (NoSuchMethodException exception) { return null; } findViewByAccessibilityIdTraversalMethod.setAccessible(true); try { return (View) findViewByAccessibilityIdTraversalMethod.invoke(this, accessibilityId); } catch (IllegalAccessException exception) { return null; } catch (InvocationTargetException exception) { return null; } } /** * Finds the descendant view that matches the provided accessibility id. * * @param accessibilityId The view accessibility id. * @param currentView The root view. * @return A descendant of currentView or currentView itself. */ @SuppressLint("DiscouragedPrivateApi") private View findViewByAccessibilityIdRootedAtCurrentView(int accessibilityId, View currentView) { Method getAccessibilityViewIdMethod; try { getAccessibilityViewIdMethod = View.class.getDeclaredMethod("getAccessibilityViewId"); } catch (NoSuchMethodException exception) { return null; } getAccessibilityViewIdMethod.setAccessible(true); try { if (getAccessibilityViewIdMethod.invoke(currentView).equals(accessibilityId)) { return currentView; } } catch (IllegalAccessException exception) { return null; } catch (InvocationTargetException exception) { return null; } if (currentView instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) currentView).getChildCount(); i++) { View view = findViewByAccessibilityIdRootedAtCurrentView( accessibilityId, ((ViewGroup) currentView).getChildAt(i)); if (view != null) { return view; } } } return null; } // TODO(mattcarroll): Confer with Ian as to why we need this method. Delete if possible, otherwise // add comments. private void resetWillNotDraw(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) { if (!flutterEngine.getRenderer().isSoftwareRenderingEnabled()) { setWillNotDraw(!(isAccessibilityEnabled || isTouchExplorationEnabled)); } else { setWillNotDraw(false); } } // -------- End: Accessibility --------- // -------- Start: Mouse ------- @Override @TargetApi(API_LEVELS.API_24) @RequiresApi(API_LEVELS.API_24) @NonNull public PointerIcon getSystemPointerIcon(int type) { return PointerIcon.getSystemIcon(getContext(), type); } // -------- End: Mouse --------- // -------- Start: Keyboard ------- @Override public BinaryMessenger getBinaryMessenger() { return flutterEngine.getDartExecutor(); } @Override public boolean onTextInputKeyEvent(@NonNull KeyEvent keyEvent) { return textInputPlugin.handleKeyEvent(keyEvent); } @Override public void redispatch(@NonNull KeyEvent keyEvent) { getRootView().dispatchKeyEvent(keyEvent); } // -------- End: Keyboard ------- /** * Connects this {@code FlutterView} to the given {@link * io.flutter.embedding.engine.FlutterEngine}. * * <p>This {@code FlutterView} will begin rendering the UI painted by the given {@link * FlutterEngine}. This {@code FlutterView} will also begin forwarding interaction events from * this {@code FlutterView} to the given {@link io.flutter.embedding.engine.FlutterEngine}, e.g., * user touch events, accessibility events, keyboard events, and others. * * <p>See {@link #detachFromFlutterEngine()} for information on how to detach from a {@link * FlutterEngine}. */ public void attachToFlutterEngine(@NonNull FlutterEngine flutterEngine) { Log.v(TAG, "Attaching to a FlutterEngine: " + flutterEngine); if (isAttachedToFlutterEngine()) { if (flutterEngine == this.flutterEngine) { // We are already attached to this FlutterEngine Log.v(TAG, "Already attached to this engine. Doing nothing."); return; } // Detach from a previous FlutterEngine so we can attach to this new one. Log.v( TAG, "Currently attached to a different engine. Detaching and then attaching" + " to new engine."); detachFromFlutterEngine(); } this.flutterEngine = flutterEngine; // Instruct our FlutterRenderer that we are now its designated RenderSurface. FlutterRenderer flutterRenderer = this.flutterEngine.getRenderer(); isFlutterUiDisplayed = flutterRenderer.isDisplayingFlutterUi(); renderSurface.attachToRenderer(flutterRenderer); flutterRenderer.addIsDisplayingFlutterUiListener(flutterUiDisplayListener); // Initialize various components that know how to process Android View I/O // in a way that Flutter understands. if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { mouseCursorPlugin = new MouseCursorPlugin(this, this.flutterEngine.getMouseCursorChannel()); } textInputPlugin = new TextInputPlugin( this, this.flutterEngine.getTextInputChannel(), this.flutterEngine.getPlatformViewsController()); try { textServicesManager = (TextServicesManager) getContext().getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE); spellCheckPlugin = new SpellCheckPlugin(textServicesManager, this.flutterEngine.getSpellCheckChannel()); } catch (Exception e) { Log.e(TAG, "TextServicesManager not supported by device, spell check disabled."); } localizationPlugin = this.flutterEngine.getLocalizationPlugin(); keyboardManager = new KeyboardManager(this); androidTouchProcessor = new AndroidTouchProcessor(this.flutterEngine.getRenderer(), /*trackMotionEvents=*/ false); accessibilityBridge = new AccessibilityBridge( this, flutterEngine.getAccessibilityChannel(), (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE), getContext().getContentResolver(), this.flutterEngine.getPlatformViewsController()); accessibilityBridge.setOnAccessibilityChangeListener(onAccessibilityChangeListener); resetWillNotDraw( accessibilityBridge.isAccessibilityEnabled(), accessibilityBridge.isTouchExplorationEnabled()); // Connect AccessibilityBridge to the PlatformViewsController within the FlutterEngine. // This allows platform Views to hook into Flutter's overall accessibility system. this.flutterEngine.getPlatformViewsController().attachAccessibilityBridge(accessibilityBridge); this.flutterEngine .getPlatformViewsController() .attachToFlutterRenderer(this.flutterEngine.getRenderer()); // Inform the Android framework that it should retrieve a new InputConnection // now that an engine is attached. // TODO(mattcarroll): once this is proven to work, move this line ot TextInputPlugin textInputPlugin.getInputMethodManager().restartInput(this); // Push View and Context related information from Android to Flutter. sendUserSettingsToFlutter(); getContext() .getContentResolver() .registerContentObserver( Settings.System.getUriFor(Settings.System.TEXT_SHOW_PASSWORD), false, systemSettingsObserver); sendViewportMetricsToFlutter(); flutterEngine.getPlatformViewsController().attachToView(this); // Notify engine attachment listeners of the attachment. for (FlutterEngineAttachmentListener listener : flutterEngineAttachmentListeners) { listener.onFlutterEngineAttachedToFlutterView(flutterEngine); } // If the first frame has already been rendered, notify all first frame listeners. // Do this after all other initialization so that listeners don't inadvertently interact // with a FlutterView that is only partially attached to a FlutterEngine. if (isFlutterUiDisplayed) { flutterUiDisplayListener.onFlutterUiDisplayed(); } } /** * Disconnects this {@code FlutterView} from a previously attached {@link * io.flutter.embedding.engine.FlutterEngine}. * * <p>This {@code FlutterView} will clear its UI and stop forwarding all events to the * previously-attached {@link io.flutter.embedding.engine.FlutterEngine}. This includes touch * events, accessibility events, keyboard events, and others. * * <p>See {@link #attachToFlutterEngine(FlutterEngine)} for information on how to attach a {@link * FlutterEngine}. */ public void detachFromFlutterEngine() { Log.v(TAG, "Detaching from a FlutterEngine: " + flutterEngine); if (!isAttachedToFlutterEngine()) { Log.v(TAG, "FlutterView not attached to an engine. Not detaching."); return; } // Notify engine attachment listeners of the detachment. for (FlutterEngineAttachmentListener listener : flutterEngineAttachmentListeners) { listener.onFlutterEngineDetachedFromFlutterView(); } getContext().getContentResolver().unregisterContentObserver(systemSettingsObserver); flutterEngine.getPlatformViewsController().detachFromView(); // Disconnect the FlutterEngine's PlatformViewsController from the AccessibilityBridge. flutterEngine.getPlatformViewsController().detachAccessibilityBridge(); // Disconnect and clean up the AccessibilityBridge. accessibilityBridge.release(); accessibilityBridge = null; // Inform the Android framework that it should retrieve a new InputConnection // now that the engine is detached. The new InputConnection will be null, which // signifies that this View does not process input (until a new engine is attached). // TODO(mattcarroll): once this is proven to work, move this line ot TextInputPlugin textInputPlugin.getInputMethodManager().restartInput(this); textInputPlugin.destroy(); keyboardManager.destroy(); if (spellCheckPlugin != null) { spellCheckPlugin.destroy(); } if (mouseCursorPlugin != null) { mouseCursorPlugin.destroy(); } // Instruct our FlutterRenderer that we are no longer interested in being its RenderSurface. FlutterRenderer flutterRenderer = flutterEngine.getRenderer(); isFlutterUiDisplayed = false; flutterRenderer.removeIsDisplayingFlutterUiListener(flutterUiDisplayListener); flutterRenderer.stopRenderingToSurface(); flutterRenderer.setSemanticsEnabled(false); // Revert the image view to previous surface if (previousRenderSurface != null && renderSurface == flutterImageView) { renderSurface = previousRenderSurface; } renderSurface.detachFromRenderer(); releaseImageView(); previousRenderSurface = null; flutterEngine = null; } private void releaseImageView() { if (flutterImageView != null) { flutterImageView.closeImageReader(); // Remove the FlutterImageView that was previously added by {@code convertToImageView} to // avoid leaks when this FlutterView is reused later in the scenario where multiple // FlutterActivity/FlutterFragment share one engine. removeView(flutterImageView); flutterImageView = null; } } @VisibleForTesting @NonNull public FlutterImageView createImageView() { return new FlutterImageView( getContext(), getWidth(), getHeight(), FlutterImageView.SurfaceKind.background); } @VisibleForTesting public FlutterImageView getCurrentImageSurface() { return flutterImageView; } /** * Converts the current render surface to a {@link FlutterImageView} if it's not one already. * Otherwise, it resizes the {@link FlutterImageView} based on the current view size. */ public void convertToImageView() { renderSurface.pause(); if (flutterImageView == null) { flutterImageView = createImageView(); addView(flutterImageView); } else { flutterImageView.resizeIfNeeded(getWidth(), getHeight()); } previousRenderSurface = renderSurface; renderSurface = flutterImageView; if (flutterEngine != null) { renderSurface.attachToRenderer(flutterEngine.getRenderer()); } } /** * If the surface is rendered by a {@link FlutterImageView}, then calling this method will stop * rendering to a {@link FlutterImageView}, and render on the previous surface instead. * * @param onDone a callback called when Flutter UI is rendered on the previous surface. Use this * callback to perform cleanups. For example, destroy overlay surfaces. */ public void revertImageView(@NonNull Runnable onDone) { if (flutterImageView == null) { Log.v(TAG, "Tried to revert the image view, but no image view is used."); return; } if (previousRenderSurface == null) { Log.v(TAG, "Tried to revert the image view, but no previous surface was used."); return; } renderSurface = previousRenderSurface; previousRenderSurface = null; final FlutterRenderer renderer = flutterEngine.getRenderer(); if (flutterEngine == null || renderer == null) { flutterImageView.detachFromRenderer(); releaseImageView(); onDone.run(); return; } // Resume rendering to the previous surface. // This surface is typically `FlutterSurfaceView` or `FlutterTextureView`. renderSurface.resume(); // Install a Flutter UI listener to wait until the first frame is rendered // in the new surface to call the `onDone` callback. renderer.addIsDisplayingFlutterUiListener( new FlutterUiDisplayListener() { @Override public void onFlutterUiDisplayed() { renderer.removeIsDisplayingFlutterUiListener(this); onDone.run(); if (!(renderSurface instanceof FlutterImageView) && flutterImageView != null) { flutterImageView.detachFromRenderer(); releaseImageView(); } } @Override public void onFlutterUiNoLongerDisplayed() { // no-op } }); } public void attachOverlaySurfaceToRender(@NonNull FlutterImageView view) { if (flutterEngine != null) { view.attachToRenderer(flutterEngine.getRenderer()); } } public boolean acquireLatestImageViewFrame() { if (flutterImageView != null) { return flutterImageView.acquireLatestImage(); } return false; } /** * Returns true if this {@code FlutterView} is currently attached to a {@link * io.flutter.embedding.engine.FlutterEngine}. */ @VisibleForTesting public boolean isAttachedToFlutterEngine() { return flutterEngine != null && flutterEngine.getRenderer() == renderSurface.getAttachedRenderer(); } /** * Returns the {@link io.flutter.embedding.engine.FlutterEngine} to which this {@code FlutterView} * is currently attached, or null if this {@code FlutterView} is not currently attached to a * {@link io.flutter.embedding.engine.FlutterEngine}. */ @VisibleForTesting @Nullable public FlutterEngine getAttachedFlutterEngine() { return flutterEngine; } /** * Adds a {@link FlutterEngineAttachmentListener}, which is notified whenever this {@code * FlutterView} attached to/detaches from a {@link io.flutter.embedding.engine.FlutterEngine}. */ @VisibleForTesting public void addFlutterEngineAttachmentListener( @NonNull FlutterEngineAttachmentListener listener) { flutterEngineAttachmentListeners.add(listener); } /** * Removes a {@link FlutterEngineAttachmentListener} that was previously added with {@link * #addFlutterEngineAttachmentListener(FlutterEngineAttachmentListener)}. */ @VisibleForTesting public void removeFlutterEngineAttachmentListener( @NonNull FlutterEngineAttachmentListener listener) { flutterEngineAttachmentListeners.remove(listener); } /** * Send various user preferences of this Android device to Flutter. * * <p>For example, sends the user's "text scale factor" preferences, as well as the user's clock * format preference. * * <p>FlutterEngine must be non-null when this method is invoked. */ @VisibleForTesting /* package */ void sendUserSettingsToFlutter() { // Lookup the current brightness of the Android OS. boolean isNightModeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES; SettingsChannel.PlatformBrightness brightness = isNightModeOn ? SettingsChannel.PlatformBrightness.dark : SettingsChannel.PlatformBrightness.light; boolean isNativeSpellCheckServiceDefined = false; if (textServicesManager != null) { if (Build.VERSION.SDK_INT >= API_LEVELS.API_31) { List<SpellCheckerInfo> enabledSpellCheckerInfos = textServicesManager.getEnabledSpellCheckerInfos(); boolean gboardSpellCheckerEnabled = enabledSpellCheckerInfos.stream() .anyMatch( spellCheckerInfo -> spellCheckerInfo .getPackageName() .equals("com.google.android.inputmethod.latin")); // Checks if enabled spell checker is the one that is suppported by Gboard, which is // the one Flutter supports by default. isNativeSpellCheckServiceDefined = textServicesManager.isSpellCheckerEnabled() && gboardSpellCheckerEnabled; } else { isNativeSpellCheckServiceDefined = true; } } flutterEngine .getSettingsChannel() .startMessage() .setTextScaleFactor(getResources().getConfiguration().fontScale) .setDisplayMetrics(getResources().getDisplayMetrics()) .setNativeSpellCheckServiceDefined(isNativeSpellCheckServiceDefined) .setBrieflyShowPassword( Settings.System.getInt( getContext().getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD, 1) == 1) .setUse24HourFormat(DateFormat.is24HourFormat(getContext())) .setPlatformBrightness(brightness) .send(); } private void sendViewportMetricsToFlutter() { if (!isAttachedToFlutterEngine()) { Log.w( TAG, "Tried to send viewport metrics from Android to Flutter but this " + "FlutterView was not attached to a FlutterEngine."); return; } viewportMetrics.devicePixelRatio = getResources().getDisplayMetrics().density; viewportMetrics.physicalTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); flutterEngine.getRenderer().setViewportMetrics(viewportMetrics); } @Override public void onProvideAutofillVirtualStructure(@NonNull ViewStructure structure, int flags) { super.onProvideAutofillVirtualStructure(structure, flags); textInputPlugin.onProvideAutofillVirtualStructure(structure, flags); } @Override public void autofill(@NonNull SparseArray<AutofillValue> values) { textInputPlugin.autofill(values); } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); // For `FlutterSurfaceView`, setting visibility to the current `FlutterView` will not take // effect since it is not in the view tree. So override this method and set the surfaceView. // See https://github.com/flutter/flutter/issues/105203 if (renderSurface instanceof FlutterSurfaceView) { ((FlutterSurfaceView) renderSurface).setVisibility(visibility); } } /** * Listener that is notified when a {@link io.flutter.embedding.engine.FlutterEngine} is attached * to/detached from a given {@code FlutterView}. */ @VisibleForTesting public interface FlutterEngineAttachmentListener { /** The given {@code engine} has been attached to the associated {@code FlutterView}. */ void onFlutterEngineAttachedToFlutterView(@NonNull FlutterEngine engine); /** * A previously attached {@link io.flutter.embedding.engine.FlutterEngine} has been detached * from the associated {@code FlutterView}. */ void onFlutterEngineDetachedFromFlutterView(); } }
engine/shell/platform/android/io/flutter/embedding/android/FlutterView.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/android/FlutterView.java", "repo_id": "engine", "token_count": 20542 }
297
// 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. package io.flutter.embedding.engine; import android.view.Surface; import androidx.annotation.Keep; import androidx.annotation.NonNull; @Keep public class FlutterOverlaySurface { @NonNull private final Surface surface; private final int id; public FlutterOverlaySurface(int id, @NonNull Surface surface) { this.id = id; this.surface = surface; } public int getId() { return id; } public Surface getSurface() { return surface; } }
engine/shell/platform/android/io/flutter/embedding/engine/FlutterOverlaySurface.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/FlutterOverlaySurface.java", "repo_id": "engine", "token_count": 198 }
298
// 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. package io.flutter.embedding.engine.plugins.activity; import androidx.annotation.NonNull; /** * {@link io.flutter.embedding.engine.plugins.FlutterPlugin} that is interested in {@link * android.app.Activity} lifecycle events related to a {@link * io.flutter.embedding.engine.FlutterEngine} running within the given {@link android.app.Activity}. */ public interface ActivityAware { /** * This {@code ActivityAware} {@link io.flutter.embedding.engine.plugins.FlutterPlugin} is now * associated with an {@link android.app.Activity}. * * <p>This method can be invoked in 1 of 2 situations: * * <ul> * <li>This {@code ActivityAware} {@link io.flutter.embedding.engine.plugins.FlutterPlugin} was * just added to a {@link io.flutter.embedding.engine.FlutterEngine} that was already * connected to a running {@link android.app.Activity}. * <li>This {@code ActivityAware} {@link io.flutter.embedding.engine.plugins.FlutterPlugin} was * already added to a {@link io.flutter.embedding.engine.FlutterEngine} and that {@link * io.flutter.embedding.engine.FlutterEngine} was just connected to an {@link * android.app.Activity}. * </ul> * * The given {@link ActivityPluginBinding} contains {@link android.app.Activity}-related * references that an {@code ActivityAware} {@link * io.flutter.embedding.engine.plugins.FlutterPlugin} may require, such as a reference to the * actual {@link android.app.Activity} in question. The {@link ActivityPluginBinding} may be * referenced until either {@link #onDetachedFromActivityForConfigChanges()} or {@link * #onDetachedFromActivity()} is invoked. At the conclusion of either of those methods, the * binding is no longer valid. Clear any references to the binding or its resources, and do not * invoke any further methods on the binding or its resources. */ void onAttachedToActivity(@NonNull ActivityPluginBinding binding); /** * The {@link android.app.Activity} that was attached and made available in {@link * #onAttachedToActivity(ActivityPluginBinding)} has been detached from this {@code * ActivityAware}'s {@link io.flutter.embedding.engine.FlutterEngine} for the purpose of * processing a configuration change. * * <p>By the end of this method, the {@link android.app.Activity} that was made available in * {@link #onAttachedToActivity(ActivityPluginBinding)} is no longer valid. Any references to the * associated {@link android.app.Activity} or {@link ActivityPluginBinding} should be cleared. * * <p>This method should be quickly followed by {@link * #onReattachedToActivityForConfigChanges(ActivityPluginBinding)}, which signifies that a new * {@link android.app.Activity} has been created with the new configuration options. That method * provides a new {@link ActivityPluginBinding}, which references the newly created and associated * {@link android.app.Activity}. * * <p>Any {@code Lifecycle} listeners that were registered in {@link * #onAttachedToActivity(ActivityPluginBinding)} should be deregistered here to avoid a possible * memory leak and other side effects. */ void onDetachedFromActivityForConfigChanges(); /** * This plugin and its {@link io.flutter.embedding.engine.FlutterEngine} have been re-attached to * an {@link android.app.Activity} after the {@link android.app.Activity} was recreated to handle * configuration changes. * * <p>{@code binding} includes a reference to the new instance of the {@link * android.app.Activity}. {@code binding} and its references may be cached and used from now until * either {@link #onDetachedFromActivityForConfigChanges()} or {@link #onDetachedFromActivity()} * is invoked. At the conclusion of either of those methods, the binding is no longer valid. Clear * any references to the binding or its resources, and do not invoke any further methods on the * binding or its resources. */ void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding); /** * This plugin has been detached from an {@link android.app.Activity}. * * <p>Detachment can occur for a number of reasons. * * <ul> * <li>The app is no longer visible and the {@link android.app.Activity} instance has been * destroyed. * <li>The {@link io.flutter.embedding.engine.FlutterEngine} that this plugin is connected to * has been detached from its {@link io.flutter.embedding.android.FlutterView}. * <li>This {@code ActivityAware} plugin has been removed from its {@link * io.flutter.embedding.engine.FlutterEngine}. * </ul> * * By the end of this method, the {@link android.app.Activity} that was made available in {@link * #onAttachedToActivity(ActivityPluginBinding)} is no longer valid. Any references to the * associated {@link android.app.Activity} or {@link ActivityPluginBinding} should be cleared. * * <p>Any {@code Lifecycle} listeners that were registered in {@link * #onAttachedToActivity(ActivityPluginBinding)} or {@link * #onReattachedToActivityForConfigChanges(ActivityPluginBinding)} should be deregistered here to * avoid a possible memory leak and other side effects. */ void onDetachedFromActivity(); }
engine/shell/platform/android/io/flutter/embedding/engine/plugins/activity/ActivityAware.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/activity/ActivityAware.java", "repo_id": "engine", "token_count": 1682 }
299
// 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. package io.flutter.embedding.engine.renderer; import static io.flutter.Build.API_LEVELS; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.graphics.ImageFormat; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.hardware.HardwareBuffer; import android.hardware.SyncFence; import android.media.Image; import android.media.ImageReader; import android.os.Build; import android.os.Handler; import android.view.Surface; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.Log; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.view.TextureRegistry; import java.io.IOException; import java.lang.ref.WeakReference; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; /** * Represents the rendering responsibilities of a {@code FlutterEngine}. * * <p>{@code FlutterRenderer} works in tandem with a provided {@link RenderSurface} to paint Flutter * pixels to an Android {@code View} hierarchy. * * <p>{@code FlutterRenderer} manages textures for rendering, and forwards some Java calls to native * Flutter code via JNI. The corresponding {@link RenderSurface} provides the Android {@link * Surface} that this renderer paints. * * <p>{@link io.flutter.embedding.android.FlutterSurfaceView} and {@link * io.flutter.embedding.android.FlutterTextureView} are implementations of {@link RenderSurface}. */ public class FlutterRenderer implements TextureRegistry { /** * Whether to always use GL textures for {@link FlutterRenderer#createSurfaceProducer()}. * * <p>This is a debug-only API intended for local development. For example, when using a newer * Android device (that normally would use {@link ImageReaderSurfaceProducer}, but wanting to test * the OpenGLES/{@link SurfaceTextureSurfaceProducer} code branch. This flag has undefined * behavior if set to true while running in a Vulkan (Impeller) context. */ @VisibleForTesting public static boolean debugForceSurfaceProducerGlTextures = false; private static final String TAG = "FlutterRenderer"; @NonNull private final FlutterJNI flutterJNI; @NonNull private final AtomicLong nextTextureId = new AtomicLong(0L); @Nullable private Surface surface; private boolean isDisplayingFlutterUi = false; private final Handler handler = new Handler(); @NonNull private final Set<WeakReference<TextureRegistry.OnTrimMemoryListener>> onTrimMemoryListeners = new HashSet<>(); @NonNull private final FlutterUiDisplayListener flutterUiDisplayListener = new FlutterUiDisplayListener() { @Override public void onFlutterUiDisplayed() { isDisplayingFlutterUi = true; } @Override public void onFlutterUiNoLongerDisplayed() { isDisplayingFlutterUi = false; } }; public FlutterRenderer(@NonNull FlutterJNI flutterJNI) { this.flutterJNI = flutterJNI; this.flutterJNI.addIsDisplayingFlutterUiListener(flutterUiDisplayListener); } /** * Returns true if this {@code FlutterRenderer} is painting pixels to an Android {@code View} * hierarchy, false otherwise. */ public boolean isDisplayingFlutterUi() { return isDisplayingFlutterUi; } /** * Adds a listener that is invoked whenever this {@code FlutterRenderer} starts and stops painting * pixels to an Android {@code View} hierarchy. */ public void addIsDisplayingFlutterUiListener(@NonNull FlutterUiDisplayListener listener) { flutterJNI.addIsDisplayingFlutterUiListener(listener); if (isDisplayingFlutterUi) { listener.onFlutterUiDisplayed(); } } /** * Removes a listener added via {@link * #addIsDisplayingFlutterUiListener(FlutterUiDisplayListener)}. */ public void removeIsDisplayingFlutterUiListener(@NonNull FlutterUiDisplayListener listener) { flutterJNI.removeIsDisplayingFlutterUiListener(listener); } private void clearDeadListeners() { final Iterator<WeakReference<OnTrimMemoryListener>> iterator = onTrimMemoryListeners.iterator(); while (iterator.hasNext()) { WeakReference<OnTrimMemoryListener> listenerRef = iterator.next(); final OnTrimMemoryListener listener = listenerRef.get(); if (listener == null) { iterator.remove(); } } } /** Adds a listener that is invoked when a memory pressure warning was forward. */ @VisibleForTesting /* package */ void addOnTrimMemoryListener(@NonNull OnTrimMemoryListener listener) { // Purge dead listener to avoid accumulating. clearDeadListeners(); onTrimMemoryListeners.add(new WeakReference<>(listener)); } /** * Removes a {@link OnTrimMemoryListener} that was added with {@link * #addOnTrimMemoryListener(OnTrimMemoryListener)}. */ @VisibleForTesting /* package */ void removeOnTrimMemoryListener(@NonNull OnTrimMemoryListener listener) { for (WeakReference<OnTrimMemoryListener> listenerRef : onTrimMemoryListeners) { if (listenerRef.get() == listener) { onTrimMemoryListeners.remove(listenerRef); break; } } } // ------ START TextureRegistry IMPLEMENTATION ----- /** * Creates and returns a new external texture {@link SurfaceProducer} managed by the Flutter * engine that is also made available to Flutter code. */ @NonNull @Override public SurfaceProducer createSurfaceProducer() { // Prior to Impeller, Flutter on Android *only* ran on OpenGLES (via Skia). That // meant that // plugins (i.e. end-users) either explicitly created a SurfaceTexture (via // createX/registerX) or an ImageTexture (via createX/registerX). // // In an Impeller world, which for the first time uses (if available) a Vulkan // rendering // backend, it is no longer possible (at least not trivially) to render an // OpenGLES-provided // texture (SurfaceTexture) in a Vulkan context. // // This function picks the "best" rendering surface based on the Android // runtime, and // provides a consumer-agnostic SurfaceProducer (which in turn vends a Surface), // and has // plugins (i.e. end-users) use the Surface instead, letting us "hide" the // consumer-side // of the implementation. // // tl;dr: If ImageTexture is available, we use it, otherwise we use a // SurfaceTexture. // Coincidentally, if ImageTexture is available, we are also on an Android // version that is // running Vulkan, so we don't have to worry about it not being supported. final SurfaceProducer entry; if (!debugForceSurfaceProducerGlTextures && Build.VERSION.SDK_INT >= API_LEVELS.API_29) { final long id = nextTextureId.getAndIncrement(); final ImageReaderSurfaceProducer producer = new ImageReaderSurfaceProducer(id); registerImageTexture(id, producer); addOnTrimMemoryListener(producer); Log.v(TAG, "New ImageReaderSurfaceProducer ID: " + id); entry = producer; } else { // TODO(matanlurey): Actually have the class named "*Producer" to well, produce // something. This is a code smell, but does guarantee the paths for both // createSurfaceTexture and createSurfaceProducer doesn't diverge. As we get more // confident in this API and any possible bugs (and have tests to check we don't // regress), reconsider this pattern. final SurfaceTextureEntry texture = createSurfaceTexture(); final SurfaceTextureSurfaceProducer producer = new SurfaceTextureSurfaceProducer(texture.id(), handler, flutterJNI, texture); Log.v(TAG, "New SurfaceTextureSurfaceProducer ID: " + texture.id()); entry = producer; } return entry; } /** * Creates and returns a new {@link SurfaceTexture} managed by the Flutter engine that is also * made available to Flutter code. */ @NonNull @Override public SurfaceTextureEntry createSurfaceTexture() { Log.v(TAG, "Creating a SurfaceTexture."); final SurfaceTexture surfaceTexture = new SurfaceTexture(0); return registerSurfaceTexture(surfaceTexture); } /** * Registers and returns a {@link SurfaceTexture} managed by the Flutter engine that is also made * available to Flutter code. */ @NonNull @Override public SurfaceTextureEntry registerSurfaceTexture(@NonNull SurfaceTexture surfaceTexture) { return registerSurfaceTexture(nextTextureId.getAndIncrement(), surfaceTexture); } /** * Similar to {@link FlutterRenderer#registerSurfaceTexture} but with an existing @{code * textureId}. * * @param surfaceTexture Surface texture to wrap. * @param textureId A texture ID already created that should be assigned to the surface texture. */ @NonNull private SurfaceTextureEntry registerSurfaceTexture( long textureId, @NonNull SurfaceTexture surfaceTexture) { surfaceTexture.detachFromGLContext(); final SurfaceTextureRegistryEntry entry = new SurfaceTextureRegistryEntry(textureId, surfaceTexture); Log.v(TAG, "New SurfaceTexture ID: " + entry.id()); registerTexture(entry.id(), entry.textureWrapper()); addOnTrimMemoryListener(entry); return entry; } @NonNull @Override public ImageTextureEntry createImageTexture() { final ImageTextureRegistryEntry entry = new ImageTextureRegistryEntry(nextTextureId.getAndIncrement()); Log.v(TAG, "New ImageTextureEntry ID: " + entry.id()); registerImageTexture(entry.id(), entry); return entry; } @Override public void onTrimMemory(int level) { final Iterator<WeakReference<OnTrimMemoryListener>> iterator = onTrimMemoryListeners.iterator(); while (iterator.hasNext()) { WeakReference<OnTrimMemoryListener> listenerRef = iterator.next(); final OnTrimMemoryListener listener = listenerRef.get(); if (listener != null) { listener.onTrimMemory(level); } else { // Purge cleared refs to avoid accumulating a lot of dead listener iterator.remove(); } } } final class SurfaceTextureRegistryEntry implements TextureRegistry.SurfaceTextureEntry, TextureRegistry.OnTrimMemoryListener { private final long id; @NonNull private final SurfaceTextureWrapper textureWrapper; private boolean released; @Nullable private OnTrimMemoryListener trimMemoryListener; @Nullable private OnFrameConsumedListener frameConsumedListener; SurfaceTextureRegistryEntry(long id, @NonNull SurfaceTexture surfaceTexture) { this.id = id; Runnable onFrameConsumed = () -> { if (frameConsumedListener != null) { frameConsumedListener.onFrameConsumed(); } }; this.textureWrapper = new SurfaceTextureWrapper(surfaceTexture, onFrameConsumed); // Even though we make sure to unregister the callback before releasing, as of // Android O, SurfaceTexture has a data race when accessing the callback, so the // callback may still be called by a stale reference after released==true and // mNativeView==null. SurfaceTexture.OnFrameAvailableListener onFrameListener = texture -> { if (released || !flutterJNI.isAttached()) { // Even though we make sure to unregister the callback before releasing, as of // Android O, SurfaceTexture has a data race when accessing the callback, so the // callback may still be called by a stale reference after released==true and // mNativeView==null. return; } textureWrapper.markDirty(); scheduleEngineFrame(); }; // The callback relies on being executed on the UI thread (unsynchronised read of // mNativeView and also the engine code check for platform thread in // Shell::OnPlatformViewMarkTextureFrameAvailable), so we explicitly pass a Handler for the // current thread. this.surfaceTexture().setOnFrameAvailableListener(onFrameListener, new Handler()); } @Override public void onTrimMemory(int level) { if (trimMemoryListener != null) { trimMemoryListener.onTrimMemory(level); } } private void removeListener() { removeOnTrimMemoryListener(this); } @NonNull public SurfaceTextureWrapper textureWrapper() { return textureWrapper; } @Override @NonNull public SurfaceTexture surfaceTexture() { return textureWrapper.surfaceTexture(); } @Override public long id() { return id; } @Override public void release() { if (released) { return; } Log.v(TAG, "Releasing a SurfaceTexture (" + id + ")."); textureWrapper.release(); unregisterTexture(id); removeListener(); released = true; } @Override protected void finalize() throws Throwable { try { if (released) { return; } handler.post(new TextureFinalizerRunnable(id, flutterJNI)); } finally { super.finalize(); } } @Override public void setOnFrameConsumedListener(@Nullable OnFrameConsumedListener listener) { frameConsumedListener = listener; } @Override public void setOnTrimMemoryListener(@Nullable OnTrimMemoryListener listener) { trimMemoryListener = listener; } } static final class TextureFinalizerRunnable implements Runnable { private final long id; private final FlutterJNI flutterJNI; TextureFinalizerRunnable(long id, @NonNull FlutterJNI flutterJNI) { this.id = id; this.flutterJNI = flutterJNI; } @Override public void run() { if (!flutterJNI.isAttached()) { return; } Log.v(TAG, "Releasing a Texture (" + id + ")."); flutterJNI.unregisterTexture(id); } } // Keep a queue of ImageReaders. // Each ImageReader holds acquired Images. // When we acquire the next image, close any ImageReaders that don't have any // more pending images. @Keep @TargetApi(API_LEVELS.API_29) final class ImageReaderSurfaceProducer implements TextureRegistry.SurfaceProducer, TextureRegistry.ImageConsumer, TextureRegistry.OnTrimMemoryListener { private static final String TAG = "ImageReaderSurfaceProducer"; private static final int MAX_IMAGES = 5; // Flip when debugging to see verbose logs. private static final boolean VERBOSE_LOGS = false; // If we cleanup the ImageReaders on memory pressure it breaks VirtualDisplay // backed platform views. Disable for now as this is only necessary to work // around a Samsung-specific Android 14 bug. private static final boolean CLEANUP_ON_MEMORY_PRESSURE = false; private final long id; private boolean released; // Will be true in tests and on Android API < 33. private boolean ignoringFence = false; // The requested width and height are updated by setSize. private int requestedWidth = 1; private int requestedHeight = 1; // Whenever the requested width and height change we set this to be true so we // create a new ImageReader (inside getSurface) with the correct width and height. // We use this flag so that we lazily create the ImageReader only when a frame // will be produced at that size. private boolean createNewReader = true; // State held to track latency of various stages. private long lastDequeueTime = 0; private long lastQueueTime = 0; private long lastScheduleTime = 0; private Object lock = new Object(); // REQUIRED: The following fields must only be accessed when lock is held. private final LinkedList<PerImageReader> imageReaderQueue = new LinkedList<PerImageReader>(); private final HashMap<ImageReader, PerImageReader> perImageReaders = new HashMap<ImageReader, PerImageReader>(); private PerImage lastDequeuedImage = null; private PerImageReader lastReaderDequeuedFrom = null; /** Internal class: state held per Image produced by ImageReaders. */ private class PerImage { public final Image image; public final long queuedTime; public PerImage(Image image, long queuedTime) { this.image = image; this.queuedTime = queuedTime; } } /** Internal class: state held per ImageReader. */ private class PerImageReader { public final ImageReader reader; private final LinkedList<PerImage> imageQueue = new LinkedList<PerImage>(); private boolean closed = false; private final ImageReader.OnImageAvailableListener onImageAvailableListener = reader -> { Image image = null; try { image = reader.acquireLatestImage(); } catch (IllegalStateException e) { Log.e(TAG, "onImageAvailable acquireLatestImage failed: " + e); } if (image == null) { return; } if (released || closed) { image.close(); return; } onImage(reader, image); }; public PerImageReader(ImageReader reader) { this.reader = reader; reader.setOnImageAvailableListener(onImageAvailableListener, new Handler()); } PerImage queueImage(Image image) { if (closed) { return null; } PerImage perImage = new PerImage(image, System.nanoTime()); imageQueue.add(perImage); // If we fall too far behind we will skip some frames. while (imageQueue.size() > 2) { PerImage r = imageQueue.removeFirst(); if (VERBOSE_LOGS) { Log.i(TAG, "" + reader.hashCode() + " force closed image=" + r.image.hashCode()); } r.image.close(); } return perImage; } PerImage dequeueImage() { if (imageQueue.size() == 0) { return null; } PerImage r = imageQueue.removeFirst(); return r; } /** returns true if we can prune this reader */ boolean canPrune() { return imageQueue.size() == 0 && lastReaderDequeuedFrom != this; } void close() { closed = true; if (VERBOSE_LOGS) { Log.i(TAG, "Closing reader=" + reader.hashCode()); } reader.close(); imageQueue.clear(); } } double deltaMillis(long deltaNanos) { double ms = (double) deltaNanos / (double) 1000000.0; return ms; } PerImageReader getOrCreatePerImageReader(ImageReader reader) { PerImageReader r = perImageReaders.get(reader); if (r == null) { r = new PerImageReader(reader); perImageReaders.put(reader, r); imageReaderQueue.add(r); if (VERBOSE_LOGS) { Log.i(TAG, "imageReaderQueue#=" + imageReaderQueue.size()); } } return r; } void pruneImageReaderQueue() { boolean change = false; // Prune nodes from the head of the ImageReader queue. while (imageReaderQueue.size() > 1) { PerImageReader r = imageReaderQueue.peekFirst(); if (!r.canPrune()) { // No more ImageReaders can be pruned this round. break; } imageReaderQueue.removeFirst(); perImageReaders.remove(r.reader); r.close(); change = true; } if (change && VERBOSE_LOGS) { Log.i(TAG, "Pruned image reader queue length=" + imageReaderQueue.size()); } } void onImage(ImageReader reader, Image image) { PerImage queuedImage = null; synchronized (lock) { PerImageReader perReader = getOrCreatePerImageReader(reader); queuedImage = perReader.queueImage(image); } if (queuedImage == null) { // We got a late image. return; } if (VERBOSE_LOGS) { if (lastQueueTime != 0) { long now = System.nanoTime(); long queueDelta = now - lastQueueTime; Log.i( TAG, "" + reader.hashCode() + " enqueued image=" + queuedImage.image.hashCode() + " queueDelta=" + deltaMillis(queueDelta)); lastQueueTime = now; } else { lastQueueTime = System.nanoTime(); } } scheduleEngineFrame(); } PerImage dequeueImage() { PerImage r = null; synchronized (lock) { for (PerImageReader reader : imageReaderQueue) { r = reader.dequeueImage(); if (r == null) { // This reader is probably about to get pruned. continue; } if (VERBOSE_LOGS) { if (lastDequeueTime != 0) { long now = System.nanoTime(); long dequeueDelta = now - lastDequeueTime; long queuedFor = now - r.queuedTime; long scheduleDelay = now - lastScheduleTime; Log.i( TAG, "" + reader.reader.hashCode() + " dequeued image=" + r.image.hashCode() + " queuedFor= " + deltaMillis(queuedFor) + " dequeueDelta=" + deltaMillis(dequeueDelta) + " scheduleDelay=" + deltaMillis(scheduleDelay)); lastDequeueTime = now; } else { lastDequeueTime = System.nanoTime(); } } if (lastDequeuedImage != null) { if (VERBOSE_LOGS) { Log.i( TAG, "" + lastReaderDequeuedFrom.reader.hashCode() + " closing image=" + lastDequeuedImage.image.hashCode()); } // We must keep the last image dequeued open until we are done presenting // it. We have just dequeued a new image (r). Close the previously dequeued // image. lastDequeuedImage.image.close(); lastDequeuedImage = null; } // Remember the last image and reader dequeued from. We do this because we must // keep both of these alive until we are done presenting the image. lastDequeuedImage = r; lastReaderDequeuedFrom = reader; break; } pruneImageReaderQueue(); } return r; } @Override public void onTrimMemory(int level) { if (!CLEANUP_ON_MEMORY_PRESSURE) { return; } cleanup(); createNewReader = true; } private void releaseInternal() { cleanup(); released = true; } private void cleanup() { synchronized (lock) { for (PerImageReader pir : perImageReaders.values()) { if (lastReaderDequeuedFrom == pir) { lastReaderDequeuedFrom = null; } pir.close(); } perImageReaders.clear(); if (lastDequeuedImage != null) { lastDequeuedImage.image.close(); lastDequeuedImage = null; } if (lastReaderDequeuedFrom != null) { lastReaderDequeuedFrom.close(); lastReaderDequeuedFrom = null; } imageReaderQueue.clear(); } } @TargetApi(API_LEVELS.API_33) private void waitOnFence(Image image) { try { SyncFence fence = image.getFence(); fence.awaitForever(); } catch (IOException e) { // Drop. } } private void maybeWaitOnFence(Image image) { if (image == null) { return; } if (ignoringFence) { return; } if (Build.VERSION.SDK_INT >= API_LEVELS.API_33) { // The fence API is only available on Android >= 33. waitOnFence(image); return; } // Log once per ImageTextureEntry. ignoringFence = true; Log.w(TAG, "ImageTextureEntry can't wait on the fence on Android < 33"); } ImageReaderSurfaceProducer(long id) { this.id = id; } @Override public long id() { return id; } @Override public void release() { if (released) { return; } releaseInternal(); unregisterTexture(id); } @Override public void setSize(int width, int height) { // Clamp to a minimum of 1. A 0x0 texture is a runtime exception in ImageReader. width = Math.max(1, width); height = Math.max(1, height); if (requestedWidth == width && requestedHeight == height) { // No size change. return; } this.createNewReader = true; this.requestedHeight = height; this.requestedWidth = width; } @Override public int getWidth() { return this.requestedWidth; } @Override public int getHeight() { return this.requestedHeight; } @Override public Surface getSurface() { PerImageReader pir = getActiveReader(); if (VERBOSE_LOGS) { Log.i(TAG, "" + pir.reader.hashCode() + " returning surface to render a new frame."); } return pir.reader.getSurface(); } @Override public void scheduleFrame() { if (VERBOSE_LOGS) { long now = System.nanoTime(); if (lastScheduleTime != 0) { long delta = now - lastScheduleTime; Log.v(TAG, "scheduleFrame delta=" + deltaMillis(delta)); } lastScheduleTime = now; } scheduleEngineFrame(); } @Override @TargetApi(API_LEVELS.API_29) public Image acquireLatestImage() { PerImage r = dequeueImage(); if (r == null) { return null; } maybeWaitOnFence(r.image); return r.image; } private PerImageReader getActiveReader() { synchronized (lock) { if (createNewReader) { createNewReader = false; // Create a new ImageReader and add it to the queue. ImageReader reader = createImageReader(); if (VERBOSE_LOGS) { Log.i( TAG, "" + reader.hashCode() + " created w=" + requestedWidth + " h=" + requestedHeight); } return getOrCreatePerImageReader(reader); } return imageReaderQueue.peekLast(); } } @Override protected void finalize() throws Throwable { try { if (released) { return; } releaseInternal(); handler.post(new TextureFinalizerRunnable(id, flutterJNI)); } finally { super.finalize(); } } @TargetApi(API_LEVELS.API_33) private ImageReader createImageReader33() { final ImageReader.Builder builder = new ImageReader.Builder(requestedWidth, requestedHeight); // Allow for double buffering. builder.setMaxImages(MAX_IMAGES); // Use PRIVATE image format so that we can support video decoding. // TODO(johnmccutchan): Should we always use PRIVATE here? It may impact our ability to // read back texture data. If we don't always want to use it, how do we decide when to // use it or not? Perhaps PlatformViews can indicate if they may contain DRM'd content. // I need to investigate how PRIVATE impacts our ability to take screenshots or capture // the output of Flutter application. builder.setImageFormat(ImageFormat.PRIVATE); // Hint that consumed images will only be read by GPU. builder.setUsage(HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE); final ImageReader reader = builder.build(); return reader; } @TargetApi(API_LEVELS.API_29) private ImageReader createImageReader29() { final ImageReader reader = ImageReader.newInstance( requestedWidth, requestedHeight, ImageFormat.PRIVATE, MAX_IMAGES, HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE); return reader; } private ImageReader createImageReader() { if (Build.VERSION.SDK_INT >= API_LEVELS.API_33) { return createImageReader33(); } else if (Build.VERSION.SDK_INT >= API_LEVELS.API_29) { return createImageReader29(); } throw new UnsupportedOperationException( "ImageReaderPlatformViewRenderTarget requires API version 29+"); } @VisibleForTesting public void disableFenceForTest() { // Roboelectric's implementation of SyncFence is borked. ignoringFence = true; } @VisibleForTesting public int numImageReaders() { synchronized (lock) { return imageReaderQueue.size(); } } @VisibleForTesting public int numImages() { int r = 0; synchronized (lock) { for (PerImageReader reader : imageReaderQueue) { r += reader.imageQueue.size(); } } return r; } } @Keep final class ImageTextureRegistryEntry implements TextureRegistry.ImageTextureEntry, TextureRegistry.ImageConsumer { private static final String TAG = "ImageTextureRegistryEntry"; private final long id; private boolean released; private boolean ignoringFence = false; private Image image; ImageTextureRegistryEntry(long id) { this.id = id; } @Override public long id() { return id; } @Override public void release() { if (released) { return; } released = true; if (image != null) { image.close(); image = null; } unregisterTexture(id); } @Override public void pushImage(Image image) { if (released) { return; } Image toClose; synchronized (this) { toClose = this.image; this.image = image; } // Close the previously pushed buffer. if (toClose != null) { Log.e(TAG, "Dropping PlatformView Frame"); toClose.close(); } if (image != null) { scheduleEngineFrame(); } } @TargetApi(API_LEVELS.API_33) private void waitOnFence(Image image) { try { SyncFence fence = image.getFence(); fence.awaitForever(); } catch (IOException e) { // Drop. } } @TargetApi(API_LEVELS.API_29) private void maybeWaitOnFence(Image image) { if (image == null) { return; } if (ignoringFence) { return; } if (Build.VERSION.SDK_INT >= API_LEVELS.API_33) { // The fence API is only available on Android >= 33. waitOnFence(image); return; } // Log once per ImageTextureEntry. ignoringFence = true; Log.w(TAG, "ImageTextureEntry can't wait on the fence on Android < 33"); } @Override @TargetApi(API_LEVELS.API_29) public Image acquireLatestImage() { Image r; synchronized (this) { r = this.image; this.image = null; } maybeWaitOnFence(r); return r; } @Override protected void finalize() throws Throwable { try { if (released) { return; } if (image != null) { // Be sure to finalize any cached image. image.close(); image = null; } released = true; handler.post(new TextureFinalizerRunnable(id, flutterJNI)); } finally { super.finalize(); } } } // ------ END TextureRegistry IMPLEMENTATION ---- /** * Notifies Flutter that the given {@code surface} was created and is available for Flutter * rendering. * * <p>If called more than once, the current native resources are released. This can be undesired * if the Engine expects to reuse this surface later. For example, this is true when platform * views are displayed in a frame, and then removed in the next frame. * * <p>To avoid releasing the current surface resources, set {@code keepCurrentSurface} to true. * * <p>See {@link android.view.SurfaceHolder.Callback} and {@link * android.view.TextureView.SurfaceTextureListener} * * @param surface The render surface. * @param onlySwap True if the current active surface should not be detached. */ public void startRenderingToSurface(@NonNull Surface surface, boolean onlySwap) { if (!onlySwap) { // Stop rendering to the surface releases the associated native resources, which causes // a glitch when toggling between rendering to an image view (hybrid composition) and // rendering directly to a Surface or Texture view. For more, // https://github.com/flutter/flutter/issues/95343 stopRenderingToSurface(); } this.surface = surface; if (onlySwap) { // In the swap case we are just swapping the surface that we render to. flutterJNI.onSurfaceWindowChanged(surface); } else { // In the non-swap case we are creating a new surface to render to. flutterJNI.onSurfaceCreated(surface); } } /** * Swaps the {@link Surface} used to render the current frame. * * <p>In hybrid composition, the root surfaces changes from {@link * android.view.SurfaceHolder#getSurface()} to {@link android.media.ImageReader#getSurface()} when * a platform view is in the current frame. */ public void swapSurface(@NonNull Surface surface) { this.surface = surface; flutterJNI.onSurfaceWindowChanged(surface); } /** * Notifies Flutter that a {@code surface} previously registered with {@link * #startRenderingToSurface(Surface, boolean)} has changed size to the given {@code width} and * {@code height}. * * <p>See {@link android.view.SurfaceHolder.Callback} and {@link * android.view.TextureView.SurfaceTextureListener} */ public void surfaceChanged(int width, int height) { flutterJNI.onSurfaceChanged(width, height); } /** * Notifies Flutter that a {@code surface} previously registered with {@link * #startRenderingToSurface(Surface, boolean)} has been destroyed and needs to be released and * cleaned up on the Flutter side. * * <p>See {@link android.view.SurfaceHolder.Callback} and {@link * android.view.TextureView.SurfaceTextureListener} */ public void stopRenderingToSurface() { if (surface != null) { flutterJNI.onSurfaceDestroyed(); // TODO(mattcarroll): the source of truth for this call should be FlutterJNI, which is // where the call to onFlutterUiDisplayed() comes from. However, no such native callback // exists yet, so until the engine and FlutterJNI are configured to call us back when // rendering stops, we will manually monitor that change here. if (isDisplayingFlutterUi) { flutterUiDisplayListener.onFlutterUiNoLongerDisplayed(); } isDisplayingFlutterUi = false; surface = null; } } /** * Notifies Flutter that the viewport metrics, e.g. window height and width, have changed. * * <p>If the width, height, or devicePixelRatio are less than or equal to 0, this update is * ignored. * * @param viewportMetrics The metrics to send to the Dart application. */ public void setViewportMetrics(@NonNull ViewportMetrics viewportMetrics) { // We might get called with just the DPR if width/height aren't available yet. // Just ignore, as it will get called again when width/height are set. if (!viewportMetrics.validate()) { return; } Log.v( TAG, "Setting viewport metrics\n" + "Size: " + viewportMetrics.width + " x " + viewportMetrics.height + "\n" + "Padding - L: " + viewportMetrics.viewPaddingLeft + ", T: " + viewportMetrics.viewPaddingTop + ", R: " + viewportMetrics.viewPaddingRight + ", B: " + viewportMetrics.viewPaddingBottom + "\n" + "Insets - L: " + viewportMetrics.viewInsetLeft + ", T: " + viewportMetrics.viewInsetTop + ", R: " + viewportMetrics.viewInsetRight + ", B: " + viewportMetrics.viewInsetBottom + "\n" + "System Gesture Insets - L: " + viewportMetrics.systemGestureInsetLeft + ", T: " + viewportMetrics.systemGestureInsetTop + ", R: " + viewportMetrics.systemGestureInsetRight + ", B: " + viewportMetrics.systemGestureInsetRight + "\n" + "Display Features: " + viewportMetrics.displayFeatures.size()); int[] displayFeaturesBounds = new int[viewportMetrics.displayFeatures.size() * 4]; int[] displayFeaturesType = new int[viewportMetrics.displayFeatures.size()]; int[] displayFeaturesState = new int[viewportMetrics.displayFeatures.size()]; for (int i = 0; i < viewportMetrics.displayFeatures.size(); i++) { DisplayFeature displayFeature = viewportMetrics.displayFeatures.get(i); displayFeaturesBounds[4 * i] = displayFeature.bounds.left; displayFeaturesBounds[4 * i + 1] = displayFeature.bounds.top; displayFeaturesBounds[4 * i + 2] = displayFeature.bounds.right; displayFeaturesBounds[4 * i + 3] = displayFeature.bounds.bottom; displayFeaturesType[i] = displayFeature.type.encodedValue; displayFeaturesState[i] = displayFeature.state.encodedValue; } flutterJNI.setViewportMetrics( viewportMetrics.devicePixelRatio, viewportMetrics.width, viewportMetrics.height, viewportMetrics.viewPaddingTop, viewportMetrics.viewPaddingRight, viewportMetrics.viewPaddingBottom, viewportMetrics.viewPaddingLeft, viewportMetrics.viewInsetTop, viewportMetrics.viewInsetRight, viewportMetrics.viewInsetBottom, viewportMetrics.viewInsetLeft, viewportMetrics.systemGestureInsetTop, viewportMetrics.systemGestureInsetRight, viewportMetrics.systemGestureInsetBottom, viewportMetrics.systemGestureInsetLeft, viewportMetrics.physicalTouchSlop, displayFeaturesBounds, displayFeaturesType, displayFeaturesState); } // TODO(mattcarroll): describe the native behavior that this invokes // TODO(mattcarroll): determine if this is nullable or nonnull public Bitmap getBitmap() { return flutterJNI.getBitmap(); } // TODO(mattcarroll): describe the native behavior that this invokes public void dispatchPointerDataPacket(@NonNull ByteBuffer buffer, int position) { flutterJNI.dispatchPointerDataPacket(buffer, position); } // TODO(mattcarroll): describe the native behavior that this invokes private void registerTexture(long textureId, @NonNull SurfaceTextureWrapper textureWrapper) { flutterJNI.registerTexture(textureId, textureWrapper); } private void registerImageTexture( long textureId, @NonNull TextureRegistry.ImageConsumer imageTexture) { flutterJNI.registerImageTexture(textureId, imageTexture); } private void scheduleEngineFrame() { flutterJNI.scheduleFrame(); } // TODO(mattcarroll): describe the native behavior that this invokes private void markTextureFrameAvailable(long textureId) { flutterJNI.markTextureFrameAvailable(textureId); } // TODO(mattcarroll): describe the native behavior that this invokes private void unregisterTexture(long textureId) { flutterJNI.unregisterTexture(textureId); } // TODO(mattcarroll): describe the native behavior that this invokes public boolean isSoftwareRenderingEnabled() { return flutterJNI.getIsSoftwareRenderingEnabled(); } // TODO(mattcarroll): describe the native behavior that this invokes public void setAccessibilityFeatures(int flags) { flutterJNI.setAccessibilityFeatures(flags); } // TODO(mattcarroll): describe the native behavior that this invokes public void setSemanticsEnabled(boolean enabled) { flutterJNI.setSemanticsEnabled(enabled); } // TODO(mattcarroll): describe the native behavior that this invokes public void dispatchSemanticsAction( int nodeId, int action, @Nullable ByteBuffer args, int argsPosition) { flutterJNI.dispatchSemanticsAction(nodeId, action, args, argsPosition); } /** * Mutable data structure that holds all viewport metrics properties that Flutter cares about. * * <p>All distance measurements, e.g., width, height, padding, viewInsets, are measured in device * pixels, not logical pixels. */ public static final class ViewportMetrics { /** A value that indicates the setting has not been set. */ public static final int unsetValue = -1; public float devicePixelRatio = 1.0f; public int width = 0; public int height = 0; public int viewPaddingTop = 0; public int viewPaddingRight = 0; public int viewPaddingBottom = 0; public int viewPaddingLeft = 0; public int viewInsetTop = 0; public int viewInsetRight = 0; public int viewInsetBottom = 0; public int viewInsetLeft = 0; public int systemGestureInsetTop = 0; public int systemGestureInsetRight = 0; public int systemGestureInsetBottom = 0; public int systemGestureInsetLeft = 0; public int physicalTouchSlop = unsetValue; /** * Whether this instance contains valid metrics for the Flutter application. * * @return True if width, height, and devicePixelRatio are > 0; false otherwise. */ boolean validate() { return width > 0 && height > 0 && devicePixelRatio > 0; } public List<DisplayFeature> displayFeatures = new ArrayList<>(); } /** * Description of a physical feature on the display. * * <p>A display feature is a distinctive physical attribute located within the display panel of * the device. It can intrude into the application window space and create a visual distortion, * visual or touch discontinuity, make some area invisible or create a logical divider or * separation in the screen space. * * <p>Based on {@link androidx.window.layout.DisplayFeature}, with added support for cutouts. */ public static final class DisplayFeature { public final Rect bounds; public final DisplayFeatureType type; public final DisplayFeatureState state; public DisplayFeature(Rect bounds, DisplayFeatureType type, DisplayFeatureState state) { this.bounds = bounds; this.type = type; this.state = state; } public DisplayFeature(Rect bounds, DisplayFeatureType type) { this.bounds = bounds; this.type = type; this.state = DisplayFeatureState.UNKNOWN; } } /** * Types of display features that can appear on the viewport. * * <p>Some, like {@link #FOLD}, can be reported without actually occluding the screen. They are * useful for knowing where the display is bent or has a crease. The {@link DisplayFeature#bounds} * can be 0-width in such cases. */ public enum DisplayFeatureType { /** * Type of display feature not yet known to Flutter. This can happen if WindowManager is updated * with new types. The {@link DisplayFeature#bounds} is the only known property. */ UNKNOWN(0), /** * A fold in the flexible display that does not occlude the screen. Corresponds to {@link * androidx.window.layout.FoldingFeature.OcclusionType#NONE} */ FOLD(1), /** * Splits the display in two separate panels that can fold. Occludes the screen. Corresponds to * {@link androidx.window.layout.FoldingFeature.OcclusionType#FULL} */ HINGE(2), /** * Area of the screen that usually houses cameras or sensors. Occludes the screen. Corresponds * to {@link android.view.DisplayCutout} */ CUTOUT(3); public final int encodedValue; DisplayFeatureType(int encodedValue) { this.encodedValue = encodedValue; } } /** * State of the display feature. * * <p>For foldables, the state is the posture. For cutouts, this property is {@link #UNKNOWN} */ public enum DisplayFeatureState { /** The display feature is a cutout or this state is new and not yet known to Flutter. */ UNKNOWN(0), /** * The foldable device is completely open. The screen space that is presented to the user is * flat. Corresponds to {@link androidx.window.layout.FoldingFeature.State#FLAT} */ POSTURE_FLAT(1), /** * The foldable device's hinge is in an intermediate position between opened and closed state. * There is a non-flat angle between parts of the flexible screen or between physical display * panels. Corresponds to {@link androidx.window.layout.FoldingFeature.State#HALF_OPENED} */ POSTURE_HALF_OPENED(2); public final int encodedValue; DisplayFeatureState(int encodedValue) { this.encodedValue = encodedValue; } } }
engine/shell/platform/android/io/flutter/embedding/engine/renderer/FlutterRenderer.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/renderer/FlutterRenderer.java", "repo_id": "engine", "token_count": 17307 }
300
// 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. package io.flutter.embedding.engine.systemchannels; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.Log; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.StandardMethodCodec; import java.util.HashMap; import java.util.Map; /** * System channel to exchange restoration data between framework and engine. * * <p>The engine can obtain the current restoration data from the framework via this channel to * store it on disk and - when the app is relaunched - provide the stored data back to the framework * to recreate the original state of the app. * * <p>The channel can be configured to delay responding to the framework's request for restoration * data via {@code waitForRestorationData} until the engine-side has provided the data. This is * useful when the engine is pre-warmed at a point in the application's life cycle where the * restoration data is not available yet. For example, if the engine is pre-warmed as part of the * Application before an Activity is created, this flag should be set to true because Android will * only provide the restoration data to the Activity during the onCreate callback. * * <p>The current restoration data provided by the framework can be read via {@code * getRestorationData()}. */ public class RestorationChannel { private static final String TAG = "RestorationChannel"; public RestorationChannel( @NonNull DartExecutor dartExecutor, @NonNull boolean waitForRestorationData) { this( new MethodChannel(dartExecutor, "flutter/restoration", StandardMethodCodec.INSTANCE), waitForRestorationData); } RestorationChannel(MethodChannel channel, @NonNull boolean waitForRestorationData) { this.channel = channel; this.waitForRestorationData = waitForRestorationData; channel.setMethodCallHandler(handler); } /** * Whether the channel delays responding to the framework's initial request for restoration data * until {@code setRestorationData} has been called. * * <p>If the engine never calls {@code setRestorationData} this flag must be set to false. If set * to true, the engine must call {@code setRestorationData} either with the actual restoration * data as argument or null if it turns out that there is no restoration data. * * <p>If the response to the framework's request for restoration data is not delayed until the * data has been set via {@code setRestorationData}, the framework may intermittently initialize * itself to default values until the restoration data has been made available. Setting this flag * to true avoids that extra work. */ public final boolean waitForRestorationData; // Holds the most current restoration data which may have been provided by the engine // via "setRestorationData" or by the framework via the method channel. This is the data the // framework should be restored to in case the app is terminated. private byte[] restorationData; private MethodChannel channel; private MethodChannel.Result pendingFrameworkRestorationChannelRequest; private boolean engineHasProvidedData = false; private boolean frameworkHasRequestedData = false; /** Obtain the most current restoration data that the framework has provided. */ @Nullable public byte[] getRestorationData() { return restorationData; } /** Set the restoration data from which the framework will restore its state. */ public void setRestorationData(@NonNull byte[] data) { engineHasProvidedData = true; if (pendingFrameworkRestorationChannelRequest != null) { // If their is a pending request from the framework, answer it. pendingFrameworkRestorationChannelRequest.success(packageData(data)); pendingFrameworkRestorationChannelRequest = null; restorationData = data; } else if (frameworkHasRequestedData) { // If the framework has previously received the engine's restoration data, push the new data // directly to it. This case can happen when "waitForRestorationData" is false and the // framework retrieved the restoration state before it was set via this method. // Experimentally, this can also be used to restore a previously used engine to another state, // e.g. when the engine is attached to a new activity. channel.invokeMethod( "push", packageData(data), new MethodChannel.Result() { @Override public void success(Object result) { restorationData = data; } @Override public void error(String errorCode, String errorMessage, Object errorDetails) { Log.e( TAG, "Error " + errorCode + " while sending restoration data to framework: " + errorMessage); } @Override public void notImplemented() { // Nothing to do. } }); } else { // Otherwise, just cache the data until the framework asks for it. restorationData = data; } } /** * Clears the current restoration data. * * <p>This should be called just prior to a hot restart. Otherwise, after the hot restart the * state prior to the hot restart will get restored. */ public void clearData() { restorationData = null; } private final MethodChannel.MethodCallHandler handler = new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) { final String method = call.method; final Object args = call.arguments; switch (method) { case "put": restorationData = (byte[]) args; result.success(null); break; case "get": frameworkHasRequestedData = true; if (engineHasProvidedData || !waitForRestorationData) { result.success(packageData(restorationData)); // Do not delete the restoration data on the engine side after sending it to the // framework. We may need to hand this data back to the operating system if the // framework never modifies the data (and thus doesn't send us any // data back). } else { pendingFrameworkRestorationChannelRequest = result; } break; default: result.notImplemented(); break; } } }; private Map<String, Object> packageData(byte[] data) { final Map<String, Object> packaged = new HashMap<String, Object>(); packaged.put("enabled", true); // Android supports state restoration. packaged.put("data", data); return packaged; } }
engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/RestorationChannel.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/RestorationChannel.java", "repo_id": "engine", "token_count": 2368 }
301
// 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. package io.flutter.plugin.common; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.BuildConfig; import java.util.Map; import org.json.JSONObject; /** Command object representing a method call on a {@link MethodChannel}. */ public final class MethodCall { /** The name of the called method. */ public final String method; /** * Arguments for the call. * * <p>Consider using {@link #arguments()} for cases where a particular run-time type is expected. * Consider using {@link #argument(String)} when that run-time type is {@link Map} or {@link * JSONObject}. */ public final Object arguments; /** * Creates a {@link MethodCall} with the specified method name and arguments. * * @param method the method name String, not null. * @param arguments the arguments, a value supported by the channel's message codec. Possibly, * null. */ public MethodCall(@NonNull String method, @Nullable Object arguments) { if (BuildConfig.DEBUG && method == null) { throw new AssertionError("Parameter method must not be null."); } this.method = method; this.arguments = arguments; } /** * Returns the arguments of this method call with a static type determined by the call-site. * * @param <T> the intended type of the arguments. * @return the arguments with static type T */ @SuppressWarnings("unchecked") @Nullable public <T> T arguments() { return (T) arguments; } /** * Returns a String-keyed argument of this method call, assuming {@link #arguments} is a {@link * Map} or a {@link JSONObject}. The static type of the returned result is determined by the * call-site. * * @param <T> the intended type of the argument. * @param key the String key. * @return the argument value at the specified key, with static type T, or {@code null}, if such * an entry is not present. * @throws ClassCastException if {@link #arguments} can be cast to neither {@link Map} nor {@link * JSONObject}. */ @SuppressWarnings("unchecked") @Nullable public <T> T argument(@NonNull String key) { if (arguments == null) { return null; } else if (arguments instanceof Map) { return (T) ((Map<?, ?>) arguments).get(key); } else if (arguments instanceof JSONObject) { return (T) ((JSONObject) arguments).opt(key); } else { throw new ClassCastException(); } } /** * Returns whether this method call involves a mapping for the given argument key, assuming {@link * #arguments} is a {@link Map} or a {@link JSONObject}. The value associated with the key, as * returned by {@link #argument(String)}, is not considered, and may be {@code null}. * * @param key the String key. * @return {@code true}, if {@link #arguments} is a {@link Map} containing key, or a {@link * JSONObject} with a mapping for key. * @throws ClassCastException if {@link #arguments} can be cast to neither {@link Map} nor {@link * JSONObject}. */ public boolean hasArgument(@NonNull String key) { if (arguments == null) { return false; } else if (arguments instanceof Map) { return ((Map<?, ?>) arguments).containsKey(key); } else if (arguments instanceof JSONObject) { return ((JSONObject) arguments).has(key); } else { throw new ClassCastException(); } } }
engine/shell/platform/android/io/flutter/plugin/common/MethodCall.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/common/MethodCall.java", "repo_id": "engine", "token_count": 1173 }
302
// 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. package io.flutter.plugin.platform; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityEvent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.view.AccessibilityBridge; /** * Delegates accessibility events to the currently attached accessibility bridge if one is attached. */ class AccessibilityEventsDelegate { private AccessibilityBridge accessibilityBridge; /** * Delegates handling of {@link android.view.ViewParent#requestSendAccessibilityEvent} to the * accessibility bridge. * * <p>This is a no-op if there is no accessibility delegate set. * * <p>This is used by embedded platform views to propagate accessibility events from their view * hierarchy to the accessibility bridge. * * <p>As the embedded view doesn't have to be the only View in the embedded hierarchy (it can have * child views) and the event might have been originated from any view in this hierarchy, this * method gets both a reference to the embedded platform view, and a reference to the view from * its hierarchy that sent the event. * * @param embeddedView the embedded platform view for which the event is delegated * @param eventOrigin the view in the embedded view's hierarchy that sent the event. * @return True if the event was sent. */ public boolean requestSendAccessibilityEvent( @NonNull View embeddedView, @NonNull View eventOrigin, @NonNull AccessibilityEvent event) { if (accessibilityBridge == null) { return false; } return accessibilityBridge.externalViewRequestSendAccessibilityEvent( embeddedView, eventOrigin, event); } public boolean onAccessibilityHoverEvent(MotionEvent event, boolean ignorePlatformViews) { if (accessibilityBridge == null) { return false; } return accessibilityBridge.onAccessibilityHoverEvent(event, ignorePlatformViews); } /* * This setter should only be used directly in PlatformViewsController when attached/detached to an accessibility * bridge. */ void setAccessibilityBridge(@Nullable AccessibilityBridge accessibilityBridge) { this.accessibilityBridge = accessibilityBridge; } }
engine/shell/platform/android/io/flutter/plugin/platform/AccessibilityEventsDelegate.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/AccessibilityEventsDelegate.java", "repo_id": "engine", "token_count": 649 }
303
package io.flutter.plugin.platform; import static android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE; import static io.flutter.Build.API_LEVELS; import android.annotation.TargetApi; import android.graphics.SurfaceTexture; import android.os.Build; import android.view.Surface; import io.flutter.view.TextureRegistry; import io.flutter.view.TextureRegistry.SurfaceTextureEntry; @TargetApi(API_LEVELS.API_26) public class SurfaceTexturePlatformViewRenderTarget implements PlatformViewRenderTarget { private static final String TAG = "SurfaceTexturePlatformViewRenderTarget"; private final SurfaceTextureEntry surfaceTextureEntry; private SurfaceTexture surfaceTexture; private Surface surface; private int bufferWidth = 0; private int bufferHeight = 0; private boolean shouldRecreateSurfaceForLowMemory = false; private final TextureRegistry.OnTrimMemoryListener trimMemoryListener = new TextureRegistry.OnTrimMemoryListener() { @Override public void onTrimMemory(int level) { // When a memory pressure warning is received and the level equal {@code // ComponentCallbacks2.TRIM_MEMORY_COMPLETE}, the Android system releases the underlying // surface. If we continue to use the surface (e.g., call lockHardwareCanvas), a crash // occurs, and we found that this crash appeared on Android 10 and above. // See https://github.com/flutter/flutter/issues/103870 for more details. // // Here our workaround is to recreate the surface before using it. if (level == TRIM_MEMORY_COMPLETE && Build.VERSION.SDK_INT >= API_LEVELS.API_29) { shouldRecreateSurfaceForLowMemory = true; } } }; private void recreateSurfaceIfNeeded() { if (surface != null && !shouldRecreateSurfaceForLowMemory) { // No need to recreate the surface. return; } if (surface != null) { surface.release(); surface = null; } surface = createSurface(); shouldRecreateSurfaceForLowMemory = false; } protected Surface createSurface() { return new Surface(surfaceTexture); } /** Implementation of PlatformViewRenderTarget */ public SurfaceTexturePlatformViewRenderTarget(SurfaceTextureEntry surfaceTextureEntry) { if (Build.VERSION.SDK_INT < API_LEVELS.API_23) { throw new UnsupportedOperationException( "Platform views cannot be displayed below API level 23" + "You can prevent this issue by setting `minSdkVersion: 23` in build.gradle."); } this.surfaceTextureEntry = surfaceTextureEntry; this.surfaceTexture = surfaceTextureEntry.surfaceTexture(); surfaceTextureEntry.setOnTrimMemoryListener(trimMemoryListener); } public void resize(int width, int height) { bufferWidth = width; bufferHeight = height; if (surfaceTexture != null) { surfaceTexture.setDefaultBufferSize(bufferWidth, bufferHeight); } } public int getWidth() { return bufferWidth; } public int getHeight() { return bufferHeight; } public long getId() { return this.surfaceTextureEntry.id(); } public boolean isReleased() { return surfaceTexture == null; } public void release() { // Don't release the texture, let the GC finalize it. surfaceTexture = null; if (surface != null) { surface.release(); surface = null; } } public Surface getSurface() { recreateSurfaceIfNeeded(); if (surfaceTexture == null || surfaceTexture.isReleased()) { return null; } return surface; } }
engine/shell/platform/android/io/flutter/plugin/platform/SurfaceTexturePlatformViewRenderTarget.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/SurfaceTexturePlatformViewRenderTarget.java", "repo_id": "engine", "token_count": 1196 }
304
// 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. package io.flutter.view; import static io.flutter.Build.API_LEVELS; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Insets; import android.graphics.PixelFormat; import android.graphics.SurfaceTexture; import android.os.Build; import android.os.Handler; import android.text.format.DateFormat; import android.util.AttributeSet; import android.util.SparseArray; import android.view.DisplayCutout; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.PointerIcon; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewStructure; import android.view.WindowInsets; import android.view.WindowManager; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeProvider; import android.view.autofill.AutofillValue; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.annotation.UiThread; import io.flutter.Log; import io.flutter.app.FlutterPluginRegistry; import io.flutter.embedding.android.AndroidTouchProcessor; import io.flutter.embedding.android.KeyboardManager; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.renderer.FlutterRenderer; import io.flutter.embedding.engine.renderer.SurfaceTextureWrapper; import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; import io.flutter.embedding.engine.systemchannels.LifecycleChannel; import io.flutter.embedding.engine.systemchannels.LocalizationChannel; import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; import io.flutter.embedding.engine.systemchannels.NavigationChannel; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.embedding.engine.systemchannels.SettingsChannel; import io.flutter.embedding.engine.systemchannels.SystemChannel; import io.flutter.embedding.engine.systemchannels.TextInputChannel; import io.flutter.plugin.common.ActivityLifecycleListener; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.editing.TextInputPlugin; import io.flutter.plugin.localization.LocalizationPlugin; import io.flutter.plugin.mouse.MouseCursorPlugin; import io.flutter.plugin.platform.PlatformPlugin; import io.flutter.plugin.platform.PlatformViewsController; import io.flutter.util.ViewUtils; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; /** * Deprecated Android view containing a Flutter app. * * @deprecated {@link io.flutter.embedding.android.FlutterView} is the new API that now replaces * this class. See https://flutter.dev/go/android-project-migration for more migration details. */ @Deprecated public class FlutterView extends SurfaceView implements BinaryMessenger, TextureRegistry, MouseCursorPlugin.MouseCursorViewDelegate, KeyboardManager.ViewDelegate { /** * Interface for those objects that maintain and expose a reference to a {@code FlutterView} (such * as a full-screen Flutter activity). * * <p>This indirection is provided to support applications that use an activity other than {@link * io.flutter.app.FlutterActivity} (e.g. Android v4 support library's {@code FragmentActivity}). * It allows Flutter plugins to deal in this interface and not require that the activity be a * subclass of {@code FlutterActivity}. */ public interface Provider { /** * Returns a reference to the Flutter view maintained by this object. This may be {@code null}. * * @return a reference to the Flutter view maintained by this object. */ FlutterView getFlutterView(); } private static final String TAG = "FlutterView"; static final class ViewportMetrics { float devicePixelRatio = 1.0f; int physicalWidth = 0; int physicalHeight = 0; int physicalViewPaddingTop = 0; int physicalViewPaddingRight = 0; int physicalViewPaddingBottom = 0; int physicalViewPaddingLeft = 0; int physicalViewInsetTop = 0; int physicalViewInsetRight = 0; int physicalViewInsetBottom = 0; int physicalViewInsetLeft = 0; int systemGestureInsetTop = 0; int systemGestureInsetRight = 0; int systemGestureInsetBottom = 0; int systemGestureInsetLeft = 0; int physicalTouchSlop = -1; } private final DartExecutor dartExecutor; private final FlutterRenderer flutterRenderer; private final NavigationChannel navigationChannel; private final LifecycleChannel lifecycleChannel; private final LocalizationChannel localizationChannel; private final PlatformChannel platformChannel; private final SettingsChannel settingsChannel; private final SystemChannel systemChannel; private final InputMethodManager mImm; private final TextInputPlugin mTextInputPlugin; private final LocalizationPlugin mLocalizationPlugin; private final MouseCursorPlugin mMouseCursorPlugin; private final KeyboardManager mKeyboardManager; private final AndroidTouchProcessor androidTouchProcessor; private AccessibilityBridge mAccessibilityNodeProvider; private final SurfaceHolder.Callback mSurfaceCallback; private final ViewportMetrics mMetrics; private final List<ActivityLifecycleListener> mActivityLifecycleListeners; private final List<FirstFrameListener> mFirstFrameListeners; private final AtomicLong nextTextureId = new AtomicLong(0L); private FlutterNativeView mNativeView; private boolean mIsSoftwareRenderingEnabled = false; // using the software renderer or not private boolean didRenderFirstFrame = false; private final AccessibilityBridge.OnAccessibilityChangeListener onAccessibilityChangeListener = new AccessibilityBridge.OnAccessibilityChangeListener() { @Override public void onAccessibilityChanged( boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) { resetWillNotDraw(isAccessibilityEnabled, isTouchExplorationEnabled); } }; public FlutterView(Context context) { this(context, null); } public FlutterView(Context context, AttributeSet attrs) { this(context, attrs, null); } public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) { super(context, attrs); Activity activity = ViewUtils.getActivity(getContext()); if (activity == null) { throw new IllegalArgumentException("Bad context"); } if (nativeView == null) { mNativeView = new FlutterNativeView(activity.getApplicationContext()); } else { mNativeView = nativeView; } dartExecutor = mNativeView.getDartExecutor(); flutterRenderer = new FlutterRenderer(mNativeView.getFlutterJNI()); mIsSoftwareRenderingEnabled = mNativeView.getFlutterJNI().getIsSoftwareRenderingEnabled(); mMetrics = new ViewportMetrics(); mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density; mMetrics.physicalTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); setFocusable(true); setFocusableInTouchMode(true); mNativeView.attachViewAndActivity(this, activity); mSurfaceCallback = new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { assertAttached(); mNativeView.getFlutterJNI().onSurfaceCreated(holder.getSurface()); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { assertAttached(); mNativeView.getFlutterJNI().onSurfaceChanged(width, height); } @Override public void surfaceDestroyed(SurfaceHolder holder) { assertAttached(); mNativeView.getFlutterJNI().onSurfaceDestroyed(); } }; getHolder().addCallback(mSurfaceCallback); mActivityLifecycleListeners = new ArrayList<>(); mFirstFrameListeners = new ArrayList<>(); // Create all platform channels navigationChannel = new NavigationChannel(dartExecutor); lifecycleChannel = new LifecycleChannel(dartExecutor); localizationChannel = new LocalizationChannel(dartExecutor); platformChannel = new PlatformChannel(dartExecutor); systemChannel = new SystemChannel(dartExecutor); settingsChannel = new SettingsChannel(dartExecutor); // Create and set up plugins PlatformPlugin platformPlugin = new PlatformPlugin(activity, platformChannel); addActivityLifecycleListener( new ActivityLifecycleListener() { @Override public void onPostResume() { platformPlugin.updateSystemUiOverlays(); } }); mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); PlatformViewsController platformViewsController = mNativeView.getPluginRegistry().getPlatformViewsController(); mTextInputPlugin = new TextInputPlugin(this, new TextInputChannel(dartExecutor), platformViewsController); mKeyboardManager = new KeyboardManager(this); if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { mMouseCursorPlugin = new MouseCursorPlugin(this, new MouseCursorChannel(dartExecutor)); } else { mMouseCursorPlugin = null; } mLocalizationPlugin = new LocalizationPlugin(context, localizationChannel); androidTouchProcessor = new AndroidTouchProcessor(flutterRenderer, /*trackMotionEvents=*/ false); platformViewsController.attachToFlutterRenderer(flutterRenderer); mNativeView .getPluginRegistry() .getPlatformViewsController() .attachTextInputPlugin(mTextInputPlugin); mNativeView.getFlutterJNI().setLocalizationPlugin(mLocalizationPlugin); // Send initial platform information to Dart mLocalizationPlugin.sendLocalesToFlutter(getResources().getConfiguration()); sendUserPlatformSettingsToDart(); } @NonNull public DartExecutor getDartExecutor() { return dartExecutor; } @Override public boolean dispatchKeyEvent(KeyEvent event) { Log.e(TAG, "dispatchKeyEvent: " + event.toString()); if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { // Tell Android to start tracking this event. getKeyDispatcherState().startTracking(event, this); } else if (event.getAction() == KeyEvent.ACTION_UP) { // Stop tracking the event. getKeyDispatcherState().handleUpEvent(event); } // If the key processor doesn't handle it, then send it on to the // superclass. The key processor will typically handle all events except // those where it has re-dispatched the event after receiving a reply from // the framework that the framework did not handle it. return (isAttached() && mKeyboardManager.handleEvent(event)) || super.dispatchKeyEvent(event); } public FlutterNativeView getFlutterNativeView() { return mNativeView; } public FlutterPluginRegistry getPluginRegistry() { return mNativeView.getPluginRegistry(); } public String getLookupKeyForAsset(String asset) { return FlutterMain.getLookupKeyForAsset(asset); } public String getLookupKeyForAsset(String asset, String packageName) { return FlutterMain.getLookupKeyForAsset(asset, packageName); } public void addActivityLifecycleListener(ActivityLifecycleListener listener) { mActivityLifecycleListeners.add(listener); } public void onStart() { lifecycleChannel.appIsInactive(); } public void onPause() { lifecycleChannel.appIsInactive(); } public void onPostResume() { for (ActivityLifecycleListener listener : mActivityLifecycleListeners) { listener.onPostResume(); } lifecycleChannel.appIsResumed(); } public void onStop() { lifecycleChannel.appIsPaused(); } public void onMemoryPressure() { mNativeView.getFlutterJNI().notifyLowMemoryWarning(); systemChannel.sendMemoryPressureWarning(); } /** * Returns true if the Flutter experience associated with this {@code FlutterView} has rendered * its first frame, or false otherwise. */ public boolean hasRenderedFirstFrame() { return didRenderFirstFrame; } /** * Provide a listener that will be called once when the FlutterView renders its first frame to the * underlaying SurfaceView. */ public void addFirstFrameListener(FirstFrameListener listener) { mFirstFrameListeners.add(listener); } /** Remove an existing first frame listener. */ public void removeFirstFrameListener(FirstFrameListener listener) { mFirstFrameListeners.remove(listener); } @Override public void enableBufferingIncomingMessages() {} @Override public void disableBufferingIncomingMessages() {} /** * Reverts this back to the {@link SurfaceView} defaults, at the back of its window and opaque. */ public void disableTransparentBackground() { setZOrderOnTop(false); getHolder().setFormat(PixelFormat.OPAQUE); } public void setInitialRoute(String route) { navigationChannel.setInitialRoute(route); } public void pushRoute(String route) { navigationChannel.pushRoute(route); } public void popRoute() { navigationChannel.popRoute(); } private void sendUserPlatformSettingsToDart() { // Lookup the current brightness of the Android OS. boolean isNightModeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES; SettingsChannel.PlatformBrightness brightness = isNightModeOn ? SettingsChannel.PlatformBrightness.dark : SettingsChannel.PlatformBrightness.light; settingsChannel .startMessage() .setTextScaleFactor(getResources().getConfiguration().fontScale) .setUse24HourFormat(DateFormat.is24HourFormat(getContext())) .setPlatformBrightness(brightness) .send(); } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mLocalizationPlugin.sendLocalesToFlutter(newConfig); sendUserPlatformSettingsToDart(); } float getDevicePixelRatio() { return mMetrics.devicePixelRatio; } public FlutterNativeView detach() { if (!isAttached()) return null; getHolder().removeCallback(mSurfaceCallback); mNativeView.detachFromFlutterView(); FlutterNativeView view = mNativeView; mNativeView = null; return view; } public void destroy() { if (!isAttached()) return; getHolder().removeCallback(mSurfaceCallback); releaseAccessibilityNodeProvider(); mNativeView.destroy(); mNativeView = null; } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return mTextInputPlugin.createInputConnection(this, mKeyboardManager, outAttrs); } @Override public boolean checkInputConnectionProxy(View view) { return mNativeView .getPluginRegistry() .getPlatformViewsController() .checkInputConnectionProxy(view); } @Override public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) { super.onProvideAutofillVirtualStructure(structure, flags); mTextInputPlugin.onProvideAutofillVirtualStructure(structure, flags); } @Override public void autofill(SparseArray<AutofillValue> values) { mTextInputPlugin.autofill(values); } @Override public boolean onTouchEvent(MotionEvent event) { if (!isAttached()) { return super.onTouchEvent(event); } requestUnbufferedDispatch(event); return androidTouchProcessor.onTouchEvent(event); } @Override public boolean onHoverEvent(MotionEvent event) { if (!isAttached()) { return super.onHoverEvent(event); } boolean handled = mAccessibilityNodeProvider.onAccessibilityHoverEvent(event); if (!handled) { // TODO(ianh): Expose hover events to the platform, // implementing ADD, REMOVE, etc. } return handled; } /** * Invoked by Android when a generic motion event occurs, e.g., joystick movement, mouse hover, * track pad touches, scroll wheel movements, etc. * * <p>Flutter handles all of its own gesture detection and processing, therefore this method * forwards all {@link MotionEvent} data from Android to Flutter. */ @Override public boolean onGenericMotionEvent(MotionEvent event) { boolean handled = isAttached() && androidTouchProcessor.onGenericMotionEvent(event, getContext()); return handled ? true : super.onGenericMotionEvent(event); } @Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { mMetrics.physicalWidth = width; mMetrics.physicalHeight = height; updateViewportMetrics(); super.onSizeChanged(width, height, oldWidth, oldHeight); } // TODO(garyq): Add support for notch cutout API // Decide if we want to zero the padding of the sides. When in Landscape orientation, // android may decide to place the software navigation bars on the side. When the nav // bar is hidden, the reported insets should be removed to prevent extra useless space // on the sides. private enum ZeroSides { NONE, LEFT, RIGHT, BOTH } private ZeroSides calculateShouldZeroSides() { // We get both orientation and rotation because rotation is all 4 // rotations relative to default rotation while orientation is portrait // or landscape. By combining both, we can obtain a more precise measure // of the rotation. Context context = getContext(); int orientation = context.getResources().getConfiguration().orientation; int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay() .getRotation(); if (orientation == Configuration.ORIENTATION_LANDSCAPE) { if (rotation == Surface.ROTATION_90) { return ZeroSides.RIGHT; } else if (rotation == Surface.ROTATION_270) { // In android API >= 23, the nav bar always appears on the "bottom" (USB) side. return Build.VERSION.SDK_INT >= API_LEVELS.API_23 ? ZeroSides.LEFT : ZeroSides.RIGHT; } // Ambiguous orientation due to landscape left/right default. Zero both sides. else if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) { return ZeroSides.BOTH; } } // Square orientation deprecated in API 16, we will not check for it and return false // to be safe and not remove any unique padding for the devices that do use it. return ZeroSides.NONE; } // TODO(garyq): Use new Android R getInsets API // TODO(garyq): The keyboard detection may interact strangely with // https://github.com/flutter/flutter/issues/22061 // Uses inset heights and screen heights as a heuristic to determine if the insets should // be padded. When the on-screen keyboard is detected, we want to include the full inset // but when the inset is just the hidden nav bar, we want to provide a zero inset so the space // can be used. private int guessBottomKeyboardInset(WindowInsets insets) { int screenHeight = getRootView().getHeight(); // Magic number due to this being a heuristic. This should be replaced, but we have not // found a clean way to do it yet (Sept. 2018) final double keyboardHeightRatioHeuristic = 0.18; if (insets.getSystemWindowInsetBottom() < screenHeight * keyboardHeightRatioHeuristic) { // Is not a keyboard, so return zero as inset. return 0; } else { // Is a keyboard, so return the full inset. return insets.getSystemWindowInsetBottom(); } } // This callback is not present in API < 20, which means lower API devices will see // the wider than expected padding when the status and navigation bars are hidden. // The annotations to suppress "InlinedApi" and "NewApi" lints prevent lint warnings // caused by usage of Android Q APIs. These calls are safe because they are // guarded. @Override @SuppressLint({"InlinedApi", "NewApi"}) public final WindowInsets onApplyWindowInsets(WindowInsets insets) { // getSystemGestureInsets() was introduced in API 29 and immediately deprecated in 30. if (Build.VERSION.SDK_INT == API_LEVELS.API_29) { Insets systemGestureInsets = insets.getSystemGestureInsets(); mMetrics.systemGestureInsetTop = systemGestureInsets.top; mMetrics.systemGestureInsetRight = systemGestureInsets.right; mMetrics.systemGestureInsetBottom = systemGestureInsets.bottom; mMetrics.systemGestureInsetLeft = systemGestureInsets.left; } boolean statusBarVisible = (SYSTEM_UI_FLAG_FULLSCREEN & getWindowSystemUiVisibility()) == 0; boolean navigationBarVisible = (SYSTEM_UI_FLAG_HIDE_NAVIGATION & getWindowSystemUiVisibility()) == 0; if (Build.VERSION.SDK_INT >= API_LEVELS.API_30) { int mask = 0; if (navigationBarVisible) { mask = mask | android.view.WindowInsets.Type.navigationBars(); } if (statusBarVisible) { mask = mask | android.view.WindowInsets.Type.statusBars(); } Insets uiInsets = insets.getInsets(mask); mMetrics.physicalViewPaddingTop = uiInsets.top; mMetrics.physicalViewPaddingRight = uiInsets.right; mMetrics.physicalViewPaddingBottom = uiInsets.bottom; mMetrics.physicalViewPaddingLeft = uiInsets.left; Insets imeInsets = insets.getInsets(android.view.WindowInsets.Type.ime()); mMetrics.physicalViewInsetTop = imeInsets.top; mMetrics.physicalViewInsetRight = imeInsets.right; mMetrics.physicalViewInsetBottom = imeInsets.bottom; // Typically, only bottom is non-zero mMetrics.physicalViewInsetLeft = imeInsets.left; Insets systemGestureInsets = insets.getInsets(android.view.WindowInsets.Type.systemGestures()); mMetrics.systemGestureInsetTop = systemGestureInsets.top; mMetrics.systemGestureInsetRight = systemGestureInsets.right; mMetrics.systemGestureInsetBottom = systemGestureInsets.bottom; mMetrics.systemGestureInsetLeft = systemGestureInsets.left; // TODO(garyq): Expose the full rects of the display cutout. // Take the max of the display cutout insets and existing padding to merge them DisplayCutout cutout = insets.getDisplayCutout(); if (cutout != null) { Insets waterfallInsets = cutout.getWaterfallInsets(); mMetrics.physicalViewPaddingTop = Math.max( Math.max(mMetrics.physicalViewPaddingTop, waterfallInsets.top), cutout.getSafeInsetTop()); mMetrics.physicalViewPaddingRight = Math.max( Math.max(mMetrics.physicalViewPaddingRight, waterfallInsets.right), cutout.getSafeInsetRight()); mMetrics.physicalViewPaddingBottom = Math.max( Math.max(mMetrics.physicalViewPaddingBottom, waterfallInsets.bottom), cutout.getSafeInsetBottom()); mMetrics.physicalViewPaddingLeft = Math.max( Math.max(mMetrics.physicalViewPaddingLeft, waterfallInsets.left), cutout.getSafeInsetLeft()); } } else { // We zero the left and/or right sides to prevent the padding the // navigation bar would have caused. ZeroSides zeroSides = ZeroSides.NONE; if (!navigationBarVisible) { zeroSides = calculateShouldZeroSides(); } // Status bar (top), navigation bar (bottom) and left/right system insets should // partially obscure the content (padding). mMetrics.physicalViewPaddingTop = statusBarVisible ? insets.getSystemWindowInsetTop() : 0; mMetrics.physicalViewPaddingRight = zeroSides == ZeroSides.RIGHT || zeroSides == ZeroSides.BOTH ? 0 : insets.getSystemWindowInsetRight(); mMetrics.physicalViewPaddingBottom = navigationBarVisible && guessBottomKeyboardInset(insets) == 0 ? insets.getSystemWindowInsetBottom() : 0; mMetrics.physicalViewPaddingLeft = zeroSides == ZeroSides.LEFT || zeroSides == ZeroSides.BOTH ? 0 : insets.getSystemWindowInsetLeft(); // Bottom system inset (keyboard) should adjust scrollable bottom edge (inset). mMetrics.physicalViewInsetTop = 0; mMetrics.physicalViewInsetRight = 0; mMetrics.physicalViewInsetBottom = guessBottomKeyboardInset(insets); mMetrics.physicalViewInsetLeft = 0; } updateViewportMetrics(); return super.onApplyWindowInsets(insets); } private boolean isAttached() { return mNativeView != null && mNativeView.isAttached(); } void assertAttached() { if (!isAttached()) throw new AssertionError("Platform view is not attached"); } private void preRun() { resetAccessibilityTree(); } void resetAccessibilityTree() { if (mAccessibilityNodeProvider != null) { mAccessibilityNodeProvider.reset(); } } private void postRun() {} public void runFromBundle(FlutterRunArguments args) { assertAttached(); preRun(); mNativeView.runFromBundle(args); postRun(); } /** * Return the most recent frame as a bitmap. * * @return A bitmap. */ public Bitmap getBitmap() { assertAttached(); return mNativeView.getFlutterJNI().getBitmap(); } private void updateViewportMetrics() { if (!isAttached()) return; mNativeView .getFlutterJNI() .setViewportMetrics( mMetrics.devicePixelRatio, mMetrics.physicalWidth, mMetrics.physicalHeight, mMetrics.physicalViewPaddingTop, mMetrics.physicalViewPaddingRight, mMetrics.physicalViewPaddingBottom, mMetrics.physicalViewPaddingLeft, mMetrics.physicalViewInsetTop, mMetrics.physicalViewInsetRight, mMetrics.physicalViewInsetBottom, mMetrics.physicalViewInsetLeft, mMetrics.systemGestureInsetTop, mMetrics.systemGestureInsetRight, mMetrics.systemGestureInsetBottom, mMetrics.systemGestureInsetLeft, mMetrics.physicalTouchSlop, new int[0], new int[0], new int[0]); } // Called by FlutterNativeView to notify first Flutter frame rendered. public void onFirstFrame() { didRenderFirstFrame = true; // Allow listeners to remove themselves when they are called. List<FirstFrameListener> listeners = new ArrayList<>(mFirstFrameListeners); for (FirstFrameListener listener : listeners) { listener.onFirstFrame(); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); PlatformViewsController platformViewsController = getPluginRegistry().getPlatformViewsController(); mAccessibilityNodeProvider = new AccessibilityBridge( this, new AccessibilityChannel(dartExecutor, getFlutterNativeView().getFlutterJNI()), (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE), getContext().getContentResolver(), platformViewsController); mAccessibilityNodeProvider.setOnAccessibilityChangeListener(onAccessibilityChangeListener); resetWillNotDraw( mAccessibilityNodeProvider.isAccessibilityEnabled(), mAccessibilityNodeProvider.isTouchExplorationEnabled()); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); releaseAccessibilityNodeProvider(); } // TODO(mattcarroll): Confer with Ian as to why we need this method. Delete if possible, otherwise // add comments. private void resetWillNotDraw(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) { if (!mIsSoftwareRenderingEnabled) { setWillNotDraw(!(isAccessibilityEnabled || isTouchExplorationEnabled)); } else { setWillNotDraw(false); } } @Override public AccessibilityNodeProvider getAccessibilityNodeProvider() { if (mAccessibilityNodeProvider != null && mAccessibilityNodeProvider.isAccessibilityEnabled()) { return mAccessibilityNodeProvider; } else { // TODO(goderbauer): when a11y is off this should return a one-off snapshot of // the a11y // tree. return null; } } private void releaseAccessibilityNodeProvider() { if (mAccessibilityNodeProvider != null) { mAccessibilityNodeProvider.release(); mAccessibilityNodeProvider = null; } } // -------- Start: Mouse ------- @Override @TargetApi(API_LEVELS.API_24) @RequiresApi(API_LEVELS.API_24) @NonNull public PointerIcon getSystemPointerIcon(int type) { return PointerIcon.getSystemIcon(getContext(), type); } // -------- End: Mouse ------- // -------- Start: Keyboard ------- @Override public BinaryMessenger getBinaryMessenger() { return this; } @Override public boolean onTextInputKeyEvent(@NonNull KeyEvent keyEvent) { return mTextInputPlugin.handleKeyEvent(keyEvent); } @Override public void redispatch(@NonNull KeyEvent keyEvent) { getRootView().dispatchKeyEvent(keyEvent); } // -------- End: Keyboard ------- @Override @UiThread public TaskQueue makeBackgroundTaskQueue(TaskQueueOptions options) { return null; } @Override @UiThread public void send(String channel, ByteBuffer message) { send(channel, message, null); } @Override @UiThread public void send(String channel, ByteBuffer message, BinaryReply callback) { if (!isAttached()) { Log.d(TAG, "FlutterView.send called on a detached view, channel=" + channel); return; } mNativeView.send(channel, message, callback); } @Override @UiThread public void setMessageHandler(@NonNull String channel, @NonNull BinaryMessageHandler handler) { mNativeView.setMessageHandler(channel, handler); } @Override @UiThread public void setMessageHandler( @NonNull String channel, @NonNull BinaryMessageHandler handler, @NonNull TaskQueue taskQueue) { mNativeView.setMessageHandler(channel, handler, taskQueue); } /** Listener will be called on the Android UI thread once when Flutter renders the first frame. */ public interface FirstFrameListener { void onFirstFrame(); } @Override @NonNull public TextureRegistry.SurfaceTextureEntry createSurfaceTexture() { final SurfaceTexture surfaceTexture = new SurfaceTexture(0); return registerSurfaceTexture(surfaceTexture); } @Override @NonNull public ImageTextureEntry createImageTexture() { throw new UnsupportedOperationException("Image textures are not supported in this mode."); } @Override public SurfaceProducer createSurfaceProducer() { throw new UnsupportedOperationException( "SurfaceProducer textures are not supported in this mode."); } @Override @NonNull public TextureRegistry.SurfaceTextureEntry registerSurfaceTexture( @NonNull SurfaceTexture surfaceTexture) { surfaceTexture.detachFromGLContext(); final SurfaceTextureRegistryEntry entry = new SurfaceTextureRegistryEntry(nextTextureId.getAndIncrement(), surfaceTexture); mNativeView.getFlutterJNI().registerTexture(entry.id(), entry.textureWrapper()); return entry; } final class SurfaceTextureRegistryEntry implements TextureRegistry.SurfaceTextureEntry { private final long id; private final SurfaceTextureWrapper textureWrapper; private boolean released; SurfaceTextureRegistryEntry(long id, SurfaceTexture surfaceTexture) { this.id = id; this.textureWrapper = new SurfaceTextureWrapper(surfaceTexture); // The callback relies on being executed on the UI thread (unsynchronised read of // mNativeView // and also the engine code check for platform thread in // Shell::OnPlatformViewMarkTextureFrameAvailable), // so we explicitly pass a Handler for the current thread. this.surfaceTexture().setOnFrameAvailableListener(onFrameListener, new Handler()); } private SurfaceTexture.OnFrameAvailableListener onFrameListener = new SurfaceTexture.OnFrameAvailableListener() { @Override public void onFrameAvailable(SurfaceTexture texture) { if (released || mNativeView == null) { // Even though we make sure to unregister the callback before releasing, as of Android // O // SurfaceTexture has a data race when accessing the callback, so the callback may // still be called by a stale reference after released==true and mNativeView==null. return; } mNativeView .getFlutterJNI() .markTextureFrameAvailable(SurfaceTextureRegistryEntry.this.id); } }; public SurfaceTextureWrapper textureWrapper() { return textureWrapper; } @NonNull @Override public SurfaceTexture surfaceTexture() { return textureWrapper.surfaceTexture(); } @Override public long id() { return id; } @Override public void release() { if (released) { return; } released = true; // The ordering of the next 3 calls is important: // First we remove the frame listener, then we release the SurfaceTexture, and only after we // unregister // the texture which actually deletes the GL texture. // Otherwise onFrameAvailableListener might be called after mNativeView==null // (https://github.com/flutter/flutter/issues/20951). See also the check in onFrameAvailable. surfaceTexture().setOnFrameAvailableListener(null); textureWrapper.release(); mNativeView.getFlutterJNI().unregisterTexture(id); } } }
engine/shell/platform/android/io/flutter/view/FlutterView.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/view/FlutterView.java", "repo_id": "engine", "token_count": 11686 }
305
// 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. #include "flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h" #include <utility> namespace flutter { void putStringAttributesIntoBuffer( const StringAttributes& attributes, int32_t* buffer_int32, size_t& position, std::vector<std::vector<uint8_t>>& string_attribute_args) { if (attributes.empty()) { buffer_int32[position++] = -1; return; } buffer_int32[position++] = attributes.size(); for (const auto& attribute : attributes) { buffer_int32[position++] = attribute->start; buffer_int32[position++] = attribute->end; buffer_int32[position++] = static_cast<int32_t>(attribute->type); switch (attribute->type) { case StringAttributeType::kSpellOut: buffer_int32[position++] = -1; break; case StringAttributeType::kLocale: buffer_int32[position++] = string_attribute_args.size(); std::shared_ptr<LocaleStringAttribute> locale_attribute = std::static_pointer_cast<LocaleStringAttribute>(attribute); string_attribute_args.push_back( {locale_attribute->locale.begin(), locale_attribute->locale.end()}); break; } } } PlatformViewAndroidDelegate::PlatformViewAndroidDelegate( std::shared_ptr<PlatformViewAndroidJNI> jni_facade) : jni_facade_(std::move(jni_facade)){}; void PlatformViewAndroidDelegate::UpdateSemantics( const flutter::SemanticsNodeUpdates& update, const flutter::CustomAccessibilityActionUpdates& actions) { constexpr size_t kBytesPerNode = 48 * sizeof(int32_t); constexpr size_t kBytesPerChild = sizeof(int32_t); constexpr size_t kBytesPerCustomAction = sizeof(int32_t); constexpr size_t kBytesPerAction = 4 * sizeof(int32_t); constexpr size_t kBytesPerStringAttribute = 4 * sizeof(int32_t); { size_t num_bytes = 0; for (const auto& value : update) { num_bytes += kBytesPerNode; num_bytes += value.second.childrenInTraversalOrder.size() * kBytesPerChild; num_bytes += value.second.childrenInHitTestOrder.size() * kBytesPerChild; num_bytes += value.second.customAccessibilityActions.size() * kBytesPerCustomAction; num_bytes += value.second.labelAttributes.size() * kBytesPerStringAttribute; num_bytes += value.second.valueAttributes.size() * kBytesPerStringAttribute; num_bytes += value.second.increasedValueAttributes.size() * kBytesPerStringAttribute; num_bytes += value.second.decreasedValueAttributes.size() * kBytesPerStringAttribute; num_bytes += value.second.hintAttributes.size() * kBytesPerStringAttribute; } // The encoding defined here is used in: // // * AccessibilityBridge.java // * AccessibilityBridgeTest.java // * accessibility_bridge.mm // // If any of the encoding structure or length is changed, those locations // must be updated (at a minimum). std::vector<uint8_t> buffer(num_bytes); int32_t* buffer_int32 = reinterpret_cast<int32_t*>(&buffer[0]); float* buffer_float32 = reinterpret_cast<float*>(&buffer[0]); std::vector<std::string> strings; std::vector<std::vector<uint8_t>> string_attribute_args; size_t position = 0; for (const auto& value : update) { // If you edit this code, make sure you update kBytesPerNode // and/or kBytesPerChild above to match the number of values you are // sending. const flutter::SemanticsNode& node = value.second; buffer_int32[position++] = node.id; buffer_int32[position++] = node.flags; buffer_int32[position++] = node.actions; buffer_int32[position++] = node.maxValueLength; buffer_int32[position++] = node.currentValueLength; buffer_int32[position++] = node.textSelectionBase; buffer_int32[position++] = node.textSelectionExtent; buffer_int32[position++] = node.platformViewId; buffer_int32[position++] = node.scrollChildren; buffer_int32[position++] = node.scrollIndex; buffer_float32[position++] = static_cast<float>(node.scrollPosition); buffer_float32[position++] = static_cast<float>(node.scrollExtentMax); buffer_float32[position++] = static_cast<float>(node.scrollExtentMin); if (node.identifier.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.identifier); } if (node.label.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.label); } putStringAttributesIntoBuffer(node.labelAttributes, buffer_int32, position, string_attribute_args); if (node.value.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.value); } putStringAttributesIntoBuffer(node.valueAttributes, buffer_int32, position, string_attribute_args); if (node.increasedValue.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.increasedValue); } putStringAttributesIntoBuffer(node.increasedValueAttributes, buffer_int32, position, string_attribute_args); if (node.decreasedValue.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.decreasedValue); } putStringAttributesIntoBuffer(node.decreasedValueAttributes, buffer_int32, position, string_attribute_args); if (node.hint.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.hint); } putStringAttributesIntoBuffer(node.hintAttributes, buffer_int32, position, string_attribute_args); if (node.tooltip.empty()) { buffer_int32[position++] = -1; } else { buffer_int32[position++] = strings.size(); strings.push_back(node.tooltip); } buffer_int32[position++] = node.textDirection; buffer_float32[position++] = node.rect.left(); buffer_float32[position++] = node.rect.top(); buffer_float32[position++] = node.rect.right(); buffer_float32[position++] = node.rect.bottom(); node.transform.getColMajor(&buffer_float32[position]); position += 16; buffer_int32[position++] = node.childrenInTraversalOrder.size(); for (int32_t child : node.childrenInTraversalOrder) { buffer_int32[position++] = child; } for (int32_t child : node.childrenInHitTestOrder) { buffer_int32[position++] = child; } buffer_int32[position++] = node.customAccessibilityActions.size(); for (int32_t child : node.customAccessibilityActions) { buffer_int32[position++] = child; } } // custom accessibility actions. size_t num_action_bytes = actions.size() * kBytesPerAction; std::vector<uint8_t> actions_buffer(num_action_bytes); int32_t* actions_buffer_int32 = reinterpret_cast<int32_t*>(&actions_buffer[0]); std::vector<std::string> action_strings; size_t actions_position = 0; for (const auto& value : actions) { // If you edit this code, make sure you update kBytesPerAction // to match the number of values you are // sending. const flutter::CustomAccessibilityAction& action = value.second; actions_buffer_int32[actions_position++] = action.id; actions_buffer_int32[actions_position++] = action.overrideId; if (action.label.empty()) { actions_buffer_int32[actions_position++] = -1; } else { actions_buffer_int32[actions_position++] = action_strings.size(); action_strings.push_back(action.label); } if (action.hint.empty()) { actions_buffer_int32[actions_position++] = -1; } else { actions_buffer_int32[actions_position++] = action_strings.size(); action_strings.push_back(action.hint); } } // Calling NewDirectByteBuffer in API level 22 and below with a size of zero // will cause a JNI crash. if (!actions_buffer.empty()) { jni_facade_->FlutterViewUpdateCustomAccessibilityActions(actions_buffer, action_strings); } if (!buffer.empty()) { jni_facade_->FlutterViewUpdateSemantics(buffer, strings, string_attribute_args); } } } } // namespace flutter
engine/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.cc/0
{ "file_path": "engine/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.cc", "repo_id": "engine", "token_count": 3704 }
306
// 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. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_H_ #include <GLES/gl.h> #include "flutter/common/graphics/texture.h" #include "flutter/shell/platform/android/platform_view_android_jni_impl.h" namespace flutter { // External texture peered to an android.graphics.SurfaceTexture. class SurfaceTextureExternalTexture : public flutter::Texture { public: SurfaceTextureExternalTexture( int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& surface_texture, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade); ~SurfaceTextureExternalTexture() override; void Paint(PaintContext& context, const SkRect& bounds, bool freeze, const DlImageSampling sampling) override; void OnGrContextCreated() override; void OnGrContextDestroyed() override; void MarkNewFrameAvailable() override; void OnTextureUnregistered() override; protected: virtual void ProcessFrame(PaintContext& context, const SkRect& bounds) = 0; virtual void Detach(); void Attach(int gl_tex_id); bool ShouldUpdate(); void Update(); enum class AttachmentState { kUninitialized, kAttached, kDetached }; std::shared_ptr<PlatformViewAndroidJNI> jni_facade_; fml::jni::ScopedJavaGlobalRef<jobject> surface_texture_; AttachmentState state_ = AttachmentState::kUninitialized; SkMatrix transform_; sk_sp<flutter::DlImage> dl_image_; FML_DISALLOW_COPY_AND_ASSIGN(SurfaceTextureExternalTexture); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_H_
engine/shell/platform/android/surface_texture_external_texture.h/0
{ "file_path": "engine/shell/platform/android/surface_texture_external_texture.h", "repo_id": "engine", "token_count": 626 }
307
package io.flutter.embedding.android; import static android.view.KeyEvent.*; import static io.flutter.embedding.android.KeyData.Type; import static io.flutter.util.KeyCodes.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.view.KeyCharacterMap; import android.view.KeyEvent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.android.KeyData.DeviceType; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.JSONMessageCodec; import io.flutter.util.FakeKeyEvent; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Collectors; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class KeyboardManagerTest { public static final int SCAN_KEY_A = 0x1e; public static final int SCAN_DIGIT1 = 0x2; public static final int SCAN_SHIFT_LEFT = 0x2a; public static final int SCAN_SHIFT_RIGHT = 0x36; public static final int SCAN_CONTROL_LEFT = 0x1d; public static final int SCAN_CONTROL_RIGHT = 0x61; public static final int SCAN_ALT_LEFT = 0x38; public static final int SCAN_ALT_RIGHT = 0x64; public static final int SCAN_ARROW_LEFT = 0x69; public static final int SCAN_ARROW_RIGHT = 0x6a; public static final int SCAN_CAPS_LOCK = 0x3a; public static final boolean DOWN_EVENT = true; public static final boolean UP_EVENT = false; public static final boolean SHIFT_LEFT_EVENT = true; public static final boolean SHIFT_RIGHT_EVENT = false; private static final int DEAD_KEY = '`' | KeyCharacterMap.COMBINING_ACCENT; /** * Records a message that {@link KeyboardManager} sends to outside. * * <p>A call record can originate from many sources, indicated by its {@link type}. Different * types will have different fields filled, leaving others empty. */ static class CallRecord { enum Kind { /** * The channel responder sent a message through the key event channel. * * <p>This call record will have a non-null {@link channelObject}, with an optional {@link * reply}. */ kChannel, /** * The embedder responder sent a message through the key data channel. * * <p>This call record will have a non-null {@link keyData}, with an optional {@link reply}. */ kEmbedder, } /** * Construct an empty call record. * * <p>Use the static functions to constuct specific types instead. */ private CallRecord() {} Kind kind; /** * The callback given by the keyboard manager. * * <p>It might be null, which probably means it is a synthesized event and requires no reply. * Otherwise, invoke this callback with whether the event is handled for the keyboard manager to * continue processing the key event. */ public Consumer<Boolean> reply; /** The data for a call record of kind {@link Kind.kChannel}. */ public JSONObject channelObject; /** The data for a call record of kind {@link Kind.kEmbedder}. */ public KeyData keyData; /** Construct a call record of kind {@link Kind.kChannel}. */ static CallRecord channelCall( @NonNull JSONObject channelObject, @Nullable Consumer<Boolean> reply) { final CallRecord record = new CallRecord(); record.kind = Kind.kChannel; record.channelObject = channelObject; record.reply = reply; return record; } /** Construct a call record of kind {@link Kind.kEmbedder}. */ static CallRecord embedderCall(@NonNull KeyData keyData, @Nullable Consumer<Boolean> reply) { final CallRecord record = new CallRecord(); record.kind = Kind.kEmbedder; record.keyData = keyData; record.reply = reply; return record; } } /** * Build a response to a channel message sent by the channel responder. * * @param handled whether the event is handled. */ static ByteBuffer buildJsonResponse(boolean handled) { JSONObject body = new JSONObject(); try { body.put("handled", handled); } catch (JSONException e) { assertNull(e); } ByteBuffer binaryReply = JSONMessageCodec.INSTANCE.encodeMessage(body); binaryReply.rewind(); return binaryReply; } /** * Build a response to an embedder message sent by the embedder responder. * * @param handled whether the event is handled. */ static ByteBuffer buildBinaryResponse(boolean handled) { byte[] body = new byte[1]; body[0] = (byte) (handled ? 1 : 0); final ByteBuffer binaryReply = ByteBuffer.wrap(body); binaryReply.rewind(); return binaryReply; } /** * Used to configure how to process a channel message. * * <p>When the channel responder sends a channel message, this functional interface will be * invoked. Its first argument will be the detailed data. The second argument will be a nullable * reply callback, which should be called to mock the reply from the framework. */ @FunctionalInterface static interface ChannelCallHandler extends BiConsumer<JSONObject, Consumer<Boolean>> {} /** * Used to configure how to process an embedder message. * * <p>When the embedder responder sends a key data, this functional interface will be invoked. Its * first argument will be the detailed data. The second argument will be a nullable reply * callback, which should be called to mock the reply from the framework. */ @FunctionalInterface static interface EmbedderCallHandler extends BiConsumer<KeyData, Consumer<Boolean>> {} static class KeyboardTester { public KeyboardTester() { respondToChannelCallsWith(false); respondToEmbedderCallsWith(false); respondToTextInputWith(false); BinaryMessenger mockMessenger = mock(BinaryMessenger.class); doAnswer(invocation -> onMessengerMessage(invocation)) .when(mockMessenger) .send(any(String.class), any(ByteBuffer.class), eq(null)); doAnswer(invocation -> onMessengerMessage(invocation)) .when(mockMessenger) .send(any(String.class), any(ByteBuffer.class), any(BinaryMessenger.BinaryReply.class)); mockView = mock(KeyboardManager.ViewDelegate.class); doAnswer(invocation -> mockMessenger).when(mockView).getBinaryMessenger(); doAnswer(invocation -> textInputResult) .when(mockView) .onTextInputKeyEvent(any(KeyEvent.class)); doAnswer( invocation -> { KeyEvent event = invocation.getArgument(0); boolean handled = keyboardManager.handleEvent(event); assertEquals(handled, false); return null; }) .when(mockView) .redispatch(any(KeyEvent.class)); keyboardManager = new KeyboardManager(mockView); } public @Mock KeyboardManager.ViewDelegate mockView; public KeyboardManager keyboardManager; /** Set channel calls to respond immediately with the given response. */ public void respondToChannelCallsWith(boolean handled) { channelHandler = (JSONObject data, Consumer<Boolean> reply) -> { if (reply != null) { reply.accept(handled); } }; } /** * Record channel calls to the given storage. * * <p>They are not responded to until the stored callbacks are manually called. */ public void recordChannelCallsTo(@NonNull ArrayList<CallRecord> storage) { channelHandler = (JSONObject data, Consumer<Boolean> reply) -> { storage.add(CallRecord.channelCall(data, reply)); }; } /** Set embedder calls to respond immediately with the given response. */ public void respondToEmbedderCallsWith(boolean handled) { embedderHandler = (KeyData keyData, Consumer<Boolean> reply) -> { if (reply != null) { reply.accept(handled); } }; } /** * Record embedder calls to the given storage. * * <p>They are not responded to until the stored callbacks are manually called. */ public void recordEmbedderCallsTo(@NonNull ArrayList<CallRecord> storage) { embedderHandler = (KeyData keyData, Consumer<Boolean> reply) -> storage.add(CallRecord.embedderCall(keyData, reply)); } /** Set text calls to respond with the given response. */ public void respondToTextInputWith(boolean response) { textInputResult = response; } private ChannelCallHandler channelHandler; private EmbedderCallHandler embedderHandler; private Boolean textInputResult; private Object onMessengerMessage(@NonNull InvocationOnMock invocation) { final String channel = invocation.getArgument(0); final ByteBuffer buffer = invocation.getArgument(1); buffer.rewind(); final BinaryMessenger.BinaryReply reply = invocation.getArgument(2); if (channel == "flutter/keyevent") { // Parse a channel call. final JSONObject jsonObject = (JSONObject) JSONMessageCodec.INSTANCE.decodeMessage(buffer); final Consumer<Boolean> jsonReply = reply == null ? null : handled -> reply.reply(buildJsonResponse(handled)); channelHandler.accept(jsonObject, jsonReply); } else if (channel == "flutter/keydata") { // Parse an embedder call. final KeyData keyData = new KeyData(buffer); final Consumer<Boolean> booleanReply = reply == null ? null : handled -> reply.reply(buildBinaryResponse(handled)); embedderHandler.accept(keyData, booleanReply); } else { assertTrue(false); } return null; } } /** * Assert that the channel call is an event that matches the given data. * * <p>For now this function only validates key code, but not scancode or characters. * * @param data the target data to be tested. * @param type the type of the data, usually "keydown" or "keyup". * @param keyCode the key code. */ static void assertChannelEventEquals( @NonNull JSONObject message, @NonNull String type, @NonNull Integer keyCode) { try { assertEquals(type, message.get("type")); assertEquals("android", message.get("keymap")); assertEquals(keyCode, message.get("keyCode")); } catch (JSONException e) { assertNull(e); } } /** Assert that the embedder call is an event that matches the given data. */ static void assertEmbedderEventEquals( @NonNull KeyData data, Type type, long physicalKey, long logicalKey, String character, boolean synthesized, DeviceType deviceType) { assertEquals(type, data.type); assertEquals(physicalKey, data.physicalKey); assertEquals(logicalKey, data.logicalKey); assertEquals(character, data.character); assertEquals(synthesized, data.synthesized); assertEquals(deviceType, data.deviceType); } static void verifyEmbedderEvents(List<CallRecord> receivedCalls, KeyData[] expectedData) { assertEquals(receivedCalls.size(), expectedData.length); for (int idx = 0; idx < receivedCalls.size(); idx += 1) { final KeyData data = expectedData[idx]; assertEmbedderEventEquals( receivedCalls.get(idx).keyData, data.type, data.physicalKey, data.logicalKey, data.character, data.synthesized, data.deviceType); } } static KeyData buildKeyData( Type type, long physicalKey, long logicalKey, @Nullable String characters, boolean synthesized, DeviceType deviceType) { final KeyData result = new KeyData(); result.physicalKey = physicalKey; result.logicalKey = logicalKey; result.timestamp = 0x0; result.type = type; result.character = characters; result.synthesized = synthesized; result.deviceType = deviceType; return result; } /** * Start a new tester, generate a ShiftRight event under the specified condition, and return the * output events for that event. * * @param preEventLeftPressed Whether ShiftLeft was recorded as pressed before the event. * @param preEventRightPressed Whether ShiftRight was recorded as pressed before the event. * @param rightEventIsDown Whether the dispatched event is a key down of key up of ShiftRight. * @param truePressed Whether Shift is pressed as shown in the metaState of the event. * @return */ public static List<CallRecord> testShiftRightEvent( boolean preEventLeftPressed, boolean preEventRightPressed, boolean rightEventIsDown, boolean truePressed) { final ArrayList<CallRecord> calls = new ArrayList<>(); // Even though the event is for ShiftRight, we still set SHIFT | SHIFT_LEFT here. // See the comment in synchronizePressingKey for the reason. final int SHIFT_LEFT_ON = META_SHIFT_LEFT_ON | META_SHIFT_ON; final KeyboardTester tester = new KeyboardTester(); tester.respondToTextInputWith(true); // Suppress redispatching if (preEventLeftPressed) { tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', SHIFT_LEFT_ON)); } if (preEventRightPressed) { tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_SHIFT_RIGHT, KEYCODE_SHIFT_RIGHT, 0, '\0', SHIFT_LEFT_ON)); } tester.recordEmbedderCallsTo(calls); tester.keyboardManager.handleEvent( new FakeKeyEvent( rightEventIsDown ? ACTION_DOWN : ACTION_UP, SCAN_SHIFT_RIGHT, KEYCODE_SHIFT_RIGHT, 0, '\0', truePressed ? SHIFT_LEFT_ON : 0)); return calls.stream() .filter(data -> data.keyData.physicalKey != 0) .collect(Collectors.toList()); } public static KeyData buildShiftKeyData(boolean isLeft, boolean isDown, boolean isSynthesized) { final KeyData data = new KeyData(); data.type = isDown ? Type.kDown : Type.kUp; data.physicalKey = isLeft ? PHYSICAL_SHIFT_LEFT : PHYSICAL_SHIFT_RIGHT; data.logicalKey = isLeft ? LOGICAL_SHIFT_LEFT : LOGICAL_SHIFT_RIGHT; data.synthesized = isSynthesized; data.deviceType = KeyData.DeviceType.kKeyboard; return data; } /** * Print each byte of the given buffer as a hex (such as "0a" for 0x0a), and return the * concatenated string. * * <p>Used to compare binary content in byte buffers. */ static String printBufferBytes(@NonNull ByteBuffer buffer) { final String[] results = new String[buffer.capacity()]; for (int byteIdx = 0; byteIdx < buffer.capacity(); byteIdx += 1) { results[byteIdx] = String.format("%02x", buffer.get(byteIdx)); } return String.join("", results); } @Before public void setUp() { MockitoAnnotations.openMocks(this); } // Tests start @Test public void serializeAndDeserializeKeyData() { // Test data1: Non-empty character, synthesized. final KeyData data1 = new KeyData(); data1.physicalKey = 0x0a; data1.logicalKey = 0x0b; data1.timestamp = 0x0c; data1.type = Type.kRepeat; data1.character = "A"; data1.synthesized = true; data1.deviceType = DeviceType.kKeyboard; final ByteBuffer data1Buffer = data1.toBytes(); assertEquals( "" + "0100000000000000" + "0c00000000000000" + "0200000000000000" + "0a00000000000000" + "0b00000000000000" + "0100000000000000" + "0000000000000000" + "41", printBufferBytes(data1Buffer)); // `position` is considered as the message size. assertEquals(57, data1Buffer.position()); data1Buffer.rewind(); final KeyData data1Loaded = new KeyData(data1Buffer); assertEquals(data1Loaded.timestamp, data1.timestamp); // Test data2: Empty character, not synthesized. final KeyData data2 = new KeyData(); data2.physicalKey = 0xaaaabbbbccccl; data2.logicalKey = 0x666677778888l; data2.timestamp = 0x333344445555l; data2.type = Type.kUp; data2.character = null; data2.synthesized = false; data2.deviceType = DeviceType.kDirectionalPad; final ByteBuffer data2Buffer = data2.toBytes(); assertEquals( "" + "0000000000000000" + "5555444433330000" + "0100000000000000" + "ccccbbbbaaaa0000" + "8888777766660000" + "0000000000000000" + "0100000000000000", printBufferBytes(data2Buffer)); data2Buffer.rewind(); final KeyData data2Loaded = new KeyData(data2Buffer); assertEquals(data2Loaded.timestamp, data2.timestamp); } @Test public void basicCombingCharactersTest() { final KeyboardManager.CharacterCombiner combiner = new KeyboardManager.CharacterCombiner(); assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); assertEquals('B', (int) combiner.applyCombiningCharacterToBaseCharacter('B')); assertEquals('B', (int) combiner.applyCombiningCharacterToBaseCharacter('B')); assertEquals('A', (int) combiner.applyCombiningCharacterToBaseCharacter('A')); assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); assertEquals('`', (int) combiner.applyCombiningCharacterToBaseCharacter(DEAD_KEY)); assertEquals('`', (int) combiner.applyCombiningCharacterToBaseCharacter(DEAD_KEY)); assertEquals('Γ€', (int) combiner.applyCombiningCharacterToBaseCharacter('A')); assertEquals('`', (int) combiner.applyCombiningCharacterToBaseCharacter(DEAD_KEY)); assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); // The 0 input should remove the combining state. assertEquals('A', (int) combiner.applyCombiningCharacterToBaseCharacter('A')); assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); assertEquals('`', (int) combiner.applyCombiningCharacterToBaseCharacter(DEAD_KEY)); assertEquals('Γ€', (int) combiner.applyCombiningCharacterToBaseCharacter('A')); } @Test public void respondsTrueWhenHandlingNewEvents() { final KeyboardTester tester = new KeyboardTester(); final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordChannelCallsTo(calls); final boolean result = tester.keyboardManager.handleEvent(keyEvent); assertEquals(true, result); assertEquals(calls.size(), 1); assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); // Don't send the key event to the text plugin if the only primary responder // hasn't responded. verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); } @Test public void channelResponderHandlesEvents() { final KeyboardTester tester = new KeyboardTester(); final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordChannelCallsTo(calls); final boolean result = tester.keyboardManager.handleEvent(keyEvent); assertEquals(true, result); assertEquals(calls.size(), 1); assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); // Don't send the key event to the text plugin if the only primary responder // hasn't responded. verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); // If a primary responder handles the key event the propagation stops. assertNotNull(calls.get(0).reply); calls.get(0).reply.accept(true); verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); } @Test public void embedderResponderHandlesEvents() { final KeyboardTester tester = new KeyboardTester(); final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); final boolean result = tester.keyboardManager.handleEvent(keyEvent); assertEquals(true, result); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard); // Don't send the key event to the text plugin if the only primary responder // hasn't responded. verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); // If a primary responder handles the key event the propagation stops. assertNotNull(calls.get(0).reply); calls.get(0).reply.accept(true); verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); } @Test public void embedderResponderHandlesNullReply() { // Regression test for https://github.com/flutter/flutter/issues/141662. final BinaryMessenger mockMessenger = mock(BinaryMessenger.class); doAnswer( invocation -> { final BinaryMessenger.BinaryReply reply = invocation.getArgument(2); // Simulate a null reply. // In release mode, a null reply might happen when the engine sends a message // before the framework has started. reply.reply(null); return null; }) .when(mockMessenger) .send(any(String.class), any(ByteBuffer.class), any(BinaryMessenger.BinaryReply.class)); final KeyboardManager.ViewDelegate mockView = mock(KeyboardManager.ViewDelegate.class); doAnswer(invocation -> mockMessenger).when(mockView).getBinaryMessenger(); final KeyboardManager keyboardManager = new KeyboardManager(mockView); final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0); boolean exceptionThrown = false; try { final boolean result = keyboardManager.handleEvent(keyEvent); } catch (Exception exception) { exceptionThrown = true; } assertEquals(false, exceptionThrown); } @Test public void bothRespondersHandlesEvents() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordChannelCallsTo(calls); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); final boolean result = tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0)); assertEquals(true, result); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard); assertChannelEventEquals(calls.get(1).channelObject, "keydown", KEYCODE_A); verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); calls.get(0).reply.accept(true); verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); calls.get(1).reply.accept(true); verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); } @Test public void textInputHandlesEventsIfNoRespondersDo() { final KeyboardTester tester = new KeyboardTester(); final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordChannelCallsTo(calls); final boolean result = tester.keyboardManager.handleEvent(keyEvent); assertEquals(true, result); assertEquals(calls.size(), 1); assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); // Don't send the key event to the text plugin if the only primary responder // hasn't responded. verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); // If no primary responder handles the key event the propagates to the text // input plugin. assertNotNull(calls.get(0).reply); // Let text input plugin handle the key event. tester.respondToTextInputWith(true); calls.get(0).reply.accept(false); verify(tester.mockView, times(1)).onTextInputKeyEvent(keyEvent); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); } @Test public void redispatchEventsIfTextInputDoesntHandle() { final KeyboardTester tester = new KeyboardTester(); final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordChannelCallsTo(calls); final boolean result = tester.keyboardManager.handleEvent(keyEvent); assertEquals(true, result); assertEquals(calls.size(), 1); assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); // Don't send the key event to the text plugin if the only primary responder // hasn't responded. verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); // Neither the primary responders nor text input plugin handles the event. tester.respondToTextInputWith(false); calls.get(0).reply.accept(false); verify(tester.mockView, times(1)).onTextInputKeyEvent(keyEvent); verify(tester.mockView, times(1)).redispatch(keyEvent); } @Test public void redispatchedEventsAreCorrectlySkipped() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordChannelCallsTo(calls); final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); final boolean result = tester.keyboardManager.handleEvent(keyEvent); assertEquals(true, result); assertEquals(calls.size(), 1); assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); // Don't send the key event to the text plugin if the only primary responder // hasn't responded. verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); // Neither the primary responders nor text input plugin handles the event. tester.respondToTextInputWith(false); calls.get(0).reply.accept(false); verify(tester.mockView, times(1)).onTextInputKeyEvent(keyEvent); verify(tester.mockView, times(1)).redispatch(keyEvent); // It's redispatched to the keyboard manager, but no eventual key calls. assertEquals(calls.size(), 1); } @Test public void tapLowerA() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard), }); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 1, 'a', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kRepeat, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard), }); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kUp, PHYSICAL_KEY_A, LOGICAL_KEY_A, null, false, DeviceType.kKeyboard), }); calls.clear(); } @Test public void tapUpperA() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching // ShiftLeft assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0x41))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard), }); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'A', 0x41))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "A", false, DeviceType.kKeyboard), }); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, 'A', 0x41))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kUp, PHYSICAL_KEY_A, LOGICAL_KEY_A, null, false, DeviceType.kKeyboard), }); calls.clear(); // ShiftLeft assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kUp, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard), }); calls.clear(); } @Test public void eventsWithMintedCodes() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching // Zero scan code. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, 0, KEYCODE_ENTER, 0, '\n', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kDown, 0x1100000042L, LOGICAL_ENTER, "\n", false, DeviceType.kKeyboard), }); calls.clear(); // Zero scan code and zero key code. assertEquals( true, tester.keyboardManager.handleEvent(new FakeKeyEvent(ACTION_DOWN, 0, 0, 0, '\0', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kDown, 0, 0, null, true, DeviceType.kKeyboard), }); calls.clear(); // Unrecognized scan code. (Fictional test) assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, 0xDEADBEEF, 0, 0, '\0', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kDown, 0x11DEADBEEFL, 0x1100000000L, null, false, DeviceType.kKeyboard), }); calls.clear(); // Zero key code. (Fictional test; I have yet to find a real case.) assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_ARROW_LEFT, 0, 0, '\0', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_ARROW_LEFT, 0x1100000000L, null, false, DeviceType.kKeyboard), }); calls.clear(); // Unrecognized key code. (Fictional test) assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_ARROW_RIGHT, 0xDEADBEEF, 0, '\0', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_ARROW_RIGHT, 0x11DEADBEEFL, null, false, DeviceType.kKeyboard), }); calls.clear(); } @Test public void duplicateDownEventsArePrecededBySynthesizedUpEvents() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard), }); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_KEY_A, LOGICAL_KEY_A, null, true, DeviceType.kKeyboard); assertEmbedderEventEquals( calls.get(1).keyData, Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard); calls.clear(); } @Test public void abruptUpEventsAreIgnored() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kDown, 0l, 0l, null, true, DeviceType.kKeyboard), }); calls.clear(); } @Test public void modifierKeys() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching // ShiftLeft tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0x41)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kUp, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard), }); calls.clear(); // ShiftRight tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_RIGHT, KEYCODE_SHIFT_RIGHT, 0, '\0', 0x41)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_SHIFT_RIGHT, LOGICAL_SHIFT_RIGHT, null, false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_RIGHT, KEYCODE_SHIFT_RIGHT, 0, '\0', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kUp, PHYSICAL_SHIFT_RIGHT, LOGICAL_SHIFT_RIGHT, null, false, DeviceType.kKeyboard), }); calls.clear(); // ControlLeft tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_CONTROL_LEFT, KEYCODE_CTRL_LEFT, 0, '\0', 0x3000)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_CONTROL_LEFT, LOGICAL_CONTROL_LEFT, null, false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_CONTROL_LEFT, KEYCODE_CTRL_LEFT, 0, '\0', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kUp, PHYSICAL_CONTROL_LEFT, LOGICAL_CONTROL_LEFT, null, false, DeviceType.kKeyboard), }); calls.clear(); // ControlRight tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_CONTROL_RIGHT, KEYCODE_CTRL_RIGHT, 0, '\0', 0x3000)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_CONTROL_RIGHT, LOGICAL_CONTROL_RIGHT, null, false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_CONTROL_RIGHT, KEYCODE_CTRL_RIGHT, 0, '\0', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kUp, PHYSICAL_CONTROL_RIGHT, LOGICAL_CONTROL_RIGHT, null, false, DeviceType.kKeyboard), }); calls.clear(); // AltLeft tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_ALT_LEFT, KEYCODE_ALT_LEFT, 0, '\0', 0x12)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_ALT_LEFT, LOGICAL_ALT_LEFT, null, false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_ALT_LEFT, KEYCODE_ALT_LEFT, 0, '\0', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kUp, PHYSICAL_ALT_LEFT, LOGICAL_ALT_LEFT, null, false, DeviceType.kKeyboard), }); calls.clear(); // AltRight tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_ALT_RIGHT, KEYCODE_ALT_RIGHT, 0, '\0', 0x12)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_ALT_RIGHT, LOGICAL_ALT_RIGHT, null, false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_ALT_RIGHT, KEYCODE_ALT_RIGHT, 0, '\0', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kUp, PHYSICAL_ALT_RIGHT, LOGICAL_ALT_RIGHT, null, false, DeviceType.kKeyboard), }); calls.clear(); } @Test public void nonUsKeys() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching // French 1 tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_DIGIT1, KEYCODE_1, 0, '1', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_DIGIT1, LOGICAL_DIGIT1, "1", false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_DIGIT1, KEYCODE_1, 0, '1', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kUp, PHYSICAL_DIGIT1, LOGICAL_DIGIT1, null, false, DeviceType.kKeyboard), }); calls.clear(); // French Shift-1 tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0x41)); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_DIGIT1, KEYCODE_1, 0, '&', 0x41)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kDown, PHYSICAL_DIGIT1, LOGICAL_DIGIT1, "&", false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_DIGIT1, KEYCODE_1, 0, '&', 0x41)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData( Type.kUp, PHYSICAL_DIGIT1, LOGICAL_DIGIT1, null, false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0)); calls.clear(); // Russian lowerA tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, '\u0444', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "Ρ„", false, DeviceType.kKeyboard), }); calls.clear(); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, '\u0444', 0)); verifyEmbedderEvents( calls, new KeyData[] { buildKeyData(Type.kUp, PHYSICAL_KEY_A, LOGICAL_KEY_A, null, false, DeviceType.kKeyboard), }); calls.clear(); } @Test public void synchronizeShiftLeftDuringForeignKeyEvents() { // Test if ShiftLeft can be synchronized during events of ArrowLeft. final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching final int SHIFT_LEFT_ON = META_SHIFT_LEFT_ON | META_SHIFT_ON; assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', SHIFT_LEFT_ON))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, true, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, true, DeviceType.kKeyboard); calls.clear(); } @Test public void synchronizeShiftLeftDuringSelfKeyEvents() { // Test if ShiftLeft can be synchronized during events of ShiftLeft. final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching final int SHIFT_LEFT_ON = META_SHIFT_LEFT_ON | META_SHIFT_ON; // All 6 cases (3 types x 2 states) are arranged in the following order so that the starting // states for each case are the desired states. // Repeat event when current state is 0. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 1, '\0', SHIFT_LEFT_ON))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); // Down event when the current state is 1. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', SHIFT_LEFT_ON))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, true, DeviceType.kKeyboard); assertEmbedderEventEquals( calls.get(1).keyData, Type.kDown, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); // Up event when the current state is 1. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); // Up event when the current state is 0. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, 0l, 0l, null, true, DeviceType.kKeyboard); calls.clear(); // Down event when the current state is 0. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', SHIFT_LEFT_ON))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); // Repeat event when the current state is 1. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 1, '\0', SHIFT_LEFT_ON))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kRepeat, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); } @Test public void synchronizeShiftLeftDuringSiblingKeyEvents() { // Test if ShiftLeft can be synchronized during events of ShiftRight. The following events seem // to have weird metaStates that don't follow Android's documentation (always using left masks) // but are indeed observed on ChromeOS. // UP_EVENT, truePressed: false verifyEmbedderEvents(testShiftRightEvent(false, false, UP_EVENT, false), new KeyData[] {}); verifyEmbedderEvents( testShiftRightEvent(false, true, UP_EVENT, false), new KeyData[] { buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, false), }); verifyEmbedderEvents( testShiftRightEvent(true, false, UP_EVENT, false), new KeyData[] { buildShiftKeyData(SHIFT_LEFT_EVENT, UP_EVENT, true), }); verifyEmbedderEvents( testShiftRightEvent(true, true, UP_EVENT, false), new KeyData[] { buildShiftKeyData(SHIFT_LEFT_EVENT, UP_EVENT, true), buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, false), }); // UP_EVENT, truePressed: true verifyEmbedderEvents( testShiftRightEvent(false, false, UP_EVENT, true), new KeyData[] { buildShiftKeyData(SHIFT_LEFT_EVENT, DOWN_EVENT, true), }); verifyEmbedderEvents( testShiftRightEvent(false, true, UP_EVENT, true), new KeyData[] { buildShiftKeyData(SHIFT_LEFT_EVENT, DOWN_EVENT, true), buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, false), }); verifyEmbedderEvents(testShiftRightEvent(true, false, UP_EVENT, true), new KeyData[] {}); verifyEmbedderEvents( testShiftRightEvent(true, true, UP_EVENT, true), new KeyData[] { buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, false), }); // DOWN_EVENT, truePressed: false - skipped, because they're impossible. // DOWN_EVENT, truePressed: true verifyEmbedderEvents( testShiftRightEvent(false, false, DOWN_EVENT, true), new KeyData[] { buildShiftKeyData(SHIFT_RIGHT_EVENT, DOWN_EVENT, false), }); verifyEmbedderEvents( testShiftRightEvent(false, true, DOWN_EVENT, true), new KeyData[] { buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, true), buildShiftKeyData(SHIFT_RIGHT_EVENT, DOWN_EVENT, false), }); verifyEmbedderEvents( testShiftRightEvent(true, false, DOWN_EVENT, true), new KeyData[] { buildShiftKeyData(SHIFT_RIGHT_EVENT, DOWN_EVENT, false), }); verifyEmbedderEvents( testShiftRightEvent(true, true, DOWN_EVENT, true), new KeyData[] { buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, true), buildShiftKeyData(SHIFT_RIGHT_EVENT, DOWN_EVENT, false), }); } @Test public void synchronizeOtherModifiers() { // Test if other modifiers can be synchronized during events of ArrowLeft. Only the minimal // cases are used here since the full logic has been tested on ShiftLeft. final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CTRL_ON))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_CONTROL_LEFT, LOGICAL_CONTROL_LEFT, null, true, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_CONTROL_LEFT, LOGICAL_CONTROL_LEFT, null, true, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_ALT_ON))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_ALT_LEFT, LOGICAL_ALT_LEFT, null, true, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_ALT_LEFT, LOGICAL_ALT_LEFT, null, true, DeviceType.kKeyboard); calls.clear(); } // Regression test for https://github.com/flutter/flutter/issues/108124 @Test public void synchronizeModifiersForConflictingMetaState() { // Test if ShiftLeft can be correctly synchronized during down events of // ShiftLeft that have 0 for their metaState. final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); // Even though the event is for ShiftRight, we still set SHIFT | SHIFT_LEFT here. // See the comment in synchronizePressingKey for the reason. final int SHIFT_LEFT_ON = META_SHIFT_LEFT_ON | META_SHIFT_ON; tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching // Test: Down event when the current state is 0. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard); assertEmbedderEventEquals( calls.get(1).keyData, Type.kUp, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, true, DeviceType.kKeyboard); calls.clear(); // A normal down event. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', SHIFT_LEFT_ON))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); // Test: Repeat event when the current state is 0. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 1, '\0', 0))); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kRepeat, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard); assertEmbedderEventEquals( calls.get(1).keyData, Type.kUp, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, true, DeviceType.kKeyboard); calls.clear(); } // Regression test for https://github.com/flutter/flutter/issues/110640 @Test public void synchronizeModifiersForZeroedScanCode() { // Test if ShiftLeft can be correctly synchronized during down events of // ShiftLeft that have 0 for their metaState and 0 for their scanCode. final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching // Test: DOWN event when the current state is 0 and scanCode is 0. final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 0, KEYCODE_SHIFT_LEFT, 0, '\0', 0); // Compute physicalKey in the same way as KeyboardManager.getPhysicalKey. final Long physicalKey = KEYCODE_SHIFT_LEFT | KeyboardMap.kAndroidPlane; assertEquals(tester.keyboardManager.handleEvent(keyEvent), true); assertEquals(calls.size(), 2); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, physicalKey, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard); assertEmbedderEventEquals( calls.get(1).keyData, Type.kUp, physicalKey, LOGICAL_SHIFT_LEFT, null, true, DeviceType.kKeyboard); calls.clear(); } @Test public void normalCapsLockEvents() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching // The following two events seem to have weird metaStates that don't follow Android's // documentation (CapsLock flag set on down events) but are indeed observed on ChromeOS. assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', META_CAPS_LOCK_ON))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', 0))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CAPS_LOCK_ON))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_ARROW_LEFT, LOGICAL_ARROW_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CAPS_LOCK_ON))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_ARROW_LEFT, LOGICAL_ARROW_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', META_CAPS_LOCK_ON))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', 0))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_ARROW_LEFT, LOGICAL_ARROW_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_ARROW_LEFT, LOGICAL_ARROW_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); } @Test public void synchronizeCapsLock() { final KeyboardTester tester = new KeyboardTester(); final ArrayList<CallRecord> calls = new ArrayList<>(); tester.recordEmbedderCallsTo(calls); tester.respondToTextInputWith(true); // Suppress redispatching assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CAPS_LOCK_ON))); assertEquals(calls.size(), 3); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, true, DeviceType.kKeyboard); assertEmbedderEventEquals( calls.get(1).keyData, Type.kUp, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, true, DeviceType.kKeyboard); assertEmbedderEventEquals( calls.get(2).keyData, Type.kDown, PHYSICAL_ARROW_LEFT, LOGICAL_ARROW_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_DOWN, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', META_CAPS_LOCK_ON))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kDown, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent( ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CAPS_LOCK_ON))); assertEquals(calls.size(), 3); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, true, DeviceType.kKeyboard); assertEmbedderEventEquals( calls.get(1).keyData, Type.kDown, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, true, DeviceType.kKeyboard); assertEmbedderEventEquals( calls.get(2).keyData, Type.kUp, PHYSICAL_ARROW_LEFT, LOGICAL_ARROW_LEFT, null, false, DeviceType.kKeyboard); calls.clear(); assertEquals( true, tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', 0))); assertEquals(calls.size(), 1); assertEmbedderEventEquals( calls.get(0).keyData, Type.kUp, PHYSICAL_CAPS_LOCK, LOGICAL_CAPS_LOCK, null, false, DeviceType.kKeyboard); calls.clear(); } @Test public void getKeyboardState() { final KeyboardTester tester = new KeyboardTester(); tester.respondToTextInputWith(true); // Suppress redispatching. // Initial pressed state is empty. assertEquals(tester.keyboardManager.getKeyboardState(), Map.of()); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 1, 'a', 0)); assertEquals(tester.keyboardManager.getKeyboardState(), Map.of(PHYSICAL_KEY_A, LOGICAL_KEY_A)); tester.keyboardManager.handleEvent( new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0)); assertEquals(tester.keyboardManager.getKeyboardState(), Map.of()); } }
engine/shell/platform/android/test/io/flutter/embedding/android/KeyboardManagerTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/android/KeyboardManagerTest.java", "repo_id": "engine", "token_count": 27592 }
308
// 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. package io.flutter.embedding.engine.loader; import static android.os.Looper.getMainLooper; import static io.flutter.Build.API_LEVELS; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyLong; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.robolectric.Shadows.shadowOf; import android.annotation.TargetApi; import android.app.ActivityManager; import android.content.Context; import android.os.Bundle; import android.util.DisplayMetrics; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.FlutterJNI; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class FlutterLoaderTest { private final Context ctx = ApplicationProvider.getApplicationContext(); @Test public void itReportsUninitializedAfterCreating() { FlutterLoader flutterLoader = new FlutterLoader(); assertFalse(flutterLoader.initialized()); } @Test public void itReportsInitializedAfterInitializing() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(ctx); flutterLoader.ensureInitializationComplete(ctx, null); shadowOf(getMainLooper()).idle(); assertTrue(flutterLoader.initialized()); verify(mockFlutterJNI, times(1)).loadLibrary(); verify(mockFlutterJNI, times(1)).updateRefreshRate(); } @Test public void itDefaultsTheOldGenHeapSizeAppropriately() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(ctx); flutterLoader.ensureInitializationComplete(ctx, null); shadowOf(getMainLooper()).idle(); ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(memInfo); int oldGenHeapSizeMegaBytes = (int) (memInfo.totalMem / 1e6 / 2); final String oldGenHeapArg = "--old-gen-heap-size=" + oldGenHeapSizeMegaBytes; ArgumentCaptor<String[]> shellArgsCaptor = ArgumentCaptor.forClass(String[].class); verify(mockFlutterJNI, times(1)) .init(eq(ctx), shellArgsCaptor.capture(), anyString(), anyString(), anyString(), anyLong()); List<String> arguments = Arrays.asList(shellArgsCaptor.getValue()); assertTrue(arguments.contains(oldGenHeapArg)); } @Test public void itDefaultsTheResourceCacheMaxBytesThresholdAppropriately() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(ctx); flutterLoader.ensureInitializationComplete(ctx, null); shadowOf(getMainLooper()).idle(); DisplayMetrics displayMetrics = ctx.getResources().getDisplayMetrics(); int screenWidth = displayMetrics.widthPixels; int screenHeight = displayMetrics.heightPixels; int resourceCacheMaxBytesThreshold = screenWidth * screenHeight * 12 * 4; final String resourceCacheMaxBytesThresholdArg = "--resource-cache-max-bytes-threshold=" + resourceCacheMaxBytesThreshold; ArgumentCaptor<String[]> shellArgsCaptor = ArgumentCaptor.forClass(String[].class); verify(mockFlutterJNI, times(1)) .init(eq(ctx), shellArgsCaptor.capture(), anyString(), anyString(), anyString(), anyLong()); List<String> arguments = Arrays.asList(shellArgsCaptor.getValue()); assertTrue(arguments.contains(resourceCacheMaxBytesThresholdArg)); } @Test public void itSetsLeakVMToTrueByDefault() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(ctx); flutterLoader.ensureInitializationComplete(ctx, null); shadowOf(getMainLooper()).idle(); final String leakVMArg = "--leak-vm=true"; ArgumentCaptor<String[]> shellArgsCaptor = ArgumentCaptor.forClass(String[].class); verify(mockFlutterJNI, times(1)) .init(eq(ctx), shellArgsCaptor.capture(), anyString(), anyString(), anyString(), anyLong()); List<String> arguments = Arrays.asList(shellArgsCaptor.getValue()); assertTrue(arguments.contains(leakVMArg)); } @Test public void itSetsTheLeakVMFromMetaData() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); Bundle metaData = new Bundle(); metaData.putBoolean("io.flutter.embedding.android.LeakVM", false); ctx.getApplicationInfo().metaData = metaData; FlutterLoader.Settings settings = new FlutterLoader.Settings(); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(ctx, settings); flutterLoader.ensureInitializationComplete(ctx, null); shadowOf(getMainLooper()).idle(); final String leakVMArg = "--leak-vm=false"; ArgumentCaptor<String[]> shellArgsCaptor = ArgumentCaptor.forClass(String[].class); verify(mockFlutterJNI, times(1)) .init(eq(ctx), shellArgsCaptor.capture(), anyString(), anyString(), anyString(), anyLong()); List<String> arguments = Arrays.asList(shellArgsCaptor.getValue()); assertTrue(arguments.contains(leakVMArg)); } @Test public void itUsesCorrectExecutorService() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); ExecutorService mockExecutorService = mock(ExecutorService.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI, mockExecutorService); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(ctx); verify(mockExecutorService, times(1)).submit(any(Callable.class)); } @Test public void itDoesNotSetEnableImpellerByDefault() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(ctx); flutterLoader.ensureInitializationComplete(ctx, null); shadowOf(getMainLooper()).idle(); final String enableImpellerArg = "--enable-impeller"; ArgumentCaptor<String[]> shellArgsCaptor = ArgumentCaptor.forClass(String[].class); verify(mockFlutterJNI, times(1)) .init(eq(ctx), shellArgsCaptor.capture(), anyString(), anyString(), anyString(), anyLong()); List<String> arguments = Arrays.asList(shellArgsCaptor.getValue()); assertFalse(arguments.contains(enableImpellerArg)); } @Test public void itDoesNotSetEnableVulkanValidationByDefault() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(ctx); flutterLoader.ensureInitializationComplete(ctx, null); shadowOf(getMainLooper()).idle(); final String enableVulkanValidationArg = "--enable-vulkan-validation"; ArgumentCaptor<String[]> shellArgsCaptor = ArgumentCaptor.forClass(String[].class); verify(mockFlutterJNI, times(1)) .init(eq(ctx), shellArgsCaptor.capture(), anyString(), anyString(), anyString(), anyLong()); List<String> arguments = Arrays.asList(shellArgsCaptor.getValue()); assertFalse(arguments.contains(enableVulkanValidationArg)); } @Test public void itSetsEnableImpellerFromMetaData() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); Bundle metaData = new Bundle(); metaData.putBoolean("io.flutter.embedding.android.EnableImpeller", true); ctx.getApplicationInfo().metaData = metaData; FlutterLoader.Settings settings = new FlutterLoader.Settings(); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(ctx, settings); flutterLoader.ensureInitializationComplete(ctx, null); shadowOf(getMainLooper()).idle(); final String enableImpellerArg = "--enable-impeller"; ArgumentCaptor<String[]> shellArgsCaptor = ArgumentCaptor.forClass(String[].class); verify(mockFlutterJNI, times(1)) .init(eq(ctx), shellArgsCaptor.capture(), anyString(), anyString(), anyString(), anyLong()); List<String> arguments = Arrays.asList(shellArgsCaptor.getValue()); assertTrue(arguments.contains(enableImpellerArg)); } @Test @TargetApi(API_LEVELS.API_23) @Config(sdk = API_LEVELS.API_23) public void itReportsFpsToVsyncWaiterAndroidM() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); Context appContextSpy = spy(ctx); assertFalse(flutterLoader.initialized()); flutterLoader.startInitialization(appContextSpy); verify(appContextSpy, never()).getSystemService(anyString()); } }
engine/shell/platform/android/test/io/flutter/embedding/engine/loader/FlutterLoaderTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/loader/FlutterLoaderTest.java", "repo_id": "engine", "token_count": 3332 }
309
// 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. package io.flutter.plugin.platform; import static android.view.View.OnFocusChangeListener; import static io.flutter.Build.API_LEVELS; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import static org.mockito.Mockito.spy; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.accessibility.AccessibilityEvent; import android.widget.FrameLayout; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.annotation.Config; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; @TargetApi(API_LEVELS.API_31) @RunWith(AndroidJUnit4.class) public class PlatformViewWrapperTest { private final Context ctx = ApplicationProvider.getApplicationContext(); @Test public void invalidateChildInParent_callsInvalidate() { final PlatformViewWrapper wrapper = spy(new PlatformViewWrapper(ctx)); // Mock Android framework calls. wrapper.invalidateChildInParent(null, null); // Verify. verify(wrapper, times(1)).invalidate(); } @Test public void draw_withoutSurface() { final PlatformViewWrapper wrapper = new PlatformViewWrapper(ctx) { @Override public void onDraw(Canvas canvas) { canvas.drawColor(Color.RED); } }; // Test. final Canvas canvas = mock(Canvas.class); wrapper.draw(canvas); // Verify. verify(canvas, times(1)).drawColor(Color.RED); } @Test public void focusChangeListener_hasFocus() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(true); final PlatformViewWrapper view = new PlatformViewWrapper(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { return viewTreeObserver; } @Override public boolean hasFocus() { return true; } }; final OnFocusChangeListener focusListener = mock(OnFocusChangeListener.class); view.setOnDescendantFocusChangeListener(focusListener); final ArgumentCaptor<ViewTreeObserver.OnGlobalFocusChangeListener> focusListenerCaptor = ArgumentCaptor.forClass(ViewTreeObserver.OnGlobalFocusChangeListener.class); verify(viewTreeObserver).addOnGlobalFocusChangeListener(focusListenerCaptor.capture()); focusListenerCaptor.getValue().onGlobalFocusChanged(null, null); verify(focusListener).onFocusChange(view, true); } @Test public void focusChangeListener_doesNotHaveFocus() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(true); final PlatformViewWrapper view = new PlatformViewWrapper(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { return viewTreeObserver; } @Override public boolean hasFocus() { return false; } }; final OnFocusChangeListener focusListener = mock(OnFocusChangeListener.class); view.setOnDescendantFocusChangeListener(focusListener); final ArgumentCaptor<ViewTreeObserver.OnGlobalFocusChangeListener> focusListenerCaptor = ArgumentCaptor.forClass(ViewTreeObserver.OnGlobalFocusChangeListener.class); verify(viewTreeObserver).addOnGlobalFocusChangeListener(focusListenerCaptor.capture()); focusListenerCaptor.getValue().onGlobalFocusChanged(null, null); verify(focusListener).onFocusChange(view, false); } @Test public void focusChangeListener_viewTreeObserverIsAliveFalseDoesNotThrow() { final PlatformViewWrapper view = new PlatformViewWrapper(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(false); return viewTreeObserver; } }; view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); } @Test public void setOnDescendantFocusChangeListener_keepsSingleListener() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(true); final PlatformViewWrapper view = new PlatformViewWrapper(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { return viewTreeObserver; } }; assertNull(view.getActiveFocusListener()); view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); assertNotNull(view.getActiveFocusListener()); final ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener = view.getActiveFocusListener(); view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); assertNotNull(view.getActiveFocusListener()); verify(viewTreeObserver, times(1)).removeOnGlobalFocusChangeListener(activeFocusListener); } @Test public void unsetOnDescendantFocusChangeListener_removesActiveListener() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(true); final PlatformViewWrapper view = new PlatformViewWrapper(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { return viewTreeObserver; } }; assertNull(view.getActiveFocusListener()); view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); assertNotNull(view.getActiveFocusListener()); final ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener = view.getActiveFocusListener(); view.unsetOnDescendantFocusChangeListener(); assertNull(view.getActiveFocusListener()); view.unsetOnDescendantFocusChangeListener(); verify(viewTreeObserver, times(1)).removeOnGlobalFocusChangeListener(activeFocusListener); } @Test @Config( shadows = { ShadowFrameLayout.class, ShadowViewGroup.class, }) public void ignoreAccessibilityEvents() { final PlatformViewWrapper wrapperView = new PlatformViewWrapper(ctx); final View embeddedView = mock(View.class); wrapperView.addView(embeddedView); when(embeddedView.getImportantForAccessibility()) .thenReturn(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); final boolean eventSent = wrapperView.requestSendAccessibilityEvent(embeddedView, mock(AccessibilityEvent.class)); assertFalse(eventSent); } @Test @Config( shadows = { ShadowFrameLayout.class, ShadowViewGroup.class, }) public void sendAccessibilityEvents() { final PlatformViewWrapper wrapperView = new PlatformViewWrapper(ctx); final View embeddedView = mock(View.class); wrapperView.addView(embeddedView); when(embeddedView.getImportantForAccessibility()) .thenReturn(View.IMPORTANT_FOR_ACCESSIBILITY_YES); boolean eventSent = wrapperView.requestSendAccessibilityEvent(embeddedView, mock(AccessibilityEvent.class)); assertTrue(eventSent); when(embeddedView.getImportantForAccessibility()) .thenReturn(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); eventSent = wrapperView.requestSendAccessibilityEvent(embeddedView, mock(AccessibilityEvent.class)); assertTrue(eventSent); } @Implements(ViewGroup.class) public static class ShadowViewGroup extends org.robolectric.shadows.ShadowViewGroup { @Implementation protected boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { return true; } } @Implements(FrameLayout.class) public static class ShadowFrameLayout extends io.flutter.plugin.platform.PlatformViewWrapperTest.ShadowViewGroup {} }
engine/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewWrapperTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewWrapperTest.java", "repo_id": "engine", "token_count": 2926 }
310
buildscript { repositories { google() mavenCentral() } dependencies { classpath "com.android.tools.build:gradle:8.0.1" } } repositories { google() mavenCentral() } apply plugin: "com.android.library" rootProject.buildDir = project.property("build_dir") // Shows warnings for usage of deprecated API usages. // TODO(reidbaker): Expand linter coverage https://github.com/flutter/flutter/issues/133154 gradle.projectsEvaluated { tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:deprecation" << "-Werror" } } def availableProcessors = Runtime.runtime.availableProcessors() ?: 1 println "==========================================" println "AVAILABLE PROCESSORS: $availableProcessors" println "==========================================" android { namespace 'io.flutter.app.test' compileSdkVersion 34 defaultConfig { minSdkVersion 21 } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } testOptions { unitTests { includeAndroidResources = true } unitTests.all { jvmArgs "-Xmx8g" // Max JVM heap size is 8G/30G available in the CI bot. maxHeapSize "8g" maxParallelForks availableProcessors // The CI bot has 8 CPUs. testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" exceptionFormat "full" showStackTraces true showStandardStreams true } } } dependencies { // Please *don't* add embedding dependencies to this file. // The embedding dependencies are configured in tools/androidx/files.json. // Only add test dependencies. implementation files(project.property("flutter_jar")) testImplementation "androidx.test:core:1.4.0" testImplementation "com.google.android.play:core:1.8.0" testImplementation "com.ibm.icu:icu4j:69.1" testImplementation "org.robolectric:robolectric:4.11.1" testImplementation "junit:junit:4.13.2" testImplementation "androidx.test.ext:junit:1.1.4-alpha07" def mockitoVersion = "4.7.0" testImplementation "org.mockito:mockito-core:$mockitoVersion" testImplementation "org.mockito:mockito-inline:$mockitoVersion" testImplementation "org.mockito:mockito-android:$mockitoVersion" } // Configure the embedding dependencies. apply from: new File(rootDir, '../../../../tools/androidx/configure.gradle').absolutePath; configureDependencies(new File(rootDir, '../../../..')) { dependency -> dependencies { testImplementation "$dependency" } } sourceSets { main { test { java { srcDirs = ["../test"] } } } } }
engine/shell/platform/android/test_runner/build.gradle/0
{ "file_path": "engine/shell/platform/android/test_runner/build.gradle", "repo_id": "engine", "token_count": 1000 }
311
// 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. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BINARY_MESSENGER_IMPL_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BINARY_MESSENGER_IMPL_H_ #include <flutter_messenger.h> #include <map> #include <string> #include "include/flutter/binary_messenger.h" namespace flutter { // Wrapper around a FlutterDesktopMessengerRef that implements the // BinaryMessenger API. class BinaryMessengerImpl : public BinaryMessenger { public: explicit BinaryMessengerImpl(FlutterDesktopMessengerRef core_messenger); virtual ~BinaryMessengerImpl(); // Prevent copying. BinaryMessengerImpl(BinaryMessengerImpl const&) = delete; BinaryMessengerImpl& operator=(BinaryMessengerImpl const&) = delete; // |flutter::BinaryMessenger| void Send(const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply) const override; // |flutter::BinaryMessenger| void SetMessageHandler(const std::string& channel, BinaryMessageHandler handler) override; private: // Handle for interacting with the C API. FlutterDesktopMessengerRef messenger_; // A map from channel names to the BinaryMessageHandler that should be called // for incoming messages on that channel. std::map<std::string, BinaryMessageHandler> handlers_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BINARY_MESSENGER_IMPL_H_
engine/shell/platform/common/client_wrapper/binary_messenger_impl.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/binary_messenger_impl.h", "repo_id": "engine", "token_count": 541 }
312
// 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. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_ #include <memory> #include <string> #include <vector> namespace flutter { // Translates between a binary message and higher-level method call and // response/error objects. template <typename T> class MessageCodec { public: MessageCodec() = default; virtual ~MessageCodec() = default; // Prevent copying. MessageCodec(MessageCodec<T> const&) = delete; MessageCodec& operator=(MessageCodec<T> const&) = delete; // Returns the message encoded in |binary_message|, or nullptr if it cannot be // decoded by this codec. std::unique_ptr<T> DecodeMessage(const uint8_t* binary_message, const size_t message_size) const { return std::move(DecodeMessageInternal(binary_message, message_size)); } // Returns the message encoded in |binary_message|, or nullptr if it cannot be // decoded by this codec. std::unique_ptr<T> DecodeMessage( const std::vector<uint8_t>& binary_message) const { size_t size = binary_message.size(); const uint8_t* data = size > 0 ? &binary_message[0] : nullptr; return std::move(DecodeMessageInternal(data, size)); } // Returns a binary encoding of the given |message|, or nullptr if the // message cannot be serialized by this codec. std::unique_ptr<std::vector<uint8_t>> EncodeMessage(const T& message) const { return std::move(EncodeMessageInternal(message)); } protected: // Implementation of the public interface, to be provided by subclasses. virtual std::unique_ptr<T> DecodeMessageInternal( const uint8_t* binary_message, const size_t message_size) const = 0; // Implementation of the public interface, to be provided by subclasses. virtual std::unique_ptr<std::vector<uint8_t>> EncodeMessageInternal( const T& message) const = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_
engine/shell/platform/common/client_wrapper/include/flutter/message_codec.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/message_codec.h", "repo_id": "engine", "token_count": 775 }
313
// 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. #include "flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h" #include <memory> #include <vector> #include "flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.h" #include "gtest/gtest.h" namespace flutter { namespace { // Stub implementation to validate calls to the API. class TestApi : public testing::StubFlutterApi { public: // |flutter::testing::StubFlutterApi| bool MessengerSend(const char* channel, const uint8_t* message, const size_t message_size) override { last_data_sent_ = message; return message_engine_result; } bool MessengerSendWithReply(const char* channel, const uint8_t* message, const size_t message_size, const FlutterDesktopBinaryReply reply, void* user_data) override { last_data_sent_ = message; return message_engine_result; } void MessengerSetCallback(const char* channel, FlutterDesktopMessageCallback callback, void* user_data) override { last_message_callback_set_ = callback; } void PluginRegistrarSetDestructionHandler( FlutterDesktopOnPluginRegistrarDestroyed callback) override { last_destruction_callback_set_ = callback; } const uint8_t* last_data_sent() { return last_data_sent_; } FlutterDesktopMessageCallback last_message_callback_set() { return last_message_callback_set_; } FlutterDesktopOnPluginRegistrarDestroyed last_destruction_callback_set() { return last_destruction_callback_set_; } private: const uint8_t* last_data_sent_ = nullptr; FlutterDesktopMessageCallback last_message_callback_set_ = nullptr; FlutterDesktopOnPluginRegistrarDestroyed last_destruction_callback_set_ = nullptr; }; // A PluginRegistrar whose destruction can be watched for by tests. class TestPluginRegistrar : public PluginRegistrar { public: explicit TestPluginRegistrar(FlutterDesktopPluginRegistrarRef core_registrar) : PluginRegistrar(core_registrar) {} virtual ~TestPluginRegistrar() { if (destruction_callback_) { destruction_callback_(); } } void SetDestructionCallback(std::function<void()> callback) { destruction_callback_ = std::move(callback); } private: std::function<void()> destruction_callback_; }; // A test plugin that tries to access registrar state during destruction and // reports it out via a flag provided at construction. class TestPlugin : public Plugin { public: // registrar_valid_at_destruction will be set at destruction to indicate // whether or not |registrar->messenger()| was non-null. TestPlugin(PluginRegistrar* registrar, bool* registrar_valid_at_destruction) : registrar_(registrar), registrar_valid_at_destruction_(registrar_valid_at_destruction) {} virtual ~TestPlugin() { *registrar_valid_at_destruction_ = registrar_->messenger() != nullptr; } private: PluginRegistrar* registrar_; bool* registrar_valid_at_destruction_; }; } // namespace // Tests that the registrar runs plugin destructors before its own teardown. TEST(PluginRegistrarTest, PluginDestroyedBeforeRegistrar) { auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); bool registrar_valid_at_destruction = false; { PluginRegistrar registrar(dummy_registrar_handle); auto plugin = std::make_unique<TestPlugin>(&registrar, &registrar_valid_at_destruction); registrar.AddPlugin(std::move(plugin)); } EXPECT_TRUE(registrar_valid_at_destruction); } // Tests that the registrar returns a messenger that passes Send through to the // C API. TEST(PluginRegistrarTest, MessengerSend) { testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique<TestApi>()); auto test_api = static_cast<TestApi*>(scoped_api_stub.stub()); auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); PluginRegistrar registrar(dummy_registrar_handle); BinaryMessenger* messenger = registrar.messenger(); std::vector<uint8_t> message = {1, 2, 3, 4}; messenger->Send("some_channel", &message[0], message.size()); EXPECT_EQ(test_api->last_data_sent(), &message[0]); } // Tests that the registrar returns a messenger that passes callback // registration and unregistration through to the C API. TEST(PluginRegistrarTest, MessengerSetMessageHandler) { testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique<TestApi>()); auto test_api = static_cast<TestApi*>(scoped_api_stub.stub()); auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); PluginRegistrar registrar(dummy_registrar_handle); BinaryMessenger* messenger = registrar.messenger(); const std::string channel_name("foo"); // Register. BinaryMessageHandler binary_handler = [](const uint8_t* message, const size_t message_size, const BinaryReply& reply) {}; messenger->SetMessageHandler(channel_name, std::move(binary_handler)); EXPECT_NE(test_api->last_message_callback_set(), nullptr); // Unregister. messenger->SetMessageHandler(channel_name, nullptr); EXPECT_EQ(test_api->last_message_callback_set(), nullptr); } // Tests that the registrar manager returns the same instance when getting // the wrapper for the same reference. TEST(PluginRegistrarTest, ManagerSameInstance) { PluginRegistrarManager* manager = PluginRegistrarManager::GetInstance(); manager->Reset(); testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique<TestApi>()); auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); EXPECT_EQ(manager->GetRegistrar<PluginRegistrar>(dummy_registrar_handle), manager->GetRegistrar<PluginRegistrar>(dummy_registrar_handle)); } // Tests that the registrar manager returns different objects for different // references. TEST(PluginRegistrarTest, ManagerDifferentInstances) { PluginRegistrarManager* manager = PluginRegistrarManager::GetInstance(); manager->Reset(); testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique<TestApi>()); auto dummy_registrar_handle_a = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); auto dummy_registrar_handle_b = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(2); EXPECT_NE(manager->GetRegistrar<PluginRegistrar>(dummy_registrar_handle_a), manager->GetRegistrar<PluginRegistrar>(dummy_registrar_handle_b)); } // Tests that the registrar manager deletes wrappers when the underlying // reference is destroyed. TEST(PluginRegistrarTest, ManagerRemovesOnDestruction) { PluginRegistrarManager* manager = PluginRegistrarManager::GetInstance(); manager->Reset(); testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique<TestApi>()); auto test_api = static_cast<TestApi*>(scoped_api_stub.stub()); auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); auto* wrapper = manager->GetRegistrar<TestPluginRegistrar>(dummy_registrar_handle); // Simulate destruction of the reference, and ensure that the wrapper // is destroyed. EXPECT_NE(test_api->last_destruction_callback_set(), nullptr); bool destroyed = false; wrapper->SetDestructionCallback([&destroyed]() { destroyed = true; }); test_api->last_destruction_callback_set()(dummy_registrar_handle); EXPECT_EQ(destroyed, true); // Requesting the wrapper should now create a new object. EXPECT_NE(manager->GetRegistrar<TestPluginRegistrar>(dummy_registrar_handle), nullptr); } // Tests that the texture registrar getter returns a non-null TextureRegistrar TEST(PluginRegistrarTest, TextureRegistrarNotNull) { auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); PluginRegistrar registrar(dummy_registrar_handle); TextureRegistrar* texture_registrar = registrar.texture_registrar(); ASSERT_NE(texture_registrar, nullptr); } } // namespace flutter
engine/shell/platform/common/client_wrapper/plugin_registrar_unittests.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/plugin_registrar_unittests.cc", "repo_id": "engine", "token_count": 2960 }
314
// 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. #include "flutter_platform_node_delegate.h" #include "flutter/third_party/accessibility/ax/ax_action_data.h" #include "gtest/gtest.h" #include "test_accessibility_bridge.h" namespace flutter { namespace testing { TEST(FlutterPlatformNodeDelegateTest, NodeDelegateHasUniqueId) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); // Add node 0: root. FlutterSemanticsNode2 node0{sizeof(FlutterSemanticsNode2), 0}; std::vector<int32_t> node0_children{1}; node0.child_count = node0_children.size(); node0.children_in_traversal_order = node0_children.data(); node0.children_in_hit_test_order = node0_children.data(); // Add node 1: text child of node 0. FlutterSemanticsNode2 node1{sizeof(FlutterSemanticsNode2), 1}; node1.label = "prefecture"; node1.value = "Kyoto"; bridge->AddFlutterSemanticsNodeUpdate(node0); bridge->AddFlutterSemanticsNodeUpdate(node1); bridge->CommitUpdates(); auto node0_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); auto node1_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); EXPECT_TRUE(node0_delegate->GetUniqueId() != node1_delegate->GetUniqueId()); } TEST(FlutterPlatformNodeDelegateTest, canPerfomActions) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root; root.id = 0; root.flags = FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField; root.actions = static_cast<FlutterSemanticsAction>(0); root.text_selection_base = -1; root.text_selection_extent = -1; root.label = "root"; root.hint = ""; root.value = ""; root.increased_value = ""; root.decreased_value = ""; root.tooltip = ""; root.child_count = 0; root.custom_accessibility_actions_count = 0; bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); auto accessibility = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); // Performs an AXAction. ui::AXActionData action_data; action_data.action = ax::mojom::Action::kDoDefault; accessibility->AccessibilityPerformAction(action_data); EXPECT_EQ(bridge->performed_actions.size(), size_t{1}); EXPECT_EQ(bridge->performed_actions[0], FlutterSemanticsAction::kFlutterSemanticsActionTap); action_data.action = ax::mojom::Action::kFocus; accessibility->AccessibilityPerformAction(action_data); EXPECT_EQ(bridge->performed_actions.size(), size_t{2}); EXPECT_EQ( bridge->performed_actions[1], FlutterSemanticsAction::kFlutterSemanticsActionDidGainAccessibilityFocus); action_data.action = ax::mojom::Action::kScrollToMakeVisible; accessibility->AccessibilityPerformAction(action_data); EXPECT_EQ(bridge->performed_actions.size(), size_t{3}); EXPECT_EQ(bridge->performed_actions[2], FlutterSemanticsAction::kFlutterSemanticsActionShowOnScreen); } TEST(FlutterPlatformNodeDelegateTest, canGetAXNode) { // Set up a flutter accessibility node. std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root; root.id = 0; root.flags = FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField; root.actions = static_cast<FlutterSemanticsAction>(0); root.text_selection_base = -1; root.text_selection_extent = -1; root.label = "root"; root.hint = ""; root.value = ""; root.increased_value = ""; root.decreased_value = ""; root.tooltip = ""; root.child_count = 0; root.custom_accessibility_actions_count = 0; bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); auto accessibility = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); EXPECT_EQ(accessibility->GetData().id, 0); } TEST(FlutterPlatformNodeDelegateTest, canCalculateBoundsCorrectly) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root; root.id = 0; root.label = "root"; root.hint = ""; root.value = ""; root.increased_value = ""; root.decreased_value = ""; root.tooltip = ""; root.child_count = 1; int32_t children[] = {1}; root.children_in_traversal_order = children; root.custom_accessibility_actions_count = 0; root.rect = {0, 0, 100, 100}; // LTRB root.transform = {1, 0, 0, 0, 1, 0, 0, 0, 1}; bridge->AddFlutterSemanticsNodeUpdate(root); FlutterSemanticsNode2 child1; child1.id = 1; child1.label = "child 1"; child1.hint = ""; child1.value = ""; child1.increased_value = ""; child1.decreased_value = ""; child1.tooltip = ""; child1.child_count = 0; child1.custom_accessibility_actions_count = 0; child1.rect = {0, 0, 50, 50}; // LTRB child1.transform = {0.5, 0, 0, 0, 0.5, 0, 0, 0, 1}; bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->CommitUpdates(); auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); ui::AXOffscreenResult result; gfx::Rect bounds = child1_node->GetBoundsRect(ui::AXCoordinateSystem::kScreenDIPs, ui::AXClippingBehavior::kClipped, &result); EXPECT_EQ(bounds.x(), 0); EXPECT_EQ(bounds.y(), 0); EXPECT_EQ(bounds.width(), 25); EXPECT_EQ(bounds.height(), 25); EXPECT_EQ(result, ui::AXOffscreenResult::kOnscreen); } TEST(FlutterPlatformNodeDelegateTest, canCalculateOffScreenBoundsCorrectly) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root; root.id = 0; root.label = "root"; root.hint = ""; root.value = ""; root.increased_value = ""; root.decreased_value = ""; root.tooltip = ""; root.child_count = 1; int32_t children[] = {1}; root.children_in_traversal_order = children; root.custom_accessibility_actions_count = 0; root.rect = {0, 0, 100, 100}; // LTRB root.transform = {1, 0, 0, 0, 1, 0, 0, 0, 1}; bridge->AddFlutterSemanticsNodeUpdate(root); FlutterSemanticsNode2 child1; child1.id = 1; child1.label = "child 1"; child1.hint = ""; child1.value = ""; child1.increased_value = ""; child1.decreased_value = ""; child1.tooltip = ""; child1.child_count = 0; child1.custom_accessibility_actions_count = 0; child1.rect = {90, 90, 100, 100}; // LTRB child1.transform = {2, 0, 0, 0, 2, 0, 0, 0, 1}; bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->CommitUpdates(); auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); ui::AXOffscreenResult result; gfx::Rect bounds = child1_node->GetBoundsRect(ui::AXCoordinateSystem::kScreenDIPs, ui::AXClippingBehavior::kUnclipped, &result); EXPECT_EQ(bounds.x(), 180); EXPECT_EQ(bounds.y(), 180); EXPECT_EQ(bounds.width(), 20); EXPECT_EQ(bounds.height(), 20); EXPECT_EQ(result, ui::AXOffscreenResult::kOffscreen); } TEST(FlutterPlatformNodeDelegateTest, canUseOwnerBridge) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root; root.id = 0; root.label = "root"; root.hint = ""; root.value = ""; root.increased_value = ""; root.decreased_value = ""; root.tooltip = ""; root.child_count = 1; int32_t children[] = {1}; root.children_in_traversal_order = children; root.custom_accessibility_actions_count = 0; root.rect = {0, 0, 100, 100}; // LTRB root.transform = {1, 0, 0, 0, 1, 0, 0, 0, 1}; bridge->AddFlutterSemanticsNodeUpdate(root); FlutterSemanticsNode2 child1; child1.id = 1; child1.label = "child 1"; child1.hint = ""; child1.value = ""; child1.increased_value = ""; child1.decreased_value = ""; child1.tooltip = ""; child1.child_count = 0; child1.custom_accessibility_actions_count = 0; child1.rect = {0, 0, 50, 50}; // LTRB child1.transform = {0.5, 0, 0, 0, 0.5, 0, 0, 0, 1}; bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->CommitUpdates(); auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); auto owner_bridge = child1_node->GetOwnerBridge().lock(); bool result; gfx::RectF bounds = owner_bridge->RelativeToGlobalBounds( child1_node->GetAXNode(), result, true); EXPECT_EQ(bounds.x(), 0); EXPECT_EQ(bounds.y(), 0); EXPECT_EQ(bounds.width(), 25); EXPECT_EQ(bounds.height(), 25); EXPECT_EQ(result, false); } TEST(FlutterPlatformNodeDelegateTest, selfIsLowestPlatformAncestor) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root; root.id = 0; root.label = "root"; root.hint = ""; root.value = ""; root.increased_value = ""; root.decreased_value = ""; root.tooltip = ""; root.child_count = 0; root.children_in_traversal_order = nullptr; root.custom_accessibility_actions_count = 0; bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); auto lowest_platform_ancestor = root_node->GetLowestPlatformAncestor(); EXPECT_EQ(root_node->GetNativeViewAccessible(), lowest_platform_ancestor); } TEST(FlutterPlatformNodeDelegateTest, canGetFromNodeID) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root; root.id = 0; root.label = "root"; root.hint = ""; root.value = ""; root.increased_value = ""; root.decreased_value = ""; root.tooltip = ""; root.child_count = 1; int32_t children[] = {1}; root.children_in_traversal_order = children; root.custom_accessibility_actions_count = 0; bridge->AddFlutterSemanticsNodeUpdate(root); FlutterSemanticsNode2 child1; child1.id = 1; child1.label = "child 1"; child1.hint = ""; child1.value = ""; child1.increased_value = ""; child1.decreased_value = ""; child1.tooltip = ""; child1.child_count = 0; child1.custom_accessibility_actions_count = 0; bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); auto node_by_id = root_node->GetFromNodeID(1); EXPECT_EQ(child1_node->GetPlatformNode(), node_by_id); } } // namespace testing } // namespace flutter
engine/shell/platform/common/flutter_platform_node_delegate_unittests.cc/0
{ "file_path": "engine/shell/platform/common/flutter_platform_node_delegate_unittests.cc", "repo_id": "engine", "token_count": 3923 }
315
// 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. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_EXPORT_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_EXPORT_H_ #ifdef FLUTTER_DESKTOP_LIBRARY // Add visibility/export annotations when building the library. #ifdef _WIN32 #define FLUTTER_EXPORT __declspec(dllexport) #else #define FLUTTER_EXPORT __attribute__((visibility("default"))) #endif #else // FLUTTER_DESKTOP_LIBRARY // Add import annotations when consuming the library. #ifdef _WIN32 #define FLUTTER_EXPORT __declspec(dllimport) #else #define FLUTTER_EXPORT #endif #endif // FLUTTER_DESKTOP_LIBRARY #endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_EXPORT_H_
engine/shell/platform/common/public/flutter_export.h/0
{ "file_path": "engine/shell/platform/common/public/flutter_export.h", "repo_id": "engine", "token_count": 295 }
316
// 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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERHEADLESSDARTRUNNER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERHEADLESSDARTRUNNER_H_ #import <Foundation/Foundation.h> #import "FlutterBinaryMessenger.h" #import "FlutterDartProject.h" #import "FlutterEngine.h" #import "FlutterMacros.h" /** * A callback for when FlutterHeadlessDartRunner has attempted to start a Dart * Isolate in the background. * * @param success YES if the Isolate was started and run successfully, NO * otherwise. */ typedef void (^FlutterHeadlessDartRunnerCallback)(BOOL success); /** * The deprecated FlutterHeadlessDartRunner runs Flutter Dart code with a null rasterizer, * and no native drawing surface. It is appropriate for use in running Dart * code e.g. in the background from a plugin. * * Most callers should prefer using `FlutterEngine` directly; this interface exists * for legacy support. */ FLUTTER_DARWIN_EXPORT FLUTTER_DEPRECATED("FlutterEngine should be used rather than FlutterHeadlessDartRunner") @interface FlutterHeadlessDartRunner : FlutterEngine /** * Initialize this FlutterHeadlessDartRunner with a `FlutterDartProject`. * * If the FlutterDartProject is not specified, the FlutterHeadlessDartRunner will attempt to locate * the project in a default location. * * A newly initialized engine will not run the `FlutterDartProject` until either * `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI` is called. * * @param labelPrefix The label prefix used to identify threads for this instance. Should * be unique across FlutterEngine instances * @param projectOrNil The `FlutterDartProject` to run. */ - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)projectOrNil; /** * Initialize this FlutterHeadlessDartRunner with a `FlutterDartProject`. * * If the FlutterDartProject is not specified, the FlutterHeadlessDartRunner will attempt to locate * the project in a default location. * * A newly initialized engine will not run the `FlutterDartProject` until either * `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI` is called. * * @param labelPrefix The label prefix used to identify threads for this instance. Should * be unique across FlutterEngine instances * @param projectOrNil The `FlutterDartProject` to run. * @param allowHeadlessExecution Must be set to `YES`. */ - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)projectOrNil allowHeadlessExecution:(BOOL)allowHeadlessExecution; /** * Initialize this FlutterHeadlessDartRunner with a `FlutterDartProject`. * * If the FlutterDartProject is not specified, the FlutterHeadlessDartRunner will attempt to locate * the project in a default location. * * A newly initialized engine will not run the `FlutterDartProject` until either * `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI` is called. * * @param labelPrefix The label prefix used to identify threads for this instance. Should * be unique across FlutterEngine instances * @param projectOrNil The `FlutterDartProject` to run. * @param allowHeadlessExecution Must be set to `YES`. * @param restorationEnabled Must be set to `NO`. */ - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)projectOrNil allowHeadlessExecution:(BOOL)allowHeadlessExecution restorationEnabled:(BOOL)restorationEnabled NS_DESIGNATED_INITIALIZER; /** * Not recommended for use - will initialize with a default label ("io.flutter.headless") * and the default FlutterDartProject. */ - (instancetype)init; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERHEADLESSDARTRUNNER_H_
engine/shell/platform/darwin/ios/framework/Headers/FlutterHeadlessDartRunner.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Headers/FlutterHeadlessDartRunner.h", "repo_id": "engine", "token_count": 1214 }
317
// 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 <OCMock/OCMock.h> #import <XCTest/XCTest.h> #include "flutter/common/constants.h" #include "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" FLUTTER_ASSERT_ARC @interface FlutterDartProjectTest : XCTestCase @end @implementation FlutterDartProjectTest - (void)setUp { } - (void)tearDown { } - (void)testOldGenHeapSizeSetting { FlutterDartProject* project = [[FlutterDartProject alloc] init]; int64_t old_gen_heap_size = std::round([NSProcessInfo processInfo].physicalMemory * .48 / flutter::kMegaByteSizeInBytes); XCTAssertEqual(project.settings.old_gen_heap_size, old_gen_heap_size); } - (void)testResourceCacheMaxBytesThresholdSetting { FlutterDartProject* project = [[FlutterDartProject alloc] init]; CGFloat scale = [UIScreen mainScreen].scale; CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width * scale; CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height * scale; size_t resource_cache_max_bytes_threshold = screenWidth * screenHeight * 12 * 4; XCTAssertEqual(project.settings.resource_cache_max_bytes_threshold, resource_cache_max_bytes_threshold); } - (void)testMainBundleSettingsAreCorrectlyParsed { NSBundle* mainBundle = [NSBundle mainBundle]; NSDictionary* appTransportSecurity = [mainBundle objectForInfoDictionaryKey:@"NSAppTransportSecurity"]; XCTAssertTrue([FlutterDartProject allowsArbitraryLoads:appTransportSecurity]); XCTAssertEqualObjects( @"[[\"invalid-site.com\",true,false],[\"sub.invalid-site.com\",false,false]]", [FlutterDartProject domainNetworkPolicy:appTransportSecurity]); } - (void)testLeakDartVMSettingsAreCorrectlyParsed { // The FLTLeakDartVM's value is defined in Info.plist NSBundle* mainBundle = [NSBundle mainBundle]; NSNumber* leakDartVM = [mainBundle objectForInfoDictionaryKey:@"FLTLeakDartVM"]; XCTAssertEqual(leakDartVM.boolValue, NO); auto settings = FLTDefaultSettingsForBundle(); // Check settings.leak_vm value is same as the value defined in Info.plist. XCTAssertEqual(settings.leak_vm, NO); } - (void)testFLTFrameworkBundleInternalWhenBundleIsNotPresent { NSBundle* found = FLTFrameworkBundleInternal(@"doesNotExist", NSBundle.mainBundle.privateFrameworksURL); XCTAssertNil(found); } - (void)testFLTFrameworkBundleInternalWhenBundleIsPresent { NSString* presentBundleID = @"io.flutter.flutter"; NSBundle* found = FLTFrameworkBundleInternal(presentBundleID, NSBundle.mainBundle.privateFrameworksURL); XCTAssertNotNil(found); } - (void)testFLTGetApplicationBundleWhenCurrentTargetIsNotExtension { NSBundle* bundle = FLTGetApplicationBundle(); XCTAssertEqual(bundle, [NSBundle mainBundle]); } - (void)testFLTGetApplicationBundleWhenCurrentTargetIsExtension { id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); NSURL* url = [[NSBundle mainBundle].bundleURL URLByAppendingPathComponent:@"foo/ext.appex"]; OCMStub([mockMainBundle bundleURL]).andReturn(url); NSBundle* bundle = FLTGetApplicationBundle(); [mockMainBundle stopMocking]; XCTAssertEqualObjects(bundle.bundleURL, [NSBundle mainBundle].bundleURL); } - (void)testFLTAssetsURLFromBundle { { // Found asset path in info.plist id mockBundle = OCMClassMock([NSBundle class]); OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); NSString* resultAssetsPath = @"path/to/foo/assets"; OCMStub([mockBundle pathForResource:@"foo/assets" ofType:nil]).andReturn(resultAssetsPath); NSString* path = FLTAssetsPathFromBundle(mockBundle); XCTAssertEqualObjects(path, @"path/to/foo/assets"); } { // Found asset path in info.plist, is not overriden by main bundle id mockBundle = OCMClassMock([NSBundle class]); id mockMainBundle = OCMPartialMock(NSBundle.mainBundle); OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); OCMStub([mockMainBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); NSString* resultAssetsPath = @"path/to/foo/assets"; OCMStub([mockBundle pathForResource:@"foo/assets" ofType:nil]).andReturn(resultAssetsPath); NSString* path = FLTAssetsPathFromBundle(mockBundle); XCTAssertEqualObjects(path, @"path/to/foo/assets"); [mockMainBundle stopMocking]; } { // No asset path in info.plist, defaults to main bundle id mockBundle = OCMClassMock([NSBundle class]); id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); NSString* resultAssetsPath = @"path/to/foo/assets"; OCMStub([mockBundle pathForResource:@"Frameworks/App.framework/flutter_assets" ofType:nil]) .andReturn(nil); OCMStub([mockMainBundle pathForResource:@"Frameworks/App.framework/flutter_assets" ofType:nil]) .andReturn(resultAssetsPath); NSString* path = FLTAssetsPathFromBundle(mockBundle); XCTAssertEqualObjects(path, @"path/to/foo/assets"); [mockMainBundle stopMocking]; } } - (void)testFLTAssetPathReturnsTheCorrectValue { { // Found assets path in info.plist id mockBundle = OCMClassMock([NSBundle class]); OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); XCTAssertEqualObjects(FLTAssetPath(mockBundle), @"foo/assets"); } { // No assets path in info.plist, use default value id mockBundle = OCMClassMock([NSBundle class]); OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); XCTAssertEqualObjects(FLTAssetPath(mockBundle), kDefaultAssetPath); } } - (void)testLookUpForAssets { { id mockBundle = OCMPartialMock([NSBundle mainBundle]); // Found assets path in info.plist OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar"]; // This is testing public API, changing this assert is likely to break plugins. XCTAssertEqualObjects(assetsPath, @"foo/assets/bar"); [mockBundle stopMocking]; } { id mockBundle = OCMPartialMock([NSBundle mainBundle]); // No assets path in info.plist, use default value OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar"]; // This is testing public API, changing this assert is likely to break plugins. XCTAssertEqualObjects(assetsPath, @"Frameworks/App.framework/flutter_assets/bar"); [mockBundle stopMocking]; } } - (void)testLookUpForAssetsFromBundle { { id mockBundle = OCMClassMock([NSBundle class]); // Found assets path in info.plist OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromBundle:mockBundle]; // This is testing public API, changing this assert is likely to break plugins. XCTAssertEqualObjects(assetsPath, @"foo/assets/bar"); } { // No assets path in info.plist, use default value id mockBundle = OCMClassMock([NSBundle class]); OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromBundle:mockBundle]; // This is testing public API, changing this assert is likely to break plugins. XCTAssertEqualObjects(assetsPath, @"Frameworks/App.framework/flutter_assets/bar"); } } - (void)testLookUpForAssetsFromPackage { { id mockBundle = OCMPartialMock([NSBundle mainBundle]); // Found assets path in info.plist OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromPackage:@"bar_package"]; // This is testing public API, changing this assert is likely to break plugins. XCTAssertEqualObjects(assetsPath, @"foo/assets/packages/bar_package/bar"); [mockBundle stopMocking]; } { id mockBundle = OCMPartialMock([NSBundle mainBundle]); // No assets path in info.plist, use default value OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromPackage:@"bar_package"]; // This is testing public API, changing this assert is likely to break plugins. XCTAssertEqualObjects(assetsPath, @"Frameworks/App.framework/flutter_assets/packages/bar_package/bar"); [mockBundle stopMocking]; } } - (void)testLookUpForAssetsFromPackageFromBundle { { id mockBundle = OCMClassMock([NSBundle class]); // Found assets path in info.plist OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromPackage:@"bar_package" fromBundle:mockBundle]; // This is testing public API, changing this assert is likely to break plugins. XCTAssertEqualObjects(assetsPath, @"foo/assets/packages/bar_package/bar"); } { id mockBundle = OCMClassMock([NSBundle class]); // No assets path in info.plist, use default value OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromPackage:@"bar_package" fromBundle:mockBundle]; // This is testing public API, changing this assert is likely to break plugins. XCTAssertEqualObjects(assetsPath, @"Frameworks/App.framework/flutter_assets/packages/bar_package/bar"); } } - (void)testDisableImpellerSettingIsCorrectlyParsed { id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); OCMStub([mockMainBundle objectForInfoDictionaryKey:@"FLTEnableImpeller"]).andReturn(@"NO"); auto settings = FLTDefaultSettingsForBundle(); // Check settings.enable_impeller value is same as the value defined in Info.plist. XCTAssertEqual(settings.enable_impeller, NO); [mockMainBundle stopMocking]; } - (void)testEnableImpellerSettingIsCorrectlyParsed { id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); OCMStub([mockMainBundle objectForInfoDictionaryKey:@"FLTEnableImpeller"]).andReturn(@"YES"); auto settings = FLTDefaultSettingsForBundle(); // Check settings.enable_impeller value is same as the value defined in Info.plist. XCTAssertEqual(settings.enable_impeller, YES); [mockMainBundle stopMocking]; } - (void)testEnableImpellerSettingIsCorrectlyOverriddenByCommandLine { id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); OCMStub([mockMainBundle objectForInfoDictionaryKey:@"FLTEnableImpeller"]).andReturn(@"NO"); id mockProcessInfo = OCMPartialMock([NSProcessInfo processInfo]); NSArray* arguments = @[ @"process_name", @"--enable-impeller" ]; OCMStub([mockProcessInfo arguments]).andReturn(arguments); auto settings = FLTDefaultSettingsForBundle(nil, mockProcessInfo); // Check settings.enable_impeller value is same as the value on command line. XCTAssertEqual(settings.enable_impeller, YES); [mockMainBundle stopMocking]; } - (void)testDisableImpellerSettingIsCorrectlyOverriddenByCommandLine { id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); OCMStub([mockMainBundle objectForInfoDictionaryKey:@"FLTEnableImpeller"]).andReturn(@"YES"); id mockProcessInfo = OCMPartialMock([NSProcessInfo processInfo]); NSArray* arguments = @[ @"process_name", @"--enable-impeller=false" ]; OCMStub([mockProcessInfo arguments]).andReturn(arguments); auto settings = FLTDefaultSettingsForBundle(nil, mockProcessInfo); // Check settings.enable_impeller value is same as the value on command line. XCTAssertEqual(settings.enable_impeller, NO); [mockMainBundle stopMocking]; } - (void)testDisableImpellerAppBundleSettingIsCorrectlyParsed { NSString* bundleId = [FlutterDartProject defaultBundleIdentifier]; id mockAppBundle = OCMClassMock([NSBundle class]); OCMStub([mockAppBundle objectForInfoDictionaryKey:@"FLTEnableImpeller"]).andReturn(@"NO"); OCMStub([mockAppBundle bundleWithIdentifier:bundleId]).andReturn(mockAppBundle); auto settings = FLTDefaultSettingsForBundle(); // Check settings.enable_impeller value is same as the value defined in Info.plist. XCTAssertEqual(settings.enable_impeller, NO); [mockAppBundle stopMocking]; } - (void)testEnableImpellerAppBundleSettingIsCorrectlyParsed { NSString* bundleId = [FlutterDartProject defaultBundleIdentifier]; id mockAppBundle = OCMClassMock([NSBundle class]); OCMStub([mockAppBundle objectForInfoDictionaryKey:@"FLTEnableImpeller"]).andReturn(@"YES"); OCMStub([mockAppBundle bundleWithIdentifier:bundleId]).andReturn(mockAppBundle); // Since FLTEnableImpeller is set to false in the main bundle, this is also // testing that setting FLTEnableImpeller in the app bundle takes // precedence over setting it in the root bundle. auto settings = FLTDefaultSettingsForBundle(); // Check settings.enable_impeller value is same as the value defined in Info.plist. XCTAssertEqual(settings.enable_impeller, YES); [mockAppBundle stopMocking]; } - (void)testEnableTraceSystraceSettingIsCorrectlyParsed { NSBundle* mainBundle = [NSBundle mainBundle]; NSNumber* enableTraceSystrace = [mainBundle objectForInfoDictionaryKey:@"FLTTraceSystrace"]; XCTAssertNotNil(enableTraceSystrace); XCTAssertEqual(enableTraceSystrace.boolValue, NO); auto settings = FLTDefaultSettingsForBundle(); XCTAssertEqual(settings.trace_systrace, NO); } - (void)testEnableDartProflingSettingIsCorrectlyParsed { NSBundle* mainBundle = [NSBundle mainBundle]; NSNumber* enableTraceSystrace = [mainBundle objectForInfoDictionaryKey:@"FLTEnableDartProfiling"]; XCTAssertNotNil(enableTraceSystrace); XCTAssertEqual(enableTraceSystrace.boolValue, NO); auto settings = FLTDefaultSettingsForBundle(); XCTAssertEqual(settings.trace_systrace, NO); } - (void)testEmptySettingsAreCorrect { XCTAssertFalse([FlutterDartProject allowsArbitraryLoads:[[NSDictionary alloc] init]]); XCTAssertEqualObjects(@"", [FlutterDartProject domainNetworkPolicy:[[NSDictionary alloc] init]]); } - (void)testAllowsArbitraryLoads { XCTAssertFalse([FlutterDartProject allowsArbitraryLoads:@{@"NSAllowsArbitraryLoads" : @false}]); XCTAssertTrue([FlutterDartProject allowsArbitraryLoads:@{@"NSAllowsArbitraryLoads" : @true}]); } - (void)testProperlyFormedExceptionDomains { NSDictionary* domainInfoOne = @{ @"NSIncludesSubdomains" : @false, @"NSExceptionAllowsInsecureHTTPLoads" : @true, @"NSExceptionMinimumTLSVersion" : @"4.0" }; NSDictionary* domainInfoTwo = @{ @"NSIncludesSubdomains" : @true, @"NSExceptionAllowsInsecureHTTPLoads" : @false, @"NSExceptionMinimumTLSVersion" : @"4.0" }; NSDictionary* domainInfoThree = @{ @"NSIncludesSubdomains" : @false, @"NSExceptionAllowsInsecureHTTPLoads" : @true, @"NSExceptionMinimumTLSVersion" : @"4.0" }; NSDictionary* exceptionDomains = @{ @"domain.name" : domainInfoOne, @"sub.domain.name" : domainInfoTwo, @"sub.two.domain.name" : domainInfoThree }; NSDictionary* appTransportSecurity = @{@"NSExceptionDomains" : exceptionDomains}; XCTAssertEqualObjects(@"[[\"domain.name\",false,true],[\"sub.domain.name\",true,false]," @"[\"sub.two.domain.name\",false,true]]", [FlutterDartProject domainNetworkPolicy:appTransportSecurity]); } - (void)testExceptionDomainsWithMissingInfo { NSDictionary* domainInfoOne = @{@"NSExceptionMinimumTLSVersion" : @"4.0"}; NSDictionary* domainInfoTwo = @{ @"NSIncludesSubdomains" : @true, }; NSDictionary* domainInfoThree = @{}; NSDictionary* exceptionDomains = @{ @"domain.name" : domainInfoOne, @"sub.domain.name" : domainInfoTwo, @"sub.two.domain.name" : domainInfoThree }; NSDictionary* appTransportSecurity = @{@"NSExceptionDomains" : exceptionDomains}; XCTAssertEqualObjects(@"[[\"domain.name\",false,false],[\"sub.domain.name\",true,false]," @"[\"sub.two.domain.name\",false,false]]", [FlutterDartProject domainNetworkPolicy:appTransportSecurity]); } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterDartProjectTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterDartProjectTest.mm", "repo_id": "engine", "token_count": 6228 }
318
// 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. #define FML_USED_ON_EMBEDDER #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterHeadlessDartRunner.h" #include <memory> #include "flutter/fml/make_copyable.h" #include "flutter/fml/message_loop.h" #include "flutter/shell/common/engine.h" #include "flutter/shell/common/rasterizer.h" #include "flutter/shell/common/run_configuration.h" #include "flutter/shell/common/shell.h" #include "flutter/shell/common/switches.h" #include "flutter/shell/common/thread_host.h" #import "flutter/shell/platform/darwin/common/command_line.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h" #import "flutter/shell/platform/darwin/ios/platform_view_ios.h" @implementation FlutterHeadlessDartRunner { } - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)projectOrNil { return [self initWithName:labelPrefix project:projectOrNil allowHeadlessExecution:YES]; } - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)projectOrNil allowHeadlessExecution:(BOOL)allowHeadlessExecution { NSAssert(allowHeadlessExecution == YES, @"Cannot initialize a FlutterHeadlessDartRunner without headless execution."); return [self initWithName:labelPrefix project:projectOrNil allowHeadlessExecution:allowHeadlessExecution restorationEnabled:NO]; } - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)projectOrNil allowHeadlessExecution:(BOOL)allowHeadlessExecution restorationEnabled:(BOOL)restorationEnabled { NSAssert(allowHeadlessExecution == YES, @"Cannot initialize a FlutterHeadlessDartRunner without headless execution."); return [super initWithName:labelPrefix project:projectOrNil allowHeadlessExecution:allowHeadlessExecution restorationEnabled:restorationEnabled]; } - (instancetype)init { return [self initWithName:@"io.flutter.headless" project:nil]; } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterHeadlessDartRunner.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterHeadlessDartRunner.mm", "repo_id": "engine", "token_count": 902 }
319
// 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 <OCMock/OCMock.h> #import <UIKit/UIKit.h> #import <XCTest/XCTest.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTouchInterceptingView_Test.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/darwin/ios/platform_view_ios.h" FLUTTER_ASSERT_ARC @class FlutterPlatformViewsTestMockPlatformView; __weak static FlutterPlatformViewsTestMockPlatformView* gMockPlatformView = nil; const float kFloatCompareEpsilon = 0.001; @interface FlutterPlatformViewsTestMockPlatformView : UIView @end @implementation FlutterPlatformViewsTestMockPlatformView - (instancetype)init { self = [super init]; if (self) { gMockPlatformView = self; } return self; } - (void)dealloc { gMockPlatformView = nil; } @end @interface FlutterPlatformViewsTestMockFlutterPlatformView : NSObject <FlutterPlatformView> @property(nonatomic, strong) UIView* view; @property(nonatomic, assign) BOOL viewCreated; @end @implementation FlutterPlatformViewsTestMockFlutterPlatformView - (instancetype)init { if (self = [super init]) { _view = [[FlutterPlatformViewsTestMockPlatformView alloc] init]; _viewCreated = NO; } return self; } - (UIView*)view { [self checkViewCreatedOnce]; return _view; } - (void)checkViewCreatedOnce { if (self.viewCreated) { abort(); } self.viewCreated = YES; } @end @interface FlutterPlatformViewsTestMockFlutterPlatformFactory : NSObject <FlutterPlatformViewFactory> @end @implementation FlutterPlatformViewsTestMockFlutterPlatformFactory - (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args { return [[FlutterPlatformViewsTestMockFlutterPlatformView alloc] init]; } @end namespace flutter { namespace { class FlutterPlatformViewsTestMockPlatformViewDelegate : public PlatformView::Delegate { public: void OnPlatformViewCreated(std::unique_ptr<Surface> surface) override {} void OnPlatformViewDestroyed() override {} void OnPlatformViewScheduleFrame() override {} void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override {} void OnPlatformViewSetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics) override {} const flutter::Settings& OnPlatformViewGetSettings() const override { return settings_; } void OnPlatformViewDispatchPlatformMessage(std::unique_ptr<PlatformMessage> message) override {} void OnPlatformViewDispatchPointerDataPacket(std::unique_ptr<PointerDataPacket> packet) override { } void OnPlatformViewDispatchSemanticsAction(int32_t id, SemanticsAction action, fml::MallocMapping args) override {} void OnPlatformViewSetSemanticsEnabled(bool enabled) override {} void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override {} void OnPlatformViewRegisterTexture(std::shared_ptr<Texture> texture) override {} void OnPlatformViewUnregisterTexture(int64_t texture_id) override {} void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override {} void LoadDartDeferredLibrary(intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> snapshot_instructions) override { } void LoadDartDeferredLibraryError(intptr_t loading_unit_id, const std::string error_message, bool transient) override {} void UpdateAssetResolverByType(std::unique_ptr<flutter::AssetResolver> updated_asset_resolver, flutter::AssetResolver::AssetResolverType type) override {} flutter::Settings settings_; }; } // namespace } // namespace flutter namespace { fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) { auto thread = std::make_unique<fml::Thread>(name); auto runner = thread->GetTaskRunner(); return runner; } } // namespace @interface FlutterPlatformViewsTest : XCTestCase @end @implementation FlutterPlatformViewsTest - (void)testFlutterViewOnlyCreateOnceInOneFrame { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack.PushTransform(screenScaleMatrix); // Push a translate matrix SkMatrix translateMatrix = SkMatrix::Translate(100, 100); stack.PushTransform(translateMatrix); SkMatrix finalMatrix; finalMatrix.setConcat(screenScaleMatrix, translateMatrix); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); flutterPlatformViewsController->GetPlatformViewRect(2); XCTAssertNotNil(gMockPlatformView); flutterPlatformViewsController->Reset(); } - (void)testCanCreatePlatformViewWithoutFlutterView { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); } - (void)testChildClippingViewHitTests { ChildClippingView* childClippingView = [[ChildClippingView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; UIView* childView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; [childClippingView addSubview:childView]; XCTAssertFalse([childClippingView pointInside:CGPointMake(50, 50) withEvent:nil]); XCTAssertFalse([childClippingView pointInside:CGPointMake(99, 100) withEvent:nil]); XCTAssertFalse([childClippingView pointInside:CGPointMake(100, 99) withEvent:nil]); XCTAssertFalse([childClippingView pointInside:CGPointMake(201, 200) withEvent:nil]); XCTAssertFalse([childClippingView pointInside:CGPointMake(200, 201) withEvent:nil]); XCTAssertFalse([childClippingView pointInside:CGPointMake(99, 200) withEvent:nil]); XCTAssertFalse([childClippingView pointInside:CGPointMake(200, 299) withEvent:nil]); XCTAssertTrue([childClippingView pointInside:CGPointMake(150, 150) withEvent:nil]); XCTAssertTrue([childClippingView pointInside:CGPointMake(100, 100) withEvent:nil]); XCTAssertTrue([childClippingView pointInside:CGPointMake(199, 100) withEvent:nil]); XCTAssertTrue([childClippingView pointInside:CGPointMake(100, 199) withEvent:nil]); XCTAssertTrue([childClippingView pointInside:CGPointMake(199, 199) withEvent:nil]); } - (void)testReleasesBackdropFilterSubviewsOnChildClippingViewDealloc { __weak NSMutableArray<UIVisualEffectView*>* weakBackdropFilterSubviews = nil; @autoreleasepool { ChildClippingView* clipping_view = [[ChildClippingView alloc] initWithFrame:CGRectZero]; weakBackdropFilterSubviews = clipping_view.backdropFilterSubviews; XCTAssertNotNil(weakBackdropFilterSubviews); clipping_view = nil; } XCTAssertNil(weakBackdropFilterSubviews); } - (void)testApplyBackdropFilter { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack CGFloat screenScale = [UIScreen mainScreen].scale; SkMatrix screenScaleMatrix = SkMatrix::Scale(screenScale, screenScale); stack.PushTransform(screenScaleMatrix); // Push a backdrop filter auto filter = std::make_shared<flutter::DlBlurImageFilter>(5, 2, flutter::DlTileMode::kClamp); stack.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; // childClippingView has visual effect view with the correct configurations. NSUInteger numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(numberOfExpectedVisualEffectView, 1u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:5]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, 1u); } - (void)testApplyBackdropFilterWithCorrectFrame { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack CGFloat screenScale = [UIScreen mainScreen].scale; SkMatrix screenScaleMatrix = SkMatrix::Scale(screenScale, screenScale); stack.PushTransform(screenScaleMatrix); // Push a backdrop filter auto filter = std::make_shared<flutter::DlBlurImageFilter>(5, 2, flutter::DlTileMode::kClamp); stack.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 8, screenScale * 8)); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(5, 10), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; // childClippingView has visual effect view with the correct configurations. NSUInteger numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(numberOfExpectedVisualEffectView, 1u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 5, 8) inputRadius:5]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, 1u); } - (void)testApplyMultipleBackdropFilters { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack CGFloat screenScale = [UIScreen mainScreen].scale; SkMatrix screenScaleMatrix = SkMatrix::Scale(screenScale, screenScale); stack.PushTransform(screenScaleMatrix); // Push backdrop filters for (int i = 0; i < 50; i++) { auto filter = std::make_shared<flutter::DlBlurImageFilter>(i, 2, flutter::DlTileMode::kClamp); stack.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(20, 20), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; NSUInteger numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(numberOfExpectedVisualEffectView, 50u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)numberOfExpectedVisualEffectView]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, (NSUInteger)numberOfExpectedVisualEffectView); } - (void)testAddBackdropFilters { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack CGFloat screenScale = [UIScreen mainScreen].scale; SkMatrix screenScaleMatrix = SkMatrix::Scale(screenScale, screenScale); stack.PushTransform(screenScaleMatrix); // Push a backdrop filter auto filter = std::make_shared<flutter::DlBlurImageFilter>(5, 2, flutter::DlTileMode::kClamp); stack.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; NSMutableArray* originalVisualEffectViews = [[NSMutableArray alloc] init]; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(originalVisualEffectViews.count, 1u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)5]) { [originalVisualEffectViews addObject:subview]; } } XCTAssertEqual(originalVisualEffectViews.count, 1u); // // Simulate adding 1 backdrop filter (create a new mutators stack) // Create embedded view params flutter::MutatorsStack stack2; // Layer tree always pushes a screen scale factor to the stack stack2.PushTransform(screenScaleMatrix); // Push backdrop filters for (int i = 0; i < 2; i++) { stack2.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; NSMutableArray* newVisualEffectViews = [[NSMutableArray alloc] init]; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(newVisualEffectViews.count, 2u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)5]) { [newVisualEffectViews addObject:subview]; } } XCTAssertEqual(newVisualEffectViews.count, 2u); for (NSUInteger i = 0; i < originalVisualEffectViews.count; i++) { UIView* originalView = originalVisualEffectViews[i]; UIView* newView = newVisualEffectViews[i]; // Compare reference. XCTAssertEqual(originalView, newView); id mockOrignalView = OCMPartialMock(originalView); OCMReject([mockOrignalView removeFromSuperview]); } } - (void)testRemoveBackdropFilters { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack CGFloat screenScale = [UIScreen mainScreen].scale; SkMatrix screenScaleMatrix = SkMatrix::Scale(screenScale, screenScale); stack.PushTransform(screenScaleMatrix); // Push backdrop filters auto filter = std::make_shared<flutter::DlBlurImageFilter>(5, 2, flutter::DlTileMode::kClamp); for (int i = 0; i < 5; i++) { stack.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; NSMutableArray* originalVisualEffectViews = [[NSMutableArray alloc] init]; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(originalVisualEffectViews.count, 5u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)5]) { [originalVisualEffectViews addObject:subview]; } } // Simulate removing 1 backdrop filter (create a new mutators stack) // Create embedded view params flutter::MutatorsStack stack2; // Layer tree always pushes a screen scale factor to the stack stack2.PushTransform(screenScaleMatrix); // Push backdrop filters for (int i = 0; i < 4; i++) { stack2.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; NSMutableArray* newVisualEffectViews = [[NSMutableArray alloc] init]; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(newVisualEffectViews.count, 4u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)5]) { [newVisualEffectViews addObject:subview]; } } XCTAssertEqual(newVisualEffectViews.count, 4u); for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { UIView* newView = newVisualEffectViews[i]; id mockNewView = OCMPartialMock(newView); UIView* originalView = originalVisualEffectViews[i]; // Compare reference. XCTAssertEqual(originalView, newView); OCMReject([mockNewView removeFromSuperview]); [mockNewView stopMocking]; } // Simulate removing all backdrop filters (replace the mutators stack) // Update embedded view params, delete except screenScaleMatrix for (int i = 0; i < 5; i++) { stack2.Pop(); } // No backdrop filters in the stack, so no nothing to push embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; NSUInteger numberOfExpectedVisualEffectView = 0u; for (UIView* subview in childClippingView.subviews) { if ([subview isKindOfClass:[UIVisualEffectView class]]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, 0u); } - (void)testEditBackdropFilters { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack CGFloat screenScale = [UIScreen mainScreen].scale; SkMatrix screenScaleMatrix = SkMatrix::Scale(screenScale, screenScale); stack.PushTransform(screenScaleMatrix); // Push backdrop filters auto filter = std::make_shared<flutter::DlBlurImageFilter>(5, 2, flutter::DlTileMode::kClamp); for (int i = 0; i < 5; i++) { stack.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; NSMutableArray* originalVisualEffectViews = [[NSMutableArray alloc] init]; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(originalVisualEffectViews.count, 5u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)5]) { [originalVisualEffectViews addObject:subview]; } } // Simulate editing 1 backdrop filter in the middle of the stack (create a new mutators stack) // Create embedded view params flutter::MutatorsStack stack2; // Layer tree always pushes a screen scale factor to the stack stack2.PushTransform(screenScaleMatrix); // Push backdrop filters for (int i = 0; i < 5; i++) { if (i == 3) { auto filter2 = std::make_shared<flutter::DlBlurImageFilter>(2, 5, flutter::DlTileMode::kClamp); stack2.PushBackdropFilter(filter2, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); continue; } stack2.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; NSMutableArray* newVisualEffectViews = [[NSMutableArray alloc] init]; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(newVisualEffectViews.count, 5u); CGFloat expectInputRadius = 5; if (newVisualEffectViews.count == 3) { expectInputRadius = 2; } if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)expectInputRadius]) { [newVisualEffectViews addObject:subview]; } } XCTAssertEqual(newVisualEffectViews.count, 5u); for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { UIView* newView = newVisualEffectViews[i]; id mockNewView = OCMPartialMock(newView); UIView* originalView = originalVisualEffectViews[i]; // Compare reference. XCTAssertEqual(originalView, newView); OCMReject([mockNewView removeFromSuperview]); [mockNewView stopMocking]; } [newVisualEffectViews removeAllObjects]; // Simulate editing 1 backdrop filter in the beginning of the stack (replace the mutators stack) // Update embedded view params, delete except screenScaleMatrix for (int i = 0; i < 5; i++) { stack2.Pop(); } // Push backdrop filters for (int i = 0; i < 5; i++) { if (i == 0) { auto filter2 = std::make_shared<flutter::DlBlurImageFilter>(2, 5, flutter::DlTileMode::kClamp); stack2.PushBackdropFilter(filter2, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); continue; } stack2.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(newVisualEffectViews.count, 5u); CGFloat expectInputRadius = 5; if (newVisualEffectViews.count == 0) { expectInputRadius = 2; } if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)expectInputRadius]) { [newVisualEffectViews addObject:subview]; } } for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { UIView* newView = newVisualEffectViews[i]; id mockNewView = OCMPartialMock(newView); UIView* originalView = originalVisualEffectViews[i]; // Compare reference. XCTAssertEqual(originalView, newView); OCMReject([mockNewView removeFromSuperview]); [mockNewView stopMocking]; } [newVisualEffectViews removeAllObjects]; // Simulate editing 1 backdrop filter in the end of the stack (replace the mutators stack) // Update embedded view params, delete except screenScaleMatrix for (int i = 0; i < 5; i++) { stack2.Pop(); } // Push backdrop filters for (int i = 0; i < 5; i++) { if (i == 4) { auto filter2 = std::make_shared<flutter::DlBlurImageFilter>(2, 5, flutter::DlTileMode::kClamp); stack2.PushBackdropFilter(filter2, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); continue; } stack2.PushBackdropFilter(filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(newVisualEffectViews.count, 5u); CGFloat expectInputRadius = 5; if (newVisualEffectViews.count == 4) { expectInputRadius = 2; } if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)expectInputRadius]) { [newVisualEffectViews addObject:subview]; } } XCTAssertEqual(newVisualEffectViews.count, 5u); for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { UIView* newView = newVisualEffectViews[i]; id mockNewView = OCMPartialMock(newView); UIView* originalView = originalVisualEffectViews[i]; // Compare reference. XCTAssertEqual(originalView, newView); OCMReject([mockNewView removeFromSuperview]); [mockNewView stopMocking]; } [newVisualEffectViews removeAllObjects]; // Simulate editing all backdrop filters in the stack (replace the mutators stack) // Update embedded view params, delete except screenScaleMatrix for (int i = 0; i < 5; i++) { stack2.Pop(); } // Push backdrop filters for (int i = 0; i < 5; i++) { auto filter2 = std::make_shared<flutter::DlBlurImageFilter>(i, 2, flutter::DlTileMode::kClamp); stack2.PushBackdropFilter(filter2, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(newVisualEffectViews.count, 5u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)newVisualEffectViews.count]) { [newVisualEffectViews addObject:subview]; } } XCTAssertEqual(newVisualEffectViews.count, 5u); for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { UIView* newView = newVisualEffectViews[i]; id mockNewView = OCMPartialMock(newView); UIView* originalView = originalVisualEffectViews[i]; // Compare reference. XCTAssertEqual(originalView, newView); OCMReject([mockNewView removeFromSuperview]); [mockNewView stopMocking]; } [newVisualEffectViews removeAllObjects]; } - (void)testApplyBackdropFilterNotDlBlurImageFilter { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack CGFloat screenScale = [UIScreen mainScreen].scale; SkMatrix screenScaleMatrix = SkMatrix::Scale(screenScale, screenScale); stack.PushTransform(screenScaleMatrix); // Push a dilate backdrop filter auto dilateFilter = std::make_shared<flutter::DlDilateImageFilter>(5, 2); stack.PushBackdropFilter(dilateFilter, SkRect::MakeEmpty()); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; NSUInteger numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if ([subview isKindOfClass:[UIVisualEffectView class]]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, 0u); // Simulate adding a non-DlBlurImageFilter in the middle of the stack (create a new mutators // stack) Create embedded view params flutter::MutatorsStack stack2; // Layer tree always pushes a screen scale factor to the stack stack2.PushTransform(screenScaleMatrix); // Push backdrop filters and dilate filter auto blurFilter = std::make_shared<flutter::DlBlurImageFilter>(5, 2, flutter::DlTileMode::kClamp); for (int i = 0; i < 5; i++) { if (i == 2) { stack2.PushBackdropFilter(dilateFilter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); continue; } stack2.PushBackdropFilter(blurFilter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(numberOfExpectedVisualEffectView, 4u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)5]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, 4u); // Simulate adding a non-DlBlurImageFilter to the beginning of the stack (replace the mutators // stack) Update embedded view params, delete except screenScaleMatrix for (int i = 0; i < 5; i++) { stack2.Pop(); } // Push backdrop filters and dilate filter for (int i = 0; i < 5; i++) { if (i == 0) { stack2.PushBackdropFilter(dilateFilter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); continue; } stack2.PushBackdropFilter(blurFilter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(numberOfExpectedVisualEffectView, 4u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)5]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, 4u); // Simulate adding a non-DlBlurImageFilter to the end of the stack (replace the mutators stack) // Update embedded view params, delete except screenScaleMatrix for (int i = 0; i < 5; i++) { stack2.Pop(); } // Push backdrop filters and dilate filter for (int i = 0; i < 5; i++) { if (i == 4) { stack2.PushBackdropFilter(dilateFilter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); continue; } stack2.PushBackdropFilter(blurFilter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(numberOfExpectedVisualEffectView, 4u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:(CGFloat)5]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, 4u); // Simulate adding only non-DlBlurImageFilter to the stack (replace the mutators stack) // Update embedded view params, delete except screenScaleMatrix for (int i = 0; i < 5; i++) { stack2.Pop(); } // Push dilate filters for (int i = 0; i < 5; i++) { stack2.PushBackdropFilter(dilateFilter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); } embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if ([subview isKindOfClass:[UIVisualEffectView class]]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, 0u); } - (void)testApplyBackdropFilterCorrectAPI { [PlatformViewFilter resetPreparation]; // The gaussianBlur filter is extracted from UIVisualEffectView. // Each test requires a new PlatformViewFilter // Valid UIVisualEffectView API UIVisualEffectView* visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; PlatformViewFilter* platformViewFilter = [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) blurRadius:5 visualEffectView:visualEffectView]; XCTAssertNotNil(platformViewFilter); } - (void)testApplyBackdropFilterAPIChangedInvalidUIVisualEffectView { [PlatformViewFilter resetPreparation]; UIVisualEffectView* visualEffectView = [[UIVisualEffectView alloc] init]; PlatformViewFilter* platformViewFilter = [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) blurRadius:5 visualEffectView:visualEffectView]; XCTAssertNil(platformViewFilter); } - (void)testApplyBackdropFilterAPIChangedNoGaussianBlurFilter { [PlatformViewFilter resetPreparation]; UIVisualEffectView* editedUIVisualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; NSArray* subviews = editedUIVisualEffectView.subviews; for (UIView* view in subviews) { if ([NSStringFromClass([view class]) hasSuffix:@"BackdropView"]) { for (CIFilter* filter in view.layer.filters) { if ([[filter valueForKey:@"name"] isEqual:@"gaussianBlur"]) { [filter setValue:@"notGaussianBlur" forKey:@"name"]; break; } } break; } } PlatformViewFilter* platformViewFilter = [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) blurRadius:5 visualEffectView:editedUIVisualEffectView]; XCTAssertNil(platformViewFilter); } - (void)testApplyBackdropFilterAPIChangedInvalidInputRadius { [PlatformViewFilter resetPreparation]; UIVisualEffectView* editedUIVisualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; NSArray* subviews = editedUIVisualEffectView.subviews; for (UIView* view in subviews) { if ([NSStringFromClass([view class]) hasSuffix:@"BackdropView"]) { for (CIFilter* filter in view.layer.filters) { if ([[filter valueForKey:@"name"] isEqual:@"gaussianBlur"]) { [filter setValue:@"invalidInputRadius" forKey:@"inputRadius"]; break; } } break; } } PlatformViewFilter* platformViewFilter = [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) blurRadius:5 visualEffectView:editedUIVisualEffectView]; XCTAssertNil(platformViewFilter); } - (void)testBackdropFilterVisualEffectSubviewBackgroundColor { UIVisualEffectView* visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; PlatformViewFilter* platformViewFilter = [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) blurRadius:5 visualEffectView:visualEffectView]; CGColorRef visualEffectSubviewBackgroundColor = nil; for (UIView* view in [platformViewFilter backdropFilterView].subviews) { if ([NSStringFromClass([view class]) hasSuffix:@"VisualEffectSubview"]) { visualEffectSubviewBackgroundColor = view.layer.backgroundColor; } } XCTAssertTrue( CGColorEqualToColor(visualEffectSubviewBackgroundColor, UIColor.clearColor.CGColor)); } - (void)testCompositePlatformView { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack.PushTransform(screenScaleMatrix); // Push a translate matrix SkMatrix translateMatrix = SkMatrix::Translate(100, 100); stack.PushTransform(translateMatrix); SkMatrix finalMatrix; finalMatrix.setConcat(screenScaleMatrix, translateMatrix); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); CGRect platformViewRectInFlutterView = [gMockPlatformView convertRect:gMockPlatformView.bounds toView:mockFlutterView]; XCTAssertTrue(CGRectEqualToRect(platformViewRectInFlutterView, CGRectMake(100, 100, 300, 300))); } - (void)testBackdropFilterCorrectlyPushedAndReset { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack CGFloat screenScale = [UIScreen mainScreen].scale; SkMatrix screenScaleMatrix = SkMatrix::Scale(screenScale, screenScale); stack.PushTransform(screenScaleMatrix); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->BeginFrame(SkISize::Make(0, 0)); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->PushVisitedPlatformView(2); auto filter = std::make_shared<flutter::DlBlurImageFilter>(5, 2, flutter::DlTileMode::kClamp); flutterPlatformViewsController->PushFilterToVisitedPlatformViews( filter, SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); flutterPlatformViewsController->CompositeEmbeddedView(2); XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; // childClippingView has visual effect view with the correct configurations. NSUInteger numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } XCTAssertLessThan(numberOfExpectedVisualEffectView, 1u); if ([self validateOneVisualEffectView:subview expectedFrame:CGRectMake(0, 0, 10, 10) inputRadius:5]) { numberOfExpectedVisualEffectView++; } } XCTAssertEqual(numberOfExpectedVisualEffectView, 1u); // New frame, with no filter pushed. auto embeddedViewParams2 = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->BeginFrame(SkISize::Make(0, 0)); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams2)); flutterPlatformViewsController->CompositeEmbeddedView(2); XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; numberOfExpectedVisualEffectView = 0; for (UIView* subview in childClippingView.subviews) { if (![subview isKindOfClass:[UIVisualEffectView class]]) { continue; } numberOfExpectedVisualEffectView++; } XCTAssertEqual(numberOfExpectedVisualEffectView, 0u); } - (void)testChildClippingViewShouldBeTheBoundingRectOfPlatformView { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack.PushTransform(screenScaleMatrix); // Push a rotate matrix SkMatrix rotateMatrix; rotateMatrix.setRotate(10); stack.PushTransform(rotateMatrix); SkMatrix finalMatrix; finalMatrix.setConcat(screenScaleMatrix, rotateMatrix); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); CGRect platformViewRectInFlutterView = [gMockPlatformView convertRect:gMockPlatformView.bounds toView:mockFlutterView]; XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; // The childclippingview's frame is set based on flow, but the platform view's frame is set based // on quartz. Although they should be the same, but we should tolerate small floating point // errors. XCTAssertLessThan(fabs(platformViewRectInFlutterView.origin.x - childClippingView.frame.origin.x), kFloatCompareEpsilon); XCTAssertLessThan(fabs(platformViewRectInFlutterView.origin.y - childClippingView.frame.origin.y), kFloatCompareEpsilon); XCTAssertLessThan( fabs(platformViewRectInFlutterView.size.width - childClippingView.frame.size.width), kFloatCompareEpsilon); XCTAssertLessThan( fabs(platformViewRectInFlutterView.size.height - childClippingView.frame.size.height), kFloatCompareEpsilon); } - (void)testClipsDoNotInterceptWithPlatformViewShouldNotAddMaskView { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params. flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack. SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack.PushTransform(screenScaleMatrix); SkMatrix translateMatrix = SkMatrix::Translate(5, 5); // The platform view's rect for this test will be (5, 5, 10, 10). stack.PushTransform(translateMatrix); // Push a clip rect, big enough to contain the entire platform view bound. SkRect rect = SkRect::MakeXYWH(0, 0, 25, 25); stack.PushClipRect(rect); // Push a clip rrect, big enough to contain the entire platform view bound without clipping it. // Make the origin (-1, -1) so that the top left rounded corner isn't clipping the PlatformView. SkRect rect_for_rrect = SkRect::MakeXYWH(-1, -1, 25, 25); SkRRect rrect = SkRRect::MakeRectXY(rect_for_rrect, 1, 1); stack.PushClipRRect(rrect); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>( SkMatrix::Concat(screenScaleMatrix, translateMatrix), SkSize::Make(5, 5), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); gMockPlatformView.backgroundColor = UIColor.redColor; XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; XCTAssertNil(childClippingView.maskView); } - (void)testClipRRectOnlyHasCornersInterceptWithPlatformViewShouldAddMaskView { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack. SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack.PushTransform(screenScaleMatrix); SkMatrix translateMatrix = SkMatrix::Translate(5, 5); // The platform view's rect for this test will be (5, 5, 10, 10). stack.PushTransform(translateMatrix); // Push a clip rrect, the rect of the rrect is the same as the PlatformView of the corner should. // clip the PlatformView. SkRect rect_for_rrect = SkRect::MakeXYWH(0, 0, 10, 10); SkRRect rrect = SkRRect::MakeRectXY(rect_for_rrect, 1, 1); stack.PushClipRRect(rrect); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>( SkMatrix::Concat(screenScaleMatrix, translateMatrix), SkSize::Make(5, 5), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); gMockPlatformView.backgroundColor = UIColor.redColor; XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; XCTAssertNotNil(childClippingView.maskView); } - (void)testClipRect { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack.PushTransform(screenScaleMatrix); // Push a clip rect SkRect rect = SkRect::MakeXYWH(2, 2, 3, 3); stack.PushClipRect(rect); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); gMockPlatformView.backgroundColor = UIColor.redColor; XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { CGPoint point = CGPointMake(i, j); int alpha = [self alphaOfPoint:CGPointMake(i, j) onView:mockFlutterView]; // Edges of the clipping might have a semi transparent pixel, we only check the pixels that // are fully inside the clipped area. CGRect insideClipping = CGRectMake(3, 3, 1, 1); if (CGRectContainsPoint(insideClipping, point)) { XCTAssertEqual(alpha, 255); } else { XCTAssertLessThan(alpha, 255); } } } } - (void)testClipRRect { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack.PushTransform(screenScaleMatrix); // Push a clip rrect SkRRect rrect = SkRRect::MakeRectXY(SkRect::MakeXYWH(2, 2, 6, 6), 1, 1); stack.PushClipRRect(rrect); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); gMockPlatformView.backgroundColor = UIColor.redColor; XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { CGPoint point = CGPointMake(i, j); int alpha = [self alphaOfPoint:CGPointMake(i, j) onView:mockFlutterView]; // Edges of the clipping might have a semi transparent pixel, we only check the pixels that // are fully inside the clipped area. CGRect insideClipping = CGRectMake(3, 3, 4, 4); if (CGRectContainsPoint(insideClipping, point)) { XCTAssertEqual(alpha, 255); } else { XCTAssertLessThan(alpha, 255); } } } } - (void)testClipPath { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack.PushTransform(screenScaleMatrix); // Push a clip path SkPath path; path.addRoundRect(SkRect::MakeXYWH(2, 2, 6, 6), 1, 1); stack.PushClipPath(path); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(screenScaleMatrix, SkSize::Make(10, 10), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); gMockPlatformView.backgroundColor = UIColor.redColor; XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; [mockFlutterView addSubview:childClippingView]; [mockFlutterView setNeedsLayout]; [mockFlutterView layoutIfNeeded]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { CGPoint point = CGPointMake(i, j); int alpha = [self alphaOfPoint:CGPointMake(i, j) onView:mockFlutterView]; // Edges of the clipping might have a semi transparent pixel, we only check the pixels that // are fully inside the clipped area. CGRect insideClipping = CGRectMake(3, 3, 4, 4); if (CGRectContainsPoint(insideClipping, point)) { XCTAssertEqual(alpha, 255); } else { XCTAssertLessThan(alpha, 255); } } } } - (void)testSetFlutterViewControllerAfterCreateCanStillDispatchTouchEvents { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); // Find touch inteceptor view UIView* touchInteceptorView = gMockPlatformView; while (touchInteceptorView != nil && ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { touchInteceptorView = touchInteceptorView.superview; } XCTAssertNotNil(touchInteceptorView); // Find ForwardGestureRecognizer UIGestureRecognizer* forwardGectureRecognizer = nil; for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { if ([gestureRecognizer isKindOfClass:NSClassFromString(@"ForwardingGestureRecognizer")]) { forwardGectureRecognizer = gestureRecognizer; break; } } // Before setting flutter view controller, events are not dispatched. NSSet* touches1 = [[NSSet alloc] init]; id event1 = OCMClassMock([UIEvent class]); id mockFlutterViewContoller = OCMClassMock([FlutterViewController class]); [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; OCMReject([mockFlutterViewContoller touchesBegan:touches1 withEvent:event1]); // Set flutter view controller allows events to be dispatched. NSSet* touches2 = [[NSSet alloc] init]; id event2 = OCMClassMock([UIEvent class]); flutterPlatformViewsController->SetFlutterViewController(mockFlutterViewContoller); [forwardGectureRecognizer touchesBegan:touches2 withEvent:event2]; OCMVerify([mockFlutterViewContoller touchesBegan:touches2 withEvent:event2]); } - (void)testSetFlutterViewControllerInTheMiddleOfTouchEventShouldStillAllowGesturesToBeHandled { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); // Find touch inteceptor view UIView* touchInteceptorView = gMockPlatformView; while (touchInteceptorView != nil && ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { touchInteceptorView = touchInteceptorView.superview; } XCTAssertNotNil(touchInteceptorView); // Find ForwardGestureRecognizer UIGestureRecognizer* forwardGectureRecognizer = nil; for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { if ([gestureRecognizer isKindOfClass:NSClassFromString(@"ForwardingGestureRecognizer")]) { forwardGectureRecognizer = gestureRecognizer; break; } } id mockFlutterViewContoller = OCMClassMock([FlutterViewController class]); { // ***** Sequence 1, finishing touch event with touchEnded ***** // flutterPlatformViewsController->SetFlutterViewController(mockFlutterViewContoller); NSSet* touches1 = [[NSSet alloc] init]; id event1 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; OCMVerify([mockFlutterViewContoller touchesBegan:touches1 withEvent:event1]); flutterPlatformViewsController->SetFlutterViewController(nil); // Allow the touch events to finish NSSet* touches2 = [[NSSet alloc] init]; id event2 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesMoved:touches2 withEvent:event2]; OCMVerify([mockFlutterViewContoller touchesMoved:touches2 withEvent:event2]); NSSet* touches3 = [[NSSet alloc] init]; id event3 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesEnded:touches3 withEvent:event3]; OCMVerify([mockFlutterViewContoller touchesEnded:touches3 withEvent:event3]); // Now the 2nd touch sequence should not be allowed. NSSet* touches4 = [[NSSet alloc] init]; id event4 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesBegan:touches4 withEvent:event4]; OCMReject([mockFlutterViewContoller touchesBegan:touches4 withEvent:event4]); NSSet* touches5 = [[NSSet alloc] init]; id event5 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesEnded:touches5 withEvent:event5]; OCMReject([mockFlutterViewContoller touchesEnded:touches5 withEvent:event5]); } { // ***** Sequence 2, finishing touch event with touchCancelled ***** // flutterPlatformViewsController->SetFlutterViewController(mockFlutterViewContoller); NSSet* touches1 = [[NSSet alloc] init]; id event1 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; OCMVerify([mockFlutterViewContoller touchesBegan:touches1 withEvent:event1]); flutterPlatformViewsController->SetFlutterViewController(nil); // Allow the touch events to finish NSSet* touches2 = [[NSSet alloc] init]; id event2 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesMoved:touches2 withEvent:event2]; OCMVerify([mockFlutterViewContoller touchesMoved:touches2 withEvent:event2]); NSSet* touches3 = [[NSSet alloc] init]; id event3 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesCancelled:touches3 withEvent:event3]; OCMVerify([mockFlutterViewContoller forceTouchesCancelled:touches3]); // Now the 2nd touch sequence should not be allowed. NSSet* touches4 = [[NSSet alloc] init]; id event4 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesBegan:touches4 withEvent:event4]; OCMReject([mockFlutterViewContoller touchesBegan:touches4 withEvent:event4]); NSSet* touches5 = [[NSSet alloc] init]; id event5 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesEnded:touches5 withEvent:event5]; OCMReject([mockFlutterViewContoller touchesEnded:touches5 withEvent:event5]); } flutterPlatformViewsController->Reset(); } - (void) testSetFlutterViewControllerInTheMiddleOfTouchEventAllowsTheNewControllerToHandleSecondTouchSequence { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); // Find touch inteceptor view UIView* touchInteceptorView = gMockPlatformView; while (touchInteceptorView != nil && ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { touchInteceptorView = touchInteceptorView.superview; } XCTAssertNotNil(touchInteceptorView); // Find ForwardGestureRecognizer UIGestureRecognizer* forwardGectureRecognizer = nil; for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { if ([gestureRecognizer isKindOfClass:NSClassFromString(@"ForwardingGestureRecognizer")]) { forwardGectureRecognizer = gestureRecognizer; break; } } id mockFlutterViewContoller = OCMClassMock([FlutterViewController class]); flutterPlatformViewsController->SetFlutterViewController(mockFlutterViewContoller); // The touches in this sequence requires 1 touch object, we always create the NSSet with one item. NSSet* touches1 = [NSSet setWithObject:@1]; id event1 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; OCMVerify([mockFlutterViewContoller touchesBegan:touches1 withEvent:event1]); UIViewController* mockFlutterViewContoller2 = OCMClassMock([UIViewController class]); flutterPlatformViewsController->SetFlutterViewController(mockFlutterViewContoller2); // Touch events should still send to the old FlutterViewController if FlutterViewController // is updated in between. NSSet* touches2 = [NSSet setWithObject:@1]; id event2 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesBegan:touches2 withEvent:event2]; OCMVerify([mockFlutterViewContoller touchesBegan:touches2 withEvent:event2]); OCMReject([mockFlutterViewContoller2 touchesBegan:touches2 withEvent:event2]); NSSet* touches3 = [NSSet setWithObject:@1]; id event3 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesMoved:touches3 withEvent:event3]; OCMVerify([mockFlutterViewContoller touchesMoved:touches3 withEvent:event3]); OCMReject([mockFlutterViewContoller2 touchesMoved:touches3 withEvent:event3]); NSSet* touches4 = [NSSet setWithObject:@1]; id event4 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesEnded:touches4 withEvent:event4]; OCMVerify([mockFlutterViewContoller touchesEnded:touches4 withEvent:event4]); OCMReject([mockFlutterViewContoller2 touchesEnded:touches4 withEvent:event4]); NSSet* touches5 = [NSSet setWithObject:@1]; id event5 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesEnded:touches5 withEvent:event5]; OCMVerify([mockFlutterViewContoller touchesEnded:touches5 withEvent:event5]); OCMReject([mockFlutterViewContoller2 touchesEnded:touches5 withEvent:event5]); // Now the 2nd touch sequence should go to the new FlutterViewController NSSet* touches6 = [NSSet setWithObject:@1]; id event6 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesBegan:touches6 withEvent:event6]; OCMVerify([mockFlutterViewContoller2 touchesBegan:touches6 withEvent:event6]); OCMReject([mockFlutterViewContoller touchesBegan:touches6 withEvent:event6]); // Allow the touch events to finish NSSet* touches7 = [NSSet setWithObject:@1]; id event7 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesMoved:touches7 withEvent:event7]; OCMVerify([mockFlutterViewContoller2 touchesMoved:touches7 withEvent:event7]); OCMReject([mockFlutterViewContoller touchesMoved:touches7 withEvent:event7]); NSSet* touches8 = [NSSet setWithObject:@1]; id event8 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesEnded:touches8 withEvent:event8]; OCMVerify([mockFlutterViewContoller2 touchesEnded:touches8 withEvent:event8]); OCMReject([mockFlutterViewContoller touchesEnded:touches8 withEvent:event8]); flutterPlatformViewsController->Reset(); } - (void)testFlutterPlatformViewTouchesCancelledEventAreForcedToBeCancelled { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); // Find touch inteceptor view UIView* touchInteceptorView = gMockPlatformView; while (touchInteceptorView != nil && ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { touchInteceptorView = touchInteceptorView.superview; } XCTAssertNotNil(touchInteceptorView); // Find ForwardGestureRecognizer UIGestureRecognizer* forwardGectureRecognizer = nil; for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { if ([gestureRecognizer isKindOfClass:NSClassFromString(@"ForwardingGestureRecognizer")]) { forwardGectureRecognizer = gestureRecognizer; break; } } id mockFlutterViewContoller = OCMClassMock([FlutterViewController class]); flutterPlatformViewsController->SetFlutterViewController(mockFlutterViewContoller); NSSet* touches1 = [NSSet setWithObject:@1]; id event1 = OCMClassMock([UIEvent class]); [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; [forwardGectureRecognizer touchesCancelled:touches1 withEvent:event1]; OCMVerify([mockFlutterViewContoller forceTouchesCancelled:touches1]); flutterPlatformViewsController->Reset(); } - (void)testFlutterPlatformViewControllerSubmitFrameWithoutFlutterViewNotCrashing { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); // Create embedded view params flutter::MutatorsStack stack; SkMatrix finalMatrix; auto embeddedViewParams_1 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams_1)); flutterPlatformViewsController->CompositeEmbeddedView(2); flutter::SurfaceFrame::FramebufferInfo framebuffer_info; auto mock_surface = std::make_unique<flutter::SurfaceFrame>( nullptr, framebuffer_info, [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return false; }, /*frame_size=*/SkISize::Make(800, 600)); XCTAssertFalse( flutterPlatformViewsController->SubmitFrame(nullptr, nullptr, std::move(mock_surface))); auto embeddedViewParams_2 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams_2)); flutterPlatformViewsController->CompositeEmbeddedView(2); auto mock_surface_submit_true = std::make_unique<flutter::SurfaceFrame>( nullptr, framebuffer_info, [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, /*frame_size=*/SkISize::Make(800, 600)); XCTAssertTrue(flutterPlatformViewsController->SubmitFrame(nullptr, nullptr, std::move(mock_surface_submit_true))); } - (void) testFlutterPlatformViewControllerResetDeallocsPlatformViewWhenRootViewsNotBindedToFlutterView { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; // autorelease pool to trigger an autorelease for all the root_views_ and touch_interceptors_. @autoreleasepool { flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); flutter::MutatorsStack stack; SkMatrix finalMatrix; auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); // Not calling |flutterPlatformViewsController::SubmitFrame| so that the platform views are not // added to flutter_view_. XCTAssertNotNil(gMockPlatformView); flutterPlatformViewsController->Reset(); } XCTAssertNil(gMockPlatformView); } - (void)testFlutterPlatformViewControllerBeginFrameShouldResetCompisitionOrder { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @0, @"viewType" : @"MockFlutterPlatformView"}], result); // First frame, |EmbeddedViewCount| is not empty after composite. flutterPlatformViewsController->BeginFrame(SkISize::Make(300, 300)); flutter::MutatorsStack stack; SkMatrix finalMatrix; auto embeddedViewParams1 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(0, std::move(embeddedViewParams1)); flutterPlatformViewsController->CompositeEmbeddedView(0); XCTAssertEqual(flutterPlatformViewsController->EmbeddedViewCount(), 1UL); // Second frame, |EmbeddedViewCount| should be empty at the start flutterPlatformViewsController->BeginFrame(SkISize::Make(300, 300)); XCTAssertEqual(flutterPlatformViewsController->EmbeddedViewCount(), 0UL); auto embeddedViewParams2 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(0, std::move(embeddedViewParams2)); flutterPlatformViewsController->CompositeEmbeddedView(0); XCTAssertEqual(flutterPlatformViewsController->EmbeddedViewCount(), 1UL); } - (void) testFlutterPlatformViewControllerSubmitFrameShouldOrderSubviewsCorrectlyWithDifferentViewHierarchy { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @0, @"viewType" : @"MockFlutterPlatformView"}], result); UIView* view1 = gMockPlatformView; // This overwrites `gMockPlatformView` to another view. flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @1, @"viewType" : @"MockFlutterPlatformView"}], result); UIView* view2 = gMockPlatformView; flutterPlatformViewsController->BeginFrame(SkISize::Make(300, 300)); flutter::MutatorsStack stack; SkMatrix finalMatrix; auto embeddedViewParams1 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(0, std::move(embeddedViewParams1)); flutterPlatformViewsController->CompositeEmbeddedView(0); auto embeddedViewParams2 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(500, 500), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(1, std::move(embeddedViewParams2)); flutterPlatformViewsController->CompositeEmbeddedView(1); // SKSurface is required if the root FlutterView is present. const SkImageInfo image_info = SkImageInfo::MakeN32Premul(1000, 1000); sk_sp<SkSurface> mock_sk_surface = SkSurfaces::Raster(image_info); flutter::SurfaceFrame::FramebufferInfo framebuffer_info; auto mock_surface = std::make_unique<flutter::SurfaceFrame>( std::move(mock_sk_surface), framebuffer_info, [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, /*frame_size=*/SkISize::Make(800, 600)); XCTAssertTrue( flutterPlatformViewsController->SubmitFrame(nullptr, nullptr, std::move(mock_surface))); // platform view is wrapped by touch interceptor, which itself is wrapped by clipping view. UIView* clippingView1 = view1.superview.superview; UIView* clippingView2 = view2.superview.superview; UIView* flutterView = clippingView1.superview; XCTAssertTrue([flutterView.subviews indexOfObject:clippingView1] < [flutterView.subviews indexOfObject:clippingView2], @"The first clipping view should be added before the second clipping view."); // Need to recreate these params since they are `std::move`ed. flutterPlatformViewsController->BeginFrame(SkISize::Make(300, 300)); // Process the second frame in the opposite order. embeddedViewParams2 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(500, 500), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(1, std::move(embeddedViewParams2)); flutterPlatformViewsController->CompositeEmbeddedView(1); embeddedViewParams1 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(0, std::move(embeddedViewParams1)); flutterPlatformViewsController->CompositeEmbeddedView(0); mock_sk_surface = SkSurfaces::Raster(image_info); mock_surface = std::make_unique<flutter::SurfaceFrame>( std::move(mock_sk_surface), framebuffer_info, [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, /*frame_size=*/SkISize::Make(800, 600)); XCTAssertTrue( flutterPlatformViewsController->SubmitFrame(nullptr, nullptr, std::move(mock_surface))); XCTAssertTrue([flutterView.subviews indexOfObject:clippingView1] > [flutterView.subviews indexOfObject:clippingView2], @"The first clipping view should be added after the second clipping view."); } - (void) testFlutterPlatformViewControllerSubmitFrameShouldOrderSubviewsCorrectlyWithSameViewHierarchy { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @0, @"viewType" : @"MockFlutterPlatformView"}], result); UIView* view1 = gMockPlatformView; // This overwrites `gMockPlatformView` to another view. flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @1, @"viewType" : @"MockFlutterPlatformView"}], result); UIView* view2 = gMockPlatformView; flutterPlatformViewsController->BeginFrame(SkISize::Make(300, 300)); flutter::MutatorsStack stack; SkMatrix finalMatrix; auto embeddedViewParams1 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(0, std::move(embeddedViewParams1)); flutterPlatformViewsController->CompositeEmbeddedView(0); auto embeddedViewParams2 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(500, 500), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(1, std::move(embeddedViewParams2)); flutterPlatformViewsController->CompositeEmbeddedView(1); // SKSurface is required if the root FlutterView is present. const SkImageInfo image_info = SkImageInfo::MakeN32Premul(1000, 1000); sk_sp<SkSurface> mock_sk_surface = SkSurfaces::Raster(image_info); flutter::SurfaceFrame::FramebufferInfo framebuffer_info; auto mock_surface = std::make_unique<flutter::SurfaceFrame>( std::move(mock_sk_surface), framebuffer_info, [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, /*frame_size=*/SkISize::Make(800, 600)); XCTAssertTrue( flutterPlatformViewsController->SubmitFrame(nullptr, nullptr, std::move(mock_surface))); // platform view is wrapped by touch interceptor, which itself is wrapped by clipping view. UIView* clippingView1 = view1.superview.superview; UIView* clippingView2 = view2.superview.superview; UIView* flutterView = clippingView1.superview; XCTAssertTrue([flutterView.subviews indexOfObject:clippingView1] < [flutterView.subviews indexOfObject:clippingView2], @"The first clipping view should be added before the second clipping view."); // Need to recreate these params since they are `std::move`ed. flutterPlatformViewsController->BeginFrame(SkISize::Make(300, 300)); // Process the second frame in the same order. embeddedViewParams1 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(0, std::move(embeddedViewParams1)); flutterPlatformViewsController->CompositeEmbeddedView(0); embeddedViewParams2 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(500, 500), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(1, std::move(embeddedViewParams2)); flutterPlatformViewsController->CompositeEmbeddedView(1); mock_sk_surface = SkSurfaces::Raster(image_info); mock_surface = std::make_unique<flutter::SurfaceFrame>( std::move(mock_sk_surface), framebuffer_info, [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, /*frame_size=*/SkISize::Make(800, 600)); XCTAssertTrue( flutterPlatformViewsController->SubmitFrame(nullptr, nullptr, std::move(mock_surface))); XCTAssertTrue([flutterView.subviews indexOfObject:clippingView1] < [flutterView.subviews indexOfObject:clippingView2], @"The first clipping view should be added before the second clipping view."); } - (void)testThreadMergeAtEndFrame { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner_platform = CreateNewThread("FlutterPlatformViewsTest1"); auto thread_task_runner_other = CreateNewThread("FlutterPlatformViewsTest2"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner_platform, /*raster=*/thread_task_runner_other, /*ui=*/thread_task_runner_other, /*io=*/thread_task_runner_other); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); XCTestExpectation* waitForPlatformView = [self expectationWithDescription:@"wait for platform view to be created"]; FlutterResult result = ^(id result) { [waitForPlatformView fulfill]; }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); [self waitForExpectations:@[ waitForPlatformView ] timeout:30]; XCTAssertNotNil(gMockPlatformView); flutterPlatformViewsController->BeginFrame(SkISize::Make(300, 300)); SkMatrix finalMatrix; flutter::MutatorsStack stack; auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger = fml::MakeRefCounted<fml::RasterThreadMerger>(thread_task_runner_platform->GetTaskQueueId(), thread_task_runner_other->GetTaskQueueId()); XCTAssertEqual(flutterPlatformViewsController->PostPrerollAction(raster_thread_merger), flutter::PostPrerollResult::kSkipAndRetryFrame); XCTAssertFalse(raster_thread_merger->IsMerged()); flutterPlatformViewsController->EndFrame(true, raster_thread_merger); XCTAssertTrue(raster_thread_merger->IsMerged()); // Unmerge threads before the end of the test // TaskRunners are required to be unmerged before destruction. while (raster_thread_merger->DecrementLease() != fml::RasterThreadStatus::kUnmergedNow) { } } - (int)alphaOfPoint:(CGPoint)point onView:(UIView*)view { unsigned char pixel[4] = {0}; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // Draw the pixel on `point` in the context. CGContextRef context = CGBitmapContextCreate( pixel, 1, 1, 8, 4, colorSpace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast); CGContextTranslateCTM(context, -point.x, -point.y); [view.layer renderInContext:context]; CGContextRelease(context); CGColorSpaceRelease(colorSpace); // Get the alpha from the pixel that we just rendered. return pixel[3]; } - (void)testHasFirstResponderInViewHierarchySubtree_viewItselfBecomesFirstResponder { // For view to become the first responder, it must be a descendant of a UIWindow UIWindow* window = [[UIWindow alloc] init]; UITextField* textField = [[UITextField alloc] init]; [window addSubview:textField]; [textField becomeFirstResponder]; XCTAssertTrue(textField.isFirstResponder); XCTAssertTrue(textField.flt_hasFirstResponderInViewHierarchySubtree); [textField resignFirstResponder]; XCTAssertFalse(textField.isFirstResponder); XCTAssertFalse(textField.flt_hasFirstResponderInViewHierarchySubtree); } - (void)testHasFirstResponderInViewHierarchySubtree_descendantViewBecomesFirstResponder { // For view to become the first responder, it must be a descendant of a UIWindow UIWindow* window = [[UIWindow alloc] init]; UIView* view = [[UIView alloc] init]; UIView* childView = [[UIView alloc] init]; UITextField* textField = [[UITextField alloc] init]; [window addSubview:view]; [view addSubview:childView]; [childView addSubview:textField]; [textField becomeFirstResponder]; XCTAssertTrue(textField.isFirstResponder); XCTAssertTrue(view.flt_hasFirstResponderInViewHierarchySubtree); [textField resignFirstResponder]; XCTAssertFalse(textField.isFirstResponder); XCTAssertFalse(view.flt_hasFirstResponderInViewHierarchySubtree); } - (void)testFlutterClippingMaskViewPoolReuseViewsAfterRecycle { FlutterClippingMaskViewPool* pool = [[FlutterClippingMaskViewPool alloc] initWithCapacity:2]; FlutterClippingMaskView* view1 = [pool getMaskViewWithFrame:CGRectZero]; FlutterClippingMaskView* view2 = [pool getMaskViewWithFrame:CGRectZero]; [pool insertViewToPoolIfNeeded:view1]; [pool insertViewToPoolIfNeeded:view2]; CGRect newRect = CGRectMake(0, 0, 10, 10); FlutterClippingMaskView* view3 = [pool getMaskViewWithFrame:newRect]; FlutterClippingMaskView* view4 = [pool getMaskViewWithFrame:newRect]; // view3 and view4 should randomly get either of view1 and view2. NSSet* set1 = [NSSet setWithObjects:view1, view2, nil]; NSSet* set2 = [NSSet setWithObjects:view3, view4, nil]; XCTAssertEqualObjects(set1, set2); XCTAssertTrue(CGRectEqualToRect(view3.frame, newRect)); XCTAssertTrue(CGRectEqualToRect(view4.frame, newRect)); } - (void)testFlutterClippingMaskViewPoolAllocsNewMaskViewsAfterReachingCapacity { FlutterClippingMaskViewPool* pool = [[FlutterClippingMaskViewPool alloc] initWithCapacity:2]; FlutterClippingMaskView* view1 = [pool getMaskViewWithFrame:CGRectZero]; FlutterClippingMaskView* view2 = [pool getMaskViewWithFrame:CGRectZero]; FlutterClippingMaskView* view3 = [pool getMaskViewWithFrame:CGRectZero]; XCTAssertNotEqual(view1, view3); XCTAssertNotEqual(view2, view3); } - (void)testMaskViewsReleasedWhenPoolIsReleased { __weak UIView* weakView; @autoreleasepool { FlutterClippingMaskViewPool* pool = [[FlutterClippingMaskViewPool alloc] initWithCapacity:2]; FlutterClippingMaskView* view = [pool getMaskViewWithFrame:CGRectZero]; weakView = view; XCTAssertNotNil(weakView); } XCTAssertNil(weakView); } - (void)testClipMaskViewIsReused { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @1, @"viewType" : @"MockFlutterPlatformView"}], result); XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack1; // Layer tree always pushes a screen scale factor to the stack SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack1.PushTransform(screenScaleMatrix); // Push a clip rect SkRect rect = SkRect::MakeXYWH(2, 2, 3, 3); stack1.PushClipRect(rect); auto embeddedViewParams1 = std::make_unique<flutter::EmbeddedViewParams>( screenScaleMatrix, SkSize::Make(10, 10), stack1); flutterPlatformViewsController->PrerollCompositeEmbeddedView(1, std::move(embeddedViewParams1)); flutterPlatformViewsController->CompositeEmbeddedView(1); UIView* childClippingView1 = gMockPlatformView.superview.superview; UIView* maskView1 = childClippingView1.maskView; XCTAssertNotNil(maskView1); // Composite a new frame. flutterPlatformViewsController->BeginFrame(SkISize::Make(100, 100)); flutter::MutatorsStack stack2; auto embeddedViewParams2 = std::make_unique<flutter::EmbeddedViewParams>( screenScaleMatrix, SkSize::Make(10, 10), stack2); auto embeddedViewParams3 = std::make_unique<flutter::EmbeddedViewParams>( screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(1, std::move(embeddedViewParams3)); flutterPlatformViewsController->CompositeEmbeddedView(1); childClippingView1 = gMockPlatformView.superview.superview; // This overrides gMockPlatformView to point to the newly created platform view. flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); auto embeddedViewParams4 = std::make_unique<flutter::EmbeddedViewParams>( screenScaleMatrix, SkSize::Make(10, 10), stack1); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams4)); flutterPlatformViewsController->CompositeEmbeddedView(2); UIView* childClippingView2 = gMockPlatformView.superview.superview; UIView* maskView2 = childClippingView2.maskView; XCTAssertEqual(maskView1, maskView2); XCTAssertNotNil(childClippingView2.maskView); XCTAssertNil(childClippingView1.maskView); } - (void)testDifferentClipMaskViewIsUsedForEachView { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @1, @"viewType" : @"MockFlutterPlatformView"}], result); UIView* view1 = gMockPlatformView; // This overwrites `gMockPlatformView` to another view. flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); UIView* view2 = gMockPlatformView; XCTAssertNotNil(gMockPlatformView); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack1; // Layer tree always pushes a screen scale factor to the stack SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack1.PushTransform(screenScaleMatrix); // Push a clip rect SkRect rect = SkRect::MakeXYWH(2, 2, 3, 3); stack1.PushClipRect(rect); auto embeddedViewParams1 = std::make_unique<flutter::EmbeddedViewParams>( screenScaleMatrix, SkSize::Make(10, 10), stack1); flutter::MutatorsStack stack2; stack2.PushClipRect(rect); auto embeddedViewParams2 = std::make_unique<flutter::EmbeddedViewParams>( screenScaleMatrix, SkSize::Make(10, 10), stack2); flutterPlatformViewsController->PrerollCompositeEmbeddedView(1, std::move(embeddedViewParams1)); flutterPlatformViewsController->CompositeEmbeddedView(1); UIView* childClippingView1 = view1.superview.superview; flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams2)); flutterPlatformViewsController->CompositeEmbeddedView(2); UIView* childClippingView2 = view2.superview.superview; UIView* maskView1 = childClippingView1.maskView; UIView* maskView2 = childClippingView2.maskView; XCTAssertNotEqual(maskView1, maskView2); } // Return true if a correct visual effect view is found. It also implies all the validation in this // method passes. // // There are two fail states for this method. 1. One of the XCTAssert method failed; or 2. No // correct visual effect view found. - (BOOL)validateOneVisualEffectView:(UIView*)visualEffectView expectedFrame:(CGRect)frame inputRadius:(CGFloat)inputRadius { XCTAssertTrue(CGRectEqualToRect(visualEffectView.frame, frame)); for (UIView* view in visualEffectView.subviews) { if (![NSStringFromClass([view class]) hasSuffix:@"BackdropView"]) { continue; } XCTAssertEqual(view.layer.filters.count, 1u); NSObject* filter = view.layer.filters.firstObject; XCTAssertEqualObjects([filter valueForKey:@"name"], @"gaussianBlur"); NSObject* inputRadiusInFilter = [filter valueForKey:@"inputRadius"]; XCTAssertTrue([inputRadiusInFilter isKindOfClass:[NSNumber class]] && flutter::BlurRadiusEqualToBlurRadius(((NSNumber*)inputRadiusInFilter).floatValue, inputRadius)); return YES; } return NO; } - (void)testDisposingViewInCompositionOrderDoNotCrash { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @0, @"viewType" : @"MockFlutterPlatformView"}], result); flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @1, @"viewType" : @"MockFlutterPlatformView"}], result); { // **** First frame, view id 0, 1 in the composition_order_, disposing view 0 is called. **** // // No view should be disposed, or removed from the composition order. flutterPlatformViewsController->BeginFrame(SkISize::Make(300, 300)); flutter::MutatorsStack stack; SkMatrix finalMatrix; auto embeddedViewParams0 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(0, std::move(embeddedViewParams0)); flutterPlatformViewsController->CompositeEmbeddedView(0); auto embeddedViewParams1 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(1, std::move(embeddedViewParams1)); flutterPlatformViewsController->CompositeEmbeddedView(1); XCTAssertEqual(flutterPlatformViewsController->EmbeddedViewCount(), 2UL); XCTestExpectation* expectation = [self expectationWithDescription:@"dispose call ended."]; FlutterResult disposeResult = ^(id result) { [expectation fulfill]; }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"dispose" arguments:@0], disposeResult); [self waitForExpectationsWithTimeout:30 handler:nil]; const SkImageInfo image_info = SkImageInfo::MakeN32Premul(1000, 1000); sk_sp<SkSurface> mock_sk_surface = SkSurfaces::Raster(image_info); flutter::SurfaceFrame::FramebufferInfo framebuffer_info; auto mock_surface = std::make_unique<flutter::SurfaceFrame>( std::move(mock_sk_surface), framebuffer_info, [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, /*frame_size=*/SkISize::Make(800, 600)); XCTAssertTrue( flutterPlatformViewsController->SubmitFrame(nullptr, nullptr, std::move(mock_surface))); // Disposing won't remove embedded views until the view is removed from the composition_order_ XCTAssertEqual(flutterPlatformViewsController->EmbeddedViewCount(), 2UL); XCTAssertNotNil(flutterPlatformViewsController->GetPlatformViewByID(0)); XCTAssertNotNil(flutterPlatformViewsController->GetPlatformViewByID(1)); } { // **** Second frame, view id 1 in the composition_order_, no disposing view is called, **** // // View 0 is removed from the composition order in this frame, hence also disposed. flutterPlatformViewsController->BeginFrame(SkISize::Make(300, 300)); flutter::MutatorsStack stack; SkMatrix finalMatrix; auto embeddedViewParams1 = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(1, std::move(embeddedViewParams1)); flutterPlatformViewsController->CompositeEmbeddedView(1); const SkImageInfo image_info = SkImageInfo::MakeN32Premul(1000, 1000); sk_sp<SkSurface> mock_sk_surface = SkSurfaces::Raster(image_info); flutter::SurfaceFrame::FramebufferInfo framebuffer_info; auto mock_surface = std::make_unique<flutter::SurfaceFrame>( std::move(mock_sk_surface), framebuffer_info, [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, /*frame_size=*/SkISize::Make(800, 600)); XCTAssertTrue( flutterPlatformViewsController->SubmitFrame(nullptr, nullptr, std::move(mock_surface))); // Disposing won't remove embedded views until the view is removed from the composition_order_ XCTAssertEqual(flutterPlatformViewsController->EmbeddedViewCount(), 1UL); XCTAssertNil(flutterPlatformViewsController->GetPlatformViewByID(0)); XCTAssertNotNil(flutterPlatformViewsController->GetPlatformViewByID(1)); } } - (void)testOnlyPlatformViewsAreRemovedWhenReset { flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; auto thread_task_runner = CreateNewThread("FlutterPlatformViewsTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_jsync_switch=*/std::make_shared<fml::SyncSwitch>()); FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); UIView* mockFlutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; flutterPlatformViewsController->SetFlutterView(mockFlutterView); // Create embedded view params flutter::MutatorsStack stack; // Layer tree always pushes a screen scale factor to the stack SkMatrix screenScaleMatrix = SkMatrix::Scale([UIScreen mainScreen].scale, [UIScreen mainScreen].scale); stack.PushTransform(screenScaleMatrix); // Push a translate matrix SkMatrix translateMatrix = SkMatrix::Translate(100, 100); stack.PushTransform(translateMatrix); SkMatrix finalMatrix; finalMatrix.setConcat(screenScaleMatrix, translateMatrix); auto embeddedViewParams = std::make_unique<flutter::EmbeddedViewParams>(finalMatrix, SkSize::Make(300, 300), stack); flutterPlatformViewsController->PrerollCompositeEmbeddedView(2, std::move(embeddedViewParams)); flutterPlatformViewsController->CompositeEmbeddedView(2); // SKSurface is required if the root FlutterView is present. const SkImageInfo image_info = SkImageInfo::MakeN32Premul(1000, 1000); sk_sp<SkSurface> mock_sk_surface = SkSurfaces::Raster(image_info); flutter::SurfaceFrame::FramebufferInfo framebuffer_info; auto mock_surface = std::make_unique<flutter::SurfaceFrame>( std::move(mock_sk_surface), framebuffer_info, [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, /*frame_size=*/SkISize::Make(800, 600)); flutterPlatformViewsController->SubmitFrame(nullptr, nullptr, std::move(mock_surface)); UIView* someView = [[UIView alloc] init]; [mockFlutterView addSubview:someView]; flutterPlatformViewsController->Reset(); XCTAssertEqual(mockFlutterView.subviews.count, 1u); XCTAssertEqual(mockFlutterView.subviews.firstObject, someView); } - (void)testFlutterTouchInterceptingViewLinksToAccessibilityContainer { FlutterTouchInterceptingView* touchInteceptorView = [[FlutterTouchInterceptingView alloc] init]; NSObject* container = [[NSObject alloc] init]; [touchInteceptorView setFlutterAccessibilityContainer:container]; XCTAssertEqualObjects([touchInteceptorView accessibilityContainer], container); } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsTest.mm", "repo_id": "engine", "token_count": 56534 }
320
// 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 "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #include "unicode/uchar.h" #include "flutter/fml/logging.h" #include "flutter/fml/platform/darwin/string_range_sanitization.h" FLUTTER_ASSERT_ARC static const char kTextAffinityDownstream[] = "TextAffinity.downstream"; static const char kTextAffinityUpstream[] = "TextAffinity.upstream"; // A delay before enabling the accessibility of FlutterTextInputView after // it is activated. static constexpr double kUITextInputAccessibilityEnablingDelaySeconds = 0.5; // A delay before reenabling the UIView areAnimationsEnabled to YES // in order for becomeFirstResponder to receive the proper value. static const NSTimeInterval kKeyboardAnimationDelaySeconds = 0.1; // A time set for the screenshot to animate back to the assigned position. static const NSTimeInterval kKeyboardAnimationTimeToCompleteion = 0.3; // The "canonical" invalid CGRect, similar to CGRectNull, used to // indicate a CGRect involved in firstRectForRange calculation is // invalid. The specific value is chosen so that if firstRectForRange // returns kInvalidFirstRect, iOS will not show the IME candidates view. const CGRect kInvalidFirstRect = {{-1, -1}, {9999, 9999}}; #pragma mark - TextInput channel method names. // See https://api.flutter.dev/flutter/services/SystemChannels/textInput-constant.html static NSString* const kShowMethod = @"TextInput.show"; static NSString* const kHideMethod = @"TextInput.hide"; static NSString* const kSetClientMethod = @"TextInput.setClient"; static NSString* const kSetPlatformViewClientMethod = @"TextInput.setPlatformViewClient"; static NSString* const kSetEditingStateMethod = @"TextInput.setEditingState"; static NSString* const kClearClientMethod = @"TextInput.clearClient"; static NSString* const kSetEditableSizeAndTransformMethod = @"TextInput.setEditableSizeAndTransform"; static NSString* const kSetMarkedTextRectMethod = @"TextInput.setMarkedTextRect"; static NSString* const kFinishAutofillContextMethod = @"TextInput.finishAutofillContext"; // TODO(justinmc): Remove the TextInput method constant when the framework has // finished transitioning to using the Scribble channel. // https://github.com/flutter/flutter/pull/104128 static NSString* const kDeprecatedSetSelectionRectsMethod = @"TextInput.setSelectionRects"; static NSString* const kSetSelectionRectsMethod = @"Scribble.setSelectionRects"; static NSString* const kStartLiveTextInputMethod = @"TextInput.startLiveTextInput"; static NSString* const kUpdateConfigMethod = @"TextInput.updateConfig"; static NSString* const kOnInteractiveKeyboardPointerMoveMethod = @"TextInput.onPointerMoveForInteractiveKeyboard"; static NSString* const kOnInteractiveKeyboardPointerUpMethod = @"TextInput.onPointerUpForInteractiveKeyboard"; #pragma mark - TextInputConfiguration Field Names static NSString* const kSecureTextEntry = @"obscureText"; static NSString* const kKeyboardType = @"inputType"; static NSString* const kKeyboardAppearance = @"keyboardAppearance"; static NSString* const kInputAction = @"inputAction"; static NSString* const kEnableDeltaModel = @"enableDeltaModel"; static NSString* const kEnableInteractiveSelection = @"enableInteractiveSelection"; static NSString* const kSmartDashesType = @"smartDashesType"; static NSString* const kSmartQuotesType = @"smartQuotesType"; static NSString* const kAssociatedAutofillFields = @"fields"; // TextInputConfiguration.autofill and sub-field names static NSString* const kAutofillProperties = @"autofill"; static NSString* const kAutofillId = @"uniqueIdentifier"; static NSString* const kAutofillEditingValue = @"editingValue"; static NSString* const kAutofillHints = @"hints"; static NSString* const kAutocorrectionType = @"autocorrect"; #pragma mark - Static Functions // Determine if the character at `range` of `text` is an emoji. static BOOL IsEmoji(NSString* text, NSRange charRange) { UChar32 codePoint; BOOL gotCodePoint = [text getBytes:&codePoint maxLength:sizeof(codePoint) usedLength:NULL encoding:NSUTF32StringEncoding options:kNilOptions range:charRange remainingRange:NULL]; return gotCodePoint && u_hasBinaryProperty(codePoint, UCHAR_EMOJI); } // "TextInputType.none" is a made-up input type that's typically // used when there's an in-app virtual keyboard. If // "TextInputType.none" is specified, disable the system // keyboard. static BOOL ShouldShowSystemKeyboard(NSDictionary* type) { NSString* inputType = type[@"name"]; return ![inputType isEqualToString:@"TextInputType.none"]; } static UIKeyboardType ToUIKeyboardType(NSDictionary* type) { NSString* inputType = type[@"name"]; if ([inputType isEqualToString:@"TextInputType.address"]) { return UIKeyboardTypeDefault; } if ([inputType isEqualToString:@"TextInputType.datetime"]) { return UIKeyboardTypeNumbersAndPunctuation; } if ([inputType isEqualToString:@"TextInputType.emailAddress"]) { return UIKeyboardTypeEmailAddress; } if ([inputType isEqualToString:@"TextInputType.multiline"]) { return UIKeyboardTypeDefault; } if ([inputType isEqualToString:@"TextInputType.name"]) { return UIKeyboardTypeNamePhonePad; } if ([inputType isEqualToString:@"TextInputType.number"]) { if ([type[@"signed"] boolValue]) { return UIKeyboardTypeNumbersAndPunctuation; } if ([type[@"decimal"] boolValue]) { return UIKeyboardTypeDecimalPad; } return UIKeyboardTypeNumberPad; } if ([inputType isEqualToString:@"TextInputType.phone"]) { return UIKeyboardTypePhonePad; } if ([inputType isEqualToString:@"TextInputType.text"]) { return UIKeyboardTypeDefault; } if ([inputType isEqualToString:@"TextInputType.url"]) { return UIKeyboardTypeURL; } if ([inputType isEqualToString:@"TextInputType.visiblePassword"]) { return UIKeyboardTypeASCIICapable; } return UIKeyboardTypeDefault; } static UITextAutocapitalizationType ToUITextAutoCapitalizationType(NSDictionary* type) { NSString* textCapitalization = type[@"textCapitalization"]; if ([textCapitalization isEqualToString:@"TextCapitalization.characters"]) { return UITextAutocapitalizationTypeAllCharacters; } else if ([textCapitalization isEqualToString:@"TextCapitalization.sentences"]) { return UITextAutocapitalizationTypeSentences; } else if ([textCapitalization isEqualToString:@"TextCapitalization.words"]) { return UITextAutocapitalizationTypeWords; } return UITextAutocapitalizationTypeNone; } static UIReturnKeyType ToUIReturnKeyType(NSString* inputType) { // Where did the term "unspecified" come from? iOS has a "default" and Android // has "unspecified." These 2 terms seem to mean the same thing but we need // to pick just one. "unspecified" was chosen because "default" is often a // reserved word in languages with switch statements (dart, java, etc). if ([inputType isEqualToString:@"TextInputAction.unspecified"]) { return UIReturnKeyDefault; } if ([inputType isEqualToString:@"TextInputAction.done"]) { return UIReturnKeyDone; } if ([inputType isEqualToString:@"TextInputAction.go"]) { return UIReturnKeyGo; } if ([inputType isEqualToString:@"TextInputAction.send"]) { return UIReturnKeySend; } if ([inputType isEqualToString:@"TextInputAction.search"]) { return UIReturnKeySearch; } if ([inputType isEqualToString:@"TextInputAction.next"]) { return UIReturnKeyNext; } if ([inputType isEqualToString:@"TextInputAction.continueAction"]) { return UIReturnKeyContinue; } if ([inputType isEqualToString:@"TextInputAction.join"]) { return UIReturnKeyJoin; } if ([inputType isEqualToString:@"TextInputAction.route"]) { return UIReturnKeyRoute; } if ([inputType isEqualToString:@"TextInputAction.emergencyCall"]) { return UIReturnKeyEmergencyCall; } if ([inputType isEqualToString:@"TextInputAction.newline"]) { return UIReturnKeyDefault; } // Present default key if bad input type is given. return UIReturnKeyDefault; } static UITextContentType ToUITextContentType(NSArray<NSString*>* hints) { if (!hints || hints.count == 0) { // If no hints are specified, use the default content type nil. return nil; } NSString* hint = hints[0]; if ([hint isEqualToString:@"addressCityAndState"]) { return UITextContentTypeAddressCityAndState; } if ([hint isEqualToString:@"addressState"]) { return UITextContentTypeAddressState; } if ([hint isEqualToString:@"addressCity"]) { return UITextContentTypeAddressCity; } if ([hint isEqualToString:@"sublocality"]) { return UITextContentTypeSublocality; } if ([hint isEqualToString:@"streetAddressLine1"]) { return UITextContentTypeStreetAddressLine1; } if ([hint isEqualToString:@"streetAddressLine2"]) { return UITextContentTypeStreetAddressLine2; } if ([hint isEqualToString:@"countryName"]) { return UITextContentTypeCountryName; } if ([hint isEqualToString:@"fullStreetAddress"]) { return UITextContentTypeFullStreetAddress; } if ([hint isEqualToString:@"postalCode"]) { return UITextContentTypePostalCode; } if ([hint isEqualToString:@"location"]) { return UITextContentTypeLocation; } if ([hint isEqualToString:@"creditCardNumber"]) { return UITextContentTypeCreditCardNumber; } if ([hint isEqualToString:@"email"]) { return UITextContentTypeEmailAddress; } if ([hint isEqualToString:@"jobTitle"]) { return UITextContentTypeJobTitle; } if ([hint isEqualToString:@"givenName"]) { return UITextContentTypeGivenName; } if ([hint isEqualToString:@"middleName"]) { return UITextContentTypeMiddleName; } if ([hint isEqualToString:@"familyName"]) { return UITextContentTypeFamilyName; } if ([hint isEqualToString:@"name"]) { return UITextContentTypeName; } if ([hint isEqualToString:@"namePrefix"]) { return UITextContentTypeNamePrefix; } if ([hint isEqualToString:@"nameSuffix"]) { return UITextContentTypeNameSuffix; } if ([hint isEqualToString:@"nickname"]) { return UITextContentTypeNickname; } if ([hint isEqualToString:@"organizationName"]) { return UITextContentTypeOrganizationName; } if ([hint isEqualToString:@"telephoneNumber"]) { return UITextContentTypeTelephoneNumber; } if ([hint isEqualToString:@"password"]) { return UITextContentTypePassword; } if ([hint isEqualToString:@"oneTimeCode"]) { return UITextContentTypeOneTimeCode; } if ([hint isEqualToString:@"newPassword"]) { return UITextContentTypeNewPassword; } return hints[0]; } // Retrieves the autofillId from an input field's configuration. Returns // nil if the field is nil and the input field is not a password field. static NSString* AutofillIdFromDictionary(NSDictionary* dictionary) { NSDictionary* autofill = dictionary[kAutofillProperties]; if (autofill) { return autofill[kAutofillId]; } // When autofill is nil, the field may still need an autofill id // if the field is for password. return [dictionary[kSecureTextEntry] boolValue] ? @"password" : nil; } // # Autofill Implementation Notes: // // Currently there're 2 types of autofills on iOS: // - Regular autofill, including contact information and one-time-code, // takes place in the form of predictive text in the quick type bar. // This type of autofill does not save user input, and the keyboard // currently only populates the focused field when a predictive text entry // is selected by the user. // // - Password autofill, includes automatic strong password and regular // password autofill. The former happens automatically when a // "new password" field is detected and focused, and only that password // field will be populated. The latter appears in the quick type bar when // an eligible input field (which either has a UITextContentTypePassword // contentType, or is a secure text entry) becomes the first responder, and may // fill both the username and the password fields. iOS will attempt // to save user input for both kinds of password fields. It's relatively // tricky to deal with password autofill since it can autofill more than one // field at a time and may employ heuristics based on what other text fields // are in the same view controller. // // When a flutter text field is focused, and autofill is not explicitly disabled // for it ("autofillable"), the framework collects its attributes and checks if // it's in an AutofillGroup, and collects the attributes of other autofillable // text fields in the same AutofillGroup if so. The attributes are sent to the // text input plugin via a "TextInput.setClient" platform channel message. If // autofill is disabled for a text field, its "autofill" field will be nil in // the configuration json. // // The text input plugin then tries to determine which kind of autofill the text // field needs. If the AutofillGroup the text field belongs to contains an // autofillable text field that's password related, this text 's autofill type // will be kFlutterAutofillTypePassword. If autofill is disabled for a text field, // then its type will be kFlutterAutofillTypeNone. Otherwise the text field will // have an autofill type of kFlutterAutofillTypeRegular. // // The text input plugin creates a new UIView for every kFlutterAutofillTypeNone // text field. The UIView instance is never reused for other flutter text fields // since the software keyboard often uses the identity of a UIView to distinguish // different views and provides the same predictive text suggestions or restore // the composing region if a UIView is reused for a different flutter text field. // // The text input plugin creates a new "autofill context" if the text field has // the type of kFlutterAutofillTypePassword, to represent the AutofillGroup of // the text field, and creates one FlutterTextInputView for every text field in // the AutofillGroup. // // The text input plugin will try to reuse a UIView if a flutter text field's // type is kFlutterAutofillTypeRegular, and has the same autofill id. typedef NS_ENUM(NSInteger, FlutterAutofillType) { // The field does not have autofillable content. Additionally if // the field is currently in the autofill context, it will be // removed from the context without triggering autofill save. kFlutterAutofillTypeNone, kFlutterAutofillTypeRegular, kFlutterAutofillTypePassword, }; static BOOL IsFieldPasswordRelated(NSDictionary* configuration) { // Autofill is explicitly disabled if the id isn't present. if (!AutofillIdFromDictionary(configuration)) { return NO; } BOOL isSecureTextEntry = [configuration[kSecureTextEntry] boolValue]; if (isSecureTextEntry) { return YES; } NSDictionary* autofill = configuration[kAutofillProperties]; UITextContentType contentType = ToUITextContentType(autofill[kAutofillHints]); if ([contentType isEqualToString:UITextContentTypePassword] || [contentType isEqualToString:UITextContentTypeUsername]) { return YES; } if ([contentType isEqualToString:UITextContentTypeNewPassword]) { return YES; } return NO; } static FlutterAutofillType AutofillTypeOf(NSDictionary* configuration) { for (NSDictionary* field in configuration[kAssociatedAutofillFields]) { if (IsFieldPasswordRelated(field)) { return kFlutterAutofillTypePassword; } } if (IsFieldPasswordRelated(configuration)) { return kFlutterAutofillTypePassword; } NSDictionary* autofill = configuration[kAutofillProperties]; UITextContentType contentType = ToUITextContentType(autofill[kAutofillHints]); return !autofill || [contentType isEqualToString:@""] ? kFlutterAutofillTypeNone : kFlutterAutofillTypeRegular; } static BOOL IsApproximatelyEqual(float x, float y, float delta) { return fabsf(x - y) <= delta; } // This is a helper function for floating cursor selection logic to determine which text // position is closer to a point. // Checks whether point should be considered closer to selectionRect compared to // otherSelectionRect. // // If `useTrailingBoundaryOfSelectionRect` is not set, it uses the leading-center point // on selectionRect and otherSelectionRect to compare. // For left-to-right text, this means the left-center point, and for right-to-left text, // this means the right-center point. // // If useTrailingBoundaryOfSelectionRect is set, the trailing-center point on selectionRect // will be used instead of the leading-center point, while leading-center point is still used // for otherSelectionRect. // // This uses special (empirically determined using a 1st gen iPad pro, 9.7" model running // iOS 14.7.1) logic for determining the closer rect, rather than a simple distance calculation. // - First, the rect with closer y distance wins. // - Otherwise (same y distance): // - If the point is above bottom of the rect, the rect boundary with closer x distance wins. // - Otherwise (point is below bottom of the rect), the rect boundary with farthest x wins. // This is because when the point is below the bottom line of text, we want to select the // whole line of text, so we mark the farthest rect as closest. static BOOL IsSelectionRectBoundaryCloserToPoint(CGPoint point, CGRect selectionRect, BOOL selectionRectIsRTL, BOOL useTrailingBoundaryOfSelectionRect, CGRect otherSelectionRect, BOOL otherSelectionRectIsRTL, CGFloat verticalPrecision) { // The point is inside the selectionRect's corresponding half-rect area. if (CGRectContainsPoint( CGRectMake( selectionRect.origin.x + ((useTrailingBoundaryOfSelectionRect ^ selectionRectIsRTL) ? 0.5 * selectionRect.size.width : 0), selectionRect.origin.y, 0.5 * selectionRect.size.width, selectionRect.size.height), point)) { return YES; } // pointForSelectionRect is either leading-center or trailing-center point of selectionRect. CGPoint pointForSelectionRect = CGPointMake( selectionRect.origin.x + (selectionRectIsRTL ^ useTrailingBoundaryOfSelectionRect ? selectionRect.size.width : 0), selectionRect.origin.y + selectionRect.size.height * 0.5); float yDist = fabs(pointForSelectionRect.y - point.y); float xDist = fabs(pointForSelectionRect.x - point.x); // pointForOtherSelectionRect is the leading-center point of otherSelectionRect. CGPoint pointForOtherSelectionRect = CGPointMake( otherSelectionRect.origin.x + (otherSelectionRectIsRTL ? otherSelectionRect.size.width : 0), otherSelectionRect.origin.y + otherSelectionRect.size.height * 0.5); float yDistOther = fabs(pointForOtherSelectionRect.y - point.y); float xDistOther = fabs(pointForOtherSelectionRect.x - point.x); // This serves a similar purpose to IsApproximatelyEqual, allowing a little buffer before // declaring something closer vertically to account for the small variations in size and position // of SelectionRects, especially when dealing with emoji. BOOL isCloserVertically = yDist < yDistOther - verticalPrecision; BOOL isEqualVertically = IsApproximatelyEqual(yDist, yDistOther, verticalPrecision); BOOL isAboveBottomOfLine = point.y <= selectionRect.origin.y + selectionRect.size.height; BOOL isCloserHorizontally = xDist < xDistOther; BOOL isBelowBottomOfLine = point.y > selectionRect.origin.y + selectionRect.size.height; // Is "farther away", or is closer to the end of the text line. BOOL isFarther; if (selectionRectIsRTL) { isFarther = selectionRect.origin.x < otherSelectionRect.origin.x; } else { isFarther = selectionRect.origin.x + (useTrailingBoundaryOfSelectionRect ? selectionRect.size.width : 0) > otherSelectionRect.origin.x; } return (isCloserVertically || (isEqualVertically && ((isAboveBottomOfLine && isCloserHorizontally) || (isBelowBottomOfLine && isFarther)))); } #pragma mark - FlutterTextPosition @implementation FlutterTextPosition + (instancetype)positionWithIndex:(NSUInteger)index { return [[FlutterTextPosition alloc] initWithIndex:index affinity:UITextStorageDirectionForward]; } + (instancetype)positionWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity { return [[FlutterTextPosition alloc] initWithIndex:index affinity:affinity]; } - (instancetype)initWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity { self = [super init]; if (self) { _index = index; _affinity = affinity; } return self; } @end #pragma mark - FlutterTextRange @implementation FlutterTextRange + (instancetype)rangeWithNSRange:(NSRange)range { return [[FlutterTextRange alloc] initWithNSRange:range]; } - (instancetype)initWithNSRange:(NSRange)range { self = [super init]; if (self) { _range = range; } return self; } - (UITextPosition*)start { return [FlutterTextPosition positionWithIndex:self.range.location affinity:UITextStorageDirectionForward]; } - (UITextPosition*)end { return [FlutterTextPosition positionWithIndex:self.range.location + self.range.length affinity:UITextStorageDirectionBackward]; } - (BOOL)isEmpty { return self.range.length == 0; } - (id)copyWithZone:(NSZone*)zone { return [[FlutterTextRange allocWithZone:zone] initWithNSRange:self.range]; } - (BOOL)isEqualTo:(FlutterTextRange*)other { return NSEqualRanges(self.range, other.range); } @end #pragma mark - FlutterTokenizer @interface FlutterTokenizer () @property(nonatomic, weak) FlutterTextInputView* textInputView; @end @implementation FlutterTokenizer - (instancetype)initWithTextInput:(UIResponder<UITextInput>*)textInput { NSAssert([textInput isKindOfClass:[FlutterTextInputView class]], @"The FlutterTokenizer can only be used in a FlutterTextInputView"); self = [super initWithTextInput:textInput]; if (self) { _textInputView = (FlutterTextInputView*)textInput; } return self; } - (UITextRange*)rangeEnclosingPosition:(UITextPosition*)position withGranularity:(UITextGranularity)granularity inDirection:(UITextDirection)direction { UITextRange* result; switch (granularity) { case UITextGranularityLine: // The default UITextInputStringTokenizer does not handle line granularity // correctly. We need to implement our own line tokenizer. result = [self lineEnclosingPosition:position inDirection:direction]; break; case UITextGranularityCharacter: case UITextGranularityWord: case UITextGranularitySentence: case UITextGranularityParagraph: case UITextGranularityDocument: // The UITextInputStringTokenizer can handle all these cases correctly. result = [super rangeEnclosingPosition:position withGranularity:granularity inDirection:direction]; break; } return result; } - (UITextRange*)lineEnclosingPosition:(UITextPosition*)position inDirection:(UITextDirection)direction { // TODO(hellohuanlin): remove iOS 17 check. The same logic should apply to older iOS version. if (@available(iOS 17.0, *)) { // According to the API doc if the text position is at a text-unit boundary, it is considered // enclosed only if the next position in the given direction is entirely enclosed. Link: // https://developer.apple.com/documentation/uikit/uitextinputtokenizer/1614464-rangeenclosingposition?language=objc FlutterTextPosition* flutterPosition = (FlutterTextPosition*)position; if (flutterPosition.index > _textInputView.text.length || (flutterPosition.index == _textInputView.text.length && direction == UITextStorageDirectionForward)) { return nil; } } // Gets the first line break position after the input position. NSString* textAfter = [_textInputView textInRange:[_textInputView textRangeFromPosition:position toPosition:[_textInputView endOfDocument]]]; NSArray<NSString*>* linesAfter = [textAfter componentsSeparatedByString:@"\n"]; NSInteger offSetToLineBreak = [linesAfter firstObject].length; UITextPosition* lineBreakAfter = [_textInputView positionFromPosition:position offset:offSetToLineBreak]; // Gets the first line break position before the input position. NSString* textBefore = [_textInputView textInRange:[_textInputView textRangeFromPosition:[_textInputView beginningOfDocument] toPosition:position]]; NSArray<NSString*>* linesBefore = [textBefore componentsSeparatedByString:@"\n"]; NSInteger offSetFromLineBreak = [linesBefore lastObject].length; UITextPosition* lineBreakBefore = [_textInputView positionFromPosition:position offset:-offSetFromLineBreak]; return [_textInputView textRangeFromPosition:lineBreakBefore toPosition:lineBreakAfter]; } @end #pragma mark - FlutterTextSelectionRect @implementation FlutterTextSelectionRect @synthesize rect = _rect; @synthesize writingDirection = _writingDirection; @synthesize containsStart = _containsStart; @synthesize containsEnd = _containsEnd; @synthesize isVertical = _isVertical; + (instancetype)selectionRectWithRectAndInfo:(CGRect)rect position:(NSUInteger)position writingDirection:(NSWritingDirection)writingDirection containsStart:(BOOL)containsStart containsEnd:(BOOL)containsEnd isVertical:(BOOL)isVertical { return [[FlutterTextSelectionRect alloc] initWithRectAndInfo:rect position:position writingDirection:writingDirection containsStart:containsStart containsEnd:containsEnd isVertical:isVertical]; } + (instancetype)selectionRectWithRect:(CGRect)rect position:(NSUInteger)position { return [[FlutterTextSelectionRect alloc] initWithRectAndInfo:rect position:position writingDirection:NSWritingDirectionNatural containsStart:NO containsEnd:NO isVertical:NO]; } + (instancetype)selectionRectWithRect:(CGRect)rect position:(NSUInteger)position writingDirection:(NSWritingDirection)writingDirection { return [[FlutterTextSelectionRect alloc] initWithRectAndInfo:rect position:position writingDirection:writingDirection containsStart:NO containsEnd:NO isVertical:NO]; } - (instancetype)initWithRectAndInfo:(CGRect)rect position:(NSUInteger)position writingDirection:(NSWritingDirection)writingDirection containsStart:(BOOL)containsStart containsEnd:(BOOL)containsEnd isVertical:(BOOL)isVertical { self = [super init]; if (self) { self.rect = rect; self.position = position; self.writingDirection = writingDirection; self.containsStart = containsStart; self.containsEnd = containsEnd; self.isVertical = isVertical; } return self; } - (BOOL)isRTL { return _writingDirection == NSWritingDirectionRightToLeft; } @end #pragma mark - FlutterTextPlaceholder @implementation FlutterTextPlaceholder - (NSArray<UITextSelectionRect*>*)rects { // Returning anything other than an empty array here seems to cause PencilKit to enter an // infinite loop of allocating placeholders until the app crashes return @[]; } @end // A FlutterTextInputView that masquerades as a UITextField, and forwards // selectors it can't respond to a shared UITextField instance. // // Relevant API docs claim that password autofill supports any custom view // that adopts the UITextInput protocol, automatic strong password seems to // currently only support UITextFields, and password saving only supports // UITextFields and UITextViews, as of iOS 13.5. @interface FlutterSecureTextInputView : FlutterTextInputView @property(nonatomic, retain, readonly) UITextField* textField; @end @implementation FlutterSecureTextInputView { UITextField* _textField; } - (UITextField*)textField { if (!_textField) { _textField = [[UITextField alloc] init]; } return _textField; } - (BOOL)isKindOfClass:(Class)aClass { return [super isKindOfClass:aClass] || (aClass == [UITextField class]); } - (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector { NSMethodSignature* signature = [super methodSignatureForSelector:aSelector]; if (!signature) { signature = [self.textField methodSignatureForSelector:aSelector]; } return signature; } - (void)forwardInvocation:(NSInvocation*)anInvocation { [anInvocation invokeWithTarget:self.textField]; } @end @interface FlutterTextInputPlugin () @property(nonatomic, readonly, weak) id<FlutterTextInputDelegate> textInputDelegate; @property(nonatomic, readonly) UIView* hostView; @end @interface FlutterTextInputView () @property(nonatomic, readonly, weak) FlutterTextInputPlugin* textInputPlugin; @property(nonatomic, copy) NSString* autofillId; @property(nonatomic, readonly) CATransform3D editableTransform; @property(nonatomic, assign) CGRect markedRect; // Disables the cursor from dismissing when firstResponder is resigned @property(nonatomic, assign) BOOL preventCursorDismissWhenResignFirstResponder; @property(nonatomic) BOOL isVisibleToAutofill; @property(nonatomic, assign) BOOL accessibilityEnabled; @property(nonatomic, assign) int textInputClient; // The composed character that is temporarily removed by the keyboard API. // This is cleared at the start of each keyboard interaction. (Enter a character, delete a character // etc) @property(nonatomic, copy) NSString* temporarilyDeletedComposedCharacter; - (void)setEditableTransform:(NSArray*)matrix; @end @implementation FlutterTextInputView { int _textInputClient; const char* _selectionAffinity; FlutterTextRange* _selectedTextRange; UIInputViewController* _inputViewController; CGRect _cachedFirstRect; FlutterScribbleInteractionStatus _scribbleInteractionStatus; BOOL _hasPlaceholder; // Whether to show the system keyboard when this view // becomes the first responder. Typically set to false // when the app shows its own in-flutter keyboard. bool _isSystemKeyboardEnabled; bool _isFloatingCursorActive; CGPoint _floatingCursorOffset; bool _enableInteractiveSelection; UITextInteraction* _textInteraction API_AVAILABLE(ios(13.0)); } @synthesize tokenizer = _tokenizer; - (instancetype)initWithOwner:(FlutterTextInputPlugin*)textInputPlugin { self = [super initWithFrame:CGRectZero]; if (self) { _textInputPlugin = textInputPlugin; _textInputClient = 0; _selectionAffinity = kTextAffinityUpstream; _preventCursorDismissWhenResignFirstResponder = NO; // UITextInput _text = [[NSMutableString alloc] init]; _selectedTextRange = [[FlutterTextRange alloc] initWithNSRange:NSMakeRange(0, 0)]; _markedRect = kInvalidFirstRect; _cachedFirstRect = kInvalidFirstRect; _scribbleInteractionStatus = FlutterScribbleInteractionStatusNone; _pendingDeltas = [[NSMutableArray alloc] init]; // Initialize with the zero matrix which is not // an affine transform. _editableTransform = CATransform3D(); // UITextInputTraits _autocapitalizationType = UITextAutocapitalizationTypeSentences; _autocorrectionType = UITextAutocorrectionTypeDefault; _spellCheckingType = UITextSpellCheckingTypeDefault; _enablesReturnKeyAutomatically = NO; _keyboardAppearance = UIKeyboardAppearanceDefault; _keyboardType = UIKeyboardTypeDefault; _returnKeyType = UIReturnKeyDone; _secureTextEntry = NO; _enableDeltaModel = NO; _enableInteractiveSelection = YES; _accessibilityEnabled = NO; _smartQuotesType = UITextSmartQuotesTypeYes; _smartDashesType = UITextSmartDashesTypeYes; _selectionRects = [[NSArray alloc] init]; if (@available(iOS 14.0, *)) { UIScribbleInteraction* interaction = [[UIScribbleInteraction alloc] initWithDelegate:self]; [self addInteraction:interaction]; } } return self; } - (void)configureWithDictionary:(NSDictionary*)configuration { NSDictionary* inputType = configuration[kKeyboardType]; NSString* keyboardAppearance = configuration[kKeyboardAppearance]; NSDictionary* autofill = configuration[kAutofillProperties]; self.secureTextEntry = [configuration[kSecureTextEntry] boolValue]; self.enableDeltaModel = [configuration[kEnableDeltaModel] boolValue]; _isSystemKeyboardEnabled = ShouldShowSystemKeyboard(inputType); self.keyboardType = ToUIKeyboardType(inputType); self.returnKeyType = ToUIReturnKeyType(configuration[kInputAction]); self.autocapitalizationType = ToUITextAutoCapitalizationType(configuration); _enableInteractiveSelection = [configuration[kEnableInteractiveSelection] boolValue]; NSString* smartDashesType = configuration[kSmartDashesType]; // This index comes from the SmartDashesType enum in the framework. bool smartDashesIsDisabled = smartDashesType && [smartDashesType isEqualToString:@"0"]; self.smartDashesType = smartDashesIsDisabled ? UITextSmartDashesTypeNo : UITextSmartDashesTypeYes; NSString* smartQuotesType = configuration[kSmartQuotesType]; // This index comes from the SmartQuotesType enum in the framework. bool smartQuotesIsDisabled = smartQuotesType && [smartQuotesType isEqualToString:@"0"]; self.smartQuotesType = smartQuotesIsDisabled ? UITextSmartQuotesTypeNo : UITextSmartQuotesTypeYes; if ([keyboardAppearance isEqualToString:@"Brightness.dark"]) { self.keyboardAppearance = UIKeyboardAppearanceDark; } else if ([keyboardAppearance isEqualToString:@"Brightness.light"]) { self.keyboardAppearance = UIKeyboardAppearanceLight; } else { self.keyboardAppearance = UIKeyboardAppearanceDefault; } NSString* autocorrect = configuration[kAutocorrectionType]; bool autocorrectIsDisabled = autocorrect && ![autocorrect boolValue]; self.autocorrectionType = autocorrectIsDisabled ? UITextAutocorrectionTypeNo : UITextAutocorrectionTypeDefault; self.spellCheckingType = autocorrectIsDisabled ? UITextSpellCheckingTypeNo : UITextSpellCheckingTypeDefault; self.autofillId = AutofillIdFromDictionary(configuration); if (autofill == nil) { self.textContentType = @""; } else { self.textContentType = ToUITextContentType(autofill[kAutofillHints]); [self setTextInputState:autofill[kAutofillEditingValue]]; NSAssert(_autofillId, @"The autofill configuration must contain an autofill id"); } // The input field needs to be visible for the system autofill // to find it. self.isVisibleToAutofill = autofill || _secureTextEntry; } - (UITextContentType)textContentType { return _textContentType; } // Prevent UIKit from showing selection handles or highlights. This is needed // because Scribble interactions require the view to have it's actual frame on // the screen. They're not needed on iOS 17 with the new // UITextSelectionDisplayInteraction API. // // These are undocumented methods. On iOS 17, the insertion point color is also // used as the highlighted background of the selected IME candidate: // https://github.com/flutter/flutter/issues/132548 // So the respondsToSelector method is overridden to return NO for this method // on iOS 17+. - (UIColor*)insertionPointColor { return [UIColor clearColor]; } - (UIColor*)selectionBarColor { return [UIColor clearColor]; } - (UIColor*)selectionHighlightColor { return [UIColor clearColor]; } - (UIInputViewController*)inputViewController { if (_isSystemKeyboardEnabled) { return nil; } if (!_inputViewController) { _inputViewController = [[UIInputViewController alloc] init]; } return _inputViewController; } - (id<FlutterTextInputDelegate>)textInputDelegate { return _textInputPlugin.textInputDelegate; } - (BOOL)respondsToSelector:(SEL)selector { if (@available(iOS 17.0, *)) { // See the comment on this method. if (selector == @selector(insertionPointColor)) { return NO; } } return [super respondsToSelector:selector]; } - (void)setTextInputClient:(int)client { _textInputClient = client; _hasPlaceholder = NO; } - (UITextInteraction*)textInteraction API_AVAILABLE(ios(13.0)) { if (!_textInteraction) { _textInteraction = [UITextInteraction textInteractionForMode:UITextInteractionModeEditable]; _textInteraction.textInput = self; } return _textInteraction; } - (void)setTextInputState:(NSDictionary*)state { if (@available(iOS 13.0, *)) { // [UITextInteraction willMoveToView:] sometimes sets the textInput's inputDelegate // to nil. This is likely a bug in UIKit. In order to inform the keyboard of text // and selection changes when that happens, add a dummy UITextInteraction to this // view so it sets a valid inputDelegate that we can call textWillChange et al. on. // See https://github.com/flutter/engine/pull/32881. if (!self.inputDelegate && self.isFirstResponder) { [self addInteraction:self.textInteraction]; } } NSString* newText = state[@"text"]; BOOL textChanged = ![self.text isEqualToString:newText]; if (textChanged) { [self.inputDelegate textWillChange:self]; [self.text setString:newText]; } NSInteger composingBase = [state[@"composingBase"] intValue]; NSInteger composingExtent = [state[@"composingExtent"] intValue]; NSRange composingRange = [self clampSelection:NSMakeRange(MIN(composingBase, composingExtent), ABS(composingBase - composingExtent)) forText:self.text]; self.markedTextRange = composingRange.length > 0 ? [FlutterTextRange rangeWithNSRange:composingRange] : nil; NSRange selectedRange = [self clampSelectionFromBase:[state[@"selectionBase"] intValue] extent:[state[@"selectionExtent"] intValue] forText:self.text]; NSRange oldSelectedRange = [(FlutterTextRange*)self.selectedTextRange range]; if (!NSEqualRanges(selectedRange, oldSelectedRange)) { [self.inputDelegate selectionWillChange:self]; [self setSelectedTextRangeLocal:[FlutterTextRange rangeWithNSRange:selectedRange]]; _selectionAffinity = kTextAffinityDownstream; if ([state[@"selectionAffinity"] isEqualToString:@(kTextAffinityUpstream)]) { _selectionAffinity = kTextAffinityUpstream; } [self.inputDelegate selectionDidChange:self]; } if (textChanged) { [self.inputDelegate textDidChange:self]; } if (@available(iOS 13.0, *)) { if (_textInteraction) { [self removeInteraction:_textInteraction]; } } } // Forward touches to the viewResponder to allow tapping inside the UITextField as normal. - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; [self resetScribbleInteractionStatusIfEnding]; [self.viewResponder touchesBegan:touches withEvent:event]; } - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { [self.viewResponder touchesMoved:touches withEvent:event]; } - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { [self.viewResponder touchesEnded:touches withEvent:event]; } - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { [self.viewResponder touchesCancelled:touches withEvent:event]; } - (void)touchesEstimatedPropertiesUpdated:(NSSet*)touches { [self.viewResponder touchesEstimatedPropertiesUpdated:touches]; } // Extracts the selection information from the editing state dictionary. // // The state may contain an invalid selection, such as when no selection was // explicitly set in the framework. This is handled here by setting the // selection to (0,0). In contrast, Android handles this situation by // clearing the selection, but the result in both cases is that the cursor // is placed at the beginning of the field. - (NSRange)clampSelectionFromBase:(int)selectionBase extent:(int)selectionExtent forText:(NSString*)text { int loc = MIN(selectionBase, selectionExtent); int len = ABS(selectionExtent - selectionBase); return loc < 0 ? NSMakeRange(0, 0) : [self clampSelection:NSMakeRange(loc, len) forText:self.text]; } - (NSRange)clampSelection:(NSRange)range forText:(NSString*)text { NSUInteger start = MIN(MAX(range.location, 0), text.length); NSUInteger length = MIN(range.length, text.length - start); return NSMakeRange(start, length); } - (BOOL)isVisibleToAutofill { return self.frame.size.width > 0 && self.frame.size.height > 0; } // An input view is generally ignored by password autofill attempts, if it's // not the first responder and is zero-sized. For input fields that are in the // autofill context but do not belong to the current autofill group, setting // their frames to CGRectZero prevents ios autofill from taking them into // account. - (void)setIsVisibleToAutofill:(BOOL)isVisibleToAutofill { // This probably needs to change (think it is getting overwritten by the updateSizeAndTransform // stuff for now). self.frame = isVisibleToAutofill ? CGRectMake(0, 0, 1, 1) : CGRectZero; } #pragma mark UIScribbleInteractionDelegate // Checks whether Scribble features are possibly available – meaning this is an iPad running iOS // 14 or higher. - (BOOL)isScribbleAvailable { if (@available(iOS 14.0, *)) { if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { return YES; } } return NO; } - (void)scribbleInteractionWillBeginWriting:(UIScribbleInteraction*)interaction API_AVAILABLE(ios(14.0)) { _scribbleInteractionStatus = FlutterScribbleInteractionStatusStarted; [self.textInputDelegate flutterTextInputViewScribbleInteractionBegan:self]; } - (void)scribbleInteractionDidFinishWriting:(UIScribbleInteraction*)interaction API_AVAILABLE(ios(14.0)) { _scribbleInteractionStatus = FlutterScribbleInteractionStatusEnding; [self.textInputDelegate flutterTextInputViewScribbleInteractionFinished:self]; } - (BOOL)scribbleInteraction:(UIScribbleInteraction*)interaction shouldBeginAtLocation:(CGPoint)location API_AVAILABLE(ios(14.0)) { return YES; } - (BOOL)scribbleInteractionShouldDelayFocus:(UIScribbleInteraction*)interaction API_AVAILABLE(ios(14.0)) { return NO; } #pragma mark - UIResponder Overrides - (BOOL)canBecomeFirstResponder { // Only the currently focused input field can // become the first responder. This prevents iOS // from changing focus by itself (the framework // focus will be out of sync if that happens). return _textInputClient != 0; } - (BOOL)resignFirstResponder { BOOL success = [super resignFirstResponder]; if (success) { if (!_preventCursorDismissWhenResignFirstResponder) { [self.textInputDelegate flutterTextInputView:self didResignFirstResponderWithTextInputClient:_textInputClient]; } } return success; } - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if (action == @selector(paste:)) { // Forbid pasting images, memojis, or other non-string content. return [UIPasteboard generalPasteboard].hasStrings; } return [super canPerformAction:action withSender:sender]; } #pragma mark - UIResponderStandardEditActions Overrides - (void)cut:(id)sender { [UIPasteboard generalPasteboard].string = [self textInRange:_selectedTextRange]; [self replaceRange:_selectedTextRange withText:@""]; } - (void)copy:(id)sender { [UIPasteboard generalPasteboard].string = [self textInRange:_selectedTextRange]; } - (void)paste:(id)sender { NSString* pasteboardString = [UIPasteboard generalPasteboard].string; if (pasteboardString != nil) { [self insertText:pasteboardString]; } } - (void)delete:(id)sender { [self replaceRange:_selectedTextRange withText:@""]; } - (void)selectAll:(id)sender { [self setSelectedTextRange:[self textRangeFromPosition:[self beginningOfDocument] toPosition:[self endOfDocument]]]; } #pragma mark - UITextInput Overrides - (id<UITextInputTokenizer>)tokenizer { if (_tokenizer == nil) { _tokenizer = [[FlutterTokenizer alloc] initWithTextInput:self]; } return _tokenizer; } - (UITextRange*)selectedTextRange { return [_selectedTextRange copy]; } // Change the range of selected text, without notifying the framework. - (void)setSelectedTextRangeLocal:(UITextRange*)selectedTextRange { if (_selectedTextRange != selectedTextRange) { if (self.hasText) { FlutterTextRange* flutterTextRange = (FlutterTextRange*)selectedTextRange; _selectedTextRange = [[FlutterTextRange rangeWithNSRange:fml::RangeForCharactersInRange(self.text, flutterTextRange.range)] copy]; } else { _selectedTextRange = [selectedTextRange copy]; } } } - (void)setSelectedTextRange:(UITextRange*)selectedTextRange { if (!_enableInteractiveSelection) { return; } [self setSelectedTextRangeLocal:selectedTextRange]; if (_enableDeltaModel) { [self updateEditingStateWithDelta:flutter::TextEditingDelta([self.text UTF8String])]; } else { [self updateEditingState]; } if (_scribbleInteractionStatus != FlutterScribbleInteractionStatusNone || _scribbleFocusStatus == FlutterScribbleFocusStatusFocused) { NSAssert([selectedTextRange isKindOfClass:[FlutterTextRange class]], @"Expected a FlutterTextRange for range (got %@).", [selectedTextRange class]); FlutterTextRange* flutterTextRange = (FlutterTextRange*)selectedTextRange; if (flutterTextRange.range.length > 0) { [self.textInputDelegate flutterTextInputView:self showToolbar:_textInputClient]; } } [self resetScribbleInteractionStatusIfEnding]; } - (id)insertDictationResultPlaceholder { return @""; } - (void)removeDictationResultPlaceholder:(id)placeholder willInsertResult:(BOOL)willInsertResult { } - (NSString*)textInRange:(UITextRange*)range { if (!range) { return nil; } NSAssert([range isKindOfClass:[FlutterTextRange class]], @"Expected a FlutterTextRange for range (got %@).", [range class]); NSRange textRange = ((FlutterTextRange*)range).range; NSAssert(textRange.location != NSNotFound, @"Expected a valid text range."); // Sanitize the range to prevent going out of bounds. NSUInteger location = MIN(textRange.location, self.text.length); NSUInteger length = MIN(self.text.length - location, textRange.length); NSRange safeRange = NSMakeRange(location, length); return [self.text substringWithRange:safeRange]; } // Replace the text within the specified range with the given text, // without notifying the framework. - (void)replaceRangeLocal:(NSRange)range withText:(NSString*)text { [self.text replaceCharactersInRange:[self clampSelection:range forText:self.text] withString:text]; // Adjust the selected range and the marked text range. There's no // documentation but UITextField always sets markedTextRange to nil, // and collapses the selection to the end of the new replacement text. const NSRange newSelectionRange = [self clampSelection:NSMakeRange(range.location + text.length, 0) forText:self.text]; [self setSelectedTextRangeLocal:[FlutterTextRange rangeWithNSRange:newSelectionRange]]; self.markedTextRange = nil; } - (void)replaceRange:(UITextRange*)range withText:(NSString*)text { NSString* textBeforeChange = [self.text copy]; NSRange replaceRange = ((FlutterTextRange*)range).range; [self replaceRangeLocal:replaceRange withText:text]; if (_enableDeltaModel) { NSRange nextReplaceRange = [self clampSelection:replaceRange forText:textBeforeChange]; [self updateEditingStateWithDelta:flutter::TextEditingDelta( [textBeforeChange UTF8String], flutter::TextRange( nextReplaceRange.location, nextReplaceRange.location + nextReplaceRange.length), [text UTF8String])]; } else { [self updateEditingState]; } } - (BOOL)shouldChangeTextInRange:(UITextRange*)range replacementText:(NSString*)text { // `temporarilyDeletedComposedCharacter` should only be used during a single text change session. // So it needs to be cleared at the start of each text editing session. self.temporarilyDeletedComposedCharacter = nil; if (self.returnKeyType == UIReturnKeyDefault && [text isEqualToString:@"\n"]) { [self.textInputDelegate flutterTextInputView:self performAction:FlutterTextInputActionNewline withClient:_textInputClient]; return YES; } if ([text isEqualToString:@"\n"]) { FlutterTextInputAction action; switch (self.returnKeyType) { case UIReturnKeyDefault: action = FlutterTextInputActionUnspecified; break; case UIReturnKeyDone: action = FlutterTextInputActionDone; break; case UIReturnKeyGo: action = FlutterTextInputActionGo; break; case UIReturnKeySend: action = FlutterTextInputActionSend; break; case UIReturnKeySearch: case UIReturnKeyGoogle: case UIReturnKeyYahoo: action = FlutterTextInputActionSearch; break; case UIReturnKeyNext: action = FlutterTextInputActionNext; break; case UIReturnKeyContinue: action = FlutterTextInputActionContinue; break; case UIReturnKeyJoin: action = FlutterTextInputActionJoin; break; case UIReturnKeyRoute: action = FlutterTextInputActionRoute; break; case UIReturnKeyEmergencyCall: action = FlutterTextInputActionEmergencyCall; break; } [self.textInputDelegate flutterTextInputView:self performAction:action withClient:_textInputClient]; return NO; } return YES; } // Either replaces the existing marked text or, if none is present, inserts it in // place of the current selection. - (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)markedSelectedRange { NSString* textBeforeChange = [self.text copy]; if (_scribbleInteractionStatus != FlutterScribbleInteractionStatusNone || _scribbleFocusStatus != FlutterScribbleFocusStatusUnfocused) { return; } if (markedText == nil) { markedText = @""; } const FlutterTextRange* currentMarkedTextRange = (FlutterTextRange*)self.markedTextRange; const NSRange& actualReplacedRange = currentMarkedTextRange && !currentMarkedTextRange.isEmpty ? currentMarkedTextRange.range : _selectedTextRange.range; // No need to call replaceRangeLocal as this method always adjusts the // selected/marked text ranges anyways. [self.text replaceCharactersInRange:actualReplacedRange withString:markedText]; const NSRange newMarkedRange = NSMakeRange(actualReplacedRange.location, markedText.length); self.markedTextRange = newMarkedRange.length > 0 ? [FlutterTextRange rangeWithNSRange:newMarkedRange] : nil; [self setSelectedTextRangeLocal: [FlutterTextRange rangeWithNSRange:[self clampSelection:NSMakeRange(markedSelectedRange.location + newMarkedRange.location, markedSelectedRange.length) forText:self.text]]]; if (_enableDeltaModel) { NSRange nextReplaceRange = [self clampSelection:actualReplacedRange forText:textBeforeChange]; [self updateEditingStateWithDelta:flutter::TextEditingDelta( [textBeforeChange UTF8String], flutter::TextRange( nextReplaceRange.location, nextReplaceRange.location + nextReplaceRange.length), [markedText UTF8String])]; } else { [self updateEditingState]; } } - (void)unmarkText { if (!self.markedTextRange) { return; } self.markedTextRange = nil; if (_enableDeltaModel) { [self updateEditingStateWithDelta:flutter::TextEditingDelta([self.text UTF8String])]; } else { [self updateEditingState]; } } - (UITextRange*)textRangeFromPosition:(UITextPosition*)fromPosition toPosition:(UITextPosition*)toPosition { NSUInteger fromIndex = ((FlutterTextPosition*)fromPosition).index; NSUInteger toIndex = ((FlutterTextPosition*)toPosition).index; if (toIndex >= fromIndex) { return [FlutterTextRange rangeWithNSRange:NSMakeRange(fromIndex, toIndex - fromIndex)]; } else { // toIndex can be smaller than fromIndex, because // UITextInputStringTokenizer does not handle CJK characters // well in some cases. See: // https://github.com/flutter/flutter/issues/58750#issuecomment-644469521 // Swap fromPosition and toPosition to match the behavior of native // UITextViews. return [FlutterTextRange rangeWithNSRange:NSMakeRange(toIndex, fromIndex - toIndex)]; } } - (NSUInteger)decrementOffsetPosition:(NSUInteger)position { return fml::RangeForCharacterAtIndex(self.text, MAX(0, position - 1)).location; } - (NSUInteger)incrementOffsetPosition:(NSUInteger)position { NSRange charRange = fml::RangeForCharacterAtIndex(self.text, position); return MIN(position + charRange.length, self.text.length); } - (UITextPosition*)positionFromPosition:(UITextPosition*)position offset:(NSInteger)offset { NSUInteger offsetPosition = ((FlutterTextPosition*)position).index; NSInteger newLocation = (NSInteger)offsetPosition + offset; if (newLocation < 0 || newLocation > (NSInteger)self.text.length) { return nil; } if (_scribbleInteractionStatus != FlutterScribbleInteractionStatusNone) { return [FlutterTextPosition positionWithIndex:newLocation]; } if (offset >= 0) { for (NSInteger i = 0; i < offset && offsetPosition < self.text.length; ++i) { offsetPosition = [self incrementOffsetPosition:offsetPosition]; } } else { for (NSInteger i = 0; i < ABS(offset) && offsetPosition > 0; ++i) { offsetPosition = [self decrementOffsetPosition:offsetPosition]; } } return [FlutterTextPosition positionWithIndex:offsetPosition]; } - (UITextPosition*)positionFromPosition:(UITextPosition*)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset { // TODO(cbracken) Add RTL handling. switch (direction) { case UITextLayoutDirectionLeft: case UITextLayoutDirectionUp: return [self positionFromPosition:position offset:offset * -1]; case UITextLayoutDirectionRight: case UITextLayoutDirectionDown: return [self positionFromPosition:position offset:1]; } } - (UITextPosition*)beginningOfDocument { return [FlutterTextPosition positionWithIndex:0 affinity:UITextStorageDirectionForward]; } - (UITextPosition*)endOfDocument { return [FlutterTextPosition positionWithIndex:self.text.length affinity:UITextStorageDirectionBackward]; } - (NSComparisonResult)comparePosition:(UITextPosition*)position toPosition:(UITextPosition*)other { NSUInteger positionIndex = ((FlutterTextPosition*)position).index; NSUInteger otherIndex = ((FlutterTextPosition*)other).index; if (positionIndex < otherIndex) { return NSOrderedAscending; } if (positionIndex > otherIndex) { return NSOrderedDescending; } UITextStorageDirection positionAffinity = ((FlutterTextPosition*)position).affinity; UITextStorageDirection otherAffinity = ((FlutterTextPosition*)other).affinity; if (positionAffinity == otherAffinity) { return NSOrderedSame; } if (positionAffinity == UITextStorageDirectionBackward) { // positionAffinity points backwards, otherAffinity points forwards return NSOrderedAscending; } // positionAffinity points forwards, otherAffinity points backwards return NSOrderedDescending; } - (NSInteger)offsetFromPosition:(UITextPosition*)from toPosition:(UITextPosition*)toPosition { return ((FlutterTextPosition*)toPosition).index - ((FlutterTextPosition*)from).index; } - (UITextPosition*)positionWithinRange:(UITextRange*)range farthestInDirection:(UITextLayoutDirection)direction { NSUInteger index; UITextStorageDirection affinity; switch (direction) { case UITextLayoutDirectionLeft: case UITextLayoutDirectionUp: index = ((FlutterTextPosition*)range.start).index; affinity = UITextStorageDirectionForward; break; case UITextLayoutDirectionRight: case UITextLayoutDirectionDown: index = ((FlutterTextPosition*)range.end).index; affinity = UITextStorageDirectionBackward; break; } return [FlutterTextPosition positionWithIndex:index affinity:affinity]; } - (UITextRange*)characterRangeByExtendingPosition:(UITextPosition*)position inDirection:(UITextLayoutDirection)direction { NSUInteger positionIndex = ((FlutterTextPosition*)position).index; NSUInteger startIndex; NSUInteger endIndex; switch (direction) { case UITextLayoutDirectionLeft: case UITextLayoutDirectionUp: startIndex = [self decrementOffsetPosition:positionIndex]; endIndex = positionIndex; break; case UITextLayoutDirectionRight: case UITextLayoutDirectionDown: startIndex = positionIndex; endIndex = [self incrementOffsetPosition:positionIndex]; break; } return [FlutterTextRange rangeWithNSRange:NSMakeRange(startIndex, endIndex - startIndex)]; } #pragma mark - UITextInput text direction handling - (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition*)position inDirection:(UITextStorageDirection)direction { // TODO(cbracken) Add RTL handling. return UITextWritingDirectionNatural; } - (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection forRange:(UITextRange*)range { // TODO(cbracken) Add RTL handling. } #pragma mark - UITextInput cursor, selection rect handling - (void)setMarkedRect:(CGRect)markedRect { _markedRect = markedRect; // Invalidate the cache. _cachedFirstRect = kInvalidFirstRect; } // This method expects a 4x4 perspective matrix // stored in a NSArray in column-major order. - (void)setEditableTransform:(NSArray*)matrix { CATransform3D* transform = &_editableTransform; transform->m11 = [matrix[0] doubleValue]; transform->m12 = [matrix[1] doubleValue]; transform->m13 = [matrix[2] doubleValue]; transform->m14 = [matrix[3] doubleValue]; transform->m21 = [matrix[4] doubleValue]; transform->m22 = [matrix[5] doubleValue]; transform->m23 = [matrix[6] doubleValue]; transform->m24 = [matrix[7] doubleValue]; transform->m31 = [matrix[8] doubleValue]; transform->m32 = [matrix[9] doubleValue]; transform->m33 = [matrix[10] doubleValue]; transform->m34 = [matrix[11] doubleValue]; transform->m41 = [matrix[12] doubleValue]; transform->m42 = [matrix[13] doubleValue]; transform->m43 = [matrix[14] doubleValue]; transform->m44 = [matrix[15] doubleValue]; // Invalidate the cache. _cachedFirstRect = kInvalidFirstRect; } // Returns the bounding CGRect of the transformed incomingRect, in the view's // coordinates. - (CGRect)localRectFromFrameworkTransform:(CGRect)incomingRect { CGPoint points[] = { incomingRect.origin, CGPointMake(incomingRect.origin.x, incomingRect.origin.y + incomingRect.size.height), CGPointMake(incomingRect.origin.x + incomingRect.size.width, incomingRect.origin.y), CGPointMake(incomingRect.origin.x + incomingRect.size.width, incomingRect.origin.y + incomingRect.size.height)}; CGPoint origin = CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX); CGPoint farthest = CGPointMake(-CGFLOAT_MAX, -CGFLOAT_MAX); for (int i = 0; i < 4; i++) { const CGPoint point = points[i]; CGFloat x = _editableTransform.m11 * point.x + _editableTransform.m21 * point.y + _editableTransform.m41; CGFloat y = _editableTransform.m12 * point.x + _editableTransform.m22 * point.y + _editableTransform.m42; const CGFloat w = _editableTransform.m14 * point.x + _editableTransform.m24 * point.y + _editableTransform.m44; if (w == 0.0) { return kInvalidFirstRect; } else if (w != 1.0) { x /= w; y /= w; } origin.x = MIN(origin.x, x); origin.y = MIN(origin.y, y); farthest.x = MAX(farthest.x, x); farthest.y = MAX(farthest.y, y); } return CGRectMake(origin.x, origin.y, farthest.x - origin.x, farthest.y - origin.y); } // The following methods are required to support force-touch cursor positioning // and to position the // candidates view for multi-stage input methods (e.g., Japanese) when using a // physical keyboard. // Returns the rect for the queried range, or a subrange through the end of line, if // the range encompasses multiple lines. - (CGRect)firstRectForRange:(UITextRange*)range { NSAssert([range.start isKindOfClass:[FlutterTextPosition class]], @"Expected a FlutterTextPosition for range.start (got %@).", [range.start class]); NSAssert([range.end isKindOfClass:[FlutterTextPosition class]], @"Expected a FlutterTextPosition for range.end (got %@).", [range.end class]); NSUInteger start = ((FlutterTextPosition*)range.start).index; NSUInteger end = ((FlutterTextPosition*)range.end).index; if (_markedTextRange != nil) { // The candidates view can't be shown if the framework has not sent the // first caret rect. if (CGRectEqualToRect(kInvalidFirstRect, _markedRect)) { return kInvalidFirstRect; } if (CGRectEqualToRect(_cachedFirstRect, kInvalidFirstRect)) { // If the width returned is too small, that means the framework sent us // the caret rect instead of the marked text rect. Expand it to 0.2 so // the IME candidates view would show up. CGRect rect = _markedRect; if (CGRectIsEmpty(rect)) { rect = CGRectInset(rect, -0.1, 0); } _cachedFirstRect = [self localRectFromFrameworkTransform:rect]; } UIView* hostView = _textInputPlugin.hostView; NSAssert(hostView == nil || [self isDescendantOfView:hostView], @"%@ is not a descendant of %@", self, hostView); return hostView ? [hostView convertRect:_cachedFirstRect toView:self] : _cachedFirstRect; } if (_scribbleInteractionStatus == FlutterScribbleInteractionStatusNone && _scribbleFocusStatus == FlutterScribbleFocusStatusUnfocused) { if (@available(iOS 17.0, *)) { // Disable auto-correction highlight feature for iOS 17+. // In iOS 17+, whenever a character is inserted or deleted, the system will always query // the rect for every single character of the current word. // GitHub Issue: https://github.com/flutter/flutter/issues/128406 } else { // This tells the framework to show the highlight for incorrectly spelled word that is // about to be auto-corrected. // There is no other UITextInput API that informs about the auto-correction highlight. // So we simply add the call here as a workaround. [self.textInputDelegate flutterTextInputView:self showAutocorrectionPromptRectForStart:start end:end withClient:_textInputClient]; } } // The iOS 16 system highlight does not repect the height returned by `firstRectForRange` // API (unlike iOS 17). So we return CGRectZero to hide it (unless if scribble is enabled). // To support scribble's advanced gestures (e.g. insert a space with a vertical bar), // at least 1 character's width is required. if (@available(iOS 17, *)) { // No-op } else if (![self isScribbleAvailable]) { return CGRectZero; } NSUInteger first = start; if (end < start) { first = end; } CGRect startSelectionRect = CGRectNull; CGRect endSelectionRect = CGRectNull; // Selection rects from different langauges may have different minY/maxY. // So we need to iterate through each rects to update minY/maxY. CGFloat minY = CGFLOAT_MAX; CGFloat maxY = CGFLOAT_MIN; FlutterTextRange* textRange = [FlutterTextRange rangeWithNSRange:fml::RangeForCharactersInRange(self.text, NSMakeRange(0, self.text.length))]; for (NSUInteger i = 0; i < [_selectionRects count]; i++) { BOOL startsOnOrBeforeStartOfRange = _selectionRects[i].position <= first; BOOL isLastSelectionRect = i + 1 == [_selectionRects count]; BOOL endOfTextIsAfterStartOfRange = isLastSelectionRect && textRange.range.length > first; BOOL nextSelectionRectIsAfterStartOfRange = !isLastSelectionRect && _selectionRects[i + 1].position > first; if (startsOnOrBeforeStartOfRange && (endOfTextIsAfterStartOfRange || nextSelectionRectIsAfterStartOfRange)) { // TODO(hellohaunlin): Remove iOS 17 check. The logic should also work for older versions. if (@available(iOS 17, *)) { startSelectionRect = _selectionRects[i].rect; } else { return _selectionRects[i].rect; } } if (!CGRectIsNull(startSelectionRect)) { minY = fmin(minY, CGRectGetMinY(_selectionRects[i].rect)); maxY = fmax(maxY, CGRectGetMaxY(_selectionRects[i].rect)); BOOL endsOnOrAfterEndOfRange = _selectionRects[i].position >= end - 1; // end is exclusive BOOL nextSelectionRectIsOnNextLine = !isLastSelectionRect && // Selection rects from different langauges in 2 lines may overlap with each other. // A good approximation is to check if the center of next rect is below the bottom of // current rect. // TODO(hellohuanlin): Consider passing the line break info from framework. CGRectGetMidY(_selectionRects[i + 1].rect) > CGRectGetMaxY(_selectionRects[i].rect); if (endsOnOrAfterEndOfRange || isLastSelectionRect || nextSelectionRectIsOnNextLine) { endSelectionRect = _selectionRects[i].rect; break; } } } if (CGRectIsNull(startSelectionRect) || CGRectIsNull(endSelectionRect)) { return CGRectZero; } else { // fmin/fmax to support both LTR and RTL languages. CGFloat minX = fmin(CGRectGetMinX(startSelectionRect), CGRectGetMinX(endSelectionRect)); CGFloat maxX = fmax(CGRectGetMaxX(startSelectionRect), CGRectGetMaxX(endSelectionRect)); return CGRectMake(minX, minY, maxX - minX, maxY - minY); } } - (CGRect)caretRectForPosition:(UITextPosition*)position { NSInteger index = ((FlutterTextPosition*)position).index; UITextStorageDirection affinity = ((FlutterTextPosition*)position).affinity; // Get the selectionRect of the characters before and after the requested caret position. NSArray<UITextSelectionRect*>* rects = [self selectionRectsForRange:[FlutterTextRange rangeWithNSRange:fml::RangeForCharactersInRange( self.text, NSMakeRange( MAX(0, index - 1), (index >= (NSInteger)self.text.length) ? 1 : 2))]]; if (rects.count == 0) { return CGRectZero; } if (index == 0) { // There is no character before the caret, so this will be the bounds of the character after the // caret position. CGRect characterAfterCaret = rects[0].rect; // Return a zero-width rectangle along the upstream edge of the character after the caret // position. if ([rects[0] isKindOfClass:[FlutterTextSelectionRect class]] && ((FlutterTextSelectionRect*)rects[0]).isRTL) { return CGRectMake(characterAfterCaret.origin.x + characterAfterCaret.size.width, characterAfterCaret.origin.y, 0, characterAfterCaret.size.height); } else { return CGRectMake(characterAfterCaret.origin.x, characterAfterCaret.origin.y, 0, characterAfterCaret.size.height); } } else if (rects.count == 2 && affinity == UITextStorageDirectionForward) { // There are characters before and after the caret, with forward direction affinity. // It's better to use the character after the caret. CGRect characterAfterCaret = rects[1].rect; // Return a zero-width rectangle along the upstream edge of the character after the caret // position. if ([rects[1] isKindOfClass:[FlutterTextSelectionRect class]] && ((FlutterTextSelectionRect*)rects[1]).isRTL) { return CGRectMake(characterAfterCaret.origin.x + characterAfterCaret.size.width, characterAfterCaret.origin.y, 0, characterAfterCaret.size.height); } else { return CGRectMake(characterAfterCaret.origin.x, characterAfterCaret.origin.y, 0, characterAfterCaret.size.height); } } // Covers 2 remaining cases: // 1. there are characters before and after the caret, with backward direction affinity. // 2. there is only 1 character before the caret (caret is at the end of text). // For both cases, return a zero-width rectangle along the downstream edge of the character // before the caret position. CGRect characterBeforeCaret = rects[0].rect; if ([rects[0] isKindOfClass:[FlutterTextSelectionRect class]] && ((FlutterTextSelectionRect*)rects[0]).isRTL) { return CGRectMake(characterBeforeCaret.origin.x, characterBeforeCaret.origin.y, 0, characterBeforeCaret.size.height); } else { return CGRectMake(characterBeforeCaret.origin.x + characterBeforeCaret.size.width, characterBeforeCaret.origin.y, 0, characterBeforeCaret.size.height); } } - (UITextPosition*)closestPositionToPoint:(CGPoint)point { if ([_selectionRects count] == 0) { NSAssert([_selectedTextRange.start isKindOfClass:[FlutterTextPosition class]], @"Expected a FlutterTextPosition for position (got %@).", [_selectedTextRange.start class]); NSUInteger currentIndex = ((FlutterTextPosition*)_selectedTextRange.start).index; UITextStorageDirection currentAffinity = ((FlutterTextPosition*)_selectedTextRange.start).affinity; return [FlutterTextPosition positionWithIndex:currentIndex affinity:currentAffinity]; } FlutterTextRange* range = [FlutterTextRange rangeWithNSRange:fml::RangeForCharactersInRange(self.text, NSMakeRange(0, self.text.length))]; return [self closestPositionToPoint:point withinRange:range]; } - (NSArray*)selectionRectsForRange:(UITextRange*)range { // At least in the simulator, swapping to the Japanese keyboard crashes the app as this method // is called immediately with a UITextRange with a UITextPosition rather than FlutterTextPosition // for the start and end. if (![range.start isKindOfClass:[FlutterTextPosition class]]) { return @[]; } NSAssert([range.start isKindOfClass:[FlutterTextPosition class]], @"Expected a FlutterTextPosition for range.start (got %@).", [range.start class]); NSAssert([range.end isKindOfClass:[FlutterTextPosition class]], @"Expected a FlutterTextPosition for range.end (got %@).", [range.end class]); NSUInteger start = ((FlutterTextPosition*)range.start).index; NSUInteger end = ((FlutterTextPosition*)range.end).index; NSMutableArray* rects = [[NSMutableArray alloc] init]; for (NSUInteger i = 0; i < [_selectionRects count]; i++) { if (_selectionRects[i].position >= start && (_selectionRects[i].position < end || (start == end && _selectionRects[i].position <= end))) { float width = _selectionRects[i].rect.size.width; if (start == end) { width = 0; } CGRect rect = CGRectMake(_selectionRects[i].rect.origin.x, _selectionRects[i].rect.origin.y, width, _selectionRects[i].rect.size.height); FlutterTextSelectionRect* selectionRect = [FlutterTextSelectionRect selectionRectWithRectAndInfo:rect position:_selectionRects[i].position writingDirection:NSWritingDirectionNatural containsStart:(i == 0) containsEnd:(i == fml::RangeForCharactersInRange( self.text, NSMakeRange(0, self.text.length)) .length) isVertical:NO]; [rects addObject:selectionRect]; } } return rects; } - (UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange*)range { NSAssert([range.start isKindOfClass:[FlutterTextPosition class]], @"Expected a FlutterTextPosition for range.start (got %@).", [range.start class]); NSAssert([range.end isKindOfClass:[FlutterTextPosition class]], @"Expected a FlutterTextPosition for range.end (got %@).", [range.end class]); NSUInteger start = ((FlutterTextPosition*)range.start).index; NSUInteger end = ((FlutterTextPosition*)range.end).index; // Selecting text using the floating cursor is not as precise as the pencil. // Allow further vertical deviation and base more of the decision on horizontal comparison. CGFloat verticalPrecision = _isFloatingCursorActive ? 10 : 1; // Find the selectionRect with a leading-center point that is closest to a given point. BOOL isFirst = YES; NSUInteger _closestRectIndex = 0; for (NSUInteger i = 0; i < [_selectionRects count]; i++) { NSUInteger position = _selectionRects[i].position; if (position >= start && position <= end) { if (isFirst || IsSelectionRectBoundaryCloserToPoint( point, _selectionRects[i].rect, _selectionRects[i].isRTL, /*useTrailingBoundaryOfSelectionRect=*/NO, _selectionRects[_closestRectIndex].rect, _selectionRects[_closestRectIndex].isRTL, verticalPrecision)) { isFirst = NO; _closestRectIndex = i; } } } FlutterTextPosition* closestPosition = [FlutterTextPosition positionWithIndex:_selectionRects[_closestRectIndex].position affinity:UITextStorageDirectionForward]; // Check if the far side of the closest rect is a better fit (e.g. tapping end of line) // Cannot simply check the _closestRectIndex result from the previous for loop due to RTL // writing direction and the gaps between selectionRects. So we also need to consider // the adjacent selectionRects to refine _closestRectIndex. for (NSUInteger i = MAX(0, _closestRectIndex - 1); i < MIN(_closestRectIndex + 2, [_selectionRects count]); i++) { NSUInteger position = _selectionRects[i].position + 1; if (position >= start && position <= end) { if (IsSelectionRectBoundaryCloserToPoint( point, _selectionRects[i].rect, _selectionRects[i].isRTL, /*useTrailingBoundaryOfSelectionRect=*/YES, _selectionRects[_closestRectIndex].rect, _selectionRects[_closestRectIndex].isRTL, verticalPrecision)) { // This is an upstream position closestPosition = [FlutterTextPosition positionWithIndex:position affinity:UITextStorageDirectionBackward]; } } } return closestPosition; } - (UITextRange*)characterRangeAtPoint:(CGPoint)point { // TODO(cbracken) Implement. NSUInteger currentIndex = ((FlutterTextPosition*)_selectedTextRange.start).index; return [FlutterTextRange rangeWithNSRange:fml::RangeForCharacterAtIndex(self.text, currentIndex)]; } // Overall logic for floating cursor's "move" gesture and "selection" gesture: // // Floating cursor's "move" gesture takes 1 finger to force press the space bar, and then move the // cursor. The process starts with `beginFloatingCursorAtPoint`. When the finger is moved, // `updateFloatingCursorAtPoint` will be called. When the finger is released, `endFloatingCursor` // will be called. In all cases, we send the point (relative to the initial point registered in // beginFloatingCursorAtPoint) to the framework, so that framework can animate the floating cursor. // // During the move gesture, the framework only animate the cursor visually. It's only // after the gesture is complete, will the framework update the selection to the cursor's // new position (with zero selection length). This means during the animation, the visual effect // of the cursor is temporarily out of sync with the selection state in both framework and engine. // But it will be in sync again after the animation is complete. // // Floating cursor's "selection" gesture also starts with 1 finger to force press the space bar, // so exactly the same functions as the "move gesture" discussed above will be called. When the // second finger is pressed, `setSelectedText` will be called. This mechanism requires // `closestPositionFromPoint` to be implemented, to allow UIKit to translate the finger touch // location displacement to the text range to select. When the selection is completed // (i.e. when both of the 2 fingers are released), similar to "move" gesture, // the `endFloatingCursor` will be called. // // When the 2nd finger is pressed, it does not trigger another startFloatingCursor call. So // floating cursor move/selection logic has to be implemented in iOS embedder rather than // just the framework side. // // Whenever a selection is updated, the engine sends the new selection to the framework. So unlike // the move gesture, the selections in the framework and the engine are always kept in sync. - (void)beginFloatingCursorAtPoint:(CGPoint)point { // For "beginFloatingCursorAtPoint" and "updateFloatingCursorAtPoint", "point" is roughly: // // CGPoint( // width >= 0 ? point.x.clamp(boundingBox.left, boundingBox.right) : point.x, // height >= 0 ? point.y.clamp(boundingBox.top, boundingBox.bottom) : point.y, // ) // where // point = keyboardPanGestureRecognizer.translationInView(textInputView) + caretRectForPosition // boundingBox = self.convertRect(bounds, fromView:textInputView) // bounds = self._selectionClipRect ?? self.bounds // // It seems impossible to use a negative "width" or "height", as the "convertRect" // call always turns a CGRect's negative dimensions into non-negative values, e.g., // (1, 2, -3, -4) would become (-2, -2, 3, 4). _isFloatingCursorActive = YES; _floatingCursorOffset = point; [self.textInputDelegate flutterTextInputView:self updateFloatingCursor:FlutterFloatingCursorDragStateStart withClient:_textInputClient withPosition:@{@"X" : @0, @"Y" : @0}]; } - (void)updateFloatingCursorAtPoint:(CGPoint)point { [self.textInputDelegate flutterTextInputView:self updateFloatingCursor:FlutterFloatingCursorDragStateUpdate withClient:_textInputClient withPosition:@{ @"X" : @(point.x - _floatingCursorOffset.x), @"Y" : @(point.y - _floatingCursorOffset.y) }]; } - (void)endFloatingCursor { _isFloatingCursorActive = NO; [self.textInputDelegate flutterTextInputView:self updateFloatingCursor:FlutterFloatingCursorDragStateEnd withClient:_textInputClient withPosition:@{@"X" : @0, @"Y" : @0}]; } #pragma mark - UIKeyInput Overrides - (void)updateEditingState { NSUInteger selectionBase = ((FlutterTextPosition*)_selectedTextRange.start).index; NSUInteger selectionExtent = ((FlutterTextPosition*)_selectedTextRange.end).index; // Empty compositing range is represented by the framework's TextRange.empty. NSInteger composingBase = -1; NSInteger composingExtent = -1; if (self.markedTextRange != nil) { composingBase = ((FlutterTextPosition*)self.markedTextRange.start).index; composingExtent = ((FlutterTextPosition*)self.markedTextRange.end).index; } NSDictionary* state = @{ @"selectionBase" : @(selectionBase), @"selectionExtent" : @(selectionExtent), @"selectionAffinity" : @(_selectionAffinity), @"selectionIsDirectional" : @(false), @"composingBase" : @(composingBase), @"composingExtent" : @(composingExtent), @"text" : [NSString stringWithString:self.text], }; if (_textInputClient == 0 && _autofillId != nil) { [self.textInputDelegate flutterTextInputView:self updateEditingClient:_textInputClient withState:state withTag:_autofillId]; } else { [self.textInputDelegate flutterTextInputView:self updateEditingClient:_textInputClient withState:state]; } } - (void)updateEditingStateWithDelta:(flutter::TextEditingDelta)delta { NSUInteger selectionBase = ((FlutterTextPosition*)_selectedTextRange.start).index; NSUInteger selectionExtent = ((FlutterTextPosition*)_selectedTextRange.end).index; // Empty compositing range is represented by the framework's TextRange.empty. NSInteger composingBase = -1; NSInteger composingExtent = -1; if (self.markedTextRange != nil) { composingBase = ((FlutterTextPosition*)self.markedTextRange.start).index; composingExtent = ((FlutterTextPosition*)self.markedTextRange.end).index; } NSDictionary* deltaToFramework = @{ @"oldText" : @(delta.old_text().c_str()), @"deltaText" : @(delta.delta_text().c_str()), @"deltaStart" : @(delta.delta_start()), @"deltaEnd" : @(delta.delta_end()), @"selectionBase" : @(selectionBase), @"selectionExtent" : @(selectionExtent), @"selectionAffinity" : @(_selectionAffinity), @"selectionIsDirectional" : @(false), @"composingBase" : @(composingBase), @"composingExtent" : @(composingExtent), }; [_pendingDeltas addObject:deltaToFramework]; if (_pendingDeltas.count == 1) { __weak FlutterTextInputView* weakSelf = self; dispatch_async(dispatch_get_main_queue(), ^{ __strong FlutterTextInputView* strongSelf = weakSelf; if (strongSelf && strongSelf.pendingDeltas.count > 0) { NSDictionary* deltas = @{ @"deltas" : strongSelf.pendingDeltas, }; [strongSelf.textInputDelegate flutterTextInputView:strongSelf updateEditingClient:strongSelf->_textInputClient withDelta:deltas]; [strongSelf.pendingDeltas removeAllObjects]; } }); } } - (BOOL)hasText { return self.text.length > 0; } - (void)insertText:(NSString*)text { if (self.temporarilyDeletedComposedCharacter.length > 0 && text.length == 1 && !text.UTF8String && [text characterAtIndex:0] == [self.temporarilyDeletedComposedCharacter characterAtIndex:0]) { // Workaround for https://github.com/flutter/flutter/issues/111494 // TODO(cyanglaz): revert this workaround if when flutter supports a minimum iOS version which // this bug is fixed by Apple. text = self.temporarilyDeletedComposedCharacter; self.temporarilyDeletedComposedCharacter = nil; } NSMutableArray<FlutterTextSelectionRect*>* copiedRects = [[NSMutableArray alloc] initWithCapacity:[_selectionRects count]]; NSAssert([_selectedTextRange.start isKindOfClass:[FlutterTextPosition class]], @"Expected a FlutterTextPosition for position (got %@).", [_selectedTextRange.start class]); NSUInteger insertPosition = ((FlutterTextPosition*)_selectedTextRange.start).index; for (NSUInteger i = 0; i < [_selectionRects count]; i++) { NSUInteger rectPosition = _selectionRects[i].position; if (rectPosition == insertPosition) { for (NSUInteger j = 0; j <= text.length; j++) { [copiedRects addObject:[FlutterTextSelectionRect selectionRectWithRect:_selectionRects[i].rect position:rectPosition + j writingDirection:_selectionRects[i].writingDirection]]; } } else { if (rectPosition > insertPosition) { rectPosition = rectPosition + text.length; } [copiedRects addObject:[FlutterTextSelectionRect selectionRectWithRect:_selectionRects[i].rect position:rectPosition writingDirection:_selectionRects[i].writingDirection]]; } } _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; [self resetScribbleInteractionStatusIfEnding]; self.selectionRects = copiedRects; _selectionAffinity = kTextAffinityDownstream; [self replaceRange:_selectedTextRange withText:text]; } - (UITextPlaceholder*)insertTextPlaceholderWithSize:(CGSize)size API_AVAILABLE(ios(13.0)) { [self.textInputDelegate flutterTextInputView:self insertTextPlaceholderWithSize:size withClient:_textInputClient]; _hasPlaceholder = YES; return [[FlutterTextPlaceholder alloc] init]; } - (void)removeTextPlaceholder:(UITextPlaceholder*)textPlaceholder API_AVAILABLE(ios(13.0)) { _hasPlaceholder = NO; [self.textInputDelegate flutterTextInputView:self removeTextPlaceholder:_textInputClient]; } - (void)deleteBackward { _selectionAffinity = kTextAffinityDownstream; _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; [self resetScribbleInteractionStatusIfEnding]; // When deleting Thai vowel, _selectedTextRange has location // but does not have length, so we have to manually set it. // In addition, we needed to delete only a part of grapheme cluster // because it is the expected behavior of Thai input. // https://github.com/flutter/flutter/issues/24203 // https://github.com/flutter/flutter/issues/21745 // https://github.com/flutter/flutter/issues/39399 // // This is needed for correct handling of the deletion of Thai vowel input. // TODO(cbracken): Get a good understanding of expected behavior of Thai // input and ensure that this is the correct solution. // https://github.com/flutter/flutter/issues/28962 if (_selectedTextRange.isEmpty && [self hasText]) { UITextRange* oldSelectedRange = _selectedTextRange; NSRange oldRange = ((FlutterTextRange*)oldSelectedRange).range; if (oldRange.location > 0) { NSRange newRange = NSMakeRange(oldRange.location - 1, 1); // We should check if the last character is a part of emoji. // If so, we must delete the entire emoji to prevent the text from being malformed. NSRange charRange = fml::RangeForCharacterAtIndex(self.text, oldRange.location - 1); if (IsEmoji(self.text, charRange)) { newRange = NSMakeRange(charRange.location, oldRange.location - charRange.location); } _selectedTextRange = [[FlutterTextRange rangeWithNSRange:newRange] copy]; } } if (!_selectedTextRange.isEmpty) { // Cache the last deleted emoji to use for an iOS bug where the next // insertion corrupts the emoji characters. // See: https://github.com/flutter/flutter/issues/111494#issuecomment-1248441346 if (IsEmoji(self.text, _selectedTextRange.range)) { NSString* deletedText = [self.text substringWithRange:_selectedTextRange.range]; NSRange deleteFirstCharacterRange = fml::RangeForCharacterAtIndex(deletedText, 0); self.temporarilyDeletedComposedCharacter = [deletedText substringWithRange:deleteFirstCharacterRange]; } [self replaceRange:_selectedTextRange withText:@""]; } } - (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(id)target { UIAccessibilityPostNotification(notification, target); } - (void)accessibilityElementDidBecomeFocused { if ([self accessibilityElementIsFocused]) { // For most of the cases, this flutter text input view should never // receive the focus. If we do receive the focus, we make the best effort // to send the focus back to the real text field. FML_DCHECK(_backingTextInputAccessibilityObject); [self postAccessibilityNotification:UIAccessibilityScreenChangedNotification target:_backingTextInputAccessibilityObject]; } } - (BOOL)accessibilityElementsHidden { return !_accessibilityEnabled; } - (void)resetScribbleInteractionStatusIfEnding { if (_scribbleInteractionStatus == FlutterScribbleInteractionStatusEnding) { _scribbleInteractionStatus = FlutterScribbleInteractionStatusNone; } } #pragma mark - Key Events Handling - (void)pressesBegan:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { [_textInputPlugin.viewController pressesBegan:presses withEvent:event]; } - (void)pressesChanged:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { [_textInputPlugin.viewController pressesChanged:presses withEvent:event]; } - (void)pressesEnded:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { [_textInputPlugin.viewController pressesEnded:presses withEvent:event]; } - (void)pressesCancelled:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { [_textInputPlugin.viewController pressesCancelled:presses withEvent:event]; } @end /** * Hides `FlutterTextInputView` from iOS accessibility system so it * does not show up twice, once where it is in the `UIView` hierarchy, * and a second time as part of the `SemanticsObject` hierarchy. * * This prevents the `FlutterTextInputView` from receiving the focus * due to swiping gesture. * * There are other cases the `FlutterTextInputView` may receive * focus. One example is during screen changes, the accessibility * tree will undergo a dramatic structural update. The Voiceover may * decide to focus the `FlutterTextInputView` that is not involved * in the structural update instead. If that happens, the * `FlutterTextInputView` will make a best effort to direct the * focus back to the `SemanticsObject`. */ @interface FlutterTextInputViewAccessibilityHider : UIView { } @end @implementation FlutterTextInputViewAccessibilityHider { } - (BOOL)accessibilityElementsHidden { return YES; } @end @interface FlutterTextInputPlugin () - (void)enableActiveViewAccessibility; @end @interface FlutterTimerProxy : NSObject @property(nonatomic, weak) FlutterTextInputPlugin* target; @end @implementation FlutterTimerProxy + (instancetype)proxyWithTarget:(FlutterTextInputPlugin*)target { FlutterTimerProxy* proxy = [[self alloc] init]; if (proxy) { proxy.target = target; } return proxy; } - (void)enableActiveViewAccessibility { [self.target enableActiveViewAccessibility]; } @end @interface FlutterTextInputPlugin () // The current password-autofillable input fields that have yet to be saved. @property(nonatomic, readonly) NSMutableDictionary<NSString*, FlutterTextInputView*>* autofillContext; @property(nonatomic, retain) FlutterTextInputView* activeView; @property(nonatomic, retain) FlutterTextInputViewAccessibilityHider* inputHider; @property(nonatomic, readonly, weak) id<FlutterViewResponder> viewResponder; @property(nonatomic, strong) UIView* keyboardViewContainer; @property(nonatomic, strong) UIView* keyboardView; @property(nonatomic, strong) UIView* cachedFirstResponder; @property(nonatomic, assign) CGRect keyboardRect; @property(nonatomic, assign) CGFloat previousPointerYPosition; @property(nonatomic, assign) CGFloat pointerYVelocity; @end @implementation FlutterTextInputPlugin { NSTimer* _enableFlutterTextInputViewAccessibilityTimer; } - (instancetype)initWithDelegate:(id<FlutterTextInputDelegate>)textInputDelegate { self = [super init]; if (self) { // `_textInputDelegate` is a weak reference because it should retain FlutterTextInputPlugin. _textInputDelegate = textInputDelegate; _autofillContext = [[NSMutableDictionary alloc] init]; _inputHider = [[FlutterTextInputViewAccessibilityHider alloc] init]; _scribbleElements = [[NSMutableDictionary alloc] init]; _keyboardViewContainer = [[UIView alloc] init]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; } return self; } - (void)handleKeyboardWillShow:(NSNotification*)notification { NSDictionary* keyboardInfo = [notification userInfo]; NSValue* keyboardFrameEnd = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey]; _keyboardRect = [keyboardFrameEnd CGRectValue]; } - (void)dealloc { [self hideTextInput]; } - (void)removeEnableFlutterTextInputViewAccessibilityTimer { if (_enableFlutterTextInputViewAccessibilityTimer) { [_enableFlutterTextInputViewAccessibilityTimer invalidate]; _enableFlutterTextInputViewAccessibilityTimer = nil; } } - (UIView<UITextInput>*)textInputView { return _activeView; } - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { NSString* method = call.method; id args = call.arguments; if ([method isEqualToString:kShowMethod]) { [self showTextInput]; result(nil); } else if ([method isEqualToString:kHideMethod]) { [self hideTextInput]; result(nil); } else if ([method isEqualToString:kSetClientMethod]) { [self setTextInputClient:[args[0] intValue] withConfiguration:args[1]]; result(nil); } else if ([method isEqualToString:kSetPlatformViewClientMethod]) { // This method call has a `platformViewId` argument, but we do not need it for iOS for now. [self setPlatformViewTextInputClient]; result(nil); } else if ([method isEqualToString:kSetEditingStateMethod]) { [self setTextInputEditingState:args]; result(nil); } else if ([method isEqualToString:kClearClientMethod]) { [self clearTextInputClient]; result(nil); } else if ([method isEqualToString:kSetEditableSizeAndTransformMethod]) { [self setEditableSizeAndTransform:args]; result(nil); } else if ([method isEqualToString:kSetMarkedTextRectMethod]) { [self updateMarkedRect:args]; result(nil); } else if ([method isEqualToString:kFinishAutofillContextMethod]) { [self triggerAutofillSave:[args boolValue]]; result(nil); // TODO(justinmc): Remove the TextInput method constant when the framework has // finished transitioning to using the Scribble channel. // https://github.com/flutter/flutter/pull/104128 } else if ([method isEqualToString:kDeprecatedSetSelectionRectsMethod]) { [self setSelectionRects:args]; result(nil); } else if ([method isEqualToString:kSetSelectionRectsMethod]) { [self setSelectionRects:args]; result(nil); } else if ([method isEqualToString:kStartLiveTextInputMethod]) { [self startLiveTextInput]; result(nil); } else if ([method isEqualToString:kUpdateConfigMethod]) { [self updateConfig:args]; result(nil); } else if ([method isEqualToString:kOnInteractiveKeyboardPointerMoveMethod]) { CGFloat pointerY = (CGFloat)[args[@"pointerY"] doubleValue]; [self handlePointerMove:pointerY]; result(nil); } else if ([method isEqualToString:kOnInteractiveKeyboardPointerUpMethod]) { CGFloat pointerY = (CGFloat)[args[@"pointerY"] doubleValue]; [self handlePointerUp:pointerY]; result(nil); } else { result(FlutterMethodNotImplemented); } } - (void)handlePointerUp:(CGFloat)pointerY { if (_keyboardView.superview != nil) { // Done to avoid the issue of a pointer up done without a screenshot // View must be loaded at this point. UIScreen* screen = _viewController.flutterScreenIfViewLoaded; CGFloat screenHeight = screen.bounds.size.height; CGFloat keyboardHeight = _keyboardRect.size.height; // Negative velocity indicates a downward movement BOOL shouldDismissKeyboardBasedOnVelocity = _pointerYVelocity < 0; [UIView animateWithDuration:kKeyboardAnimationTimeToCompleteion animations:^{ double keyboardDestination = shouldDismissKeyboardBasedOnVelocity ? screenHeight : screenHeight - keyboardHeight; _keyboardViewContainer.frame = CGRectMake( 0, keyboardDestination, _viewController.flutterScreenIfViewLoaded.bounds.size.width, _keyboardViewContainer.frame.size.height); } completion:^(BOOL finished) { if (shouldDismissKeyboardBasedOnVelocity) { [self.textInputDelegate flutterTextInputView:self.activeView didResignFirstResponderWithTextInputClient:self.activeView.textInputClient]; [self dismissKeyboardScreenshot]; } else { [self showKeyboardAndRemoveScreenshot]; } }]; } } - (void)dismissKeyboardScreenshot { for (UIView* subView in _keyboardViewContainer.subviews) { [subView removeFromSuperview]; } } - (void)showKeyboardAndRemoveScreenshot { [UIView setAnimationsEnabled:NO]; [_cachedFirstResponder becomeFirstResponder]; // UIKit does not immediately access the areAnimationsEnabled Boolean so a delay is needed before // returned dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kKeyboardAnimationDelaySeconds * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [UIView setAnimationsEnabled:YES]; [self dismissKeyboardScreenshot]; }); } - (void)handlePointerMove:(CGFloat)pointerY { // View must be loaded at this point. UIScreen* screen = _viewController.flutterScreenIfViewLoaded; CGFloat screenHeight = screen.bounds.size.height; CGFloat keyboardHeight = _keyboardRect.size.height; if (screenHeight - keyboardHeight <= pointerY) { // If the pointer is within the bounds of the keyboard. if (_keyboardView.superview == nil) { // If no screenshot has been taken. [self takeKeyboardScreenshotAndDisplay]; [self hideKeyboardWithoutAnimationAndAvoidCursorDismissUpdate]; } else { [self setKeyboardContainerHeight:pointerY]; _pointerYVelocity = _previousPointerYPosition - pointerY; } } else { if (_keyboardView.superview != nil) { // Keeps keyboard at proper height. _keyboardViewContainer.frame = _keyboardRect; _pointerYVelocity = _previousPointerYPosition - pointerY; } } _previousPointerYPosition = pointerY; } - (void)setKeyboardContainerHeight:(CGFloat)pointerY { CGRect frameRect = _keyboardRect; frameRect.origin.y = pointerY; _keyboardViewContainer.frame = frameRect; } - (void)hideKeyboardWithoutAnimationAndAvoidCursorDismissUpdate { [UIView setAnimationsEnabled:NO]; _cachedFirstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder; _activeView.preventCursorDismissWhenResignFirstResponder = YES; [_cachedFirstResponder resignFirstResponder]; _activeView.preventCursorDismissWhenResignFirstResponder = NO; [UIView setAnimationsEnabled:YES]; } - (void)takeKeyboardScreenshotAndDisplay { // View must be loaded at this point UIScreen* screen = _viewController.flutterScreenIfViewLoaded; UIView* keyboardSnap = [screen snapshotViewAfterScreenUpdates:YES]; keyboardSnap = [keyboardSnap resizableSnapshotViewFromRect:_keyboardRect afterScreenUpdates:YES withCapInsets:UIEdgeInsetsZero]; _keyboardView = keyboardSnap; [_keyboardViewContainer addSubview:_keyboardView]; if (_keyboardViewContainer.superview == nil) { [UIApplication.sharedApplication.delegate.window.rootViewController.view addSubview:_keyboardViewContainer]; } _keyboardViewContainer.layer.zPosition = NSIntegerMax; _keyboardViewContainer.frame = _keyboardRect; } - (void)setEditableSizeAndTransform:(NSDictionary*)dictionary { NSArray* transform = dictionary[@"transform"]; [_activeView setEditableTransform:transform]; const int leftIndex = 12; const int topIndex = 13; if ([_activeView isScribbleAvailable]) { // This is necessary to set up where the scribble interactable element will be. _inputHider.frame = CGRectMake([transform[leftIndex] intValue], [transform[topIndex] intValue], [dictionary[@"width"] intValue], [dictionary[@"height"] intValue]); _activeView.frame = CGRectMake(0, 0, [dictionary[@"width"] intValue], [dictionary[@"height"] intValue]); _activeView.tintColor = [UIColor clearColor]; } else { // TODO(hellohuanlin): Also need to handle iOS 16 case, where the auto-correction highlight does // not match the size of text. // See https://github.com/flutter/flutter/issues/131695 if (@available(iOS 17, *)) { // Move auto-correction highlight to overlap with the actual text. // This is to fix an issue where the system auto-correction highlight is displayed at // the top left corner of the screen on iOS 17+. // This problem also happens on iOS 16, but the size of highlight does not match the text. // See https://github.com/flutter/flutter/issues/131695 // TODO(hellohuanlin): Investigate if we can use non-zero size. _inputHider.frame = CGRectMake([transform[leftIndex] intValue], [transform[topIndex] intValue], 0, 0); } } } - (void)updateMarkedRect:(NSDictionary*)dictionary { NSAssert(dictionary[@"x"] != nil && dictionary[@"y"] != nil && dictionary[@"width"] != nil && dictionary[@"height"] != nil, @"Expected a dictionary representing a CGRect, got %@", dictionary); CGRect rect = CGRectMake([dictionary[@"x"] doubleValue], [dictionary[@"y"] doubleValue], [dictionary[@"width"] doubleValue], [dictionary[@"height"] doubleValue]); _activeView.markedRect = rect.size.width < 0 && rect.size.height < 0 ? kInvalidFirstRect : rect; } - (void)setSelectionRects:(NSArray*)encodedRects { NSMutableArray<FlutterTextSelectionRect*>* rectsAsRect = [[NSMutableArray alloc] initWithCapacity:[encodedRects count]]; for (NSUInteger i = 0; i < [encodedRects count]; i++) { NSArray<NSNumber*>* encodedRect = encodedRects[i]; [rectsAsRect addObject:[FlutterTextSelectionRect selectionRectWithRect:CGRectMake([encodedRect[0] floatValue], [encodedRect[1] floatValue], [encodedRect[2] floatValue], [encodedRect[3] floatValue]) position:[encodedRect[4] unsignedIntegerValue] writingDirection:[encodedRect[5] unsignedIntegerValue] == 1 ? NSWritingDirectionLeftToRight : NSWritingDirectionRightToLeft]]; } // TODO(hellohuanlin): Investigate why notifying the text input system about text changes (via // textWillChange and textDidChange APIs) causes a bug where we cannot enter text with IME // keyboards. Issue: https://github.com/flutter/flutter/issues/133908 _activeView.selectionRects = rectsAsRect; } - (void)startLiveTextInput { if (@available(iOS 15.0, *)) { if (_activeView == nil || !_activeView.isFirstResponder) { return; } [_activeView captureTextFromCamera:nil]; } } - (void)showTextInput { _activeView.viewResponder = _viewResponder; [self addToInputParentViewIfNeeded:_activeView]; // Adds a delay to prevent the text view from receiving accessibility // focus in case it is activated during semantics updates. // // One common case is when the app navigates to a page with an auto // focused text field. The text field will activate the FlutterTextInputView // with a semantics update sent to the engine. The voiceover will focus // the newly attached active view while performing accessibility update. // This results in accessibility focus stuck at the FlutterTextInputView. if (!_enableFlutterTextInputViewAccessibilityTimer) { _enableFlutterTextInputViewAccessibilityTimer = [NSTimer scheduledTimerWithTimeInterval:kUITextInputAccessibilityEnablingDelaySeconds target:[FlutterTimerProxy proxyWithTarget:self] selector:@selector(enableActiveViewAccessibility) userInfo:nil repeats:NO]; } [_activeView becomeFirstResponder]; } - (void)enableActiveViewAccessibility { if (_activeView.isFirstResponder) { _activeView.accessibilityEnabled = YES; } [self removeEnableFlutterTextInputViewAccessibilityTimer]; } - (void)hideTextInput { [self removeEnableFlutterTextInputViewAccessibilityTimer]; _activeView.accessibilityEnabled = NO; [_activeView resignFirstResponder]; [_activeView removeFromSuperview]; [_inputHider removeFromSuperview]; } - (void)triggerAutofillSave:(BOOL)saveEntries { [_activeView resignFirstResponder]; if (saveEntries) { // Make all the input fields in the autofill context visible, // then remove them to trigger autofill save. [self cleanUpViewHierarchy:YES clearText:YES delayRemoval:NO]; [_autofillContext removeAllObjects]; [self changeInputViewsAutofillVisibility:YES]; } else { [_autofillContext removeAllObjects]; } [self cleanUpViewHierarchy:YES clearText:!saveEntries delayRemoval:NO]; [self addToInputParentViewIfNeeded:_activeView]; } - (void)setPlatformViewTextInputClient { // No need to track the platformViewID (unlike in Android). When a platform view // becomes the first responder, simply hide this dummy text input view (`_activeView`) // for the previously focused widget. [self removeEnableFlutterTextInputViewAccessibilityTimer]; _activeView.accessibilityEnabled = NO; [_activeView removeFromSuperview]; [_inputHider removeFromSuperview]; } - (void)setTextInputClient:(int)client withConfiguration:(NSDictionary*)configuration { [self resetAllClientIds]; // Hide all input views from autofill, only make those in the new configuration visible // to autofill. [self changeInputViewsAutofillVisibility:NO]; // Update the current active view. switch (AutofillTypeOf(configuration)) { case kFlutterAutofillTypeNone: self.activeView = [self createInputViewWith:configuration]; break; case kFlutterAutofillTypeRegular: // If the group does not involve password autofill, only install the // input view that's being focused. self.activeView = [self updateAndShowAutofillViews:nil focusedField:configuration isPasswordRelated:NO]; break; case kFlutterAutofillTypePassword: self.activeView = [self updateAndShowAutofillViews:configuration[kAssociatedAutofillFields] focusedField:configuration isPasswordRelated:YES]; break; } [_activeView setTextInputClient:client]; [_activeView reloadInputViews]; // Clean up views that no longer need to be in the view hierarchy, according to // the current autofill context. The "garbage" input views are already made // invisible to autofill and they can't `becomeFirstResponder`, we only remove // them to free up resources and reduce the number of input views in the view // hierarchy. // // The garbage views are decommissioned immediately, but the removeFromSuperview // call is scheduled on the runloop and delayed by 0.1s so we don't remove the // text fields immediately (which seems to make the keyboard flicker). // See: https://github.com/flutter/flutter/issues/64628. [self cleanUpViewHierarchy:NO clearText:YES delayRemoval:YES]; } // Creates and shows an input field that is not password related and has no autofill // info. This method returns a new FlutterTextInputView instance when called, since // UIKit uses the identity of `UITextInput` instances (or the identity of the input // views) to decide whether the IME's internal states should be reset. See: // https://github.com/flutter/flutter/issues/79031 . - (FlutterTextInputView*)createInputViewWith:(NSDictionary*)configuration { NSString* autofillId = AutofillIdFromDictionary(configuration); if (autofillId) { [_autofillContext removeObjectForKey:autofillId]; } FlutterTextInputView* newView = [[FlutterTextInputView alloc] initWithOwner:self]; [newView configureWithDictionary:configuration]; [self addToInputParentViewIfNeeded:newView]; for (NSDictionary* field in configuration[kAssociatedAutofillFields]) { NSString* autofillId = AutofillIdFromDictionary(field); if (autofillId && AutofillTypeOf(field) == kFlutterAutofillTypeNone) { [_autofillContext removeObjectForKey:autofillId]; } } return newView; } - (FlutterTextInputView*)updateAndShowAutofillViews:(NSArray*)fields focusedField:(NSDictionary*)focusedField isPasswordRelated:(BOOL)isPassword { FlutterTextInputView* focused = nil; NSString* focusedId = AutofillIdFromDictionary(focusedField); NSAssert(focusedId, @"autofillId must not be null for the focused field: %@", focusedField); if (!fields) { // DO NOT push the current autofillable input fields to the context even // if it's password-related, because it is not in an autofill group. focused = [self getOrCreateAutofillableView:focusedField isPasswordAutofill:isPassword]; [_autofillContext removeObjectForKey:focusedId]; } for (NSDictionary* field in fields) { NSString* autofillId = AutofillIdFromDictionary(field); NSAssert(autofillId, @"autofillId must not be null for field: %@", field); BOOL hasHints = AutofillTypeOf(field) != kFlutterAutofillTypeNone; BOOL isFocused = [focusedId isEqualToString:autofillId]; if (isFocused) { focused = [self getOrCreateAutofillableView:field isPasswordAutofill:isPassword]; } if (hasHints) { // Push the current input field to the context if it has hints. _autofillContext[autofillId] = isFocused ? focused : [self getOrCreateAutofillableView:field isPasswordAutofill:isPassword]; } else { // Mark for deletion. [_autofillContext removeObjectForKey:autofillId]; } } NSAssert(focused, @"The current focused input view must not be nil."); return focused; } // Returns a new non-reusable input view (and put it into the view hierarchy), or get the // view from the current autofill context, if an input view with the same autofill id // already exists in the context. // This is generally used for input fields that are autofillable (UIKit tracks these veiws // for autofill purposes so they should not be reused for a different type of views). - (FlutterTextInputView*)getOrCreateAutofillableView:(NSDictionary*)field isPasswordAutofill:(BOOL)needsPasswordAutofill { NSString* autofillId = AutofillIdFromDictionary(field); FlutterTextInputView* inputView = _autofillContext[autofillId]; if (!inputView) { inputView = needsPasswordAutofill ? [FlutterSecureTextInputView alloc] : [FlutterTextInputView alloc]; inputView = [inputView initWithOwner:self]; [self addToInputParentViewIfNeeded:inputView]; } [inputView configureWithDictionary:field]; return inputView; } // The UIView to add FlutterTextInputViews to. - (UIView*)hostView { UIView* host = _viewController.view; NSAssert(host != nullptr, @"The application must have a host view since the keyboard client " @"must be part of the responder chain to function. The host view controller is %@", _viewController); return host; } // The UIView to add FlutterTextInputViews to. - (NSArray<UIView*>*)textInputViews { return _inputHider.subviews; } // Removes every installed input field, unless it's in the current autofill context. // // The active view will be removed from its superview too, if includeActiveView is YES. // When clearText is YES, the text on the input fields will be set to empty before // they are removed from the view hierarchy, to avoid triggering autofill save. // If delayRemoval is true, removeFromSuperview will be scheduled on the runloop and // will be delayed by 0.1s so we don't remove the text fields immediately (which seems // to make the keyboard flicker). // See: https://github.com/flutter/flutter/issues/64628. - (void)cleanUpViewHierarchy:(BOOL)includeActiveView clearText:(BOOL)clearText delayRemoval:(BOOL)delayRemoval { for (UIView* view in self.textInputViews) { if ([view isKindOfClass:[FlutterTextInputView class]] && (includeActiveView || view != _activeView)) { FlutterTextInputView* inputView = (FlutterTextInputView*)view; if (_autofillContext[inputView.autofillId] != view) { if (clearText) { [inputView replaceRangeLocal:NSMakeRange(0, inputView.text.length) withText:@""]; } if (delayRemoval) { [inputView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.1]; } else { [inputView removeFromSuperview]; } } } } } // Changes the visibility of every FlutterTextInputView currently in the // view hierarchy. - (void)changeInputViewsAutofillVisibility:(BOOL)newVisibility { for (UIView* view in self.textInputViews) { if ([view isKindOfClass:[FlutterTextInputView class]]) { FlutterTextInputView* inputView = (FlutterTextInputView*)view; inputView.isVisibleToAutofill = newVisibility; } } } // Resets the client id of every FlutterTextInputView in the view hierarchy // to 0. // Called before establishing a new text input connection. // For views in the current autofill context, they need to // stay in the view hierachy but should not be allowed to // send messages (other than autofill related ones) to the // framework. - (void)resetAllClientIds { for (UIView* view in self.textInputViews) { if ([view isKindOfClass:[FlutterTextInputView class]]) { FlutterTextInputView* inputView = (FlutterTextInputView*)view; [inputView setTextInputClient:0]; } } } - (void)addToInputParentViewIfNeeded:(FlutterTextInputView*)inputView { if (![inputView isDescendantOfView:_inputHider]) { [_inputHider addSubview:inputView]; } if (_viewController.view == nil) { // If view controller's view has detached from flutter engine, we don't add _inputHider // in parent view to fallback and avoid crash. // https://github.com/flutter/flutter/issues/106404. return; } UIView* parentView = self.hostView; if (_inputHider.superview != parentView) { [parentView addSubview:_inputHider]; } } - (void)setTextInputEditingState:(NSDictionary*)state { [_activeView setTextInputState:state]; } - (void)clearTextInputClient { [_activeView setTextInputClient:0]; _activeView.frame = CGRectZero; } - (void)updateConfig:(NSDictionary*)dictionary { BOOL isSecureTextEntry = [dictionary[kSecureTextEntry] boolValue]; for (UIView* view in self.textInputViews) { if ([view isKindOfClass:[FlutterTextInputView class]]) { FlutterTextInputView* inputView = (FlutterTextInputView*)view; // The feature of holding and draging spacebar to move cursor is affected by // secureTextEntry, so when obscureText is updated, we need to update secureTextEntry // and call reloadInputViews. // https://github.com/flutter/flutter/issues/122139 if (inputView.isSecureTextEntry != isSecureTextEntry) { inputView.secureTextEntry = isSecureTextEntry; [inputView reloadInputViews]; } } } } #pragma mark UIIndirectScribbleInteractionDelegate - (BOOL)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction isElementFocused:(UIScribbleElementIdentifier)elementIdentifier API_AVAILABLE(ios(14.0)) { return _activeView.scribbleFocusStatus == FlutterScribbleFocusStatusFocused; } - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction focusElementIfNeeded:(UIScribbleElementIdentifier)elementIdentifier referencePoint:(CGPoint)focusReferencePoint completion:(void (^)(UIResponder<UITextInput>* focusedInput))completion API_AVAILABLE(ios(14.0)) { _activeView.scribbleFocusStatus = FlutterScribbleFocusStatusFocusing; [_indirectScribbleDelegate flutterTextInputPlugin:self focusElement:elementIdentifier atPoint:focusReferencePoint result:^(id _Nullable result) { _activeView.scribbleFocusStatus = FlutterScribbleFocusStatusFocused; completion(_activeView); }]; } - (BOOL)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction shouldDelayFocusForElement:(UIScribbleElementIdentifier)elementIdentifier API_AVAILABLE(ios(14.0)) { return NO; } - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction willBeginWritingInElement:(UIScribbleElementIdentifier)elementIdentifier API_AVAILABLE(ios(14.0)) { } - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction didFinishWritingInElement:(UIScribbleElementIdentifier)elementIdentifier API_AVAILABLE(ios(14.0)) { } - (CGRect)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction frameForElement:(UIScribbleElementIdentifier)elementIdentifier API_AVAILABLE(ios(14.0)) { NSValue* elementValue = [_scribbleElements objectForKey:elementIdentifier]; if (elementValue == nil) { return CGRectZero; } return [elementValue CGRectValue]; } - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction requestElementsInRect:(CGRect)rect completion: (void (^)(NSArray<UIScribbleElementIdentifier>* elements))completion API_AVAILABLE(ios(14.0)) { [_indirectScribbleDelegate flutterTextInputPlugin:self requestElementsInRect:rect result:^(id _Nullable result) { NSMutableArray<UIScribbleElementIdentifier>* elements = [[NSMutableArray alloc] init]; if ([result isKindOfClass:[NSArray class]]) { for (NSArray* elementArray in result) { [elements addObject:elementArray[0]]; [_scribbleElements setObject:[NSValue valueWithCGRect:CGRectMake( [elementArray[1] floatValue], [elementArray[2] floatValue], [elementArray[3] floatValue], [elementArray[4] floatValue])] forKey:elementArray[0]]; } } completion(elements); }]; } #pragma mark - Methods related to Scribble support - (void)setUpIndirectScribbleInteraction:(id<FlutterViewResponder>)viewResponder { if (_viewResponder != viewResponder) { if (@available(iOS 14.0, *)) { UIView* parentView = viewResponder.view; if (parentView != nil) { UIIndirectScribbleInteraction* scribbleInteraction = [[UIIndirectScribbleInteraction alloc] initWithDelegate:(id<UIIndirectScribbleInteractionDelegate>)self]; [parentView addInteraction:scribbleInteraction]; } } } _viewResponder = viewResponder; } - (void)resetViewResponder { _viewResponder = nil; } #pragma mark - #pragma mark FlutterKeySecondaryResponder /** * Handles key down events received from the view controller, responding YES if * the event was handled. */ - (BOOL)handlePress:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { return NO; } @end /** * Recursively searches the UIView's subviews to locate the First Responder */ @implementation UIView (FindFirstResponder) - (id)flutterFirstResponder { if (self.isFirstResponder) { return self; } for (UIView* subView in self.subviews) { UIView* firstResponder = subView.flutterFirstResponder; if (firstResponder) { return firstResponder; } } return nil; } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm", "repo_id": "engine", "token_count": 46195 }
321
// 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 <OCMock/OCMock.h> #import <XCTest/XCTest.h> #include "flutter/fml/platform/darwin/message_loop_darwin.h" #import "flutter/lib/ui/window/platform_configuration.h" #include "flutter/lib/ui/window/pointer_data.h" #import "flutter/lib/ui/window/viewport_metrics.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" #import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" #import "flutter/shell/platform/embedder/embedder.h" #import "flutter/third_party/spring_animation/spring_animation.h" FLUTTER_ASSERT_ARC using namespace flutter::testing; @interface FlutterEngine () - (FlutterTextInputPlugin*)textInputPlugin; - (void)sendKeyEvent:(const FlutterKeyEvent&)event callback:(nullable FlutterKeyEventCallback)callback userData:(nullable void*)userData; - (fml::RefPtr<fml::TaskRunner>)uiTaskRunner; @end /// Sometimes we have to use a custom mock to avoid retain cycles in OCMock. /// Used for testing low memory notification. @interface FlutterEnginePartialMock : FlutterEngine @property(nonatomic, strong) FlutterBasicMessageChannel* lifecycleChannel; @property(nonatomic, strong) FlutterBasicMessageChannel* keyEventChannel; @property(nonatomic, weak) FlutterViewController* viewController; @property(nonatomic, strong) FlutterTextInputPlugin* textInputPlugin; @property(nonatomic, assign) BOOL didCallNotifyLowMemory; - (FlutterTextInputPlugin*)textInputPlugin; - (void)sendKeyEvent:(const FlutterKeyEvent&)event callback:(nullable FlutterKeyEventCallback)callback userData:(nullable void*)userData; @end @implementation FlutterEnginePartialMock @synthesize viewController; @synthesize lifecycleChannel; @synthesize keyEventChannel; @synthesize textInputPlugin; - (void)notifyLowMemory { _didCallNotifyLowMemory = YES; } - (void)sendKeyEvent:(const FlutterKeyEvent&)event callback:(FlutterKeyEventCallback)callback userData:(void*)userData API_AVAILABLE(ios(9.0)) { if (callback == nil) { return; } // NSAssert(callback != nullptr, @"Invalid callback"); // Response is async, so we have to post it to the run loop instead of calling // it directly. CFRunLoopPerformBlock(CFRunLoopGetCurrent(), fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode, ^() { callback(true, userData); }); } @end @interface FlutterEngine () - (BOOL)createShell:(NSString*)entrypoint libraryURI:(NSString*)libraryURI initialRoute:(NSString*)initialRoute; - (void)dispatchPointerDataPacket:(std::unique_ptr<flutter::PointerDataPacket>)packet; - (void)updateViewportMetrics:(flutter::ViewportMetrics)viewportMetrics; - (void)attachView; @end @interface FlutterEngine (TestLowMemory) - (void)notifyLowMemory; @end extern NSNotificationName const FlutterViewControllerWillDealloc; /// A simple mock class for FlutterEngine. /// /// OCMClassMock can't be used for FlutterEngine sometimes because OCMock retains arguments to /// invocations and since the init for FlutterViewController calls a method on the /// FlutterEngine it creates a retain cycle that stops us from testing behaviors related to /// deleting FlutterViewControllers. /// /// Used for testing deallocation. @interface MockEngine : NSObject @property(nonatomic, strong) FlutterDartProject* project; @end @implementation MockEngine - (FlutterViewController*)viewController { return nil; } - (void)setViewController:(FlutterViewController*)viewController { // noop } @end @interface FlutterKeyboardManager (Tests) @property(nonatomic, retain, readonly) NSMutableArray<id<FlutterKeyPrimaryResponder>>* primaryResponders; @end @interface FlutterEmbedderKeyResponder (Tests) @property(nonatomic, copy, readonly) FlutterSendKeyEvent sendEvent; @end @interface FlutterViewController (Tests) @property(nonatomic, assign) double targetViewInsetBottom; @property(nonatomic, assign) BOOL isKeyboardInOrTransitioningFromBackground; @property(nonatomic, assign) BOOL keyboardAnimationIsShowing; @property(nonatomic, strong) VSyncClient* keyboardAnimationVSyncClient; @property(nonatomic, strong) VSyncClient* touchRateCorrectionVSyncClient; - (void)createTouchRateCorrectionVSyncClientIfNeeded; - (void)surfaceUpdated:(BOOL)appeared; - (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences; - (void)handlePressEvent:(FlutterUIPressProxy*)press nextAction:(void (^)())next API_AVAILABLE(ios(13.4)); - (void)discreteScrollEvent:(UIPanGestureRecognizer*)recognizer; - (void)updateViewportMetricsIfNeeded; - (void)onUserSettingsChanged:(NSNotification*)notification; - (void)applicationWillTerminate:(NSNotification*)notification; - (void)goToApplicationLifecycle:(nonnull NSString*)state; - (void)handleKeyboardNotification:(NSNotification*)notification; - (CGFloat)calculateKeyboardInset:(CGRect)keyboardFrame keyboardMode:(int)keyboardMode; - (BOOL)shouldIgnoreKeyboardNotification:(NSNotification*)notification; - (FlutterKeyboardMode)calculateKeyboardAttachMode:(NSNotification*)notification; - (CGFloat)calculateMultitaskingAdjustment:(CGRect)screenRect keyboardFrame:(CGRect)keyboardFrame; - (void)startKeyBoardAnimation:(NSTimeInterval)duration; - (UIView*)keyboardAnimationView; - (SpringAnimation*)keyboardSpringAnimation; - (void)setUpKeyboardSpringAnimationIfNeeded:(CAAnimation*)keyboardAnimation; - (void)setUpKeyboardAnimationVsyncClient: (FlutterKeyboardAnimationCallback)keyboardAnimationCallback; - (void)ensureViewportMetricsIsCorrect; - (void)invalidateKeyboardAnimationVSyncClient; - (void)addInternalPlugins; - (flutter::PointerData)generatePointerDataForFake; - (void)sharedSetupWithProject:(nullable FlutterDartProject*)project initialRoute:(nullable NSString*)initialRoute; - (void)applicationBecameActive:(NSNotification*)notification; - (void)applicationWillResignActive:(NSNotification*)notification; - (void)applicationWillTerminate:(NSNotification*)notification; - (void)applicationDidEnterBackground:(NSNotification*)notification; - (void)applicationWillEnterForeground:(NSNotification*)notification; - (void)sceneBecameActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)); - (void)sceneWillResignActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)); - (void)sceneWillDisconnect:(NSNotification*)notification API_AVAILABLE(ios(13.0)); - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)); - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)); - (void)triggerTouchRateCorrectionIfNeeded:(NSSet*)touches; @end @interface FlutterViewControllerTest : XCTestCase @property(nonatomic, strong) id mockEngine; @property(nonatomic, strong) id mockTextInputPlugin; @property(nonatomic, strong) id messageSent; - (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback; @end @interface UITouch () @property(nonatomic, readwrite) UITouchPhase phase; @end @interface VSyncClient (Testing) - (CADisplayLink*)getDisplayLink; @end @implementation FlutterViewControllerTest - (void)setUp { self.mockEngine = OCMClassMock([FlutterEngine class]); self.mockTextInputPlugin = OCMClassMock([FlutterTextInputPlugin class]); OCMStub([self.mockEngine textInputPlugin]).andReturn(self.mockTextInputPlugin); self.messageSent = nil; } - (void)tearDown { // We stop mocking here to avoid retain cycles that stop // FlutterViewControllers from deallocing. [self.mockEngine stopMocking]; self.mockEngine = nil; self.mockTextInputPlugin = nil; self.messageSent = nil; } - (id)setUpMockScreen { UIScreen* mockScreen = OCMClassMock([UIScreen class]); // iPhone 14 pixels CGRect screenBounds = CGRectMake(0, 0, 1170, 2532); OCMStub([mockScreen bounds]).andReturn(screenBounds); CGFloat screenScale = 1; OCMStub([mockScreen scale]).andReturn(screenScale); return mockScreen; } - (id)setUpMockView:(FlutterViewController*)viewControllerMock screen:(UIScreen*)screen viewFrame:(CGRect)viewFrame convertedFrame:(CGRect)convertedFrame { OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); id mockView = OCMClassMock([UIView class]); OCMStub([mockView frame]).andReturn(viewFrame); OCMStub([mockView convertRect:viewFrame toCoordinateSpace:[OCMArg any]]) .andReturn(convertedFrame); OCMStub([viewControllerMock viewIfLoaded]).andReturn(mockView); return mockView; } - (void)testViewDidLoadWillInvokeCreateTouchRateCorrectionVSyncClient { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); [viewControllerMock loadView]; [viewControllerMock viewDidLoad]; OCMVerify([viewControllerMock createTouchRateCorrectionVSyncClientIfNeeded]); } - (void)testStartKeyboardAnimationWillInvokeSetupKeyboardSpringAnimationIfNeeded { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); viewControllerMock.targetViewInsetBottom = 100; [viewControllerMock startKeyBoardAnimation:0.25]; CAAnimation* keyboardAnimation = [[viewControllerMock keyboardAnimationView].layer animationForKey:@"position"]; OCMVerify([viewControllerMock setUpKeyboardSpringAnimationIfNeeded:keyboardAnimation]); } - (void)testSetupKeyboardSpringAnimationIfNeeded { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); UIScreen* screen = [self setUpMockScreen]; CGRect viewFrame = screen.bounds; [self setUpMockView:viewControllerMock screen:screen viewFrame:viewFrame convertedFrame:viewFrame]; // Null check. [viewControllerMock setUpKeyboardSpringAnimationIfNeeded:nil]; SpringAnimation* keyboardSpringAnimation = [viewControllerMock keyboardSpringAnimation]; XCTAssertTrue(keyboardSpringAnimation == nil); // CAAnimation that is not a CASpringAnimation. CABasicAnimation* nonSpringAnimation = [CABasicAnimation animation]; nonSpringAnimation.duration = 1.0; nonSpringAnimation.fromValue = [NSNumber numberWithFloat:0.0]; nonSpringAnimation.toValue = [NSNumber numberWithFloat:1.0]; nonSpringAnimation.keyPath = @"position"; [viewControllerMock setUpKeyboardSpringAnimationIfNeeded:nonSpringAnimation]; keyboardSpringAnimation = [viewControllerMock keyboardSpringAnimation]; XCTAssertTrue(keyboardSpringAnimation == nil); // CASpringAnimation. CASpringAnimation* springAnimation = [CASpringAnimation animation]; springAnimation.mass = 1.0; springAnimation.stiffness = 100.0; springAnimation.damping = 10.0; springAnimation.keyPath = @"position"; springAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)]; springAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(100, 100)]; [viewControllerMock setUpKeyboardSpringAnimationIfNeeded:springAnimation]; keyboardSpringAnimation = [viewControllerMock keyboardSpringAnimation]; XCTAssertTrue(keyboardSpringAnimation != nil); } - (void)testKeyboardAnimationIsShowingAndCompounding { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); UIScreen* screen = [self setUpMockScreen]; CGRect viewFrame = screen.bounds; [self setUpMockView:viewControllerMock screen:screen viewFrame:viewFrame convertedFrame:viewFrame]; BOOL isLocal = YES; CGFloat screenHeight = screen.bounds.size.height; CGFloat screenWidth = screen.bounds.size.height; // Start show keyboard animation. CGRect initialShowKeyboardBeginFrame = CGRectMake(0, screenHeight, screenWidth, 250); CGRect initialShowKeyboardEndFrame = CGRectMake(0, screenHeight - 250, screenWidth, 500); NSNotification* fakeNotification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameBeginUserInfoKey" : @(initialShowKeyboardBeginFrame), @"UIKeyboardFrameEndUserInfoKey" : @(initialShowKeyboardEndFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; viewControllerMock.targetViewInsetBottom = 0; [viewControllerMock handleKeyboardNotification:fakeNotification]; BOOL isShowingAnimation1 = viewControllerMock.keyboardAnimationIsShowing; XCTAssertTrue(isShowingAnimation1); // Start compounding show keyboard animation. CGRect compoundingShowKeyboardBeginFrame = CGRectMake(0, screenHeight - 250, screenWidth, 250); CGRect compoundingShowKeyboardEndFrame = CGRectMake(0, screenHeight - 500, screenWidth, 500); fakeNotification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameBeginUserInfoKey" : @(compoundingShowKeyboardBeginFrame), @"UIKeyboardFrameEndUserInfoKey" : @(compoundingShowKeyboardEndFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; [viewControllerMock handleKeyboardNotification:fakeNotification]; BOOL isShowingAnimation2 = viewControllerMock.keyboardAnimationIsShowing; XCTAssertTrue(isShowingAnimation2); XCTAssertTrue(isShowingAnimation1 == isShowingAnimation2); // Start hide keyboard animation. CGRect initialHideKeyboardBeginFrame = CGRectMake(0, screenHeight - 500, screenWidth, 250); CGRect initialHideKeyboardEndFrame = CGRectMake(0, screenHeight - 250, screenWidth, 500); fakeNotification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameBeginUserInfoKey" : @(initialHideKeyboardBeginFrame), @"UIKeyboardFrameEndUserInfoKey" : @(initialHideKeyboardEndFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; [viewControllerMock handleKeyboardNotification:fakeNotification]; BOOL isShowingAnimation3 = viewControllerMock.keyboardAnimationIsShowing; XCTAssertFalse(isShowingAnimation3); XCTAssertTrue(isShowingAnimation2 != isShowingAnimation3); // Start compounding hide keyboard animation. CGRect compoundingHideKeyboardBeginFrame = CGRectMake(0, screenHeight - 250, screenWidth, 250); CGRect compoundingHideKeyboardEndFrame = CGRectMake(0, screenHeight, screenWidth, 500); fakeNotification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameBeginUserInfoKey" : @(compoundingHideKeyboardBeginFrame), @"UIKeyboardFrameEndUserInfoKey" : @(compoundingHideKeyboardEndFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; [viewControllerMock handleKeyboardNotification:fakeNotification]; BOOL isShowingAnimation4 = viewControllerMock.keyboardAnimationIsShowing; XCTAssertFalse(isShowingAnimation4); XCTAssertTrue(isShowingAnimation3 == isShowingAnimation4); } - (void)testShouldIgnoreKeyboardNotification { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); UIScreen* screen = [self setUpMockScreen]; CGRect viewFrame = screen.bounds; [self setUpMockView:viewControllerMock screen:screen viewFrame:viewFrame convertedFrame:viewFrame]; CGFloat screenWidth = screen.bounds.size.width; CGFloat screenHeight = screen.bounds.size.height; CGRect emptyKeyboard = CGRectZero; CGRect zeroHeightKeyboard = CGRectMake(0, 0, screenWidth, 0); CGRect validKeyboardEndFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320); BOOL isLocal = NO; // Hide notification, valid keyboard NSNotification* notification = [NSNotification notificationWithName:UIKeyboardWillHideNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; BOOL shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; XCTAssertTrue(shouldIgnore == NO); // All zero keyboard isLocal = YES; notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(emptyKeyboard), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; XCTAssertTrue(shouldIgnore == YES); // Zero height keyboard isLocal = NO; notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(zeroHeightKeyboard), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; XCTAssertTrue(shouldIgnore == NO); // Valid keyboard, triggered from another app isLocal = NO; notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; XCTAssertTrue(shouldIgnore == YES); // Valid keyboard isLocal = YES; notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; XCTAssertTrue(shouldIgnore == NO); if (@available(iOS 13.0, *)) { // noop } else { // Valid keyboard, keyboard is in background OCMStub([viewControllerMock isKeyboardInOrTransitioningFromBackground]).andReturn(YES); isLocal = YES; notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; XCTAssertTrue(shouldIgnore == YES); } } - (void)testKeyboardAnimationWillNotCrashWhenEngineDestroyed { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController setUpKeyboardAnimationVsyncClient:^(fml::TimePoint){ }]; [engine destroyContext]; } - (void)testKeyboardAnimationWillWaitUIThreadVsync { // We need to make sure the new viewport metrics get sent after the // begin frame event has processed. And this test is to expect that the callback // will sync with UI thread. So just simulate a lot of works on UI thread and // test the keyboard animation callback will execute until UI task completed. // Related issue: https://github.com/flutter/flutter/issues/120555. FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; // Post a task to UI thread to block the thread. const int delayTime = 1; [engine uiTaskRunner]->PostTask([] { sleep(delayTime); }); XCTestExpectation* expectation = [self expectationWithDescription:@"keyboard animation callback"]; __block CFTimeInterval fulfillTime; FlutterKeyboardAnimationCallback callback = ^(fml::TimePoint targetTime) { fulfillTime = CACurrentMediaTime(); [expectation fulfill]; }; CFTimeInterval startTime = CACurrentMediaTime(); [viewController setUpKeyboardAnimationVsyncClient:callback]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; XCTAssertTrue(fulfillTime - startTime > delayTime); } - (void)testCalculateKeyboardAttachMode { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); UIScreen* screen = [self setUpMockScreen]; CGRect viewFrame = screen.bounds; [self setUpMockView:viewControllerMock screen:screen viewFrame:viewFrame convertedFrame:viewFrame]; CGFloat screenWidth = screen.bounds.size.width; CGFloat screenHeight = screen.bounds.size.height; // hide notification CGRect keyboardFrame = CGRectZero; NSNotification* notification = [NSNotification notificationWithName:UIKeyboardWillHideNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(YES) }]; FlutterKeyboardMode keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden); // all zeros keyboardFrame = CGRectZero; notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(YES) }]; keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; XCTAssertTrue(keyboardMode == FlutterKeyboardModeFloating); // 0 height keyboardFrame = CGRectMake(0, 0, screenWidth, 0); notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(YES) }]; keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden); // floating keyboardFrame = CGRectMake(0, 0, 320, 320); notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(YES) }]; keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; XCTAssertTrue(keyboardMode == FlutterKeyboardModeFloating); // undocked keyboardFrame = CGRectMake(0, 0, screenWidth, 320); notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(YES) }]; keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; XCTAssertTrue(keyboardMode == FlutterKeyboardModeFloating); // docked keyboardFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320); notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(YES) }]; keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; XCTAssertTrue(keyboardMode == FlutterKeyboardModeDocked); // docked - rounded values CGFloat longDecimalHeight = 320.666666666666666; keyboardFrame = CGRectMake(0, screenHeight - longDecimalHeight, screenWidth, longDecimalHeight); notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(YES) }]; keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; XCTAssertTrue(keyboardMode == FlutterKeyboardModeDocked); // hidden - rounded values keyboardFrame = CGRectMake(0, screenHeight - .0000001, screenWidth, longDecimalHeight); notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(YES) }]; keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden); // hidden keyboardFrame = CGRectMake(0, screenHeight, screenWidth, 320); notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(YES) }]; keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden); } - (void)testCalculateMultitaskingAdjustment { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); UIScreen* screen = [self setUpMockScreen]; CGFloat screenWidth = screen.bounds.size.width; CGFloat screenHeight = screen.bounds.size.height; CGRect screenRect = screen.bounds; CGRect viewOrigFrame = CGRectMake(0, 0, 320, screenHeight - 40); CGRect convertedViewFrame = CGRectMake(20, 20, 320, screenHeight - 40); CGRect keyboardFrame = CGRectMake(20, screenHeight - 320, screenWidth, 300); id mockView = [self setUpMockView:viewControllerMock screen:screen viewFrame:viewOrigFrame convertedFrame:convertedViewFrame]; id mockTraitCollection = OCMClassMock([UITraitCollection class]); OCMStub([mockTraitCollection userInterfaceIdiom]).andReturn(UIUserInterfaceIdiomPad); OCMStub([mockTraitCollection horizontalSizeClass]).andReturn(UIUserInterfaceSizeClassCompact); OCMStub([mockTraitCollection verticalSizeClass]).andReturn(UIUserInterfaceSizeClassRegular); OCMStub([mockView traitCollection]).andReturn(mockTraitCollection); CGFloat adjustment = [viewControllerMock calculateMultitaskingAdjustment:screenRect keyboardFrame:keyboardFrame]; XCTAssertTrue(adjustment == 20); } - (void)testCalculateKeyboardInset { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); UIScreen* screen = [self setUpMockScreen]; OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); CGFloat screenWidth = screen.bounds.size.width; CGFloat screenHeight = screen.bounds.size.height; CGRect viewOrigFrame = CGRectMake(0, 0, 320, screenHeight - 40); CGRect convertedViewFrame = CGRectMake(20, 20, 320, screenHeight - 40); CGRect keyboardFrame = CGRectMake(20, screenHeight - 320, screenWidth, 300); [self setUpMockView:viewControllerMock screen:screen viewFrame:viewOrigFrame convertedFrame:convertedViewFrame]; CGFloat inset = [viewControllerMock calculateKeyboardInset:keyboardFrame keyboardMode:FlutterKeyboardModeDocked]; XCTAssertTrue(inset == 300 * screen.scale); } - (void)testHandleKeyboardNotification { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; // keyboard is empty UIScreen* screen = [self setUpMockScreen]; CGFloat screenWidth = screen.bounds.size.width; CGFloat screenHeight = screen.bounds.size.height; CGRect keyboardFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320); CGRect viewFrame = screen.bounds; BOOL isLocal = YES; NSNotification* notification = [NSNotification notificationWithName:UIKeyboardWillShowNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); [self setUpMockView:viewControllerMock screen:screen viewFrame:viewFrame convertedFrame:viewFrame]; viewControllerMock.targetViewInsetBottom = 0; XCTestExpectation* expectation = [self expectationWithDescription:@"update viewport"]; OCMStub([viewControllerMock updateViewportMetricsIfNeeded]).andDo(^(NSInvocation* invocation) { [expectation fulfill]; }); [viewControllerMock handleKeyboardNotification:notification]; XCTAssertTrue(viewControllerMock.targetViewInsetBottom == 320 * screen.scale); OCMVerify([viewControllerMock startKeyBoardAnimation:0.25]); [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testEnsureBottomInsetIsZeroWhenKeyboardDismissed { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); CGRect keyboardFrame = CGRectZero; BOOL isLocal = YES; NSNotification* fakeNotification = [NSNotification notificationWithName:UIKeyboardWillHideNotification object:nil userInfo:@{ @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) }]; viewControllerMock.targetViewInsetBottom = 10; [viewControllerMock handleKeyboardNotification:fakeNotification]; XCTAssertTrue(viewControllerMock.targetViewInsetBottom == 0); } - (void)testEnsureViewportMetricsWillInvokeAndDisplayLinkWillInvalidateInViewDidDisappear { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; id viewControllerMock = OCMPartialMock(viewController); [viewControllerMock viewDidDisappear:YES]; OCMVerify([viewControllerMock ensureViewportMetricsIsCorrect]); OCMVerify([viewControllerMock invalidateKeyboardAnimationVSyncClient]); } - (void)testViewDidDisappearDoesntPauseEngineWhenNotTheViewController { id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]); FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; mockEngine.lifecycleChannel = lifecycleChannel; FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; id viewControllerMock = OCMPartialMock(viewControllerA); OCMStub([viewControllerMock surfaceUpdated:NO]); mockEngine.viewController = viewControllerB; [viewControllerA viewDidDisappear:NO]; OCMReject([lifecycleChannel sendMessage:@"AppLifecycleState.paused"]); OCMReject([viewControllerMock surfaceUpdated:[OCMArg any]]); } - (void)testAppWillTerminateViewDidDestroyTheEngine { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; id viewControllerMock = OCMPartialMock(viewController); OCMStub([viewControllerMock goToApplicationLifecycle:@"AppLifecycleState.detached"]); OCMStub([mockEngine destroyContext]); [viewController applicationWillTerminate:nil]; OCMVerify([viewControllerMock goToApplicationLifecycle:@"AppLifecycleState.detached"]); OCMVerify([mockEngine destroyContext]); } - (void)testViewDidDisappearDoesPauseEngineWhenIsTheViewController { id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]); FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; mockEngine.lifecycleChannel = lifecycleChannel; __weak FlutterViewController* weakViewController; @autoreleasepool { FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; weakViewController = viewController; id viewControllerMock = OCMPartialMock(viewController); OCMStub([viewControllerMock surfaceUpdated:NO]); [viewController viewDidDisappear:NO]; OCMVerify([lifecycleChannel sendMessage:@"AppLifecycleState.paused"]); OCMVerify([viewControllerMock surfaceUpdated:NO]); } XCTAssertNil(weakViewController); } - (void) testEngineConfigSyncMethodWillExecuteWhenViewControllerInEngineIsCurrentViewControllerInViewWillAppear { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; [viewController viewWillAppear:YES]; OCMVerify([viewController onUserSettingsChanged:nil]); } - (void) testEngineConfigSyncMethodWillNotExecuteWhenViewControllerInEngineIsNotCurrentViewControllerInViewWillAppear { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = nil; FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = nil; mockEngine.viewController = viewControllerB; [viewControllerA viewWillAppear:YES]; OCMVerify(never(), [viewControllerA onUserSettingsChanged:nil]); } - (void) testEngineConfigSyncMethodWillExecuteWhenViewControllerInEngineIsCurrentViewControllerInViewDidAppear { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; [viewController viewDidAppear:YES]; OCMVerify([viewController onUserSettingsChanged:nil]); } - (void) testEngineConfigSyncMethodWillNotExecuteWhenViewControllerInEngineIsNotCurrentViewControllerInViewDidAppear { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = nil; FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = nil; mockEngine.viewController = viewControllerB; [viewControllerA viewDidAppear:YES]; OCMVerify(never(), [viewControllerA onUserSettingsChanged:nil]); } - (void) testEngineConfigSyncMethodWillExecuteWhenViewControllerInEngineIsCurrentViewControllerInViewWillDisappear { id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]); FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; mockEngine.lifecycleChannel = lifecycleChannel; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = viewController; [viewController viewWillDisappear:NO]; OCMVerify([lifecycleChannel sendMessage:@"AppLifecycleState.inactive"]); } - (void) testEngineConfigSyncMethodWillNotExecuteWhenViewControllerInEngineIsNotCurrentViewControllerInViewWillDisappear { id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]); FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; mockEngine.lifecycleChannel = lifecycleChannel; FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = viewControllerB; [viewControllerA viewDidDisappear:NO]; OCMReject([lifecycleChannel sendMessage:@"AppLifecycleState.inactive"]); } - (void)testUpdateViewportMetricsIfNeeded_DoesntInvokeEngineWhenNotTheViewController { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = nil; FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = viewControllerB; [viewControllerA updateViewportMetricsIfNeeded]; flutter::ViewportMetrics viewportMetrics; OCMVerify(never(), [mockEngine updateViewportMetrics:viewportMetrics]); } - (void)testUpdateViewportMetricsIfNeeded_DoesInvokeEngineWhenIsTheViewController { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = viewController; flutter::ViewportMetrics viewportMetrics; OCMExpect([mockEngine updateViewportMetrics:viewportMetrics]).ignoringNonObjectArgs(); [viewController updateViewportMetricsIfNeeded]; OCMVerifyAll(mockEngine); } - (void)testUpdateViewportMetricsIfNeeded_DoesNotInvokeEngineWhenShouldBeIgnoredDuringRotation { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); UIScreen* screen = [self setUpMockScreen]; OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); mockEngine.viewController = viewController; id mockCoordinator = OCMProtocolMock(@protocol(UIViewControllerTransitionCoordinator)); OCMStub([mockCoordinator transitionDuration]).andReturn(0.5); // Mimic the device rotation. [viewController viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:mockCoordinator]; // Should not trigger the engine call when during rotation. [viewController updateViewportMetricsIfNeeded]; OCMVerify(never(), [mockEngine updateViewportMetrics:flutter::ViewportMetrics()]); } - (void)testViewWillTransitionToSize_DoesDelayEngineCallIfNonZeroDuration { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); UIScreen* screen = [self setUpMockScreen]; OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); mockEngine.viewController = viewController; // Mimic the device rotation with non-zero transition duration. NSTimeInterval transitionDuration = 0.5; id mockCoordinator = OCMProtocolMock(@protocol(UIViewControllerTransitionCoordinator)); OCMStub([mockCoordinator transitionDuration]).andReturn(transitionDuration); flutter::ViewportMetrics viewportMetrics; OCMExpect([mockEngine updateViewportMetrics:viewportMetrics]).ignoringNonObjectArgs(); [viewController viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:mockCoordinator]; // Should not immediately call the engine (this request should be ignored). [viewController updateViewportMetricsIfNeeded]; OCMVerify(never(), [mockEngine updateViewportMetrics:flutter::ViewportMetrics()]); // Should delay the engine call for half of the transition duration. // Wait for additional transitionDuration to allow updateViewportMetrics calls if any. XCTWaiterResult result = [XCTWaiter waitForExpectations:@[ [self expectationWithDescription:@"Waiting for rotation duration"] ] timeout:transitionDuration]; XCTAssertEqual(result, XCTWaiterResultTimedOut); OCMVerifyAll(mockEngine); } - (void)testViewWillTransitionToSize_DoesNotDelayEngineCallIfZeroDuration { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; FlutterViewController* viewControllerMock = OCMPartialMock(viewController); UIScreen* screen = [self setUpMockScreen]; OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); mockEngine.viewController = viewController; // Mimic the device rotation with zero transition duration. id mockCoordinator = OCMProtocolMock(@protocol(UIViewControllerTransitionCoordinator)); OCMStub([mockCoordinator transitionDuration]).andReturn(0); flutter::ViewportMetrics viewportMetrics; OCMExpect([mockEngine updateViewportMetrics:viewportMetrics]).ignoringNonObjectArgs(); // Should immediately trigger the engine call, without delay. [viewController viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:mockCoordinator]; [viewController updateViewportMetricsIfNeeded]; OCMVerifyAll(mockEngine); } - (void)testViewDidLoadDoesntInvokeEngineWhenNotTheViewController { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = nil; FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = viewControllerB; UIView* view = viewControllerA.view; XCTAssertNotNil(view); OCMVerify(never(), [mockEngine attachView]); } - (void)testViewDidLoadDoesInvokeEngineWhenIsTheViewController { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; mockEngine.viewController = nil; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; mockEngine.viewController = viewController; UIView* view = viewController.view; XCTAssertNotNil(view); OCMVerify(times(1), [mockEngine attachView]); } - (void)testViewDidLoadDoesntInvokeEngineAttachViewWhenEngineNeedsLaunch { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; mockEngine.viewController = nil; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; // sharedSetupWithProject sets the engine needs to be launched. [viewController sharedSetupWithProject:nil initialRoute:nil]; mockEngine.viewController = viewController; UIView* view = viewController.view; XCTAssertNotNil(view); OCMVerify(never(), [mockEngine attachView]); } - (void)testSplashScreenViewRemoveNotCrash { FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:nil]; [engine runWithEntrypoint:nil]; FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [flutterViewController setSplashScreenView:[[UIView alloc] init]]; [flutterViewController setSplashScreenView:nil]; } - (void)testInternalPluginsWeakPtrNotCrash { FlutterSendKeyEvent sendEvent; @autoreleasepool { FlutterViewController* vc = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil]; [vc addInternalPlugins]; FlutterKeyboardManager* keyboardManager = vc.keyboardManager; FlutterEmbedderKeyResponder* keyPrimaryResponder = (FlutterEmbedderKeyResponder*) [(NSArray<id<FlutterKeyPrimaryResponder>>*)keyboardManager.primaryResponders firstObject]; sendEvent = [keyPrimaryResponder sendEvent]; } if (sendEvent) { sendEvent({}, nil, nil); } } // Regression test for https://github.com/flutter/engine/pull/32098. - (void)testInternalPluginsInvokeInViewDidLoad { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; UIView* view = viewController.view; // The implementation in viewDidLoad requires the viewControllers.viewLoaded is true. // Accessing the view to make sure the view loads in the memory, // which makes viewControllers.viewLoaded true. XCTAssertNotNil(view); [viewController viewDidLoad]; OCMVerify([viewController addInternalPlugins]); } - (void)testBinaryMessenger { FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; XCTAssertNotNil(vc); id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub([self.mockEngine binaryMessenger]).andReturn(messenger); XCTAssertEqual(vc.binaryMessenger, messenger); OCMVerify([self.mockEngine binaryMessenger]); } - (void)testViewControllerIsReleased { __weak FlutterViewController* weakViewController; @autoreleasepool { FlutterViewController* viewController = [[FlutterViewController alloc] init]; weakViewController = viewController; [viewController viewDidLoad]; } XCTAssertNil(weakViewController); } #pragma mark - Platform Brightness - (void)testItReportsLightPlatformBrightnessByDefault { // Setup test. id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel); FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; // Exercise behavior under test. [vc traitCollectionDidChange:nil]; // Verify behavior. OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { return [message[@"platformBrightness"] isEqualToString:@"light"]; }]]); // Clean up mocks [settingsChannel stopMocking]; } - (void)testItReportsPlatformBrightnessWhenViewWillAppear { // Setup test. id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; OCMStub([mockEngine settingsChannel]).andReturn(settingsChannel); FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; // Exercise behavior under test. [vc viewWillAppear:false]; // Verify behavior. OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { return [message[@"platformBrightness"] isEqualToString:@"light"]; }]]); // Clean up mocks [settingsChannel stopMocking]; } - (void)testItReportsDarkPlatformBrightnessWhenTraitCollectionRequestsIt { if (@available(iOS 13, *)) { // noop } else { return; } // Setup test. id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel); id mockTraitCollection = [self fakeTraitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark]; // We partially mock the real FlutterViewController to act as the OS and report // the UITraitCollection of our choice. Mocking the object under test is not // desirable, but given that the OS does not offer a DI approach to providing // our own UITraitCollection, this seems to be the least bad option. id partialMockVC = OCMPartialMock([[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]); OCMStub([partialMockVC traitCollection]).andReturn(mockTraitCollection); // Exercise behavior under test. [partialMockVC traitCollectionDidChange:nil]; // Verify behavior. OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { return [message[@"platformBrightness"] isEqualToString:@"dark"]; }]]); // Clean up mocks [partialMockVC stopMocking]; [settingsChannel stopMocking]; [mockTraitCollection stopMocking]; } // Creates a mocked UITraitCollection with nil values for everything except userInterfaceStyle, // which is set to the given "style". - (UITraitCollection*)fakeTraitCollectionWithUserInterfaceStyle:(UIUserInterfaceStyle)style { id mockTraitCollection = OCMClassMock([UITraitCollection class]); OCMStub([mockTraitCollection userInterfaceStyle]).andReturn(style); return mockTraitCollection; } #pragma mark - Platform Contrast - (void)testItReportsNormalPlatformContrastByDefault { if (@available(iOS 13, *)) { // noop } else { return; } // Setup test. id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel); FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; // Exercise behavior under test. [vc traitCollectionDidChange:nil]; // Verify behavior. OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { return [message[@"platformContrast"] isEqualToString:@"normal"]; }]]); // Clean up mocks [settingsChannel stopMocking]; } - (void)testItReportsPlatformContrastWhenViewWillAppear { if (@available(iOS 13, *)) { // noop } else { return; } FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; // Setup test. id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); OCMStub([mockEngine settingsChannel]).andReturn(settingsChannel); FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; // Exercise behavior under test. [vc viewWillAppear:false]; // Verify behavior. OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { return [message[@"platformContrast"] isEqualToString:@"normal"]; }]]); // Clean up mocks [settingsChannel stopMocking]; } - (void)testItReportsHighContrastWhenTraitCollectionRequestsIt { if (@available(iOS 13, *)) { // noop } else { return; } // Setup test. id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel); id mockTraitCollection = [self fakeTraitCollectionWithContrast:UIAccessibilityContrastHigh]; // We partially mock the real FlutterViewController to act as the OS and report // the UITraitCollection of our choice. Mocking the object under test is not // desirable, but given that the OS does not offer a DI approach to providing // our own UITraitCollection, this seems to be the least bad option. id partialMockVC = OCMPartialMock([[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]); OCMStub([partialMockVC traitCollection]).andReturn(mockTraitCollection); // Exercise behavior under test. [partialMockVC traitCollectionDidChange:mockTraitCollection]; // Verify behavior. OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { return [message[@"platformContrast"] isEqualToString:@"high"]; }]]); // Clean up mocks [partialMockVC stopMocking]; [settingsChannel stopMocking]; [mockTraitCollection stopMocking]; } - (void)testItReportsAccessibilityOnOffSwitchLabelsFlagNotSet { if (@available(iOS 13, *)) { // noop } else { return; } // Setup test. FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; id partialMockViewController = OCMPartialMock(viewController); OCMStub([partialMockViewController accessibilityIsOnOffSwitchLabelsEnabled]).andReturn(NO); // Exercise behavior under test. int32_t flags = [partialMockViewController accessibilityFlags]; // Verify behavior. XCTAssert((flags & (int32_t)flutter::AccessibilityFeatureFlag::kOnOffSwitchLabels) == 0); } - (void)testItReportsAccessibilityOnOffSwitchLabelsFlagSet { if (@available(iOS 13, *)) { // noop } else { return; } // Setup test. FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; id partialMockViewController = OCMPartialMock(viewController); OCMStub([partialMockViewController accessibilityIsOnOffSwitchLabelsEnabled]).andReturn(YES); // Exercise behavior under test. int32_t flags = [partialMockViewController accessibilityFlags]; // Verify behavior. XCTAssert((flags & (int32_t)flutter::AccessibilityFeatureFlag::kOnOffSwitchLabels) != 0); } - (void)testAccessibilityPerformEscapePopsRoute { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; id mockNavigationChannel = OCMClassMock([FlutterMethodChannel class]); OCMStub([mockEngine navigationChannel]).andReturn(mockNavigationChannel); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; XCTAssertTrue([viewController accessibilityPerformEscape]); OCMVerify([mockNavigationChannel invokeMethod:@"popRoute" arguments:nil]); [mockNavigationChannel stopMocking]; } - (void)testPerformOrientationUpdateForcesOrientationChange { [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait currentOrientation:UIInterfaceOrientationLandscapeLeft didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationPortrait]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait currentOrientation:UIInterfaceOrientationLandscapeRight didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationPortrait]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait currentOrientation:UIInterfaceOrientationPortraitUpsideDown didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationPortrait]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown currentOrientation:UIInterfaceOrientationLandscapeLeft didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationPortraitUpsideDown]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown currentOrientation:UIInterfaceOrientationLandscapeRight didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationPortraitUpsideDown]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown currentOrientation:UIInterfaceOrientationPortrait didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationPortraitUpsideDown]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape currentOrientation:UIInterfaceOrientationPortrait didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationLandscapeLeft]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape currentOrientation:UIInterfaceOrientationPortraitUpsideDown didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationLandscapeLeft]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft currentOrientation:UIInterfaceOrientationPortrait didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationLandscapeLeft]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft currentOrientation:UIInterfaceOrientationLandscapeRight didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationLandscapeLeft]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft currentOrientation:UIInterfaceOrientationPortraitUpsideDown didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationLandscapeLeft]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight currentOrientation:UIInterfaceOrientationPortrait didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationLandscapeRight]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight currentOrientation:UIInterfaceOrientationLandscapeLeft didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationLandscapeRight]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight currentOrientation:UIInterfaceOrientationPortraitUpsideDown didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationLandscapeRight]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown currentOrientation:UIInterfaceOrientationPortraitUpsideDown didChangeOrientation:YES resultingOrientation:UIInterfaceOrientationPortrait]; } - (void)testPerformOrientationUpdateDoesNotForceOrientationChange { [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll currentOrientation:UIInterfaceOrientationPortrait didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll currentOrientation:UIInterfaceOrientationPortraitUpsideDown didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll currentOrientation:UIInterfaceOrientationLandscapeLeft didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll currentOrientation:UIInterfaceOrientationLandscapeRight didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown currentOrientation:UIInterfaceOrientationPortrait didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown currentOrientation:UIInterfaceOrientationLandscapeLeft didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown currentOrientation:UIInterfaceOrientationLandscapeRight didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait currentOrientation:UIInterfaceOrientationPortrait didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown currentOrientation:UIInterfaceOrientationPortraitUpsideDown didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape currentOrientation:UIInterfaceOrientationLandscapeLeft didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape currentOrientation:UIInterfaceOrientationLandscapeRight didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft currentOrientation:UIInterfaceOrientationLandscapeLeft didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight currentOrientation:UIInterfaceOrientationLandscapeRight didChangeOrientation:NO resultingOrientation:static_cast<UIInterfaceOrientation>(0)]; } // Perform an orientation update test that fails when the expected outcome // for an orientation update is not met - (void)orientationTestWithOrientationUpdate:(UIInterfaceOrientationMask)mask currentOrientation:(UIInterfaceOrientation)currentOrientation didChangeOrientation:(BOOL)didChange resultingOrientation:(UIInterfaceOrientation)resultingOrientation { id mockApplication = OCMClassMock([UIApplication class]); id mockWindowScene; id deviceMock; id mockVC; __block __weak id weakPreferences; @autoreleasepool { FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; if (@available(iOS 16.0, *)) { mockWindowScene = OCMClassMock([UIWindowScene class]); mockVC = OCMPartialMock(realVC); OCMStub([mockVC flutterWindowSceneIfViewLoaded]).andReturn(mockWindowScene); if (realVC.supportedInterfaceOrientations == mask) { OCMReject([mockWindowScene requestGeometryUpdateWithPreferences:[OCMArg any] errorHandler:[OCMArg any]]); } else { // iOS 16 will decide whether to rotate based on the new preference, so always set it // when it changes. OCMExpect([mockWindowScene requestGeometryUpdateWithPreferences:[OCMArg checkWithBlock:^BOOL( UIWindowSceneGeometryPreferencesIOS* preferences) { weakPreferences = preferences; return preferences.interfaceOrientations == mask; }] errorHandler:[OCMArg any]]); } OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); OCMStub([mockApplication connectedScenes]).andReturn([NSSet setWithObject:mockWindowScene]); } else { deviceMock = OCMPartialMock([UIDevice currentDevice]); if (!didChange) { OCMReject([deviceMock setValue:[OCMArg any] forKey:@"orientation"]); } else { OCMExpect([deviceMock setValue:@(resultingOrientation) forKey:@"orientation"]); } if (@available(iOS 13.0, *)) { mockWindowScene = OCMClassMock([UIWindowScene class]); mockVC = OCMPartialMock(realVC); OCMStub([mockVC flutterWindowSceneIfViewLoaded]).andReturn(mockWindowScene); OCMStub(((UIWindowScene*)mockWindowScene).interfaceOrientation) .andReturn(currentOrientation); } else { OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); OCMStub([mockApplication statusBarOrientation]).andReturn(currentOrientation); } } [realVC performOrientationUpdate:mask]; if (@available(iOS 16.0, *)) { OCMVerifyAll(mockWindowScene); } else { OCMVerifyAll(deviceMock); } } [mockWindowScene stopMocking]; [deviceMock stopMocking]; [mockApplication stopMocking]; XCTAssertNil(weakPreferences); } // Creates a mocked UITraitCollection with nil values for everything except accessibilityContrast, // which is set to the given "contrast". - (UITraitCollection*)fakeTraitCollectionWithContrast:(UIAccessibilityContrast)contrast { id mockTraitCollection = OCMClassMock([UITraitCollection class]); OCMStub([mockTraitCollection accessibilityContrast]).andReturn(contrast); return mockTraitCollection; } - (void)testWillDeallocNotification { XCTestExpectation* expectation = [[XCTestExpectation alloc] initWithDescription:@"notification called"]; id engine = [[MockEngine alloc] init]; @autoreleasepool { // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores) FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [[NSNotificationCenter defaultCenter] addObserverForName:FlutterViewControllerWillDealloc object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification* _Nonnull note) { [expectation fulfill]; }]; XCTAssertNotNil(realVC); realVC = nil; } [self waitForExpectations:@[ expectation ] timeout:1.0]; } - (void)testReleasesKeyboardManagerOnDealloc { __weak FlutterKeyboardManager* weakKeyboardManager = nil; @autoreleasepool { FlutterViewController* viewController = [[FlutterViewController alloc] init]; [viewController addInternalPlugins]; weakKeyboardManager = viewController.keyboardManager; XCTAssertNotNil(weakKeyboardManager); [viewController deregisterNotifications]; viewController = nil; } // View controller has released the keyboard manager. XCTAssertNil(weakKeyboardManager); } - (void)testDoesntLoadViewInInit { FlutterDartProject* project = [[FlutterDartProject alloc] init]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; [engine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; XCTAssertFalse([realVC isViewLoaded], @"shouldn't have loaded since it hasn't been shown"); engine.viewController = nil; } - (void)testHideOverlay { FlutterDartProject* project = [[FlutterDartProject alloc] init]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; [engine createShell:@"" libraryURI:@"" initialRoute:nil]; FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; XCTAssertFalse(realVC.prefersHomeIndicatorAutoHidden, @""); [[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerHideHomeIndicator object:nil]; XCTAssertTrue(realVC.prefersHomeIndicatorAutoHidden, @""); engine.viewController = nil; } - (void)testNotifyLowMemory { FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; id viewControllerMock = OCMPartialMock(viewController); OCMStub([viewControllerMock surfaceUpdated:NO]); [viewController beginAppearanceTransition:NO animated:NO]; [viewController endAppearanceTransition]; XCTAssertTrue(mockEngine.didCallNotifyLowMemory); } - (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback { NSMutableDictionary* replyMessage = [@{ @"handled" : @YES, } mutableCopy]; // Response is async, so we have to post it to the run loop instead of calling // it directly. self.messageSent = message; CFRunLoopPerformBlock(CFRunLoopGetCurrent(), fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode, ^() { callback(replyMessage); }); } - (void)testValidKeyUpEvent API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { // noop } else { return; } FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; mockEngine.keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); OCMStub([mockEngine.keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) .andCall(self, @selector(sendMessage:reply:)); OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES); mockEngine.textInputPlugin = self.mockTextInputPlugin; FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; // Allocate the keyboard manager in the view controller by adding the internal // plugins. [vc addInternalPlugins]; [vc handlePressEvent:keyUpEvent(UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0) nextAction:^(){ }]; XCTAssert(self.messageSent != nil); XCTAssert([self.messageSent[@"keymap"] isEqualToString:@"ios"]); XCTAssert([self.messageSent[@"type"] isEqualToString:@"keyup"]); XCTAssert([self.messageSent[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]]); XCTAssert([self.messageSent[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:0]]); XCTAssert([self.messageSent[@"characters"] isEqualToString:@""]); XCTAssert([self.messageSent[@"charactersIgnoringModifiers"] isEqualToString:@""]); [vc deregisterNotifications]; } - (void)testValidKeyDownEvent API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { // noop } else { return; } FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; mockEngine.keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); OCMStub([mockEngine.keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) .andCall(self, @selector(sendMessage:reply:)); OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES); mockEngine.textInputPlugin = self.mockTextInputPlugin; __strong FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; // Allocate the keyboard manager in the view controller by adding the internal // plugins. [vc addInternalPlugins]; [vc handlePressEvent:keyDownEvent(UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0f, "A", "a") nextAction:^(){ }]; XCTAssert(self.messageSent != nil); XCTAssert([self.messageSent[@"keymap"] isEqualToString:@"ios"]); XCTAssert([self.messageSent[@"type"] isEqualToString:@"keydown"]); XCTAssert([self.messageSent[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]]); XCTAssert([self.messageSent[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:0]]); XCTAssert([self.messageSent[@"characters"] isEqualToString:@"A"]); XCTAssert([self.messageSent[@"charactersIgnoringModifiers"] isEqualToString:@"a"]); [vc deregisterNotifications]; vc = nil; } - (void)testIgnoredKeyEvents API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { // noop } else { return; } id keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); OCMStub([keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) .andCall(self, @selector(sendMessage:reply:)); OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES); OCMStub([self.mockEngine keyEventChannel]).andReturn(keyEventChannel); FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; // Allocate the keyboard manager in the view controller by adding the internal // plugins. [vc addInternalPlugins]; [vc handlePressEvent:keyEventWithPhase(UIPressPhaseStationary, UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0) nextAction:^(){ }]; [vc handlePressEvent:keyEventWithPhase(UIPressPhaseCancelled, UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0) nextAction:^(){ }]; [vc handlePressEvent:keyEventWithPhase(UIPressPhaseChanged, UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0) nextAction:^(){ }]; XCTAssert(self.messageSent == nil); OCMVerify(never(), [keyEventChannel sendMessage:[OCMArg any]]); [vc deregisterNotifications]; } - (void)testPanGestureRecognizer API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { // noop } else { return; } FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; XCTAssertNotNil(vc); UIView* view = vc.view; XCTAssertNotNil(view); NSArray* gestureRecognizers = view.gestureRecognizers; XCTAssertNotNil(gestureRecognizers); BOOL found = NO; for (id gesture in gestureRecognizers) { if ([gesture isKindOfClass:[UIPanGestureRecognizer class]]) { found = YES; break; } } XCTAssertTrue(found); } - (void)testMouseSupport API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { // noop } else { return; } FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; XCTAssertNotNil(vc); id mockPanGestureRecognizer = OCMClassMock([UIPanGestureRecognizer class]); XCTAssertNotNil(mockPanGestureRecognizer); [vc discreteScrollEvent:mockPanGestureRecognizer]; [[[self.mockEngine verify] ignoringNonObjectArgs] dispatchPointerDataPacket:std::make_unique<flutter::PointerDataPacket>(0)]; } - (void)testFakeEventTimeStamp { FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; XCTAssertNotNil(vc); flutter::PointerData pointer_data = [vc generatePointerDataForFake]; int64_t current_micros = [[NSProcessInfo processInfo] systemUptime] * 1000 * 1000; int64_t interval_micros = current_micros - pointer_data.time_stamp; const int64_t tolerance_millis = 2; XCTAssertTrue(interval_micros / 1000 < tolerance_millis, @"PointerData.time_stamp should be equal to NSProcessInfo.systemUptime"); } - (void)testSplashScreenViewCanSetNil { FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil]; [flutterViewController setSplashScreenView:nil]; } - (void)testLifeCycleNotificationBecameActive { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; UIWindow* window = [[UIWindow alloc] init]; [window addSubview:flutterViewController.view]; flutterViewController.view.bounds = CGRectMake(0, 0, 100, 100); [flutterViewController viewDidLayoutSubviews]; NSNotification* sceneNotification = [NSNotification notificationWithName:UISceneDidActivateNotification object:nil userInfo:nil]; NSNotification* applicationNotification = [NSNotification notificationWithName:UIApplicationDidBecomeActiveNotification object:nil userInfo:nil]; id mockVC = OCMPartialMock(flutterViewController); [[NSNotificationCenter defaultCenter] postNotification:sceneNotification]; [[NSNotificationCenter defaultCenter] postNotification:applicationNotification]; #if APPLICATION_EXTENSION_API_ONLY OCMVerify([mockVC sceneBecameActive:[OCMArg any]]); OCMReject([mockVC applicationBecameActive:[OCMArg any]]); #else OCMReject([mockVC sceneBecameActive:[OCMArg any]]); OCMVerify([mockVC applicationBecameActive:[OCMArg any]]); #endif XCTAssertFalse(flutterViewController.isKeyboardInOrTransitioningFromBackground); OCMVerify([mockVC surfaceUpdated:YES]); XCTestExpectation* timeoutApplicationLifeCycle = [self expectationWithDescription:@"timeoutApplicationLifeCycle"]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [timeoutApplicationLifeCycle fulfill]; OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.resumed"]); [flutterViewController deregisterNotifications]; }); [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testLifeCycleNotificationWillResignActive { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; NSNotification* sceneNotification = [NSNotification notificationWithName:UISceneWillDeactivateNotification object:nil userInfo:nil]; NSNotification* applicationNotification = [NSNotification notificationWithName:UIApplicationWillResignActiveNotification object:nil userInfo:nil]; id mockVC = OCMPartialMock(flutterViewController); [[NSNotificationCenter defaultCenter] postNotification:sceneNotification]; [[NSNotificationCenter defaultCenter] postNotification:applicationNotification]; #if APPLICATION_EXTENSION_API_ONLY OCMVerify([mockVC sceneWillResignActive:[OCMArg any]]); OCMReject([mockVC applicationWillResignActive:[OCMArg any]]); #else OCMReject([mockVC sceneWillResignActive:[OCMArg any]]); OCMVerify([mockVC applicationWillResignActive:[OCMArg any]]); #endif OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]); [flutterViewController deregisterNotifications]; } - (void)testLifeCycleNotificationWillTerminate { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; NSNotification* sceneNotification = [NSNotification notificationWithName:UISceneDidDisconnectNotification object:nil userInfo:nil]; NSNotification* applicationNotification = [NSNotification notificationWithName:UIApplicationWillTerminateNotification object:nil userInfo:nil]; id mockVC = OCMPartialMock(flutterViewController); id mockEngine = OCMPartialMock(engine); OCMStub([mockVC engine]).andReturn(mockEngine); [[NSNotificationCenter defaultCenter] postNotification:sceneNotification]; [[NSNotificationCenter defaultCenter] postNotification:applicationNotification]; #if APPLICATION_EXTENSION_API_ONLY OCMVerify([mockVC sceneWillDisconnect:[OCMArg any]]); OCMReject([mockVC applicationWillTerminate:[OCMArg any]]); #else OCMReject([mockVC sceneWillDisconnect:[OCMArg any]]); OCMVerify([mockVC applicationWillTerminate:[OCMArg any]]); #endif OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.detached"]); OCMVerify([mockEngine destroyContext]); [flutterViewController deregisterNotifications]; } - (void)testLifeCycleNotificationDidEnterBackground { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; NSNotification* sceneNotification = [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification object:nil userInfo:nil]; NSNotification* applicationNotification = [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification object:nil userInfo:nil]; id mockVC = OCMPartialMock(flutterViewController); [[NSNotificationCenter defaultCenter] postNotification:sceneNotification]; [[NSNotificationCenter defaultCenter] postNotification:applicationNotification]; #if APPLICATION_EXTENSION_API_ONLY OCMVerify([mockVC sceneDidEnterBackground:[OCMArg any]]); OCMReject([mockVC applicationDidEnterBackground:[OCMArg any]]); #else OCMReject([mockVC sceneDidEnterBackground:[OCMArg any]]); OCMVerify([mockVC applicationDidEnterBackground:[OCMArg any]]); #endif XCTAssertTrue(flutterViewController.isKeyboardInOrTransitioningFromBackground); OCMVerify([mockVC surfaceUpdated:NO]); OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.paused"]); [flutterViewController deregisterNotifications]; } - (void)testLifeCycleNotificationWillEnterForeground { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; NSNotification* sceneNotification = [NSNotification notificationWithName:UISceneWillEnterForegroundNotification object:nil userInfo:nil]; NSNotification* applicationNotification = [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification object:nil userInfo:nil]; id mockVC = OCMPartialMock(flutterViewController); [[NSNotificationCenter defaultCenter] postNotification:sceneNotification]; [[NSNotificationCenter defaultCenter] postNotification:applicationNotification]; #if APPLICATION_EXTENSION_API_ONLY OCMVerify([mockVC sceneWillEnterForeground:[OCMArg any]]); OCMReject([mockVC applicationWillEnterForeground:[OCMArg any]]); #else OCMReject([mockVC sceneWillEnterForeground:[OCMArg any]]); OCMVerify([mockVC applicationWillEnterForeground:[OCMArg any]]); #endif OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]); [flutterViewController deregisterNotifications]; } - (void)testLifeCycleNotificationCancelledInvalidResumed { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; NSNotification* applicationDidBecomeActiveNotification = [NSNotification notificationWithName:UIApplicationDidBecomeActiveNotification object:nil userInfo:nil]; NSNotification* applicationWillResignActiveNotification = [NSNotification notificationWithName:UIApplicationWillResignActiveNotification object:nil userInfo:nil]; id mockVC = OCMPartialMock(flutterViewController); [[NSNotificationCenter defaultCenter] postNotification:applicationDidBecomeActiveNotification]; [[NSNotificationCenter defaultCenter] postNotification:applicationWillResignActiveNotification]; #if APPLICATION_EXTENSION_API_ONLY #else OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]); #endif XCTestExpectation* timeoutApplicationLifeCycle = [self expectationWithDescription:@"timeoutApplicationLifeCycle"]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ OCMReject([mockVC goToApplicationLifecycle:@"AppLifecycleState.resumed"]); [timeoutApplicationLifeCycle fulfill]; [flutterViewController deregisterNotifications]; }); [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testSetupKeyboardAnimationVsyncClientWillCreateNewVsyncClientForFlutterViewController { id bundleMock = OCMPartialMock([NSBundle mainBundle]); OCMStub([bundleMock objectForInfoDictionaryKey:@"CADisableMinimumFrameDurationOnPhone"]) .andReturn(@YES); id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; double maxFrameRate = 120; [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; FlutterKeyboardAnimationCallback callback = ^(fml::TimePoint targetTime) { }; [viewController setUpKeyboardAnimationVsyncClient:callback]; XCTAssertNotNil(viewController.keyboardAnimationVSyncClient); CADisplayLink* link = [viewController.keyboardAnimationVSyncClient getDisplayLink]; XCTAssertNotNil(link); if (@available(iOS 15.0, *)) { XCTAssertEqual(link.preferredFrameRateRange.maximum, maxFrameRate); XCTAssertEqual(link.preferredFrameRateRange.preferred, maxFrameRate); XCTAssertEqual(link.preferredFrameRateRange.minimum, maxFrameRate / 2); } else { XCTAssertEqual(link.preferredFramesPerSecond, maxFrameRate); } } - (void) testCreateTouchRateCorrectionVSyncClientWillCreateVsyncClientWhenRefreshRateIsLargerThan60HZ { id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; double maxFrameRate = 120; [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController createTouchRateCorrectionVSyncClientIfNeeded]; XCTAssertNotNil(viewController.touchRateCorrectionVSyncClient); } - (void)testCreateTouchRateCorrectionVSyncClientWillNotCreateNewVSyncClientWhenClientAlreadyExists { id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; double maxFrameRate = 120; [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController createTouchRateCorrectionVSyncClientIfNeeded]; VSyncClient* clientBefore = viewController.touchRateCorrectionVSyncClient; XCTAssertNotNil(clientBefore); [viewController createTouchRateCorrectionVSyncClientIfNeeded]; VSyncClient* clientAfter = viewController.touchRateCorrectionVSyncClient; XCTAssertNotNil(clientAfter); XCTAssertTrue(clientBefore == clientAfter); } - (void)testCreateTouchRateCorrectionVSyncClientWillNotCreateVsyncClientWhenRefreshRateIs60HZ { id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; double maxFrameRate = 60; [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController createTouchRateCorrectionVSyncClientIfNeeded]; XCTAssertNil(viewController.touchRateCorrectionVSyncClient); } - (void)testTriggerTouchRateCorrectionVSyncClientCorrectly { id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; double maxFrameRate = 120; [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController loadView]; [viewController viewDidLoad]; VSyncClient* client = viewController.touchRateCorrectionVSyncClient; CADisplayLink* link = [client getDisplayLink]; UITouch* fakeTouchBegan = [[UITouch alloc] init]; fakeTouchBegan.phase = UITouchPhaseBegan; UITouch* fakeTouchMove = [[UITouch alloc] init]; fakeTouchMove.phase = UITouchPhaseMoved; UITouch* fakeTouchEnd = [[UITouch alloc] init]; fakeTouchEnd.phase = UITouchPhaseEnded; UITouch* fakeTouchCancelled = [[UITouch alloc] init]; fakeTouchCancelled.phase = UITouchPhaseCancelled; [viewController triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchBegan, nil]]; XCTAssertFalse(link.isPaused); [viewController triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchEnd, nil]]; XCTAssertTrue(link.isPaused); [viewController triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchMove, nil]]; XCTAssertFalse(link.isPaused); [viewController triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchCancelled, nil]]; XCTAssertTrue(link.isPaused); [viewController triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchBegan, fakeTouchEnd, nil]]; XCTAssertFalse(link.isPaused); [viewController triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchEnd, fakeTouchCancelled, nil]]; XCTAssertTrue(link.isPaused); [viewController triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchMove, fakeTouchEnd, nil]]; XCTAssertFalse(link.isPaused); } - (void)testFlutterViewControllerStartKeyboardAnimationWillCreateVsyncClientCorrectly { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; viewController.targetViewInsetBottom = 100; [viewController startKeyBoardAnimation:0.25]; XCTAssertNotNil(viewController.keyboardAnimationVSyncClient); } - (void) testSetupKeyboardAnimationVsyncClientWillNotCreateNewVsyncClientWhenKeyboardAnimationCallbackIsNil { FlutterEngine* engine = [[FlutterEngine alloc] init]; [engine runWithEntrypoint:nil]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController setUpKeyboardAnimationVsyncClient:nil]; XCTAssertNil(viewController.keyboardAnimationVSyncClient); } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm", "repo_id": "engine", "token_count": 47279 }
322
// 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 "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" #include <utility> #include "flutter/fml/logging.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_text_entry.h" #import "flutter/shell/platform/darwin/ios/platform_view_ios.h" #pragma GCC diagnostic error "-Wundeclared-selector" FLUTTER_ASSERT_NOT_ARC namespace flutter { namespace { constexpr int32_t kSemanticObjectIdInvalid = -1; class DefaultIosDelegate : public AccessibilityBridge::IosDelegate { public: bool IsFlutterViewControllerPresentingModalViewController( FlutterViewController* view_controller) override { if (view_controller) { return view_controller.isPresentingViewController; } else { return false; } } void PostAccessibilityNotification(UIAccessibilityNotifications notification, id argument) override { UIAccessibilityPostNotification(notification, argument); } }; } // namespace AccessibilityBridge::AccessibilityBridge( FlutterViewController* view_controller, PlatformViewIOS* platform_view, std::shared_ptr<FlutterPlatformViewsController> platform_views_controller, std::unique_ptr<IosDelegate> ios_delegate) : view_controller_(view_controller), platform_view_(platform_view), platform_views_controller_(std::move(platform_views_controller)), last_focused_semantics_object_id_(kSemanticObjectIdInvalid), objects_([[NSMutableDictionary alloc] init]), previous_routes_({}), ios_delegate_(ios_delegate ? std::move(ios_delegate) : std::make_unique<DefaultIosDelegate>()), weak_factory_(this) { accessibility_channel_.reset([[FlutterBasicMessageChannel alloc] initWithName:@"flutter/accessibility" binaryMessenger:platform_view->GetOwnerViewController().get().engine.binaryMessenger codec:[FlutterStandardMessageCodec sharedInstance]]); [accessibility_channel_.get() setMessageHandler:^(id message, FlutterReply reply) { HandleEvent((NSDictionary*)message); }]; } AccessibilityBridge::~AccessibilityBridge() { [accessibility_channel_.get() setMessageHandler:nil]; clearState(); view_controller_.viewIfLoaded.accessibilityElements = nil; } UIView<UITextInput>* AccessibilityBridge::textInputView() { return [[platform_view_->GetOwnerViewController().get().engine textInputPlugin] textInputView]; } void AccessibilityBridge::AccessibilityObjectDidBecomeFocused(int32_t id) { last_focused_semantics_object_id_ = id; [accessibility_channel_.get() sendMessage:@{@"type" : @"didGainFocus", @"nodeId" : @(id)}]; } void AccessibilityBridge::AccessibilityObjectDidLoseFocus(int32_t id) { if (last_focused_semantics_object_id_ == id) { last_focused_semantics_object_id_ = kSemanticObjectIdInvalid; } } void AccessibilityBridge::UpdateSemantics( flutter::SemanticsNodeUpdates nodes, const flutter::CustomAccessibilityActionUpdates& actions) { BOOL layoutChanged = NO; BOOL scrollOccured = NO; BOOL needsAnnouncement = NO; for (const auto& entry : actions) { const flutter::CustomAccessibilityAction& action = entry.second; actions_[action.id] = action; } for (const auto& entry : nodes) { const flutter::SemanticsNode& node = entry.second; SemanticsObject* object = GetOrCreateObject(node.id, nodes); layoutChanged = layoutChanged || [object nodeWillCauseLayoutChange:&node]; scrollOccured = scrollOccured || [object nodeWillCauseScroll:&node]; needsAnnouncement = [object nodeShouldTriggerAnnouncement:&node]; [object setSemanticsNode:&node]; NSUInteger newChildCount = node.childrenInTraversalOrder.size(); NSMutableArray* newChildren = [[[NSMutableArray alloc] initWithCapacity:newChildCount] autorelease]; for (NSUInteger i = 0; i < newChildCount; ++i) { SemanticsObject* child = GetOrCreateObject(node.childrenInTraversalOrder[i], nodes); [newChildren addObject:child]; } NSMutableArray* newChildrenInHitTestOrder = [[[NSMutableArray alloc] initWithCapacity:newChildCount] autorelease]; for (NSUInteger i = 0; i < newChildCount; ++i) { SemanticsObject* child = GetOrCreateObject(node.childrenInHitTestOrder[i], nodes); [newChildrenInHitTestOrder addObject:child]; } object.children = newChildren; object.childrenInHitTestOrder = newChildrenInHitTestOrder; if (!node.customAccessibilityActions.empty()) { NSMutableArray<FlutterCustomAccessibilityAction*>* accessibilityCustomActions = [[[NSMutableArray alloc] init] autorelease]; for (int32_t action_id : node.customAccessibilityActions) { flutter::CustomAccessibilityAction& action = actions_[action_id]; if (action.overrideId != -1) { // iOS does not support overriding standard actions, so we ignore any // custom actions that have an override id provided. continue; } NSString* label = @(action.label.data()); SEL selector = @selector(onCustomAccessibilityAction:); FlutterCustomAccessibilityAction* customAction = [[[FlutterCustomAccessibilityAction alloc] initWithName:label target:object selector:selector] autorelease]; customAction.uid = action_id; [accessibilityCustomActions addObject:customAction]; } object.accessibilityCustomActions = accessibilityCustomActions; } if (needsAnnouncement) { // Try to be more polite - iOS 11+ supports // UIAccessibilitySpeechAttributeQueueAnnouncement which should avoid // interrupting system notifications or other elements. // Expectation: roughly match the behavior of polite announcements on // Android. NSString* announcement = [[[NSString alloc] initWithUTF8String:object.node.label.c_str()] autorelease]; UIAccessibilityPostNotification( UIAccessibilityAnnouncementNotification, [[[NSAttributedString alloc] initWithString:announcement attributes:@{ UIAccessibilitySpeechAttributeQueueAnnouncement : @YES }] autorelease]); } } SemanticsObject* root = objects_.get()[@(kRootNodeId)]; bool routeChanged = false; SemanticsObject* lastAdded = nil; if (root) { if (!view_controller_.view.accessibilityElements) { view_controller_.view.accessibilityElements = @[ [root accessibilityContainer] ?: [NSNull null] ]; } NSMutableArray<SemanticsObject*>* newRoutes = [[[NSMutableArray alloc] init] autorelease]; [root collectRoutes:newRoutes]; // Finds the last route that is not in the previous routes. for (SemanticsObject* route in newRoutes) { if (std::find(previous_routes_.begin(), previous_routes_.end(), [route uid]) == previous_routes_.end()) { lastAdded = route; } } // If all the routes are in the previous route, get the last route. if (lastAdded == nil && [newRoutes count] > 0) { int index = [newRoutes count] - 1; lastAdded = [newRoutes objectAtIndex:index]; } // There are two cases if lastAdded != nil // 1. lastAdded is not in previous routes. In this case, // [lastAdded uid] != previous_route_id_ // 2. All new routes are in previous routes and // lastAdded = newRoutes.last. // In the first case, we need to announce new route. In the second case, // we need to announce if one list is shorter than the other. if (lastAdded != nil && ([lastAdded uid] != previous_route_id_ || [newRoutes count] != previous_routes_.size())) { previous_route_id_ = [lastAdded uid]; routeChanged = true; } previous_routes_.clear(); for (SemanticsObject* route in newRoutes) { previous_routes_.push_back([route uid]); } } else { view_controller_.viewIfLoaded.accessibilityElements = nil; } NSMutableArray<NSNumber*>* doomed_uids = [NSMutableArray arrayWithArray:[objects_ allKeys]]; if (root) { VisitObjectsRecursivelyAndRemove(root, doomed_uids); } [objects_ removeObjectsForKeys:doomed_uids]; for (SemanticsObject* object in [objects_ allValues]) { [object accessibilityBridgeDidFinishUpdate]; } if (!ios_delegate_->IsFlutterViewControllerPresentingModalViewController(view_controller_)) { layoutChanged = layoutChanged || [doomed_uids count] > 0; if (routeChanged) { NSString* routeName = [lastAdded routeName]; ios_delegate_->PostAccessibilityNotification(UIAccessibilityScreenChangedNotification, routeName); } if (layoutChanged) { SemanticsObject* next = FindNextFocusableIfNecessary(); SemanticsObject* lastFocused = [objects_.get() objectForKey:@(last_focused_semantics_object_id_)]; // Only specify the focus item if the new focus is different, avoiding double focuses on the // same item. See: https://github.com/flutter/flutter/issues/104176. If there is a route // change, we always refocus. ios_delegate_->PostAccessibilityNotification( UIAccessibilityLayoutChangedNotification, (routeChanged || next != lastFocused) ? next.nativeAccessibility : NULL); } else if (scrollOccured) { // TODO(chunhtai): figure out what string to use for notification. At this // point, it is guarantee the previous focused object is still in the tree // so that we don't need to worry about focus lost. (e.g. "Screen 0 of 3") ios_delegate_->PostAccessibilityNotification( UIAccessibilityPageScrolledNotification, FindNextFocusableIfNecessary().nativeAccessibility); } } } void AccessibilityBridge::DispatchSemanticsAction(int32_t uid, flutter::SemanticsAction action) { platform_view_->DispatchSemanticsAction(uid, action, {}); } void AccessibilityBridge::DispatchSemanticsAction(int32_t uid, flutter::SemanticsAction action, fml::MallocMapping args) { platform_view_->DispatchSemanticsAction(uid, action, std::move(args)); } static void ReplaceSemanticsObject(SemanticsObject* oldObject, SemanticsObject* newObject, NSMutableDictionary<NSNumber*, SemanticsObject*>* objects) { // `newObject` should represent the same id as `oldObject`. FML_DCHECK(oldObject.node.id == newObject.uid); NSNumber* nodeId = @(oldObject.node.id); NSUInteger positionInChildlist = [oldObject.parent.children indexOfObject:oldObject]; [[oldObject retain] autorelease]; oldObject.children = @[]; [oldObject.parent replaceChildAtIndex:positionInChildlist withChild:newObject]; [objects removeObjectForKey:nodeId]; objects[nodeId] = newObject; } static SemanticsObject* CreateObject(const flutter::SemanticsNode& node, const fml::WeakPtr<AccessibilityBridge>& weak_ptr) { if (node.HasFlag(flutter::SemanticsFlags::kIsTextField) && !node.HasFlag(flutter::SemanticsFlags::kIsReadOnly)) { // Text fields are backed by objects that implement UITextInput. return [[[TextInputSemanticsObject alloc] initWithBridge:weak_ptr uid:node.id] autorelease]; } else if (!node.HasFlag(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup) && (node.HasFlag(flutter::SemanticsFlags::kHasToggledState) || node.HasFlag(flutter::SemanticsFlags::kHasCheckedState))) { return [[[FlutterSwitchSemanticsObject alloc] initWithBridge:weak_ptr uid:node.id] autorelease]; } else if (node.HasFlag(flutter::SemanticsFlags::kHasImplicitScrolling)) { return [[[FlutterScrollableSemanticsObject alloc] initWithBridge:weak_ptr uid:node.id] autorelease]; } else if (node.IsPlatformViewNode()) { return [[[FlutterPlatformViewSemanticsContainer alloc] initWithBridge:weak_ptr uid:node.id platformView:weak_ptr->GetPlatformViewsController()->GetFlutterTouchInterceptingViewByID( node.platformViewId)] autorelease]; } else { return [[[FlutterSemanticsObject alloc] initWithBridge:weak_ptr uid:node.id] autorelease]; } } static bool DidFlagChange(const flutter::SemanticsNode& oldNode, const flutter::SemanticsNode& newNode, SemanticsFlags flag) { return oldNode.HasFlag(flag) != newNode.HasFlag(flag); } SemanticsObject* AccessibilityBridge::GetOrCreateObject(int32_t uid, flutter::SemanticsNodeUpdates& updates) { SemanticsObject* object = objects_.get()[@(uid)]; if (!object) { object = CreateObject(updates[uid], GetWeakPtr()); objects_.get()[@(uid)] = object; } else { // Existing node case auto nodeEntry = updates.find(object.node.id); if (nodeEntry != updates.end()) { // There's an update for this node flutter::SemanticsNode node = nodeEntry->second; if (DidFlagChange(object.node, node, flutter::SemanticsFlags::kIsTextField) || DidFlagChange(object.node, node, flutter::SemanticsFlags::kIsReadOnly) || DidFlagChange(object.node, node, flutter::SemanticsFlags::kHasCheckedState) || DidFlagChange(object.node, node, flutter::SemanticsFlags::kHasToggledState) || DidFlagChange(object.node, node, flutter::SemanticsFlags::kHasImplicitScrolling)) { // The node changed its type. In this case, we cannot reuse the existing // SemanticsObject implementation. Instead, we replace it with a new // instance. SemanticsObject* newSemanticsObject = CreateObject(node, GetWeakPtr()); ReplaceSemanticsObject(object, newSemanticsObject, objects_.get()); object = newSemanticsObject; } } } return object; } void AccessibilityBridge::VisitObjectsRecursivelyAndRemove(SemanticsObject* object, NSMutableArray<NSNumber*>* doomed_uids) { [doomed_uids removeObject:@(object.uid)]; for (SemanticsObject* child in [object children]) VisitObjectsRecursivelyAndRemove(child, doomed_uids); } SemanticsObject* AccessibilityBridge::FindNextFocusableIfNecessary() { // This property will be -1 if the focus is outside of the flutter // application. In this case, we should not refocus anything. if (last_focused_semantics_object_id_ == kSemanticObjectIdInvalid) { return nil; } // Tries to refocus the previous focused semantics object to avoid random jumps. return FindFirstFocusable([objects_.get() objectForKey:@(last_focused_semantics_object_id_)]); } SemanticsObject* AccessibilityBridge::FindFirstFocusable(SemanticsObject* parent) { SemanticsObject* currentObject = parent ?: objects_.get()[@(kRootNodeId)]; if (!currentObject) { return nil; } if (currentObject.isAccessibilityElement) { return currentObject; } for (SemanticsObject* child in [currentObject children]) { SemanticsObject* candidate = FindFirstFocusable(child); if (candidate) { return candidate; } } return nil; } void AccessibilityBridge::HandleEvent(NSDictionary<NSString*, id>* annotatedEvent) { NSString* type = annotatedEvent[@"type"]; if ([type isEqualToString:@"announce"]) { NSString* message = annotatedEvent[@"data"][@"message"]; ios_delegate_->PostAccessibilityNotification(UIAccessibilityAnnouncementNotification, message); } if ([type isEqualToString:@"focus"]) { SemanticsObject* node = objects_.get()[annotatedEvent[@"nodeId"]]; ios_delegate_->PostAccessibilityNotification(UIAccessibilityLayoutChangedNotification, node); } } fml::WeakPtr<AccessibilityBridge> AccessibilityBridge::GetWeakPtr() { return weak_factory_.GetWeakPtr(); } void AccessibilityBridge::clearState() { [objects_ removeAllObjects]; previous_route_id_ = 0; previous_routes_.clear(); } } // namespace flutter
engine/shell/platform/darwin/ios/framework/Source/accessibility_bridge.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/accessibility_bridge.mm", "repo_id": "engine", "token_count": 6263 }
323
// 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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_H_ #include <memory> #include "flutter/common/graphics/gl_context_switch.h" #include "flutter/common/graphics/msaa_sample_count.h" #include "flutter/common/graphics/texture.h" #include "flutter/fml/concurrent_message_loop.h" #include "flutter/fml/macros.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" #include "flutter/fml/synchronization/sync_switch.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" #import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace impeller { class Context; } // namespace impeller namespace flutter { //------------------------------------------------------------------------------ /// @brief Manages the lifetime of the on-screen and off-screen rendering /// contexts on iOS. On-screen contexts are used by Flutter for /// rendering into the surface. The lifecycle of this context may be /// tied to the lifecycle of the surface. On the other hand, the /// lifecycle of the off-screen context it tied to that of the /// platform view. This one object used to manage both context /// because GPU handles may need to be shared between the two /// context. To achieve this, context may need references to one /// another at creation time. This one object manages the creation, /// use and collection of both contexts in a client rendering API /// agnostic manner. /// class IOSContext { public: //---------------------------------------------------------------------------- /// @brief Create an iOS context object capable of creating the on-screen /// and off-screen GPU context for use by Skia. /// /// In case the engine does not support the specified client /// rendering API, this a `nullptr` may be returned. /// /// @param[in] api A client rendering API supported by the /// engine/platform. /// @param[in] backend A client rendering backend supported by the /// engine/platform. /// @param[in] msaa_samples /// The number of MSAA samples to use. Only supplied to /// Skia, must be either 0, 1, 2, 4, or 8. /// /// @return A valid context on success. `nullptr` on failure. /// static std::unique_ptr<IOSContext> Create( IOSRenderingAPI api, IOSRenderingBackend backend, MsaaSampleCount msaa_samples, const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch); //---------------------------------------------------------------------------- /// @brief Collects the context object. This must happen on the thread on /// which this object was created. /// virtual ~IOSContext(); //---------------------------------------------------------------------------- /// @brief Get the rendering backend used by this context. /// /// @return The rendering backend. /// virtual IOSRenderingBackend GetBackend() const; //---------------------------------------------------------------------------- /// @brief Create a resource context for use on the IO task runner. This /// resource context is used by Skia to upload texture to /// asynchronously and collect resources that are no longer needed /// on the render task runner. /// /// @attention Client rendering APIs for which a GrDirectContext cannot be realized /// (software rendering), this method will always return null. /// /// @return A non-null Skia context on success. `nullptr` on failure. /// virtual sk_sp<GrDirectContext> CreateResourceContext() = 0; //---------------------------------------------------------------------------- /// @brief When using client rendering APIs whose contexts need to be /// bound to a specific thread, the engine will call this method /// to give the on-screen context a chance to bind to the current /// thread. /// /// @attention Client rendering APIs that have no-concept of thread local /// bindings (anything that is not OpenGL) will always return /// `true`. /// /// @attention Client rendering APIs for which a GrDirectContext cannot be created /// (software rendering) will always return `false`. /// /// @attention This binds the on-screen context to the current thread. To /// bind the off-screen context to the thread, use the /// `ResoruceMakeCurrent` method instead. /// /// @attention Only one context may be bound to a thread at any given time. /// Making a binding on a thread, clears the old binding. /// /// @return A GLContextResult that represents the result of the method. /// The GetResult() returns a bool that indicates If the on-screen context could be /// bound to the current /// thread. /// virtual std::unique_ptr<GLContextResult> MakeCurrent() = 0; //---------------------------------------------------------------------------- /// @brief Creates an external texture proxy of the appropriate client /// rendering API. /// /// @param[in] texture_id The texture identifier /// @param[in] texture The texture /// /// @return The texture proxy if the rendering backend supports embedder /// provided external textures. /// virtual std::unique_ptr<Texture> CreateExternalTexture( int64_t texture_id, fml::scoped_nsobject<NSObject<FlutterTexture>> texture) = 0; //---------------------------------------------------------------------------- /// @brief Accessor for the Skia context associated with IOSSurfaces and /// the raster thread. /// @details There can be any number of resource contexts but this is the /// one context that will be used by surfaces to draw to the /// screen from the raster thread. /// @returns `nullptr` on failure. /// @attention The software context doesn't have a Skia context, so this /// value will be nullptr. /// @see For contexts which are used for offscreen work like loading /// textures see IOSContext::CreateResourceContext. /// virtual sk_sp<GrDirectContext> GetMainContext() const = 0; virtual std::shared_ptr<impeller::Context> GetImpellerContext() const; MsaaSampleCount GetMsaaSampleCount() const { return msaa_samples_; } protected: explicit IOSContext(MsaaSampleCount msaa_samples); private: MsaaSampleCount msaa_samples_ = MsaaSampleCount::kNone; FML_DISALLOW_COPY_AND_ASSIGN(IOSContext); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_H_
engine/shell/platform/darwin/ios/ios_context.h/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_context.h", "repo_id": "engine", "token_count": 2403 }
324
// 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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_METAL_SKIA_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_METAL_SKIA_H_ #include "flutter/fml/macros.h" #include "flutter/shell/gpu/gpu_surface_metal_delegate.h" #import "flutter/shell/platform/darwin/ios/ios_surface.h" #include "third_party/skia/include/gpu/ganesh/mtl/GrMtlTypes.h" @class CAMetalLayer; namespace flutter { class SK_API_AVAILABLE_CA_METAL_LAYER IOSSurfaceMetalSkia final : public IOSSurface, public GPUSurfaceMetalDelegate { public: IOSSurfaceMetalSkia(const fml::scoped_nsobject<CAMetalLayer>& layer, std::shared_ptr<IOSContext> context); // |IOSSurface| ~IOSSurfaceMetalSkia(); private: fml::scoped_nsobject<CAMetalLayer> layer_; id<MTLDevice> device_; id<MTLCommandQueue> command_queue_; bool is_valid_ = false; // |IOSSurface| bool IsValid() const override; // |IOSSurface| void UpdateStorageSizeIfNecessary() override; // |IOSSurface| std::unique_ptr<Surface> CreateGPUSurface(GrDirectContext* gr_context) override; // |GPUSurfaceMetalDelegate| GPUCAMetalLayerHandle GetCAMetalLayer(const SkISize& frame_info) const override; // |GPUSurfaceMetalDelegate| bool PresentDrawable(GrMTLHandle drawable) const override; // |GPUSurfaceMetalDelegate| GPUMTLTextureInfo GetMTLTexture(const SkISize& frame_info) const override; // |GPUSurfaceMetalDelegate| bool PresentTexture(GPUMTLTextureInfo texture) const override; // |GPUSurfaceMetalDelegate| bool AllowsDrawingWhenGpuDisabled() const override; FML_DISALLOW_COPY_AND_ASSIGN(IOSSurfaceMetalSkia); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_METAL_SKIA_H_
engine/shell/platform/darwin/ios/ios_surface_metal_skia.h/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_surface_metal_skia.h", "repo_id": "engine", "token_count": 790 }
325
// 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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERMACOS_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERMACOS_H_ #import "FlutterAppDelegate.h" #import "FlutterAppLifecycleDelegate.h" #import "FlutterBinaryMessenger.h" #import "FlutterChannels.h" #import "FlutterCodecs.h" #import "FlutterDartProject.h" #import "FlutterEngine.h" #import "FlutterMacros.h" #import "FlutterPluginMacOS.h" #import "FlutterPluginRegistrarMacOS.h" #import "FlutterTexture.h" #import "FlutterViewController.h" #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERMACOS_H_
engine/shell/platform/darwin/macos/framework/Headers/FlutterMacOS.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Headers/FlutterMacOS.h", "repo_id": "engine", "token_count": 303 }
326
// 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 "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #include <objc/objc.h> #include <algorithm> #include <functional> #include <thread> #include <vector> #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/lib/ui/window/platform_message.h" #include "flutter/shell/platform/common/accessibility_bridge.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" #import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/embedder_engine.h" #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" #include "flutter/testing/stream_capture.h" #include "flutter/testing/test_dart_native_resolver.h" #include "gtest/gtest.h" // CREATE_NATIVE_ENTRY and MOCK_ENGINE_PROC are leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) constexpr int64_t kImplicitViewId = 0ll; @interface FlutterEngine (Test) /** * The FlutterCompositor object currently in use by the FlutterEngine. * * May be nil if the compositor has not been initialized yet. */ @property(nonatomic, readonly, nullable) flutter::FlutterCompositor* macOSCompositor; @end @interface TestPlatformViewFactory : NSObject <FlutterPlatformViewFactory> @end @implementation TestPlatformViewFactory - (nonnull NSView*)createWithViewIdentifier:(int64_t)viewId arguments:(nullable id)args { return viewId == 42 ? [[NSView alloc] init] : nil; } @end @interface PlainAppDelegate : NSObject <NSApplicationDelegate> @end @implementation PlainAppDelegate - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication* _Nonnull)sender { // Always cancel, so that the test doesn't exit. return NSTerminateCancel; } @end #pragma mark - @interface FakeLifecycleProvider : NSObject <FlutterAppLifecycleProvider, NSApplicationDelegate> @property(nonatomic, strong, readonly) NSPointerArray* registeredDelegates; // True if the given delegate is currently registered. - (BOOL)hasDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate; @end @implementation FakeLifecycleProvider { /** * All currently registered delegates. * * This does not use NSPointerArray or any other weak-pointer * system, because a weak pointer will be nil'd out at the start of dealloc, which will break * queries. E.g., if a delegate is dealloc'd without being unregistered, a weak pointer array * would no longer contain that pointer even though removeApplicationLifecycleDelegate: was never * called, causing tests to pass incorrectly. */ std::vector<void*> _delegates; } - (void)addApplicationLifecycleDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate { _delegates.push_back((__bridge void*)delegate); } - (void)removeApplicationLifecycleDelegate: (nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate { auto delegateIndex = std::find(_delegates.begin(), _delegates.end(), (__bridge void*)delegate); NSAssert(delegateIndex != _delegates.end(), @"Attempting to unregister a delegate that was not registered."); _delegates.erase(delegateIndex); } - (BOOL)hasDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate { return std::find(_delegates.begin(), _delegates.end(), (__bridge void*)delegate) != _delegates.end(); } @end #pragma mark - @interface FakeAppDelegatePlugin : NSObject <FlutterPlugin> @end @implementation FakeAppDelegatePlugin + (void)registerWithRegistrar:(id<FlutterPluginRegistrar>)registrar { } @end #pragma mark - @interface MockableFlutterEngine : FlutterEngine @end @implementation MockableFlutterEngine - (NSArray<NSScreen*>*)screens { id mockScreen = OCMClassMock([NSScreen class]); OCMStub([mockScreen backingScaleFactor]).andReturn(2.0); OCMStub([mockScreen deviceDescription]).andReturn(@{ @"NSScreenNumber" : [NSNumber numberWithInt:10] }); OCMStub([mockScreen frame]).andReturn(NSMakeRect(10, 20, 30, 40)); return [NSArray arrayWithObject:mockScreen]; } @end #pragma mark - namespace flutter::testing { TEST_F(FlutterEngineTest, CanLaunch) { FlutterEngine* engine = GetFlutterEngine(); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); ASSERT_TRUE(engine.running); } TEST_F(FlutterEngineTest, HasNonNullExecutableName) { FlutterEngine* engine = GetFlutterEngine(); std::string executable_name = [[engine executableName] UTF8String]; ASSERT_FALSE(executable_name.empty()); // Block until notified by the Dart test of the value of Platform.executable. fml::AutoResetWaitableEvent latch; AddNativeCallback("NotifyStringValue", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { const auto dart_string = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); EXPECT_EQ(executable_name, dart_string); latch.Signal(); })); // Launch the test entrypoint. EXPECT_TRUE([engine runWithEntrypoint:@"executableNameNotNull"]); latch.Wait(); } #ifndef FLUTTER_RELEASE TEST_F(FlutterEngineTest, Switches) { setenv("FLUTTER_ENGINE_SWITCHES", "2", 1); setenv("FLUTTER_ENGINE_SWITCH_1", "abc", 1); setenv("FLUTTER_ENGINE_SWITCH_2", "foo=\"bar, baz\"", 1); FlutterEngine* engine = GetFlutterEngine(); std::vector<std::string> switches = engine.switches; ASSERT_EQ(switches.size(), 2UL); EXPECT_EQ(switches[0], "--abc"); EXPECT_EQ(switches[1], "--foo=\"bar, baz\""); unsetenv("FLUTTER_ENGINE_SWITCHES"); unsetenv("FLUTTER_ENGINE_SWITCH_1"); unsetenv("FLUTTER_ENGINE_SWITCH_2"); } #endif // !FLUTTER_RELEASE TEST_F(FlutterEngineTest, MessengerSend) { FlutterEngine* engine = GetFlutterEngine(); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); NSData* test_message = [@"a message" dataUsingEncoding:NSUTF8StringEncoding]; bool called = false; engine.embedderAPI.SendPlatformMessage = MOCK_ENGINE_PROC( SendPlatformMessage, ([&called, test_message](auto engine, auto message) { called = true; EXPECT_STREQ(message->channel, "test"); EXPECT_EQ(memcmp(message->message, test_message.bytes, message->message_size), 0); return kSuccess; })); [engine.binaryMessenger sendOnChannel:@"test" message:test_message]; EXPECT_TRUE(called); } TEST_F(FlutterEngineTest, CanLogToStdout) { // Block until completion of print statement. fml::AutoResetWaitableEvent latch; AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); // Replace stdout stream buffer with our own. StreamCapture stdout_capture(&std::cout); // Launch the test entrypoint. FlutterEngine* engine = GetFlutterEngine(); EXPECT_TRUE([engine runWithEntrypoint:@"canLogToStdout"]); ASSERT_TRUE(engine.running); latch.Wait(); stdout_capture.Stop(); // Verify hello world was written to stdout. EXPECT_TRUE(stdout_capture.GetOutput().find("Hello logging") != std::string::npos); } TEST_F(FlutterEngineTest, BackgroundIsBlack) { FlutterEngine* engine = GetFlutterEngine(); // Latch to ensure the entire layer tree has been generated and presented. fml::AutoResetWaitableEvent latch; AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { CALayer* rootLayer = engine.viewController.flutterView.layer; EXPECT_TRUE(rootLayer.backgroundColor != nil); if (rootLayer.backgroundColor != nil) { NSColor* actualBackgroundColor = [NSColor colorWithCGColor:rootLayer.backgroundColor]; EXPECT_EQ(actualBackgroundColor, [NSColor blackColor]); } latch.Signal(); })); // Launch the test entrypoint. EXPECT_TRUE([engine runWithEntrypoint:@"backgroundTest"]); ASSERT_TRUE(engine.running); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController loadView]; viewController.flutterView.frame = CGRectMake(0, 0, 800, 600); latch.Wait(); } TEST_F(FlutterEngineTest, CanOverrideBackgroundColor) { FlutterEngine* engine = GetFlutterEngine(); // Latch to ensure the entire layer tree has been generated and presented. fml::AutoResetWaitableEvent latch; AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { CALayer* rootLayer = engine.viewController.flutterView.layer; EXPECT_TRUE(rootLayer.backgroundColor != nil); if (rootLayer.backgroundColor != nil) { NSColor* actualBackgroundColor = [NSColor colorWithCGColor:rootLayer.backgroundColor]; EXPECT_EQ(actualBackgroundColor, [NSColor whiteColor]); } latch.Signal(); })); // Launch the test entrypoint. EXPECT_TRUE([engine runWithEntrypoint:@"backgroundTest"]); ASSERT_TRUE(engine.running); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController loadView]; viewController.flutterView.frame = CGRectMake(0, 0, 800, 600); viewController.flutterView.backgroundColor = [NSColor whiteColor]; latch.Wait(); } TEST_F(FlutterEngineTest, CanToggleAccessibility) { FlutterEngine* engine = GetFlutterEngine(); // Capture the update callbacks before the embedder API initializes. auto original_init = engine.embedderAPI.Initialize; std::function<void(const FlutterSemanticsUpdate2*, void*)> update_semantics_callback; engine.embedderAPI.Initialize = MOCK_ENGINE_PROC( Initialize, ([&update_semantics_callback, &original_init]( size_t version, const FlutterRendererConfig* config, const FlutterProjectArgs* args, void* user_data, auto engine_out) { update_semantics_callback = args->update_semantics_callback2; return original_init(version, config, args, user_data, engine_out); })); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); // Set up view controller. FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController loadView]; // Enable the semantics. bool enabled_called = false; engine.embedderAPI.UpdateSemanticsEnabled = MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) { enabled_called = enabled; return kSuccess; })); engine.semanticsEnabled = YES; EXPECT_TRUE(enabled_called); // Send flutter semantics updates. FlutterSemanticsNode2 root; root.id = 0; root.flags = static_cast<FlutterSemanticsFlag>(0); root.actions = static_cast<FlutterSemanticsAction>(0); root.text_selection_base = -1; root.text_selection_extent = -1; root.label = "root"; root.hint = ""; root.value = ""; root.increased_value = ""; root.decreased_value = ""; root.tooltip = ""; root.child_count = 1; int32_t children[] = {1}; root.children_in_traversal_order = children; root.custom_accessibility_actions_count = 0; FlutterSemanticsNode2 child1; child1.id = 1; child1.flags = static_cast<FlutterSemanticsFlag>(0); child1.actions = static_cast<FlutterSemanticsAction>(0); child1.text_selection_base = -1; child1.text_selection_extent = -1; child1.label = "child 1"; child1.hint = ""; child1.value = ""; child1.increased_value = ""; child1.decreased_value = ""; child1.tooltip = ""; child1.child_count = 0; child1.custom_accessibility_actions_count = 0; FlutterSemanticsUpdate2 update; update.node_count = 2; FlutterSemanticsNode2* nodes[] = {&root, &child1}; update.nodes = nodes; update.custom_action_count = 0; update_semantics_callback(&update, (__bridge void*)engine); // Verify the accessibility tree is attached to the flutter view. EXPECT_EQ([engine.viewController.flutterView.accessibilityChildren count], 1u); NSAccessibilityElement* native_root = engine.viewController.flutterView.accessibilityChildren[0]; std::string root_label = [native_root.accessibilityLabel UTF8String]; EXPECT_TRUE(root_label == "root"); EXPECT_EQ(native_root.accessibilityRole, NSAccessibilityGroupRole); EXPECT_EQ([native_root.accessibilityChildren count], 1u); NSAccessibilityElement* native_child1 = native_root.accessibilityChildren[0]; std::string child1_value = [native_child1.accessibilityValue UTF8String]; EXPECT_TRUE(child1_value == "child 1"); EXPECT_EQ(native_child1.accessibilityRole, NSAccessibilityStaticTextRole); EXPECT_EQ([native_child1.accessibilityChildren count], 0u); // Disable the semantics. bool semanticsEnabled = true; engine.embedderAPI.UpdateSemanticsEnabled = MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&semanticsEnabled](auto engine, bool enabled) { semanticsEnabled = enabled; return kSuccess; })); engine.semanticsEnabled = NO; EXPECT_FALSE(semanticsEnabled); // Verify the accessibility tree is removed from the view. EXPECT_EQ([engine.viewController.flutterView.accessibilityChildren count], 0u); [engine setViewController:nil]; } TEST_F(FlutterEngineTest, CanToggleAccessibilityWhenHeadless) { FlutterEngine* engine = GetFlutterEngine(); // Capture the update callbacks before the embedder API initializes. auto original_init = engine.embedderAPI.Initialize; std::function<void(const FlutterSemanticsUpdate2*, void*)> update_semantics_callback; engine.embedderAPI.Initialize = MOCK_ENGINE_PROC( Initialize, ([&update_semantics_callback, &original_init]( size_t version, const FlutterRendererConfig* config, const FlutterProjectArgs* args, void* user_data, auto engine_out) { update_semantics_callback = args->update_semantics_callback2; return original_init(version, config, args, user_data, engine_out); })); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); // Enable the semantics without attaching a view controller. bool enabled_called = false; engine.embedderAPI.UpdateSemanticsEnabled = MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) { enabled_called = enabled; return kSuccess; })); engine.semanticsEnabled = YES; EXPECT_TRUE(enabled_called); // Send flutter semantics updates. FlutterSemanticsNode2 root; root.id = 0; root.flags = static_cast<FlutterSemanticsFlag>(0); root.actions = static_cast<FlutterSemanticsAction>(0); root.text_selection_base = -1; root.text_selection_extent = -1; root.label = "root"; root.hint = ""; root.value = ""; root.increased_value = ""; root.decreased_value = ""; root.tooltip = ""; root.child_count = 1; int32_t children[] = {1}; root.children_in_traversal_order = children; root.custom_accessibility_actions_count = 0; FlutterSemanticsNode2 child1; child1.id = 1; child1.flags = static_cast<FlutterSemanticsFlag>(0); child1.actions = static_cast<FlutterSemanticsAction>(0); child1.text_selection_base = -1; child1.text_selection_extent = -1; child1.label = "child 1"; child1.hint = ""; child1.value = ""; child1.increased_value = ""; child1.decreased_value = ""; child1.tooltip = ""; child1.child_count = 0; child1.custom_accessibility_actions_count = 0; FlutterSemanticsUpdate2 update; update.node_count = 2; FlutterSemanticsNode2* nodes[] = {&root, &child1}; update.nodes = nodes; update.custom_action_count = 0; // This call updates semantics for the implicit view, which does not exist, // and therefore this call is invalid. But the engine should not crash. update_semantics_callback(&update, (__bridge void*)engine); // No crashes. EXPECT_EQ(engine.viewController, nil); // Disable the semantics. bool semanticsEnabled = true; engine.embedderAPI.UpdateSemanticsEnabled = MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&semanticsEnabled](auto engine, bool enabled) { semanticsEnabled = enabled; return kSuccess; })); engine.semanticsEnabled = NO; EXPECT_FALSE(semanticsEnabled); // Still no crashes EXPECT_EQ(engine.viewController, nil); } TEST_F(FlutterEngineTest, ProducesAccessibilityTreeWhenAddingViews) { FlutterEngine* engine = GetFlutterEngine(); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); // Enable the semantics without attaching a view controller. bool enabled_called = false; engine.embedderAPI.UpdateSemanticsEnabled = MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) { enabled_called = enabled; return kSuccess; })); engine.semanticsEnabled = YES; EXPECT_TRUE(enabled_called); EXPECT_EQ(engine.viewController, nil); // Assign the view controller after enabling semantics FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; engine.viewController = viewController; EXPECT_NE(viewController.accessibilityBridge.lock(), nullptr); } TEST_F(FlutterEngineTest, NativeCallbacks) { fml::AutoResetWaitableEvent latch; bool latch_called = false; AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch_called = true; latch.Signal(); })); FlutterEngine* engine = GetFlutterEngine(); EXPECT_TRUE([engine runWithEntrypoint:@"nativeCallback"]); ASSERT_TRUE(engine.running); latch.Wait(); ASSERT_TRUE(latch_called); } TEST_F(FlutterEngineTest, Compositor) { NSString* fixtures = @(flutter::testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController loadView]; [viewController viewDidLoad]; viewController.flutterView.frame = CGRectMake(0, 0, 800, 600); EXPECT_TRUE([engine runWithEntrypoint:@"canCompositePlatformViews"]); [engine.platformViewController registerViewFactory:[[TestPlatformViewFactory alloc] init] withId:@"factory_id"]; [engine.platformViewController handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{ @"id" : @(42), @"viewType" : @"factory_id", }] result:^(id result){ }]; [engine.testThreadSynchronizer blockUntilFrameAvailable]; CALayer* rootLayer = viewController.flutterView.layer; // There are two layers with Flutter contents and one view EXPECT_EQ(rootLayer.sublayers.count, 2u); EXPECT_EQ(viewController.flutterView.subviews.count, 1u); // TODO(gw280): add support for screenshot tests in this test harness [engine shutDownEngine]; } // namespace flutter::testing TEST_F(FlutterEngineTest, DartEntrypointArguments) { NSString* fixtures = @(flutter::testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; project.dartEntrypointArguments = @[ @"arg1", @"arg2" ]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project]; bool called = false; auto original_init = engine.embedderAPI.Initialize; engine.embedderAPI.Initialize = MOCK_ENGINE_PROC( Initialize, ([&called, &original_init](size_t version, const FlutterRendererConfig* config, const FlutterProjectArgs* args, void* user_data, FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) { called = true; EXPECT_EQ(args->dart_entrypoint_argc, 2); NSString* arg1 = [[NSString alloc] initWithCString:args->dart_entrypoint_argv[0] encoding:NSUTF8StringEncoding]; NSString* arg2 = [[NSString alloc] initWithCString:args->dart_entrypoint_argv[1] encoding:NSUTF8StringEncoding]; EXPECT_TRUE([arg1 isEqualToString:@"arg1"]); EXPECT_TRUE([arg2 isEqualToString:@"arg2"]); return original_init(version, config, args, user_data, engine_out); })); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); EXPECT_TRUE(called); } // Verify that the engine is not retained indirectly via the binary messenger held by channels and // plugins. Previously, FlutterEngine.binaryMessenger returned the engine itself, and thus plugins // could cause a retain cycle, preventing the engine from being deallocated. // FlutterEngine.binaryMessenger now returns a FlutterBinaryMessengerRelay whose weak pointer back // to the engine is cleared when the engine is deallocated. // Issue: https://github.com/flutter/flutter/issues/116445 TEST_F(FlutterEngineTest, FlutterBinaryMessengerDoesNotRetainEngine) { __weak FlutterEngine* weakEngine; id<FlutterBinaryMessenger> binaryMessenger = nil; @autoreleasepool { // Create a test engine. NSString* fixtures = @(flutter::testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:YES]; weakEngine = engine; binaryMessenger = engine.binaryMessenger; } // Once the engine has been deallocated, verify the weak engine pointer is nil, and thus not // retained by the relay. EXPECT_NE(binaryMessenger, nil); EXPECT_EQ(weakEngine, nil); } // Verify that the engine is not retained indirectly via the texture registry held by plugins. // Issue: https://github.com/flutter/flutter/issues/116445 TEST_F(FlutterEngineTest, FlutterTextureRegistryDoesNotReturnEngine) { __weak FlutterEngine* weakEngine; id<FlutterTextureRegistry> textureRegistry; @autoreleasepool { // Create a test engine. NSString* fixtures = @(flutter::testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:YES]; id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:@"MyPlugin"]; textureRegistry = registrar.textures; } // Once the engine has been deallocated, verify the weak engine pointer is nil, and thus not // retained via the texture registry. EXPECT_NE(textureRegistry, nil); EXPECT_EQ(weakEngine, nil); } TEST_F(FlutterEngineTest, PublishedValueNilForUnknownPlugin) { NSString* fixtures = @(flutter::testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:YES]; EXPECT_EQ([engine valuePublishedByPlugin:@"NoSuchPlugin"], nil); } TEST_F(FlutterEngineTest, PublishedValueNSNullIfNoPublishedValue) { NSString* fixtures = @(flutter::testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:YES]; NSString* pluginName = @"MyPlugin"; // Request the registarar to register the plugin as existing. [engine registrarForPlugin:pluginName]; // The documented behavior is that a plugin that exists but hasn't published // anything returns NSNull, rather than nil, as on iOS. EXPECT_EQ([engine valuePublishedByPlugin:pluginName], [NSNull null]); } TEST_F(FlutterEngineTest, PublishedValueReturnsLastPublished) { NSString* fixtures = @(flutter::testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:YES]; NSString* pluginName = @"MyPlugin"; id<FlutterPluginRegistrar> registrar = [engine registrarForPlugin:pluginName]; NSString* firstValue = @"A published value"; NSArray* secondValue = @[ @"A different published value" ]; [registrar publish:firstValue]; EXPECT_EQ([engine valuePublishedByPlugin:pluginName], firstValue); [registrar publish:secondValue]; EXPECT_EQ([engine valuePublishedByPlugin:pluginName], secondValue); } // If a channel overrides a previous channel with the same name, cleaning // the previous channel should not affect the new channel. // // This is important when recreating classes that uses a channel, because the // new instance would create the channel before the first class is deallocated // and clears the channel. TEST_F(FlutterEngineTest, MessengerCleanupConnectionWorks) { FlutterEngine* engine = GetFlutterEngine(); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); NSString* channel = @"_test_"; NSData* channel_data = [channel dataUsingEncoding:NSUTF8StringEncoding]; // Mock SendPlatformMessage so that if a message is sent to // "test/send_message", act as if the framework has sent an empty message to // the channel marked by the `sendOnChannel:message:` call's message. engine.embedderAPI.SendPlatformMessage = MOCK_ENGINE_PROC( SendPlatformMessage, ([](auto engine_, auto message_) { if (strcmp(message_->channel, "test/send_message") == 0) { // The simplest message that is acceptable to a method channel. std::string message = R"|({"method": "a"})|"; std::string channel(reinterpret_cast<const char*>(message_->message), message_->message_size); reinterpret_cast<EmbedderEngine*>(engine_) ->GetShell() .GetPlatformView() ->HandlePlatformMessage(std::make_unique<PlatformMessage>( channel.c_str(), fml::MallocMapping::Copy(message.c_str(), message.length()), fml::RefPtr<PlatformMessageResponse>())); } return kSuccess; })); __block int record = 0; FlutterMethodChannel* channel1 = [FlutterMethodChannel methodChannelWithName:channel binaryMessenger:engine.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]; [channel1 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { record += 1; }]; [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data]; EXPECT_EQ(record, 1); FlutterMethodChannel* channel2 = [FlutterMethodChannel methodChannelWithName:channel binaryMessenger:engine.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]; [channel2 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { record += 10; }]; [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data]; EXPECT_EQ(record, 11); [channel1 setMethodCallHandler:nil]; [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data]; EXPECT_EQ(record, 21); } TEST_F(FlutterEngineTest, HasStringsWhenPasteboardEmpty) { id engineMock = CreateMockFlutterEngine(nil); // Call hasStrings and expect it to be false. __block bool calledAfterClear = false; __block bool valueAfterClear; FlutterResult resultAfterClear = ^(id result) { calledAfterClear = true; NSNumber* valueNumber = [result valueForKey:@"value"]; valueAfterClear = [valueNumber boolValue]; }; FlutterMethodCall* methodCallAfterClear = [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil]; [engineMock handleMethodCall:methodCallAfterClear result:resultAfterClear]; EXPECT_TRUE(calledAfterClear); EXPECT_FALSE(valueAfterClear); } TEST_F(FlutterEngineTest, HasStringsWhenPasteboardFull) { id engineMock = CreateMockFlutterEngine(@"some string"); // Call hasStrings and expect it to be true. __block bool called = false; __block bool value; FlutterResult result = ^(id result) { called = true; NSNumber* valueNumber = [result valueForKey:@"value"]; value = [valueNumber boolValue]; }; FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil]; [engineMock handleMethodCall:methodCall result:result]; EXPECT_TRUE(called); EXPECT_TRUE(value); } TEST_F(FlutterEngineTest, ResponseAfterEngineDied) { FlutterEngine* engine = GetFlutterEngine(); FlutterBasicMessageChannel* channel = [[FlutterBasicMessageChannel alloc] initWithName:@"foo" binaryMessenger:engine.binaryMessenger codec:[FlutterStandardMessageCodec sharedInstance]]; __block BOOL didCallCallback = NO; [channel setMessageHandler:^(id message, FlutterReply callback) { ShutDownEngine(); callback(nil); didCallCallback = YES; }]; EXPECT_TRUE([engine runWithEntrypoint:@"sendFooMessage"]); engine = nil; while (!didCallCallback) { [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; } } TEST_F(FlutterEngineTest, ResponseFromBackgroundThread) { FlutterEngine* engine = GetFlutterEngine(); FlutterBasicMessageChannel* channel = [[FlutterBasicMessageChannel alloc] initWithName:@"foo" binaryMessenger:engine.binaryMessenger codec:[FlutterStandardMessageCodec sharedInstance]]; __block BOOL didCallCallback = NO; [channel setMessageHandler:^(id message, FlutterReply callback) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ callback(nil); dispatch_async(dispatch_get_main_queue(), ^{ didCallCallback = YES; }); }); }]; EXPECT_TRUE([engine runWithEntrypoint:@"sendFooMessage"]); while (!didCallCallback) { [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; } } TEST_F(FlutterEngineTest, ThreadSynchronizerNotBlockingRasterThreadAfterShutdown) { FlutterThreadSynchronizer* threadSynchronizer = [[FlutterThreadSynchronizer alloc] init]; [threadSynchronizer shutdown]; std::thread rasterThread([&threadSynchronizer] { [threadSynchronizer performCommitForView:kImplicitViewId size:CGSizeMake(100, 100) notify:^{ }]; }); rasterThread.join(); } TEST_F(FlutterEngineTest, ManageControllersIfInitiatedByController) { NSString* fixtures = @(flutter::testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine; FlutterViewController* viewController1; @autoreleasepool { // Create FVC1. viewController1 = [[FlutterViewController alloc] initWithProject:project]; EXPECT_EQ(viewController1.viewId, 0ll); engine = viewController1.engine; engine.viewController = nil; // Create FVC2 based on the same engine. FlutterViewController* viewController2 = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; EXPECT_EQ(engine.viewController, viewController2); } // FVC2 is deallocated but FVC1 is retained. EXPECT_EQ(engine.viewController, nil); engine.viewController = viewController1; EXPECT_EQ(engine.viewController, viewController1); EXPECT_EQ(viewController1.viewId, 0ll); } TEST_F(FlutterEngineTest, ManageControllersIfInitiatedByEngine) { // Don't create the engine with `CreateMockFlutterEngine`, because it adds // additional references to FlutterViewControllers, which is crucial to this // test case. FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"io.flutter" project:nil allowHeadlessExecution:NO]; FlutterViewController* viewController1; @autoreleasepool { viewController1 = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; EXPECT_EQ(viewController1.viewId, 0ll); EXPECT_EQ(engine.viewController, viewController1); engine.viewController = nil; FlutterViewController* viewController2 = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; EXPECT_EQ(viewController2.viewId, 0ll); EXPECT_EQ(engine.viewController, viewController2); } // FVC2 is deallocated but FVC1 is retained. EXPECT_EQ(engine.viewController, nil); engine.viewController = viewController1; EXPECT_EQ(engine.viewController, viewController1); EXPECT_EQ(viewController1.viewId, 0ll); } TEST_F(FlutterEngineTest, HandlesTerminationRequest) { id engineMock = CreateMockFlutterEngine(nil); __block NSString* nextResponse = @"exit"; __block BOOL triedToTerminate = NO; FlutterEngineTerminationHandler* terminationHandler = [[FlutterEngineTerminationHandler alloc] initWithEngine:engineMock terminator:^(id sender) { triedToTerminate = TRUE; // Don't actually terminate, of course. }]; OCMStub([engineMock terminationHandler]).andReturn(terminationHandler); id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub( // NOLINT(google-objc-avoid-throwing-exception) [engineMock binaryMessenger]) .andReturn(binaryMessengerMock); OCMStub([engineMock sendOnChannel:@"flutter/platform" message:[OCMArg any] binaryReply:[OCMArg any]]) .andDo((^(NSInvocation* invocation) { [invocation retainArguments]; FlutterBinaryReply callback; NSData* returnedMessage; [invocation getArgument:&callback atIndex:4]; if ([nextResponse isEqualToString:@"error"]) { FlutterError* errorResponse = [FlutterError errorWithCode:@"Error" message:@"Failed" details:@"Details"]; returnedMessage = [[FlutterJSONMethodCodec sharedInstance] encodeErrorEnvelope:errorResponse]; } else { NSDictionary* responseDict = @{@"response" : nextResponse}; returnedMessage = [[FlutterJSONMethodCodec sharedInstance] encodeSuccessEnvelope:responseDict]; } callback(returnedMessage); })); __block NSString* calledAfterTerminate = @""; FlutterResult appExitResult = ^(id result) { NSDictionary* resultDict = result; calledAfterTerminate = resultDict[@"response"]; }; FlutterMethodCall* methodExitApplication = [FlutterMethodCall methodCallWithMethodName:@"System.exitApplication" arguments:@{@"type" : @"cancelable"}]; // Always terminate when the binding isn't ready (which is the default). triedToTerminate = NO; calledAfterTerminate = @""; nextResponse = @"cancel"; [engineMock handleMethodCall:methodExitApplication result:appExitResult]; EXPECT_STREQ([calledAfterTerminate UTF8String], ""); EXPECT_TRUE(triedToTerminate); // Once the binding is ready, handle the request. terminationHandler.acceptingRequests = YES; triedToTerminate = NO; calledAfterTerminate = @""; nextResponse = @"exit"; [engineMock handleMethodCall:methodExitApplication result:appExitResult]; EXPECT_STREQ([calledAfterTerminate UTF8String], "exit"); EXPECT_TRUE(triedToTerminate); triedToTerminate = NO; calledAfterTerminate = @""; nextResponse = @"cancel"; [engineMock handleMethodCall:methodExitApplication result:appExitResult]; EXPECT_STREQ([calledAfterTerminate UTF8String], "cancel"); EXPECT_FALSE(triedToTerminate); // Check that it doesn't crash on error. triedToTerminate = NO; calledAfterTerminate = @""; nextResponse = @"error"; [engineMock handleMethodCall:methodExitApplication result:appExitResult]; EXPECT_STREQ([calledAfterTerminate UTF8String], ""); EXPECT_TRUE(triedToTerminate); } TEST_F(FlutterEngineTest, IgnoresTerminationRequestIfNotFlutterAppDelegate) { id<NSApplicationDelegate> previousDelegate = [[NSApplication sharedApplication] delegate]; id<NSApplicationDelegate> plainDelegate = [[PlainAppDelegate alloc] init]; [NSApplication sharedApplication].delegate = plainDelegate; // Creating the engine shouldn't fail here, even though the delegate isn't a // FlutterAppDelegate. CreateMockFlutterEngine(nil); // Asking to terminate the app should cancel. EXPECT_EQ([[[NSApplication sharedApplication] delegate] applicationShouldTerminate:NSApp], NSTerminateCancel); [NSApplication sharedApplication].delegate = previousDelegate; } TEST_F(FlutterEngineTest, HandleAccessibilityEvent) { __block BOOL announced = NO; id engineMock = CreateMockFlutterEngine(nil); OCMStub([engineMock announceAccessibilityMessage:[OCMArg any] withPriority:NSAccessibilityPriorityMedium]) .andDo((^(NSInvocation* invocation) { announced = TRUE; [invocation retainArguments]; NSString* message; [invocation getArgument:&message atIndex:2]; EXPECT_EQ(message, @"error message"); })); NSDictionary<NSString*, id>* annotatedEvent = @{@"type" : @"announce", @"data" : @{@"message" : @"error message"}}; [engineMock handleAccessibilityEvent:annotatedEvent]; EXPECT_TRUE(announced); } TEST_F(FlutterEngineTest, HandleLifecycleStates) API_AVAILABLE(macos(10.9)) { __block flutter::AppLifecycleState sentState; id engineMock = CreateMockFlutterEngine(nil); // Have to enumerate all the values because OCMStub can't capture // non-Objective-C object arguments. OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kDetached]) .andDo((^(NSInvocation* invocation) { sentState = flutter::AppLifecycleState::kDetached; })); OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kResumed]) .andDo((^(NSInvocation* invocation) { sentState = flutter::AppLifecycleState::kResumed; })); OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kInactive]) .andDo((^(NSInvocation* invocation) { sentState = flutter::AppLifecycleState::kInactive; })); OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kHidden]) .andDo((^(NSInvocation* invocation) { sentState = flutter::AppLifecycleState::kHidden; })); OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kPaused]) .andDo((^(NSInvocation* invocation) { sentState = flutter::AppLifecycleState::kPaused; })); __block NSApplicationOcclusionState visibility = NSApplicationOcclusionStateVisible; id mockApplication = OCMPartialMock([NSApplication sharedApplication]); OCMStub((NSApplicationOcclusionState)[mockApplication occlusionState]) .andDo(^(NSInvocation* invocation) { [invocation setReturnValue:&visibility]; }); NSNotification* willBecomeActive = [[NSNotification alloc] initWithName:NSApplicationWillBecomeActiveNotification object:nil userInfo:nil]; NSNotification* willResignActive = [[NSNotification alloc] initWithName:NSApplicationWillResignActiveNotification object:nil userInfo:nil]; NSNotification* didChangeOcclusionState; didChangeOcclusionState = [[NSNotification alloc] initWithName:NSApplicationDidChangeOcclusionStateNotification object:nil userInfo:nil]; [engineMock handleDidChangeOcclusionState:didChangeOcclusionState]; EXPECT_EQ(sentState, flutter::AppLifecycleState::kInactive); [engineMock handleWillBecomeActive:willBecomeActive]; EXPECT_EQ(sentState, flutter::AppLifecycleState::kResumed); [engineMock handleWillResignActive:willResignActive]; EXPECT_EQ(sentState, flutter::AppLifecycleState::kInactive); visibility = 0; [engineMock handleDidChangeOcclusionState:didChangeOcclusionState]; EXPECT_EQ(sentState, flutter::AppLifecycleState::kHidden); [engineMock handleWillBecomeActive:willBecomeActive]; EXPECT_EQ(sentState, flutter::AppLifecycleState::kHidden); [engineMock handleWillResignActive:willResignActive]; EXPECT_EQ(sentState, flutter::AppLifecycleState::kHidden); [mockApplication stopMocking]; } TEST_F(FlutterEngineTest, ForwardsPluginDelegateRegistration) { id<NSApplicationDelegate> previousDelegate = [[NSApplication sharedApplication] delegate]; FakeLifecycleProvider* fakeAppDelegate = [[FakeLifecycleProvider alloc] init]; [NSApplication sharedApplication].delegate = fakeAppDelegate; FakeAppDelegatePlugin* plugin = [[FakeAppDelegatePlugin alloc] init]; FlutterEngine* engine = CreateMockFlutterEngine(nil); [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin]; EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]); [NSApplication sharedApplication].delegate = previousDelegate; } TEST_F(FlutterEngineTest, UnregistersPluginsOnEngineDestruction) { id<NSApplicationDelegate> previousDelegate = [[NSApplication sharedApplication] delegate]; FakeLifecycleProvider* fakeAppDelegate = [[FakeLifecycleProvider alloc] init]; [NSApplication sharedApplication].delegate = fakeAppDelegate; FakeAppDelegatePlugin* plugin = [[FakeAppDelegatePlugin alloc] init]; @autoreleasepool { FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin]; EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]); } // When the engine is released, it should unregister any plugins it had // registered on its behalf. EXPECT_FALSE([fakeAppDelegate hasDelegate:plugin]); [NSApplication sharedApplication].delegate = previousDelegate; } TEST_F(FlutterEngineTest, RunWithEntrypointUpdatesDisplayConfig) { BOOL updated = NO; FlutterEngine* engine = GetFlutterEngine(); auto original_update_displays = engine.embedderAPI.NotifyDisplayUpdate; engine.embedderAPI.NotifyDisplayUpdate = MOCK_ENGINE_PROC( NotifyDisplayUpdate, ([&updated, &original_update_displays]( auto engine, auto update_type, auto* displays, auto display_count) { updated = YES; return original_update_displays(engine, update_type, displays, display_count); })); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); EXPECT_TRUE(updated); updated = NO; [[NSNotificationCenter defaultCenter] postNotificationName:NSApplicationDidChangeScreenParametersNotification object:nil]; EXPECT_TRUE(updated); } TEST_F(FlutterEngineTest, NotificationsUpdateDisplays) { BOOL updated = NO; FlutterEngine* engine = GetFlutterEngine(); auto original_set_viewport_metrics = engine.embedderAPI.SendWindowMetricsEvent; engine.embedderAPI.SendWindowMetricsEvent = MOCK_ENGINE_PROC( SendWindowMetricsEvent, ([&updated, &original_set_viewport_metrics](auto engine, auto* window_metrics) { updated = YES; return original_set_viewport_metrics(engine, window_metrics); })); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); updated = NO; [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidChangeScreenNotification object:nil]; // No VC. EXPECT_FALSE(updated); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController loadView]; viewController.flutterView.frame = CGRectMake(0, 0, 800, 600); [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidChangeScreenNotification object:nil]; EXPECT_TRUE(updated); } TEST_F(FlutterEngineTest, DisplaySizeIsInPhysicalPixel) { NSString* fixtures = @(testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; project.rootIsolateCreateCallback = FlutterEngineTest::IsolateCreateCallback; MockableFlutterEngine* engine = [[MockableFlutterEngine alloc] initWithName:@"foobar" project:project allowHeadlessExecution:true]; BOOL updated = NO; auto original_update_displays = engine.embedderAPI.NotifyDisplayUpdate; engine.embedderAPI.NotifyDisplayUpdate = MOCK_ENGINE_PROC( NotifyDisplayUpdate, ([&updated, &original_update_displays]( auto engine, auto update_type, auto* displays, auto display_count) { EXPECT_EQ(display_count, 1UL); EXPECT_EQ(displays->display_id, 10UL); EXPECT_EQ(displays->width, 60UL); EXPECT_EQ(displays->height, 80UL); EXPECT_EQ(displays->device_pixel_ratio, 2UL); updated = YES; return original_update_displays(engine, update_type, displays, display_count); })); EXPECT_TRUE([engine runWithEntrypoint:@"main"]); EXPECT_TRUE(updated); [engine shutDownEngine]; engine = nil; } } // namespace flutter::testing // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm", "repo_id": "engine", "token_count": 19711 }
327
// 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 <objc/message.h> #import "FlutterMouseCursorPlugin.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" static NSString* const kMouseCursorChannel = @"flutter/mousecursor"; static NSString* const kActivateSystemCursorMethod = @"activateSystemCursor"; static NSString* const kKindKey = @"kind"; static NSString* const kKindValueNone = @"none"; static NSDictionary* systemCursors; /** * Maps a Flutter's constant to a platform's cursor object. * * Returns the arrow cursor for unknown constants, including kSystemShapeNone. */ static NSCursor* GetCursorForKind(NSString* kind) { // The following mapping must be kept in sync with Flutter framework's // mouse_cursor.dart if (systemCursors == nil) { systemCursors = @{ @"alias" : [NSCursor dragLinkCursor], @"basic" : [NSCursor arrowCursor], @"click" : [NSCursor pointingHandCursor], @"contextMenu" : [NSCursor contextualMenuCursor], @"copy" : [NSCursor dragCopyCursor], @"disappearing" : [NSCursor disappearingItemCursor], @"forbidden" : [NSCursor operationNotAllowedCursor], @"grab" : [NSCursor openHandCursor], @"grabbing" : [NSCursor closedHandCursor], @"noDrop" : [NSCursor operationNotAllowedCursor], @"precise" : [NSCursor crosshairCursor], @"text" : [NSCursor IBeamCursor], @"resizeColumn" : [NSCursor resizeLeftRightCursor], @"resizeDown" : [NSCursor resizeDownCursor], @"resizeLeft" : [NSCursor resizeLeftCursor], @"resizeLeftRight" : [NSCursor resizeLeftRightCursor], @"resizeRight" : [NSCursor resizeRightCursor], @"resizeRow" : [NSCursor resizeUpDownCursor], @"resizeUp" : [NSCursor resizeUpCursor], @"resizeUpDown" : [NSCursor resizeUpDownCursor], @"verticalText" : [NSCursor IBeamCursorForVerticalLayout], }; } NSCursor* result = [systemCursors objectForKey:kind]; if (result == nil) { return [NSCursor arrowCursor]; } return result; } @interface FlutterMouseCursorPlugin () /** * Whether the cursor is currently hidden. */ @property(nonatomic) BOOL hidden; /** * Handles the method call that activates a system cursor. * * Returns a FlutterError if the arguments can not be recognized. Otherwise * returns nil. */ - (FlutterError*)activateSystemCursor:(nonnull NSDictionary*)arguments; /** * Displays the specified cursor. * * Unhides the cursor before displaying the cursor, and updates * internal states. */ - (void)displayCursorObject:(nonnull NSCursor*)cursorObject; /** * Hides the cursor. */ - (void)hide; /** * Handles all method calls from Flutter. */ - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; @end @implementation FlutterMouseCursorPlugin #pragma mark - Private NSMutableDictionary* cachedSystemCursors; - (instancetype)init { self = [super init]; if (self) { cachedSystemCursors = [NSMutableDictionary dictionary]; } return self; } - (void)dealloc { if (_hidden) { [NSCursor unhide]; } } - (FlutterError*)activateSystemCursor:(nonnull NSDictionary*)arguments { NSString* kindArg = arguments[kKindKey]; if (!kindArg) { return [FlutterError errorWithCode:@"error" message:@"Missing argument" details:@"Missing argument while trying to activate system cursor"]; } if ([kindArg isEqualToString:kKindValueNone]) { [self hide]; return nil; } NSCursor* cursorObject = [FlutterMouseCursorPlugin cursorFromKind:kindArg]; [self displayCursorObject:cursorObject]; return nil; } - (void)displayCursorObject:(nonnull NSCursor*)cursorObject { [cursorObject set]; if (_hidden) { [NSCursor unhide]; } _hidden = NO; } - (void)hide { if (!_hidden) { [NSCursor hide]; } _hidden = YES; } + (NSCursor*)cursorFromKind:(NSString*)kind { NSCursor* cachedValue = [cachedSystemCursors objectForKey:kind]; if (!cachedValue) { cachedValue = GetCursorForKind(kind); [cachedSystemCursors setValue:cachedValue forKey:kind]; } return cachedValue; } #pragma mark - FlutterPlugin implementation + (void)registerWithRegistrar:(id<FlutterPluginRegistrar>)registrar { FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:kMouseCursorChannel binaryMessenger:registrar.messenger]; FlutterMouseCursorPlugin* instance = [[FlutterMouseCursorPlugin alloc] init]; [registrar addMethodCallDelegate:instance channel:channel]; } - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { NSString* method = call.method; if ([method isEqualToString:kActivateSystemCursorMethod]) { result([self activateSystemCursor:call.arguments]); } else { result(FlutterMethodNotImplemented); } } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.mm", "repo_id": "engine", "token_count": 1834 }
328
// 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 <Cocoa/Cocoa.h> #import <Metal/Metal.h> #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h" #include "flutter/testing/testing.h" #include "gtest/gtest.h" @interface TestView : NSView <FlutterSurfaceManagerDelegate> @property(readwrite, nonatomic) CGSize presentedFrameSize; - (nonnull instancetype)init; @end @implementation TestView - (instancetype)init { self = [super initWithFrame:NSZeroRect]; if (self) { [self setWantsLayer:YES]; self.layer.contentsScale = 2.0; } return self; } - (void)onPresent:(CGSize)frameSize withBlock:(nonnull dispatch_block_t)block { self.presentedFrameSize = frameSize; block(); } @end namespace flutter::testing { static FlutterSurfaceManager* CreateSurfaceManager(TestView* testView) { id<MTLDevice> device = MTLCreateSystemDefaultDevice(); id<MTLCommandQueue> commandQueue = [device newCommandQueue]; CALayer* layer = reinterpret_cast<CALayer*>(testView.layer); return [[FlutterSurfaceManager alloc] initWithDevice:device commandQueue:commandQueue layer:layer delegate:testView]; } static FlutterSurfacePresentInfo* CreatePresentInfo( FlutterSurface* surface, CGPoint offset = CGPointZero, size_t index = 0, const std::vector<FlutterRect>& paintRegion = {}) { FlutterSurfacePresentInfo* res = [[FlutterSurfacePresentInfo alloc] init]; res.surface = surface; res.offset = offset; res.zIndex = index; res.paintRegion = paintRegion; return res; } TEST(FlutterSurfaceManager, MetalTextureSizeMatchesSurfaceSize) { TestView* testView = [[TestView alloc] init]; FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); // Get back buffer, lookup should work for borrowed surfaces util present. auto surface = [surfaceManager surfaceForSize:CGSizeMake(100, 50)]; auto texture = surface.asFlutterMetalTexture; id<MTLTexture> metalTexture = (__bridge id)texture.texture; EXPECT_EQ(metalTexture.width, 100ul); EXPECT_EQ(metalTexture.height, 50ul); texture.destruction_callback(texture.user_data); } TEST(FlutterSurfaceManager, TestSurfaceLookupFromTexture) { TestView* testView = [[TestView alloc] init]; FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); // Get back buffer, lookup should work for borrowed surfaces util present. auto surface = [surfaceManager surfaceForSize:CGSizeMake(100, 50)]; // SurfaceManager should keep texture alive while borrowed. auto texture = surface.asFlutterMetalTexture; texture.destruction_callback(texture.user_data); FlutterMetalTexture dummyTexture{.texture_id = 1, .texture = nullptr, .user_data = nullptr}; auto surface1 = [FlutterSurface fromFlutterMetalTexture:&dummyTexture]; EXPECT_EQ(surface1, nil); auto surface2 = [FlutterSurface fromFlutterMetalTexture:&texture]; EXPECT_EQ(surface2, surface); } TEST(FlutterSurfaceManager, BackBufferCacheDoesNotLeak) { TestView* testView = [[TestView alloc] init]; FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); auto surface1 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface1) ] atTime:0 notify:nil]; EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); auto surface2 = [surfaceManager surfaceForSize:CGSizeMake(110, 110)]; [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface2) ] atTime:0 notify:nil]; EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); auto surface3 = [surfaceManager surfaceForSize:CGSizeMake(120, 120)]; [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface3) ] atTime:0 notify:nil]; // Cache should be cleaned during present and only contain the last visible // surface(s). EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); auto surfaceFromCache = [surfaceManager surfaceForSize:CGSizeMake(110, 110)]; EXPECT_EQ(surfaceFromCache, surface2); [surfaceManager presentSurfaces:@[] atTime:0 notify:nil]; EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); [surfaceManager presentSurfaces:@[] atTime:0 notify:nil]; EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); } TEST(FlutterSurfaceManager, SurfacesAreRecycled) { TestView* testView = [[TestView alloc] init]; FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); EXPECT_EQ(surfaceManager.frontSurfaces.count, 0ul); // Get first surface and present it. auto surface1 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; EXPECT_TRUE(CGSizeEqualToSize(surface1.size, CGSizeMake(100, 100))); EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); EXPECT_EQ(surfaceManager.frontSurfaces.count, 0ul); [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface1) ] atTime:0 notify:nil]; EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); EXPECT_EQ(surfaceManager.frontSurfaces.count, 1ul); EXPECT_EQ(testView.layer.sublayers.count, 1ul); // Get second surface and present it. auto surface2 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; EXPECT_TRUE(CGSizeEqualToSize(surface2.size, CGSizeMake(100, 100))); EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface2) ] atTime:0 notify:nil]; // Check that current front surface returns to cache. EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); EXPECT_EQ(surfaceManager.frontSurfaces.count, 1ul); EXPECT_EQ(testView.layer.sublayers.count, 1ull); // Check that surface is properly reused. auto surface3 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; EXPECT_EQ(surface3, surface1); } inline bool operator==(const CGRect& lhs, const CGRect& rhs) { return CGRectEqualToRect(lhs, rhs); } TEST(FlutterSurfaceManager, LayerManagement) { TestView* testView = [[TestView alloc] init]; FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); EXPECT_EQ(testView.layer.sublayers.count, 0ul); auto surface1_1 = [surfaceManager surfaceForSize:CGSizeMake(50, 30)]; [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface1_1, CGPointMake(20, 10)) ] atTime:0 notify:nil]; EXPECT_EQ(testView.layer.sublayers.count, 1ul); EXPECT_TRUE(CGSizeEqualToSize(testView.presentedFrameSize, CGSizeMake(70, 40))); auto surface2_1 = [surfaceManager surfaceForSize:CGSizeMake(50, 30)]; auto surface2_2 = [surfaceManager surfaceForSize:CGSizeMake(20, 20)]; [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface2_1, CGPointMake(20, 10), 1), CreatePresentInfo(surface2_2, CGPointMake(40, 50), 2, { FlutterRect{0, 0, 20, 20}, FlutterRect{40, 0, 60, 20}, }) ] atTime:0 notify:nil]; EXPECT_EQ(testView.layer.sublayers.count, 2ul); EXPECT_EQ(testView.layer.sublayers[0].zPosition, 1.0); EXPECT_EQ(testView.layer.sublayers[1].zPosition, 2.0); CALayer* firstOverlaySublayer; { NSArray<CALayer*>* sublayers = testView.layer.sublayers[1].sublayers; EXPECT_EQ(sublayers.count, 2ul); EXPECT_TRUE(CGRectEqualToRect(sublayers[0].frame, CGRectMake(0, 0, 10, 10))); EXPECT_TRUE(CGRectEqualToRect(sublayers[1].frame, CGRectMake(20, 0, 10, 10))); EXPECT_TRUE(CGRectEqualToRect(sublayers[0].contentsRect, CGRectMake(0, 0, 1, 1))); EXPECT_TRUE(CGRectEqualToRect(sublayers[1].contentsRect, CGRectMake(2, 0, 1, 1))); EXPECT_EQ(sublayers[0].contents, sublayers[1].contents); firstOverlaySublayer = sublayers[0]; } EXPECT_TRUE(CGSizeEqualToSize(testView.presentedFrameSize, CGSizeMake(70, 70))); // Check second overlay sublayer is removed while first is reused and updated [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface2_1, CGPointMake(20, 10), 1), CreatePresentInfo(surface2_2, CGPointMake(40, 50), 2, { FlutterRect{0, 10, 20, 20}, }) ] atTime:0 notify:nil]; EXPECT_EQ(testView.layer.sublayers.count, 2ul); { NSArray<CALayer*>* sublayers = testView.layer.sublayers[1].sublayers; EXPECT_EQ(sublayers.count, 1ul); EXPECT_EQ(sublayers[0], firstOverlaySublayer); EXPECT_TRUE(CGRectEqualToRect(sublayers[0].frame, CGRectMake(0, 5, 10, 5))); } // Check that second overlay sublayer is added back while first is reused and updated [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface2_1, CGPointMake(20, 10), 1), CreatePresentInfo(surface2_2, CGPointMake(40, 50), 2, { FlutterRect{0, 0, 20, 20}, FlutterRect{40, 0, 60, 20}, }) ] atTime:0 notify:nil]; EXPECT_EQ(testView.layer.sublayers.count, 2ul); { NSArray<CALayer*>* sublayers = testView.layer.sublayers[1].sublayers; EXPECT_EQ(sublayers.count, 2ul); EXPECT_EQ(sublayers[0], firstOverlaySublayer); EXPECT_TRUE(CGRectEqualToRect(sublayers[0].frame, CGRectMake(0, 0, 10, 10))); EXPECT_TRUE(CGRectEqualToRect(sublayers[1].frame, CGRectMake(20, 0, 10, 10))); EXPECT_EQ(sublayers[0].contents, sublayers[1].contents); } auto surface3_1 = [surfaceManager surfaceForSize:CGSizeMake(50, 30)]; [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface3_1, CGPointMake(20, 10)) ] atTime:0 notify:nil]; EXPECT_EQ(testView.layer.sublayers.count, 1ul); EXPECT_TRUE(CGSizeEqualToSize(testView.presentedFrameSize, CGSizeMake(70, 40))); // Check removal of all surfaces. [surfaceManager presentSurfaces:@[] atTime:0 notify:nil]; EXPECT_EQ(testView.layer.sublayers.count, 0ul); EXPECT_TRUE(CGSizeEqualToSize(testView.presentedFrameSize, CGSizeMake(0, 0))); } } // namespace flutter::testing
engine/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManagerTest.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManagerTest.mm", "repo_id": "engine", "token_count": 4092 }
329
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h" #include "flutter/fml/logging.h" #include <optional> #include <vector> #if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE) #define VSYNC_TRACING_ENABLED 1 #endif #if VSYNC_TRACING_ENABLED #include <OSLog/OSLog.h> // Trace vsync events using os_signpost so that they can be seen in Instruments "Points of // Interest". #define TRACE_VSYNC(event_type, baton) \ do { \ os_log_t log = os_log_create("FlutterVSync", "PointsOfInterest"); \ os_signpost_event_emit(log, OS_SIGNPOST_ID_EXCLUSIVE, event_type, "baton %lx", baton); \ } while (0) #else #define TRACE_VSYNC(event_type, baton) \ do { \ } while (0) #endif @interface FlutterVSyncWaiter () <FlutterDisplayLinkDelegate> @end // It's preferable to fire the timers slightly early than too late due to scheduling latency. // 1ms before vsync should be late enough for all events to be processed. static const CFTimeInterval kTimerLatencyCompensation = 0.001; @implementation FlutterVSyncWaiter { std::optional<std::uintptr_t> _pendingBaton; FlutterDisplayLink* _displayLink; void (^_block)(CFTimeInterval, CFTimeInterval, uintptr_t); NSRunLoop* _runLoop; CFTimeInterval _lastTargetTimestamp; BOOL _warmUpFrame; } - (instancetype)initWithDisplayLink:(FlutterDisplayLink*)displayLink block:(void (^)(CFTimeInterval timestamp, CFTimeInterval targetTimestamp, uintptr_t baton))block { FML_DCHECK([NSThread isMainThread]); if (self = [super init]) { _block = block; _displayLink = displayLink; _displayLink.delegate = self; // Get at least one callback to initialize _lastTargetTimestamp. _displayLink.paused = NO; _warmUpFrame = YES; } return self; } // Called on same thread as the vsync request (UI thread). - (void)processDisplayLink:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp { FML_DCHECK([NSRunLoop currentRunLoop] == _runLoop); _lastTargetTimestamp = targetTimestamp; // CVDisplayLink callback is called one and a half frame before the target // timestamp. That can cause frame-pacing issues if the frame is rendered too early, // it may also trigger frame start before events are processed. CFTimeInterval minStart = targetTimestamp - _displayLink.nominalOutputRefreshPeriod; CFTimeInterval current = CACurrentMediaTime(); CFTimeInterval remaining = std::max(minStart - current - kTimerLatencyCompensation, 0.0); TRACE_VSYNC("DisplayLinkCallback-Original", _pendingBaton.value_or(0)); NSTimer* timer = [NSTimer timerWithTimeInterval:remaining repeats:NO block:^(NSTimer* _Nonnull timer) { if (!_pendingBaton.has_value()) { TRACE_VSYNC("DisplayLinkPaused", size_t(0)); _displayLink.paused = YES; return; } TRACE_VSYNC("DisplayLinkCallback-Delayed", _pendingBaton.value_or(0)); _block(minStart, targetTimestamp, *_pendingBaton); _pendingBaton = std::nullopt; }]; [_runLoop addTimer:timer forMode:NSRunLoopCommonModes]; } // Called from display link thread. - (void)onDisplayLink:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp { @synchronized(self) { if (_runLoop == nil) { // Initial vsync - timestamp will be used to determine vsync phase. _lastTargetTimestamp = targetTimestamp; _displayLink.paused = YES; } else { [_runLoop performBlock:^{ [self processDisplayLink:timestamp targetTimestamp:targetTimestamp]; }]; } } } // Called from UI thread. - (void)waitForVSync:(uintptr_t)baton { // CVDisplayLink start -> callback latency is two frames, there is // no need to delay the warm-up frame. if (_warmUpFrame) { _warmUpFrame = NO; TRACE_VSYNC("WarmUpFrame", baton); [[NSRunLoop currentRunLoop] performBlock:^{ CFTimeInterval now = CACurrentMediaTime(); _block(now, now, baton); }]; return; } // RunLoop is accessed both from main thread and from the display link thread. @synchronized(self) { if (_runLoop == nil) { _runLoop = [NSRunLoop currentRunLoop]; } } FML_DCHECK(_runLoop == [NSRunLoop currentRunLoop]); if (_pendingBaton.has_value()) { FML_LOG(WARNING) << "Engine requested vsync while another was pending"; _block(0, 0, *_pendingBaton); _pendingBaton = std::nullopt; } TRACE_VSYNC("VSyncRequest", _pendingBaton.value_or(0)); CFTimeInterval tick_interval = _displayLink.nominalOutputRefreshPeriod; if (_displayLink.paused || tick_interval == 0) { // When starting display link the first notification will come in the middle // of next frame, which would incur a whole frame period of latency. // To avoid that, first vsync notification will be fired using a timer // scheduled to fire where the next frame is expected to start. // Also use a timer if display link does not belong to any display // (nominalOutputRefreshPeriod being 0) // Start of the vsync interval. CFTimeInterval start = CACurrentMediaTime(); // Timer delay is calculated as the time to the next frame start. CFTimeInterval delay = 0; if (tick_interval != 0 && _lastTargetTimestamp != 0) { CFTimeInterval phase = fmod(_lastTargetTimestamp, tick_interval); CFTimeInterval now = start; start = now - (fmod(now, tick_interval)) + phase; if (start < now) { start += tick_interval; } delay = std::max(start - now - kTimerLatencyCompensation, 0.0); } NSTimer* timer = [NSTimer timerWithTimeInterval:delay repeats:NO block:^(NSTimer* timer) { CFTimeInterval targetTimestamp = start + tick_interval; TRACE_VSYNC("SynthesizedInitialVSync", baton); _block(start, targetTimestamp, baton); }]; [_runLoop addTimer:timer forMode:NSRunLoopCommonModes]; _displayLink.paused = NO; } else { _pendingBaton = baton; } } - (void)dealloc { if (_pendingBaton.has_value()) { FML_LOG(WARNING) << "Deallocating FlutterVSyncWaiter with a pending vsync"; } [_displayLink invalidate]; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.mm", "repo_id": "engine", "token_count": 3039 }
330
// 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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_ #import <Cocoa/Cocoa.h> #include <cinttypes> #include <vector> namespace flutter { /** * Maps macOS-specific key code values representing |PhysicalKeyboardKey|. * * MacOS doesn't provide a scan code, but a virtual keycode to represent a physical key. */ extern const NSDictionary* keyCodeToPhysicalKey; /** * A map from macOS key codes to Flutter's logical key values. * * This is used to derive logical keys that can't or shouldn't be derived from * |charactersIgnoringModifiers|. */ extern const NSDictionary* keyCodeToLogicalKey; // Several mask constants. See KeyCodeMap.g.mm for their descriptions. /** * Mask for the 32-bit value portion of the key code. */ extern const uint64_t kValueMask; /** * The plane value for keys which have a Unicode representation. */ extern const uint64_t kUnicodePlane; /** * The plane value for the private keys defined by the macOS embedding. */ extern const uint64_t kMacosPlane; /** * Map |NSEvent.keyCode| to its corresponding bitmask of NSEventModifierFlags. * * This does not include CapsLock, for it is handled specially. */ extern const NSDictionary* keyCodeToModifierFlag; /** * Map a bit of bitmask of NSEventModifierFlags to its corresponding * |NSEvent.keyCode|. * * This does not include CapsLock, for it is handled specially. */ extern const NSDictionary* modifierFlagToKeyCode; /** * The physical key for CapsLock, which needs special handling. */ extern const uint64_t kCapsLockPhysicalKey; /** * The logical key for CapsLock, which needs special handling. */ extern const uint64_t kCapsLockLogicalKey; /** * Bits in |NSEvent.modifierFlags| indicating whether a modifier key is pressed. * * These constants are not written in the official documentation, but derived * from experiments. This is currently the only way to know whether a one-side * modifier key (such as ShiftLeft) is pressed, instead of the general combined * modifier state (such as Shift). */ typedef enum { kModifierFlagControlLeft = 0x1, kModifierFlagShiftLeft = 0x2, kModifierFlagShiftRight = 0x4, kModifierFlagMetaLeft = 0x8, kModifierFlagMetaRight = 0x10, kModifierFlagAltLeft = 0x20, kModifierFlagAltRight = 0x40, kModifierFlagControlRight = 0x200, } ModifierFlag; /** * A character that Flutter wants to derive layout for, and guides on how to * derive it. */ typedef struct { // The key code for a key that prints `keyChar` in the US keyboard layout. uint16_t keyCode; // The printable string to derive logical key for. uint64_t keyChar; // If the goal is mandatory, the keyboard manager will make sure to find a // logical key for this character, falling back to the US keyboard layout. bool mandatory; } LayoutGoal; /** * All keys that Flutter wants to derive layout for, and guides on how to derive * them. */ extern const std::vector<LayoutGoal> kLayoutGoals; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_
engine/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h", "repo_id": "engine", "token_count": 1030 }
331
// 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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_TEXTURE_GL_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_TEXTURE_GL_H_ #include "flutter/common/graphics/texture.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/embedder/embedder.h" #include "third_party/skia/include/core/SkSize.h" namespace flutter { class EmbedderExternalTextureGL : public flutter::Texture { public: using ExternalTextureCallback = std::function< std::unique_ptr<FlutterOpenGLTexture>(int64_t, size_t, size_t)>; EmbedderExternalTextureGL(int64_t texture_identifier, const ExternalTextureCallback& callback); ~EmbedderExternalTextureGL(); private: const ExternalTextureCallback& external_texture_callback_; sk_sp<DlImage> last_image_; sk_sp<DlImage> ResolveTexture(int64_t texture_id, GrDirectContext* context, const SkISize& size); // |flutter::Texture| void Paint(PaintContext& context, const SkRect& bounds, bool freeze, const DlImageSampling sampling) override; // |flutter::Texture| void OnGrContextCreated() override; // |flutter::Texture| void OnGrContextDestroyed() override; // |flutter::Texture| void MarkNewFrameAvailable() override; // |flutter::Texture| void OnTextureUnregistered() override; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderExternalTextureGL); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_TEXTURE_GL_H_
engine/shell/platform/embedder/embedder_external_texture_gl.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_external_texture_gl.h", "repo_id": "engine", "token_count": 672 }
332
// 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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_H_ #include <memory> #include "flutter/fml/closure.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/embedder/embedder.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkSurface.h" namespace impeller { class RenderTarget; class AiksContext; } // namespace impeller namespace flutter { //------------------------------------------------------------------------------ /// @brief Describes a surface whose backing store is managed by the /// embedder. The type of surface depends on the client rendering /// API used. The embedder is notified of the collection of this /// render target via a callback. /// class EmbedderRenderTarget { public: //---------------------------------------------------------------------------- /// @brief Destroys this instance of the render target and invokes the /// callback for the embedder to release its resource associated /// with the particular backing store. /// virtual ~EmbedderRenderTarget(); //---------------------------------------------------------------------------- /// @brief A render surface the rasterizer can use to draw into the /// backing store of this render target. /// /// @return The render surface. /// virtual sk_sp<SkSurface> GetSkiaSurface() const = 0; //---------------------------------------------------------------------------- /// @brief An impeller render target the rasterizer can use to draw into /// the backing store. /// /// @return The Impeller render target. /// virtual impeller::RenderTarget* GetImpellerRenderTarget() const = 0; //---------------------------------------------------------------------------- /// @brief Returns the AiksContext that should be used for rendering, if /// this render target is backed by Impeller. /// /// @return The Impeller Aiks context. /// virtual std::shared_ptr<impeller::AiksContext> GetAiksContext() const = 0; //---------------------------------------------------------------------------- /// @brief Returns the size of the render target. /// /// @return The size of the render target. /// virtual SkISize GetRenderTargetSize() const = 0; //---------------------------------------------------------------------------- /// @brief The embedder backing store descriptor. This is the descriptor /// that was given to the engine by the embedder. This descriptor /// may contain context the embedder can use to associate it /// resources with the compositor layers when they are given back /// to it in present callback. The engine does not use this in any /// way. /// /// @return The backing store. /// const FlutterBackingStore* GetBackingStore() const; protected: //---------------------------------------------------------------------------- /// @brief Creates a render target whose backing store is managed by the /// embedder. The way this render target is exposed to the engine /// is via an SkSurface and a callback that is invoked by this /// object in its destructor. /// /// @param[in] backing_store The backing store describing this render /// target. /// @param[in] on_release The callback to invoke (eventually forwarded /// to the embedder) when the backing store is no /// longer required by the engine. /// EmbedderRenderTarget(FlutterBackingStore backing_store, fml::closure on_release); private: FlutterBackingStore backing_store_; fml::closure on_release_; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderRenderTarget); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_H_
engine/shell/platform/embedder/embedder_render_target.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_render_target.h", "repo_id": "engine", "token_count": 1387 }
333
// 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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_METAL_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_METAL_H_ #include "flutter/fml/macros.h" #include "flutter/shell/gpu/gpu_surface_metal_delegate.h" #include "flutter/shell/gpu/gpu_surface_metal_skia.h" #include "flutter/shell/platform/embedder/embedder_external_view_embedder.h" #include "flutter/shell/platform/embedder/embedder_surface.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { class EmbedderSurfaceMetal final : public EmbedderSurface, public GPUSurfaceMetalDelegate { public: struct MetalDispatchTable { std::function<bool(GPUMTLTextureInfo texture)> present; // required std::function<GPUMTLTextureInfo(const SkISize& frame_size)> get_texture; // required }; EmbedderSurfaceMetal( GPUMTLDeviceHandle device, GPUMTLCommandQueueHandle command_queue, MetalDispatchTable dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder); ~EmbedderSurfaceMetal() override; private: bool valid_ = false; MetalDispatchTable metal_dispatch_table_; std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder_; sk_sp<SkSurface> surface_; sk_sp<GrDirectContext> main_context_; sk_sp<GrDirectContext> resource_context_; // |EmbedderSurface| bool IsValid() const override; // |EmbedderSurface| std::unique_ptr<Surface> CreateGPUSurface() override; // |EmbedderSurface| sk_sp<GrDirectContext> CreateResourceContext() const override; // |GPUSurfaceMetalDelegate| GPUCAMetalLayerHandle GetCAMetalLayer( const SkISize& frame_size) const override; // |GPUSurfaceMetalDelegate| bool PresentDrawable(GrMTLHandle drawable) const override; // |GPUSurfaceMetalDelegate| GPUMTLTextureInfo GetMTLTexture(const SkISize& frame_size) const override; // |GPUSurfaceMetalDelegate| bool PresentTexture(GPUMTLTextureInfo texture) const override; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderSurfaceMetal); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_METAL_H_
engine/shell/platform/embedder/embedder_surface_metal.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_surface_metal.h", "repo_id": "engine", "token_count": 851 }
334
// 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. #include "tests/embedder_test_context.h" #define FML_USED_ON_EMBEDDER #include <atomic> #include <string> #include <vector> #include "vulkan/vulkan.h" #include "GLES3/gl3.h" #include "flutter/flow/raster_cache.h" #include "flutter/fml/file.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/mapping.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/message_loop_task_queues.h" #include "flutter/fml/native_library.h" #include "flutter/fml/paths.h" #include "flutter/fml/synchronization/count_down_latch.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/fml/task_source.h" #include "flutter/fml/thread.h" #include "flutter/lib/ui/painting/image.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/platform/embedder/embedder_surface_gl_impeller.h" #include "flutter/shell/platform/embedder/tests/embedder_assertions.h" #include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" #include "flutter/shell/platform/embedder/tests/embedder_test.h" #include "flutter/shell/platform/embedder/tests/embedder_test_context_gl.h" #include "flutter/shell/platform/embedder/tests/embedder_unittests_util.h" #include "flutter/testing/assertions_skia.h" #include "flutter/testing/test_gl_surface.h" #include "flutter/testing/testing.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/tonic/converter/dart_converter.h" // CREATE_NATIVE_ENTRY is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) namespace flutter { namespace testing { using EmbedderTest = testing::EmbedderTest; TEST_F(EmbedderTest, CanGetVulkanEmbedderContext) { auto& context = GetEmbedderContext(EmbedderTestContextType::kVulkanContext); EmbedderConfigBuilder builder(context); } TEST_F(EmbedderTest, CanCreateOpenGLRenderingEngine) { EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kOpenGLContext)); builder.SetOpenGLRendererConfig(SkISize::Make(1, 1)); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } //------------------------------------------------------------------------------ /// If an incorrectly configured compositor is set on the engine, the engine /// must fail to launch instead of failing to render a frame at a later point in /// time. /// TEST_F(EmbedderTest, MustPreventEngineLaunchWhenRequiredCompositorArgsAreAbsent) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(1, 1)); builder.SetCompositor(); builder.GetCompositor().create_backing_store_callback = nullptr; builder.GetCompositor().collect_backing_store_callback = nullptr; builder.GetCompositor().present_layers_callback = nullptr; builder.GetCompositor().present_view_callback = nullptr; auto engine = builder.LaunchEngine(); ASSERT_FALSE(engine.is_valid()); } //------------------------------------------------------------------------------ /// Either present_layers_callback or present_view_callback must be provided, /// but not both, otherwise the engine must fail to launch instead of failing to /// render a frame at a later point in time. /// TEST_F(EmbedderTest, LaunchFailsWhenMultiplePresentCallbacks) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(1, 1)); builder.SetCompositor(); builder.GetCompositor().present_layers_callback = [](const FlutterLayer** layers, size_t layers_count, void* user_data) { return true; }; builder.GetCompositor().present_view_callback = [](const FlutterPresentViewInfo* info) { return true; }; auto engine = builder.LaunchEngine(); ASSERT_FALSE(engine.is_valid()); } //------------------------------------------------------------------------------ /// Must be able to render to a custom compositor whose render targets are fully /// complete OpenGL textures. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToOpenGLFramebuffer) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); fml::CountDownLatch latch(3); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(2, 3, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } //------------------------------------------------------------------------------ /// Layers in a hierarchy containing a platform view should not be cached. The /// other layers in the hierarchy should be, however. TEST_F(EmbedderTest, RasterCacheDisabledWithPlatformViews) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_with_opacity"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); fml::CountDownLatch setup(3); fml::CountDownLatch verify(1); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(3, 3, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } setup.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&setup](Dart_NativeArguments args) { setup.CountDown(); })); UniqueEngine engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); setup.Wait(); const flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); shell.GetTaskRunners().GetRasterTaskRunner()->PostTask([&] { const flutter::RasterCache& raster_cache = shell.GetRasterizer()->compositor_context()->raster_cache(); // 3 layers total, but one of them had the platform view. So the cache // should only have 2 entries. ASSERT_EQ(raster_cache.GetCachedEntriesCount(), 2u); verify.CountDown(); }); verify.Wait(); } //------------------------------------------------------------------------------ /// The RasterCache should normally be enabled. /// TEST_F(EmbedderTest, RasterCacheEnabled) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_with_opacity"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); fml::CountDownLatch setup(3); fml::CountDownLatch verify(1); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 1u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } setup.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&setup](Dart_NativeArguments args) { setup.CountDown(); })); UniqueEngine engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); setup.Wait(); const flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); shell.GetTaskRunners().GetRasterTaskRunner()->PostTask([&] { const flutter::RasterCache& raster_cache = shell.GetRasterizer()->compositor_context()->raster_cache(); ASSERT_EQ(raster_cache.GetCachedEntriesCount(), 1u); verify.CountDown(); }); verify.Wait(); } //------------------------------------------------------------------------------ /// Must be able to render using a custom compositor whose render targets for /// the individual layers are OpenGL textures. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToOpenGLTexture) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(3); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(2, 3, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } //------------------------------------------------------------------------------ /// Must be able to render using a custom compositor whose render target for the /// individual layers are software buffers. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToSoftwareBuffer) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); fml::CountDownLatch latch(3); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; ASSERT_FLOAT_EQ( backing_store.software.row_bytes * backing_store.software.height, 800 * 4 * 600.0); FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(2, 3, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom compositor. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownScene) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(5); auto scene_image = context.GetNextSceneImage(); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 5u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(20.0, 20.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(30, 30, 80, 180), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } // Layer 3 { FlutterPlatformView platform_view = *layers[3]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 2; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(40.0, 40.0); ASSERT_EQ(*layers[3], layer); } // Layer 4 { FlutterBackingStore backing_store = *layers[4]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(50, 50, 100, 200), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[4], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrDirectContext* context) -> sk_sp<SkImage> { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; case 2: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorMAGENTA); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("compositor.png", scene_image)); // There should no present calls on the root surface. ASSERT_EQ(context.GetSurfacePresentCount(), 0u); } //------------------------------------------------------------------------------ /// Custom compositor must play nicely with a custom task runner. The raster /// thread merging mechanism must not interfere with the custom compositor. /// TEST_F(EmbedderTest, CustomCompositorMustWorkWithCustomTaskRunner) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views"); auto platform_task_runner = CreateNewThread("test_platform_thread"); static std::mutex engine_mutex; UniqueEngine engine; fml::AutoResetWaitableEvent sync_latch; EmbedderTestTaskRunner test_task_runner( platform_task_runner, [&](FlutterTask task) { std::scoped_lock lock(engine_mutex); if (!engine.is_valid()) { return; } ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); }); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(3); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(2, 3, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(2, 3, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); const auto task_runner_description = test_task_runner.GetFlutterTaskRunnerDescription(); builder.SetPlatformTaskRunner(&task_runner_description); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); platform_task_runner->PostTask([&]() { std::scoped_lock lock(engine_mutex); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); sync_latch.Signal(); }); sync_latch.Wait(); latch.Wait(); platform_task_runner->PostTask([&]() { std::scoped_lock lock(engine_mutex); engine.reset(); sync_latch.Signal(); }); sync_latch.Wait(); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom compositor /// and a single layer. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderWithRootLayerOnly) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint( "can_composite_platform_views_with_root_layer_only"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(3); auto scene_image = context.GetNextSceneImage(); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 1u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } latch.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE( ImageMatchesFixture("compositor_with_root_layer_only.png", scene_image)); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom compositor /// and ensure that a redundant layer is not added. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderWithPlatformLayerOnBottom) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint( "can_composite_platform_views_with_platform_layer_on_bottom"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(3); auto scene_image = context.GetNextSceneImage(); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(20.0, 20.0); ASSERT_EQ(*layers[1], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrDirectContext* context) -> sk_sp<SkImage> { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture( "compositor_with_platform_layer_on_bottom.png", scene_image)); ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 1u); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom compositor /// with a root surface transformation. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownSceneWithRootSurfaceTransformation) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); // This must match the transformation provided in the // |CanRenderGradientWithoutCompositorWithXform| test to ensure that // transforms are consistent respected. const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); fml::CountDownLatch latch(5); auto scene_image = context.GetNextSceneImage(); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 5u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 600, 800), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(150.0, 50.0); layer.offset = FlutterPointMake(20.0, 730.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(30, 720, 180, 770), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } // Layer 3 { FlutterPlatformView platform_view = *layers[3]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 2; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(150.0, 50.0); layer.offset = FlutterPointMake(40.0, 710.0); ASSERT_EQ(*layers[3], layer); } // Layer 4 { FlutterBackingStore backing_store = *layers[4]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(50, 700, 200, 750), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[4], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrDirectContext* context) -> sk_sp<SkImage> { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; case 2: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorMAGENTA); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. Only the root surface is rotated. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("compositor_root_surface_xformation.png", scene_image)); } TEST_F(EmbedderTest, CanRenderSceneWithoutCustomCompositor) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture("scene_without_custom_compositor.png", rendered_scene)); } TEST_F(EmbedderTest, CanRenderSceneWithoutCustomCompositorWithTransformation) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture( "scene_without_custom_compositor_with_xform.png", rendered_scene)); } TEST_P(EmbedderTestMultiBackend, CanRenderGradientWithoutCompositor) { EmbedderTestContextType backend = GetParam(); auto& context = GetEmbedderContext(backend); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient"); builder.SetRendererConfig(backend, SkISize::Make(800, 600)); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture( FixtureNameForBackend(backend, "gradient.png"), rendered_scene)); } TEST_F(EmbedderTest, CanRenderGradientWithoutCompositorWithXform) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); EmbedderConfigBuilder builder(context); const auto surface_size = SkISize::Make(600, 800); builder.SetDartEntrypoint("render_gradient"); builder.SetOpenGLRendererConfig(surface_size); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture("gradient_xform.png", rendered_scene)); } TEST_P(EmbedderTestMultiBackend, CanRenderGradientWithCompositor) { EmbedderTestContextType backend = GetParam(); auto& context = GetEmbedderContext(backend); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient"); builder.SetRendererConfig(backend, SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetRenderTargetType(GetRenderTargetFromBackend(backend, true)); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture( FixtureNameForBackend(backend, "gradient.png"), rendered_scene)); } TEST_F(EmbedderTest, CanRenderGradientWithCompositorWithXform) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); // This must match the transformation provided in the // |CanRenderGradientWithoutCompositorWithXform| test to ensure that // transforms are consistent respected. const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient"); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); builder.SetCompositor(); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture("gradient_xform.png", rendered_scene)); } TEST_P(EmbedderTestMultiBackend, CanRenderGradientWithCompositorOnNonRootLayer) { EmbedderTestContextType backend = GetParam(); auto& context = GetEmbedderContext(backend); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient_on_non_root_backing_store"); builder.SetRendererConfig(backend, SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetRenderTargetType(GetRenderTargetFromBackend(backend, true)); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.did_update = true; ConfigureBackingStore(backing_store, backend, true); FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(100.0, 200.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.did_update = true; ConfigureBackingStore(backing_store, backend, true); FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrDirectContext* context) -> sk_sp<SkImage> { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { FML_CHECK(layer.size.width == 100); FML_CHECK(layer.size.height == 200); // This is occluded anyway. We just want to make sure we see this. } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture( FixtureNameForBackend(backend, "gradient.png"), rendered_scene)); } TEST_F(EmbedderTest, CanRenderGradientWithCompositorOnNonRootLayerWithXform) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); // This must match the transformation provided in the // |CanRenderGradientWithoutCompositorWithXform| test to ensure that // transforms are consistent respected. const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient_on_non_root_backing_store"); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); builder.SetCompositor(); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 600, 800), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(200.0, 100.0); layer.offset = FlutterPointMake(0.0, 700.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 600, 800), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrDirectContext* context) -> sk_sp<SkImage> { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { FML_CHECK(layer.size.width == 200); FML_CHECK(layer.size.height == 100); // This is occluded anyway. We just want to make sure we see this. } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture("gradient_xform.png", rendered_scene)); } TEST_F(EmbedderTest, VerifyB141980393) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); // The Flutter application is 800 x 600 but rendering on a surface that is 600 // x 800 achieved using a root surface transformation. const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); const auto flutter_application_rect = SkRect::MakeWH(800, 600); const auto root_surface_rect = root_surface_transformation.mapRect(flutter_application_rect); ASSERT_DOUBLE_EQ(root_surface_rect.width(), 600.0); ASSERT_DOUBLE_EQ(root_surface_rect.height(), 800.0); // Configure the fixture for the surface transformation. context.SetRootSurfaceTransformation(root_surface_transformation); // Configure the Flutter project args for the root surface transformation. builder.SetOpenGLRendererConfig( SkISize::Make(root_surface_rect.width(), root_surface_rect.height())); // Use a compositor instead of rendering directly to the surface. builder.SetCompositor(); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); builder.SetDartEntrypoint("verify_b141980393"); fml::AutoResetWaitableEvent latch; context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 1u); // Layer Root { FlutterPlatformView platform_view = *layers[0]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1337; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; // From the Dart side. These dimensions match those specified in Dart // code and are free of root surface transformations. const double unxformed_top_margin = 31.0; const double unxformed_bottom_margin = 37.0; const auto unxformed_platform_view_rect = SkRect::MakeXYWH( 0.0, // x unxformed_top_margin, // y (top margin) 800, // width 600 - unxformed_top_margin - unxformed_bottom_margin // height ); // The platform views are in the coordinate space of the root surface // with top-left origin. The embedder has specified a transformation // to this surface which it must account for in the coordinates it // receives here. const auto xformed_platform_view_rect = root_surface_transformation.mapRect(unxformed_platform_view_rect); // Spell out the value that we are going to be checking below for // clarity. ASSERT_EQ(xformed_platform_view_rect, SkRect::MakeXYWH(31.0, // x 0.0, // y 532.0, // width 800.0 // height )); // Verify that the engine is giving us the right size and offset. layer.offset = FlutterPointMake(xformed_platform_view_rect.x(), xformed_platform_view_rect.y()); layer.size = FlutterSizeMake(xformed_platform_view_rect.width(), xformed_platform_view_rect.height()); ASSERT_EQ(*layers[0], layer); } latch.Signal(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // The Flutter application is 800 x 600 rendering on a surface 600 x 800 // achieved via a root surface transformation. event.width = flutter_application_rect.width(); event.height = flutter_application_rect.height(); event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } //------------------------------------------------------------------------------ /// Asserts that embedders can provide a task runner for the render thread. /// TEST_F(EmbedderTest, CanCreateEmbedderWithCustomRenderTaskRunner) { std::mutex engine_mutex; UniqueEngine engine; fml::AutoResetWaitableEvent task_latch; bool task_executed = false; EmbedderTestTaskRunner render_task_runner( CreateNewThread("custom_render_thread"), [&](FlutterTask task) { std::scoped_lock engine_lock(engine_mutex); if (engine.is_valid()) { ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); task_executed = true; task_latch.Signal(); } }); EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kOpenGLContext)); builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetRenderTaskRunner( &render_task_runner.GetFlutterTaskRunnerDescription()); { std::scoped_lock lock(engine_mutex); engine = builder.InitializeEngine(); } ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); task_latch.Wait(); ASSERT_TRUE(task_executed); ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); { std::scoped_lock engine_lock(engine_mutex); engine.reset(); } } //------------------------------------------------------------------------------ /// Asserts that the render task runner can be the same as the platform task /// runner. /// TEST_P(EmbedderTestMultiBackend, CanCreateEmbedderWithCustomRenderTaskRunnerTheSameAsPlatformTaskRunner) { // A new thread needs to be created for the platform thread because the test // can't wait for assertions to be completed on the same thread that services // platform task runner tasks. auto platform_task_runner = CreateNewThread("platform_thread"); static std::mutex engine_mutex; static UniqueEngine engine; fml::AutoResetWaitableEvent task_latch; bool task_executed = false; EmbedderTestTaskRunner common_task_runner( platform_task_runner, [&](FlutterTask task) { std::scoped_lock engine_lock(engine_mutex); if (engine.is_valid()) { ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); task_executed = true; task_latch.Signal(); } }); platform_task_runner->PostTask([&]() { EmbedderTestContextType backend = GetParam(); EmbedderConfigBuilder builder(GetEmbedderContext(backend)); builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); builder.SetRendererConfig(backend, SkISize::Make(800, 600)); builder.SetRenderTaskRunner( &common_task_runner.GetFlutterTaskRunnerDescription()); builder.SetPlatformTaskRunner( &common_task_runner.GetFlutterTaskRunnerDescription()); { std::scoped_lock lock(engine_mutex); engine = builder.InitializeEngine(); } ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); }); task_latch.Wait(); // Don't use the task latch because that may be called multiple time // (including during the shutdown process). fml::AutoResetWaitableEvent shutdown_latch; platform_task_runner->PostTask([&]() { ASSERT_TRUE(task_executed); ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); { std::scoped_lock engine_lock(engine_mutex); engine.reset(); } shutdown_latch.Signal(); }); shutdown_latch.Wait(); { std::scoped_lock engine_lock(engine_mutex); // Engine should have been killed by this point. ASSERT_FALSE(engine.is_valid()); } } TEST_P(EmbedderTestMultiBackend, CompositorMustBeAbleToRenderKnownScenePixelRatioOnSurface) { EmbedderTestContextType backend = GetParam(); auto& context = GetEmbedderContext(backend); EmbedderConfigBuilder builder(context); builder.SetRendererConfig(backend, SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_display_platform_view_with_pixel_ratio"); builder.SetRenderTargetType(GetRenderTargetFromBackend(backend, false)); fml::CountDownLatch latch(1); auto rendered_scene = context.GetNextSceneImage(); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); // Layer 0 (Root) { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.did_update = true; ConfigureBackingStore(backing_store, backend, false); FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(800.0, 560.0); layer.offset = FlutterPointMake(0.0, 40.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.did_update = true; ConfigureBackingStore(backing_store, backend, false); FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 400 * 2.0; event.height = 300 * 2.0; event.pixel_ratio = 2.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture( FixtureNameForBackend(backend, "dpr_noxform.png"), rendered_scene)); } TEST_F( EmbedderTest, CompositorMustBeAbleToRenderKnownScenePixelRatioOnSurfaceWithRootSurfaceXformation) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); builder.SetCompositor(); builder.SetDartEntrypoint("can_display_platform_view_with_pixel_ratio"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); auto rendered_scene = context.GetNextSceneImage(); fml::CountDownLatch latch(1); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); // Layer 0 (Root) { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 600, 800), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(560.0, 800.0); layer.offset = FlutterPointMake(40.0, 0.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 600, 800), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 400 * 2.0; event.height = 300 * 2.0; event.pixel_ratio = 2.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("dpr_xform.png", rendered_scene)); } TEST_F(EmbedderTest, PushingMutlipleFramesSetsUpNewRecordingCanvasWithCustomCompositor) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 1024)); builder.SetCompositor(); builder.SetDartEntrypoint("push_frames_over_and_over"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); const auto root_surface_transformation = SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1024; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); constexpr size_t frames_expected = 10; fml::CountDownLatch frame_latch(frames_expected); std::atomic_size_t frames_seen = 0; context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { frames_seen++; frame_latch.CountDown(); })); frame_latch.Wait(); ASSERT_GE(frames_seen, frames_expected); FlutterEngineShutdown(engine.release()); } TEST_F(EmbedderTest, PushingMutlipleFramesSetsUpNewRecordingCanvasWithoutCustomCompositor) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 1024)); builder.SetDartEntrypoint("push_frames_over_and_over"); const auto root_surface_transformation = SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1024; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); constexpr size_t frames_expected = 10; fml::CountDownLatch frame_latch(frames_expected); std::atomic_size_t frames_seen = 0; context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { frames_seen++; frame_latch.CountDown(); })); frame_latch.Wait(); ASSERT_GE(frames_seen, frames_expected); FlutterEngineShutdown(engine.release()); } TEST_P(EmbedderTestMultiBackend, PlatformViewMutatorsAreValid) { EmbedderTestContextType backend = GetParam(); auto& context = GetEmbedderContext(backend); EmbedderConfigBuilder builder(context); builder.SetRendererConfig(backend, SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("platform_view_mutators"); builder.SetRenderTargetType(GetRenderTargetFromBackend(backend, false)); fml::CountDownLatch latch(1); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer 0 (Root) { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.did_update = true; ConfigureBackingStore(backing_store, backend, false); FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 2 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; platform_view.mutations_count = 3; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[1], layer); // There are no ordering guarantees. for (size_t i = 0; i < platform_view.mutations_count; i++) { FlutterPlatformViewMutation mutation = *platform_view.mutations[i]; switch (mutation.type) { case kFlutterPlatformViewMutationTypeClipRoundedRect: mutation.clip_rounded_rect = FlutterRoundedRectMake(SkRRect::MakeRectXY( SkRect::MakeLTRB(10.0, 10.0, 800.0 - 10.0, 600.0 - 10.0), 14.0, 14.0)); break; case kFlutterPlatformViewMutationTypeClipRect: mutation.type = kFlutterPlatformViewMutationTypeClipRect; mutation.clip_rect = FlutterRectMake( SkRect::MakeXYWH(10.0, 10.0, 800.0 - 20.0, 600.0 - 20.0)); break; case kFlutterPlatformViewMutationTypeOpacity: mutation.type = kFlutterPlatformViewMutationTypeOpacity; mutation.opacity = 128.0 / 255.0; break; case kFlutterPlatformViewMutationTypeTransformation: FML_CHECK(false) << "There should be no transformation in the test."; break; } ASSERT_EQ(*platform_view.mutations[i], mutation); } } latch.CountDown(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } TEST_F(EmbedderTest, PlatformViewMutatorsAreValidWithPixelRatio) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("platform_view_mutators_with_pixel_ratio"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(1); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer 0 (Root) { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 2 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; platform_view.mutations_count = 3; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[1], layer); // There are no ordering guarantees. for (size_t i = 0; i < platform_view.mutations_count; i++) { FlutterPlatformViewMutation mutation = *platform_view.mutations[i]; switch (mutation.type) { case kFlutterPlatformViewMutationTypeClipRoundedRect: mutation.clip_rounded_rect = FlutterRoundedRectMake(SkRRect::MakeRectXY( SkRect::MakeLTRB(5.0, 5.0, 400.0 - 5.0, 300.0 - 5.0), 7.0, 7.0)); break; case kFlutterPlatformViewMutationTypeClipRect: mutation.type = kFlutterPlatformViewMutationTypeClipRect; mutation.clip_rect = FlutterRectMake( SkRect::MakeXYWH(5.0, 5.0, 400.0 - 10.0, 300.0 - 10.0)); break; case kFlutterPlatformViewMutationTypeOpacity: mutation.type = kFlutterPlatformViewMutationTypeOpacity; mutation.opacity = 128.0 / 255.0; break; case kFlutterPlatformViewMutationTypeTransformation: mutation.type = kFlutterPlatformViewMutationTypeTransformation; mutation.transformation = FlutterTransformationMake(SkMatrix::Scale(2.0, 2.0)); break; } ASSERT_EQ(*platform_view.mutations[i], mutation); } } latch.CountDown(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 2.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } TEST_F(EmbedderTest, PlatformViewMutatorsAreValidWithPixelRatioAndRootSurfaceTransformation) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("platform_view_mutators_with_pixel_ratio"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); static const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); fml::CountDownLatch latch(1); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer 0 (Root) { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 600, 800), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 2 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; platform_view.mutations_count = 4; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[1], layer); // There are no ordering guarantees. for (size_t i = 0; i < platform_view.mutations_count; i++) { FlutterPlatformViewMutation mutation = *platform_view.mutations[i]; switch (mutation.type) { case kFlutterPlatformViewMutationTypeClipRoundedRect: mutation.clip_rounded_rect = FlutterRoundedRectMake(SkRRect::MakeRectXY( SkRect::MakeLTRB(5.0, 5.0, 400.0 - 5.0, 300.0 - 5.0), 7.0, 7.0)); break; case kFlutterPlatformViewMutationTypeClipRect: mutation.type = kFlutterPlatformViewMutationTypeClipRect; mutation.clip_rect = FlutterRectMake( SkRect::MakeXYWH(5.0, 5.0, 400.0 - 10.0, 300.0 - 10.0)); break; case kFlutterPlatformViewMutationTypeOpacity: mutation.type = kFlutterPlatformViewMutationTypeOpacity; mutation.opacity = 128.0 / 255.0; break; case kFlutterPlatformViewMutationTypeTransformation: mutation.type = kFlutterPlatformViewMutationTypeTransformation; mutation.transformation = FlutterTransformationMake(root_surface_transformation); break; } ASSERT_EQ(*platform_view.mutations[i], mutation); } } latch.CountDown(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 2.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } TEST_F(EmbedderTest, EmptySceneIsAcceptable) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("empty_scene"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, SceneWithNoRootContainerIsAcceptable) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); builder.SetDartEntrypoint("scene_with_no_container"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } // Verifies that https://skia-review.googlesource.com/c/skia/+/259174 is pulled // into the engine. TEST_F(EmbedderTest, ArcEndCapsAreDrawnCorrectly) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 1024)); builder.SetCompositor(); builder.SetDartEntrypoint("arc_end_caps_correct"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); const auto root_surface_transformation = SkMatrix() .preScale(1.0, -1.0) .preTranslate(1024.0, -800.0) .preRotate(90.0); context.SetRootSurfaceTransformation(root_surface_transformation); auto engine = builder.LaunchEngine(); auto scene_image = context.GetNextSceneImage(); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 1024; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture("arc_end_caps.png", scene_image)); } TEST_F(EmbedderTest, ClipsAreCorrectlyCalculated) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(400, 300)); builder.SetCompositor(); builder.SetDartEntrypoint("scene_builder_with_clips"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); const auto root_surface_transformation = SkMatrix().preTranslate(0, 400).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); fml::AutoResetWaitableEvent latch; context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); { FlutterPlatformView platform_view = *layers[0]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(300.0, 400.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); bool clip_assertions_checked = false; // The total transformation on the stack upto the platform view. const auto total_xformation = GetTotalMutationTransformationMatrix(layers[0]->platform_view); FilterMutationsByType( layers[0]->platform_view, kFlutterPlatformViewMutationTypeClipRect, [&](const auto& mutation) { FlutterRect clip = mutation.clip_rect; // The test is only set up to supply one clip. Make sure it is // the one we expect. const auto rect_to_compare = SkRect::MakeLTRB(10.0, 10.0, 390, 290); ASSERT_EQ(clip, FlutterRectMake(rect_to_compare)); // This maps the clip from device space into surface space. SkRect mapped; ASSERT_TRUE(total_xformation.mapRect(&mapped, rect_to_compare)); ASSERT_EQ(mapped, SkRect::MakeLTRB(10, 10, 290, 390)); clip_assertions_checked = true; }); ASSERT_TRUE(clip_assertions_checked); } latch.Signal(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 400; event.height = 300; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, ComplexClipsAreCorrectlyCalculated) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(1024, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("scene_builder_with_complex_clips"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); const auto root_surface_transformation = SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); fml::AutoResetWaitableEvent latch; context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); { FlutterPlatformView platform_view = *layers[0]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(600.0, 1024.0); layer.offset = FlutterPointMake(0.0, -256.0); ASSERT_EQ(*layers[0], layer); const auto** mutations = platform_view.mutations; ASSERT_EQ(mutations[0]->type, kFlutterPlatformViewMutationTypeTransformation); ASSERT_EQ(SkMatrixMake(mutations[0]->transformation), root_surface_transformation); ASSERT_EQ(mutations[1]->type, kFlutterPlatformViewMutationTypeClipRect); ASSERT_EQ(SkRectMake(mutations[1]->clip_rect), SkRect::MakeLTRB(0.0, 0.0, 1024.0, 600.0)); ASSERT_EQ(mutations[2]->type, kFlutterPlatformViewMutationTypeTransformation); ASSERT_EQ(SkMatrixMake(mutations[2]->transformation), SkMatrix::Translate(512.0, 0.0)); ASSERT_EQ(mutations[3]->type, kFlutterPlatformViewMutationTypeClipRect); ASSERT_EQ(SkRectMake(mutations[3]->clip_rect), SkRect::MakeLTRB(0.0, 0.0, 512.0, 600.0)); ASSERT_EQ(mutations[4]->type, kFlutterPlatformViewMutationTypeTransformation); ASSERT_EQ(SkMatrixMake(mutations[4]->transformation), SkMatrix::Translate(-256.0, 0.0)); ASSERT_EQ(mutations[5]->type, kFlutterPlatformViewMutationTypeClipRect); ASSERT_EQ(SkRectMake(mutations[5]->clip_rect), SkRect::MakeLTRB(0.0, 0.0, 1024.0, 600.0)); } latch.Signal(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1024; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, ObjectsCanBePostedViaPorts) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 1024)); builder.SetDartEntrypoint("objects_can_be_posted"); // Synchronously acquire the send port from the Dart end. We will be using // this to send message. The Dart end will just echo those messages back to us // for inspection. FlutterEngineDartPort port = 0; fml::AutoResetWaitableEvent event; context.AddNativeCallback("SignalNativeCount", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { port = tonic::DartConverter<int64_t>::FromDart( Dart_GetNativeArgument(args, 0)); event.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); event.Wait(); ASSERT_NE(port, 0); using Trampoline = std::function<void(Dart_Handle message)>; Trampoline trampoline; context.AddNativeCallback("SendObjectToNativeCode", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { FML_CHECK(trampoline); auto trampoline_copy = trampoline; trampoline = nullptr; trampoline_copy(Dart_GetNativeArgument(args, 0)); })); // Check null. { FlutterEngineDartObject object = {}; object.type = kFlutterEngineDartObjectTypeNull; trampoline = [&](Dart_Handle handle) { ASSERT_TRUE(Dart_IsNull(handle)); event.Signal(); }; ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), kSuccess); event.Wait(); } // Check bool. { FlutterEngineDartObject object = {}; object.type = kFlutterEngineDartObjectTypeBool; object.bool_value = true; trampoline = [&](Dart_Handle handle) { ASSERT_TRUE(tonic::DartConverter<bool>::FromDart(handle)); event.Signal(); }; ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), kSuccess); event.Wait(); } // Check int32. { FlutterEngineDartObject object = {}; object.type = kFlutterEngineDartObjectTypeInt32; object.int32_value = 1988; trampoline = [&](Dart_Handle handle) { ASSERT_EQ(tonic::DartConverter<int32_t>::FromDart(handle), 1988); event.Signal(); }; ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), kSuccess); event.Wait(); } // Check int64. { FlutterEngineDartObject object = {}; object.type = kFlutterEngineDartObjectTypeInt64; object.int64_value = 1988; trampoline = [&](Dart_Handle handle) { ASSERT_EQ(tonic::DartConverter<int64_t>::FromDart(handle), 1988); event.Signal(); }; ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), kSuccess); event.Wait(); } // Check double. { FlutterEngineDartObject object = {}; object.type = kFlutterEngineDartObjectTypeDouble; object.double_value = 1988.0; trampoline = [&](Dart_Handle handle) { ASSERT_DOUBLE_EQ(tonic::DartConverter<double>::FromDart(handle), 1988.0); event.Signal(); }; ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), kSuccess); event.Wait(); } // Check string. { const char* message = "Hello. My name is Inigo Montoya."; FlutterEngineDartObject object = {}; object.type = kFlutterEngineDartObjectTypeString; object.string_value = message; trampoline = [&](Dart_Handle handle) { ASSERT_EQ(tonic::DartConverter<std::string>::FromDart(handle), std::string{message}); event.Signal(); }; ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), kSuccess); event.Wait(); } // Check buffer (copied out). { std::vector<uint8_t> message; message.resize(1988); ASSERT_TRUE(MemsetPatternSetOrCheck( message, MemsetPatternOp::kMemsetPatternOpSetBuffer)); FlutterEngineDartBuffer buffer = {}; buffer.struct_size = sizeof(buffer); buffer.user_data = nullptr; buffer.buffer_collect_callback = nullptr; buffer.buffer = message.data(); buffer.buffer_size = message.size(); FlutterEngineDartObject object = {}; object.type = kFlutterEngineDartObjectTypeBuffer; object.buffer_value = &buffer; trampoline = [&](Dart_Handle handle) { intptr_t length = 0; Dart_ListLength(handle, &length); ASSERT_EQ(length, 1988); // TODO(chinmaygarde); The std::vector<uint8_t> specialization for // DartConvertor in tonic is broken which is preventing the buffer // being checked here. Fix tonic and strengthen this check. For now, just // the buffer length is checked. event.Signal(); }; ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), kSuccess); event.Wait(); } std::vector<uint8_t> message; fml::AutoResetWaitableEvent buffer_released_latch; // Check buffer (caller own buffer with zero copy transfer). { message.resize(1988); ASSERT_TRUE(MemsetPatternSetOrCheck( message, MemsetPatternOp::kMemsetPatternOpSetBuffer)); FlutterEngineDartBuffer buffer = {}; buffer.struct_size = sizeof(buffer); buffer.user_data = &buffer_released_latch; buffer.buffer_collect_callback = +[](void* user_data) { reinterpret_cast<fml::AutoResetWaitableEvent*>(user_data)->Signal(); }; buffer.buffer = message.data(); buffer.buffer_size = message.size(); FlutterEngineDartObject object = {}; object.type = kFlutterEngineDartObjectTypeBuffer; object.buffer_value = &buffer; trampoline = [&](Dart_Handle handle) { intptr_t length = 0; Dart_ListLength(handle, &length); ASSERT_EQ(length, 1988); // TODO(chinmaygarde); The std::vector<uint8_t> specialization for // DartConvertor in tonic is broken which is preventing the buffer // being checked here. Fix tonic and strengthen this check. For now, just // the buffer length is checked. event.Signal(); }; ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), kSuccess); event.Wait(); } engine.reset(); // We cannot determine when the VM will GC objects that might have external // typed data finalizers. Since we need to ensure that we correctly wired up // finalizers from the embedders, we force the VM to collect all objects but // just shutting it down. buffer_released_latch.Wait(); } TEST_F(EmbedderTest, CompositorCanPostZeroLayersForPresentation) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(300, 200)); builder.SetCompositor(); builder.SetDartEntrypoint("empty_scene_posts_zero_layers_to_compositor"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::AutoResetWaitableEvent latch; context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 0u); latch.Signal(); }); auto engine = builder.LaunchEngine(); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 300; event.height = 200; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 0u); } TEST_F(EmbedderTest, CompositorCanPostOnlyPlatformViews) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(300, 200)); builder.SetCompositor(); builder.SetDartEntrypoint("compositor_can_post_only_platform_views"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::AutoResetWaitableEvent latch; context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer 0 { FlutterPlatformView platform_view = *layers[0]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(300.0, 200.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 24; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(300.0, 200.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[1], layer); } latch.Signal(); }); auto engine = builder.LaunchEngine(); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 300; event.height = 200; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 0u); } TEST_F(EmbedderTest, CompositorRenderTargetsAreRecycled) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(300, 200)); builder.SetCompositor(); builder.SetDartEntrypoint("render_targets_are_recycled"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(2); context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.CountDown(); })); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 20u); latch.CountDown(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 300; event.height = 200; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 10u); ASSERT_EQ(context.GetCompositor().GetBackingStoresCreatedCount(), 10u); ASSERT_EQ(context.GetCompositor().GetBackingStoresCollectedCount(), 0u); // Killing the engine should immediately collect all pending render targets. engine.reset(); ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 0u); ASSERT_EQ(context.GetCompositor().GetBackingStoresCreatedCount(), 10u); ASSERT_EQ(context.GetCompositor().GetBackingStoresCollectedCount(), 10u); } TEST_F(EmbedderTest, CompositorRenderTargetsAreInStableOrder) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(300, 200)); builder.SetCompositor(); builder.SetDartEntrypoint("render_targets_are_in_stable_order"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(2); context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.CountDown(); })); size_t frame_count = 0; std::vector<void*> first_frame_backing_store_user_data; context.GetCompositor().SetPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 20u); if (first_frame_backing_store_user_data.empty()) { for (size_t i = 0; i < layers_count; ++i) { if (layers[i]->type == kFlutterLayerContentTypeBackingStore) { first_frame_backing_store_user_data.push_back( layers[i]->backing_store->user_data); } } return; } ASSERT_EQ(first_frame_backing_store_user_data.size(), 10u); frame_count++; std::vector<void*> backing_store_user_data; for (size_t i = 0; i < layers_count; ++i) { if (layers[i]->type == kFlutterLayerContentTypeBackingStore) { backing_store_user_data.push_back( layers[i]->backing_store->user_data); } } ASSERT_EQ(backing_store_user_data.size(), 10u); ASSERT_EQ(first_frame_backing_store_user_data, backing_store_user_data); if (frame_count == 20) { latch.CountDown(); } }, false // one shot ); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 300; event.height = 200; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, FrameInfoContainsValidWidthAndHeight) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 1024)); builder.SetDartEntrypoint("push_frames_over_and_over"); const auto root_surface_transformation = SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. static FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1024; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); static fml::CountDownLatch frame_latch(10); context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { /* Nothing to do. */ })); static_cast<EmbedderTestContextGL&>(context).SetGLGetFBOCallback( [](FlutterFrameInfo frame_info) { // width and height are rotated by 90 deg ASSERT_EQ(frame_info.size.width, event.height); ASSERT_EQ(frame_info.size.height, event.width); frame_latch.CountDown(); }); frame_latch.Wait(); } TEST_F(EmbedderTest, MustNotRunWithBothFBOCallbacksSet) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 1024)); builder.SetOpenGLFBOCallBack(); auto engine = builder.LaunchEngine(); ASSERT_FALSE(engine.is_valid()); } TEST_F(EmbedderTest, MustNotRunWithBothPresentCallbacksSet) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 1024)); builder.SetOpenGLPresentCallBack(); auto engine = builder.LaunchEngine(); ASSERT_FALSE(engine.is_valid()); } TEST_F(EmbedderTest, MustStillRunWhenPopulateExistingDamageIsNotProvided) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(1, 1)); builder.GetRendererConfig().open_gl.populate_existing_damage = nullptr; auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, MustRunWhenPopulateExistingDamageIsProvided) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(1, 1)); builder.GetRendererConfig().open_gl.populate_existing_damage = [](void* context, const intptr_t id, FlutterDamage* existing_damage) -> void { return reinterpret_cast<EmbedderTestContextGL*>(context) ->GLPopulateExistingDamage(id, existing_damage); }; auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, MustRunWithPopulateExistingDamageAndFBOCallback) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(1, 1)); builder.GetRendererConfig().open_gl.fbo_callback = [](void* context) -> uint32_t { return 0; }; builder.GetRendererConfig().open_gl.fbo_with_frame_info_callback = nullptr; builder.GetRendererConfig().open_gl.populate_existing_damage = [](void* context, const intptr_t id, FlutterDamage* existing_damage) -> void { return reinterpret_cast<EmbedderTestContextGL*>(context) ->GLPopulateExistingDamage(id, existing_damage); }; auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, MustNotRunWhenPopulateExistingDamageButNoOtherFBOCallback) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(1, 1)); builder.GetRendererConfig().open_gl.fbo_callback = nullptr; builder.GetRendererConfig().open_gl.fbo_with_frame_info_callback = nullptr; builder.GetRendererConfig().open_gl.populate_existing_damage = [](void* context, const intptr_t id, FlutterDamage* existing_damage) -> void { return reinterpret_cast<EmbedderTestContextGL*>(context) ->GLPopulateExistingDamage(id, existing_damage); }; auto engine = builder.LaunchEngine(); ASSERT_FALSE(engine.is_valid()); } TEST_F(EmbedderTest, PresentInfoContainsValidFBOId) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 1024)); builder.SetDartEntrypoint("push_frames_over_and_over"); const auto root_surface_transformation = SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1024; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); static fml::CountDownLatch frame_latch(10); context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { /* Nothing to do. */ })); const uint32_t window_fbo_id = static_cast<EmbedderTestContextGL&>(context).GetWindowFBOId(); static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [window_fbo_id = window_fbo_id](FlutterPresentInfo present_info) { ASSERT_EQ(present_info.fbo_id, window_fbo_id); frame_latch.CountDown(); }); frame_latch.Wait(); } TEST_F(EmbedderTest, PresentInfoReceivesFullDamageWhenExistingDamageIsWholeScreen) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetDartEntrypoint("render_gradient_retained"); builder.GetRendererConfig().open_gl.populate_existing_damage = [](void* context, const intptr_t id, FlutterDamage* existing_damage) -> void { return reinterpret_cast<EmbedderTestContextGL*>(context) ->GLPopulateExistingDamage(id, existing_damage); }; // Return existing damage as the entire screen on purpose. static_cast<EmbedderTestContextGL&>(context) .SetGLPopulateExistingDamageCallback( [](const intptr_t id, FlutterDamage* existing_damage_ptr) { const size_t num_rects = 1; // The array must be valid after the callback returns. static FlutterRect existing_damage_rects[num_rects] = { FlutterRect{0, 0, 800, 600}}; existing_damage_ptr->num_rects = num_rects; existing_damage_ptr->damage = existing_damage_rects; }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); fml::AutoResetWaitableEvent latch; // First frame should be entirely rerendered. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 800); ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 0); ASSERT_EQ(present_info.buffer_damage.damage->top, 0); ASSERT_EQ(present_info.buffer_damage.damage->right, 800); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); latch.Signal(); }); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); // Because it's the same as the first frame, the second frame damage should // be empty but, because there was a full existing buffer damage, the buffer // damage should be the entire screen. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 0); ASSERT_EQ(present_info.frame_damage.damage->bottom, 0); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 0); ASSERT_EQ(present_info.buffer_damage.damage->top, 0); ASSERT_EQ(present_info.buffer_damage.damage->right, 800); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); latch.Signal(); }); ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, PresentInfoReceivesEmptyDamage) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetDartEntrypoint("render_gradient_retained"); builder.GetRendererConfig().open_gl.populate_existing_damage = [](void* context, const intptr_t id, FlutterDamage* existing_damage) -> void { return reinterpret_cast<EmbedderTestContextGL*>(context) ->GLPopulateExistingDamage(id, existing_damage); }; // Return no existing damage on purpose. static_cast<EmbedderTestContextGL&>(context) .SetGLPopulateExistingDamageCallback( [](const intptr_t id, FlutterDamage* existing_damage_ptr) { const size_t num_rects = 1; // The array must be valid after the callback returns. static FlutterRect existing_damage_rects[num_rects] = { FlutterRect{0, 0, 0, 0}}; existing_damage_ptr->num_rects = num_rects; existing_damage_ptr->damage = existing_damage_rects; }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); fml::AutoResetWaitableEvent latch; // First frame should be entirely rerendered. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 800); ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 0); ASSERT_EQ(present_info.buffer_damage.damage->top, 0); ASSERT_EQ(present_info.buffer_damage.damage->right, 800); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); latch.Signal(); }); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); // Because it's the same as the first frame, the second frame should not be // rerendered assuming there is no existing damage. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 0); ASSERT_EQ(present_info.frame_damage.damage->bottom, 0); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 0); ASSERT_EQ(present_info.buffer_damage.damage->top, 0); ASSERT_EQ(present_info.buffer_damage.damage->right, 0); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 0); latch.Signal(); }); ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, PresentInfoReceivesPartialDamage) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetDartEntrypoint("render_gradient_retained"); builder.GetRendererConfig().open_gl.populate_existing_damage = [](void* context, const intptr_t id, FlutterDamage* existing_damage) -> void { return reinterpret_cast<EmbedderTestContextGL*>(context) ->GLPopulateExistingDamage(id, existing_damage); }; // Return existing damage as only part of the screen on purpose. static_cast<EmbedderTestContextGL&>(context) .SetGLPopulateExistingDamageCallback( [&](const intptr_t id, FlutterDamage* existing_damage_ptr) { const size_t num_rects = 1; // The array must be valid after the callback returns. static FlutterRect existing_damage_rects[num_rects] = { FlutterRect{200, 150, 400, 300}}; existing_damage_ptr->num_rects = num_rects; existing_damage_ptr->damage = existing_damage_rects; }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); fml::AutoResetWaitableEvent latch; // First frame should be entirely rerendered. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 800); ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 0); ASSERT_EQ(present_info.buffer_damage.damage->top, 0); ASSERT_EQ(present_info.buffer_damage.damage->right, 800); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); latch.Signal(); }); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); // Because it's the same as the first frame, the second frame damage should be // empty but, because there was a partial existing damage, the buffer damage // should represent that partial damage area. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 0); ASSERT_EQ(present_info.frame_damage.damage->bottom, 0); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 200); ASSERT_EQ(present_info.buffer_damage.damage->top, 150); ASSERT_EQ(present_info.buffer_damage.damage->right, 400); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 300); latch.Signal(); }); ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, PopulateExistingDamageReceivesValidID) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetDartEntrypoint("render_gradient_retained"); builder.GetRendererConfig().open_gl.populate_existing_damage = [](void* context, const intptr_t id, FlutterDamage* existing_damage) -> void { return reinterpret_cast<EmbedderTestContextGL*>(context) ->GLPopulateExistingDamage(id, existing_damage); }; auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); const uint32_t window_fbo_id = static_cast<EmbedderTestContextGL&>(context).GetWindowFBOId(); static_cast<EmbedderTestContextGL&>(context) .SetGLPopulateExistingDamageCallback( [window_fbo_id = window_fbo_id](intptr_t id, FlutterDamage* existing_damage) { ASSERT_EQ(id, window_fbo_id); existing_damage->num_rects = 0; existing_damage->damage = nullptr; }); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); } TEST_F(EmbedderTest, PopulateExistingDamageReceivesInvalidID) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetDartEntrypoint("render_gradient_retained"); builder.GetRendererConfig().open_gl.populate_existing_damage = [](void* context, const intptr_t id, FlutterDamage* existing_damage) -> void { return reinterpret_cast<EmbedderTestContextGL*>(context) ->GLPopulateExistingDamage(id, existing_damage); }; // Return a bad FBO ID on purpose. builder.GetRendererConfig().open_gl.fbo_with_frame_info_callback = [](void* context, const FlutterFrameInfo* frame_info) -> uint32_t { return 123; }; auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { /* Nothing to do. */ })); const uint32_t window_fbo_id = static_cast<EmbedderTestContextGL&>(context).GetWindowFBOId(); static_cast<EmbedderTestContextGL&>(context) .SetGLPopulateExistingDamageCallback( [window_fbo_id = window_fbo_id](intptr_t id, FlutterDamage* existing_damage) { ASSERT_NE(id, window_fbo_id); existing_damage->num_rects = 0; existing_damage->damage = nullptr; }); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); } TEST_F(EmbedderTest, SetSingleDisplayConfigurationWithDisplayId) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("empty_scene"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterEngineDisplay display; display.struct_size = sizeof(FlutterEngineDisplay); display.display_id = 1; display.refresh_rate = 20; std::vector<FlutterEngineDisplay> displays = {display}; const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), displays.size()); ASSERT_EQ(result, kSuccess); flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); ASSERT_EQ(shell.GetMainDisplayRefreshRate(), display.refresh_rate); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, SetSingleDisplayConfigurationWithoutDisplayId) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("empty_scene"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterEngineDisplay display; display.struct_size = sizeof(FlutterEngineDisplay); display.single_display = true; display.refresh_rate = 20; std::vector<FlutterEngineDisplay> displays = {display}; const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), displays.size()); ASSERT_EQ(result, kSuccess); flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); ASSERT_EQ(shell.GetMainDisplayRefreshRate(), display.refresh_rate); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, SetValidMultiDisplayConfiguration) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("empty_scene"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterEngineDisplay display_1; display_1.struct_size = sizeof(FlutterEngineDisplay); display_1.display_id = 1; display_1.single_display = false; display_1.refresh_rate = 20; FlutterEngineDisplay display_2; display_2.struct_size = sizeof(FlutterEngineDisplay); display_2.display_id = 2; display_2.single_display = false; display_2.refresh_rate = 60; std::vector<FlutterEngineDisplay> displays = {display_1, display_2}; const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), displays.size()); ASSERT_EQ(result, kSuccess); flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); ASSERT_EQ(shell.GetMainDisplayRefreshRate(), display_1.refresh_rate); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, MultipleDisplaysWithSingleDisplayTrueIsInvalid) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("empty_scene"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterEngineDisplay display_1; display_1.struct_size = sizeof(FlutterEngineDisplay); display_1.display_id = 1; display_1.single_display = true; display_1.refresh_rate = 20; FlutterEngineDisplay display_2; display_2.struct_size = sizeof(FlutterEngineDisplay); display_2.display_id = 2; display_2.single_display = true; display_2.refresh_rate = 60; std::vector<FlutterEngineDisplay> displays = {display_1, display_2}; const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), displays.size()); ASSERT_NE(result, kSuccess); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, MultipleDisplaysWithSameDisplayIdIsInvalid) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("empty_scene"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterEngineDisplay display_1; display_1.struct_size = sizeof(FlutterEngineDisplay); display_1.display_id = 1; display_1.single_display = false; display_1.refresh_rate = 20; FlutterEngineDisplay display_2; display_2.struct_size = sizeof(FlutterEngineDisplay); display_2.display_id = 1; display_2.single_display = false; display_2.refresh_rate = 60; std::vector<FlutterEngineDisplay> displays = {display_1, display_2}; const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), displays.size()); ASSERT_NE(result, kSuccess); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, CompositorRenderTargetsNotRecycledWhenAvoidsCacheSet) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(300, 200)); builder.SetCompositor(/*avoid_backing_store_cache=*/true); builder.SetDartEntrypoint("render_targets_are_recycled"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); const unsigned num_frames = 8; const unsigned num_engine_layers = 10; const unsigned num_backing_stores = num_frames * num_engine_layers; fml::CountDownLatch latch(1 + num_frames); // 1 for native test signal. context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.CountDown(); })); context.GetCompositor().SetPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 20u); latch.CountDown(); }, /*one_shot=*/false); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 300; event.height = 200; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_EQ(context.GetCompositor().GetBackingStoresCreatedCount(), num_backing_stores); // Killing the engine should collect all the frames. engine.reset(); ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 0u); } TEST_F(EmbedderTest, SnapshotRenderTargetScalesDownToDriverMax) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); auto max_size = context.GetCompositor().GetGrContext()->maxRenderTargetSize(); context.AddIsolateCreateCallback([&]() { Dart_Handle snapshot_large_scene = Dart_GetField( Dart_RootLibrary(), tonic::ToDart("snapshot_large_scene")); tonic::DartInvoke(snapshot_large_scene, {tonic::ToDart<int64_t>(max_size)}); }); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SnapshotsCallback", CREATE_NATIVE_ENTRY(([&](Dart_NativeArguments args) { auto get_arg = [&args](int index) { Dart_Handle dart_image = Dart_GetNativeArgument(args, index); Dart_Handle internal_image = Dart_GetField(dart_image, tonic::ToDart("_image")); return tonic::DartConverter<flutter::CanvasImage*>::FromDart( internal_image); }; CanvasImage* big_image = get_arg(0); ASSERT_EQ(big_image->width(), max_size); ASSERT_EQ(big_image->height(), max_size / 2); CanvasImage* small_image = get_arg(1); ASSERT_TRUE(ImageMatchesFixture("snapshot_large_scene.png", small_image->image()->skia_image())); latch.Signal(); }))); UniqueEngine engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } TEST_F(EmbedderTest, ObjectsPostedViaPortsServicedOnSecondaryTaskHeap) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 1024)); builder.SetDartEntrypoint("objects_can_be_posted"); // Synchronously acquire the send port from the Dart end. We will be using // this to send message. The Dart end will just echo those messages back to us // for inspection. FlutterEngineDartPort port = 0; fml::AutoResetWaitableEvent event; context.AddNativeCallback("SignalNativeCount", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { port = tonic::DartConverter<int64_t>::FromDart( Dart_GetNativeArgument(args, 0)); event.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); event.Wait(); ASSERT_NE(port, 0); using Trampoline = std::function<void(Dart_Handle message)>; Trampoline trampoline; context.AddNativeCallback("SendObjectToNativeCode", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { FML_CHECK(trampoline); auto trampoline_copy = trampoline; trampoline = nullptr; trampoline_copy(Dart_GetNativeArgument(args, 0)); })); // Send a boolean value and assert that it's received by the right heap. { FlutterEngineDartObject object = {}; object.type = kFlutterEngineDartObjectTypeBool; object.bool_value = true; trampoline = [&](Dart_Handle handle) { ASSERT_TRUE(tonic::DartConverter<bool>::FromDart(handle)); auto task_grade = fml::MessageLoopTaskQueues::GetCurrentTaskSourceGrade(); EXPECT_EQ(task_grade, fml::TaskSourceGrade::kDartEventLoop); event.Signal(); }; ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), kSuccess); event.Wait(); } } TEST_F(EmbedderTest, CreateInvalidBackingstoreOpenGLTexture) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); builder.SetDartEntrypoint("invalid_backingstore"); class TestCollectOnce { public: // Collect() should only be called once void Collect() { ASSERT_FALSE(collected_); collected_ = true; } private: bool collected_ = false; }; fml::AutoResetWaitableEvent latch; builder.GetCompositor().create_backing_store_callback = [](const FlutterBackingStoreConfig* config, // FlutterBackingStore* backing_store_out, // void* user_data // ) { backing_store_out->type = kFlutterBackingStoreTypeOpenGL; // Deliberately set this to be invalid backing_store_out->user_data = nullptr; backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeTexture; backing_store_out->open_gl.texture.target = 0; backing_store_out->open_gl.texture.name = 0; backing_store_out->open_gl.texture.format = 0; static TestCollectOnce collect_once_user_data; collect_once_user_data = {}; backing_store_out->open_gl.texture.user_data = &collect_once_user_data; backing_store_out->open_gl.texture.destruction_callback = [](void* user_data) { reinterpret_cast<TestCollectOnce*>(user_data)->Collect(); }; return true; }; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } TEST_F(EmbedderTest, CreateInvalidBackingstoreOpenGLFramebuffer) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); builder.SetDartEntrypoint("invalid_backingstore"); class TestCollectOnce { public: // Collect() should only be called once void Collect() { ASSERT_FALSE(collected_); collected_ = true; } private: bool collected_ = false; }; fml::AutoResetWaitableEvent latch; builder.GetCompositor().create_backing_store_callback = [](const FlutterBackingStoreConfig* config, // FlutterBackingStore* backing_store_out, // void* user_data // ) { backing_store_out->type = kFlutterBackingStoreTypeOpenGL; // Deliberately set this to be invalid backing_store_out->user_data = nullptr; backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; backing_store_out->open_gl.framebuffer.target = 0; backing_store_out->open_gl.framebuffer.name = 0; static TestCollectOnce collect_once_user_data; collect_once_user_data = {}; backing_store_out->open_gl.framebuffer.user_data = &collect_once_user_data; backing_store_out->open_gl.framebuffer.destruction_callback = [](void* user_data) { reinterpret_cast<TestCollectOnce*>(user_data)->Collect(); }; return true; }; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } TEST_F(EmbedderTest, ExternalTextureGLRefreshedTooOften) { TestGLSurface surface(SkISize::Make(100, 100)); auto context = surface.GetGrContext(); typedef void (*glGenTexturesProc)(uint32_t n, uint32_t* textures); typedef void (*glFinishProc)(); glGenTexturesProc glGenTextures; glFinishProc glFinish; glGenTextures = reinterpret_cast<glGenTexturesProc>( surface.GetProcAddress("glGenTextures")); glFinish = reinterpret_cast<glFinishProc>(surface.GetProcAddress("glFinish")); uint32_t name; glGenTextures(1, &name); bool resolve_called = false; EmbedderExternalTextureGL::ExternalTextureCallback callback( [&](int64_t, size_t, size_t) { resolve_called = true; auto res = std::make_unique<FlutterOpenGLTexture>(); res->target = GL_TEXTURE_2D; res->name = name; res->format = GL_RGBA8; res->user_data = nullptr; res->destruction_callback = [](void*) {}; res->width = res->height = 100; return res; }); EmbedderExternalTextureGL texture(1, callback); auto skia_surface = surface.GetOnscreenSurface(); DlSkCanvasAdapter canvas(skia_surface->getCanvas()); Texture* texture_ = &texture; Texture::PaintContext ctx{ .canvas = &canvas, .gr_context = context.get(), }; texture_->Paint(ctx, SkRect::MakeXYWH(0, 0, 100, 100), false, DlImageSampling::kLinear); EXPECT_TRUE(resolve_called); resolve_called = false; texture_->Paint(ctx, SkRect::MakeXYWH(0, 0, 100, 100), false, DlImageSampling::kLinear); EXPECT_FALSE(resolve_called); texture_->MarkNewFrameAvailable(); texture_->Paint(ctx, SkRect::MakeXYWH(0, 0, 100, 100), false, DlImageSampling::kLinear); EXPECT_TRUE(resolve_called); glFinish(); } TEST_F( EmbedderTest, PresentInfoReceivesFullScreenDamageWhenPopulateExistingDamageIsNotProvided) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetDartEntrypoint("render_gradient_retained"); builder.GetRendererConfig().open_gl.populate_existing_damage = nullptr; auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); fml::AutoResetWaitableEvent latch; // First frame should be entirely rerendered. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 800); ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 0); ASSERT_EQ(present_info.buffer_damage.damage->top, 0); ASSERT_EQ(present_info.buffer_damage.damage->right, 800); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); latch.Signal(); }); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); // Since populate_existing_damage is not provided, the partial repaint // functionality is actually disabled. So, the next frame should be entirely // new frame. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 800); ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 0); ASSERT_EQ(present_info.buffer_damage.damage->top, 0); ASSERT_EQ(present_info.buffer_damage.damage->right, 800); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); latch.Signal(); }); ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, PresentInfoReceivesJoinedDamageWhenExistingDamageContainsMultipleRects) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetDartEntrypoint("render_gradient_retained"); builder.GetRendererConfig().open_gl.populate_existing_damage = [](void* context, const intptr_t id, FlutterDamage* existing_damage) -> void { return reinterpret_cast<EmbedderTestContextGL*>(context) ->GLPopulateExistingDamage(id, existing_damage); }; // Return existing damage as the entire screen on purpose. static_cast<EmbedderTestContextGL&>(context) .SetGLPopulateExistingDamageCallback( [](const intptr_t id, FlutterDamage* existing_damage_ptr) { const size_t num_rects = 2; // The array must be valid after the callback returns. static FlutterRect existing_damage_rects[num_rects] = { FlutterRect{100, 150, 200, 250}, FlutterRect{200, 250, 300, 350}, }; existing_damage_ptr->num_rects = num_rects; existing_damage_ptr->damage = existing_damage_rects; }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); fml::AutoResetWaitableEvent latch; // First frame should be entirely rerendered. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 800); ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 0); ASSERT_EQ(present_info.buffer_damage.damage->top, 0); ASSERT_EQ(present_info.buffer_damage.damage->right, 800); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); latch.Signal(); }); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); // Because it's the same as the first frame, the second frame damage should // be empty but, because there was a full existing buffer damage, the buffer // damage should be the entire screen. static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&](FlutterPresentInfo present_info) { const size_t num_rects = 1; ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); ASSERT_EQ(present_info.frame_damage.damage->left, 0); ASSERT_EQ(present_info.frame_damage.damage->top, 0); ASSERT_EQ(present_info.frame_damage.damage->right, 0); ASSERT_EQ(present_info.frame_damage.damage->bottom, 0); ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); ASSERT_EQ(present_info.buffer_damage.damage->left, 100); ASSERT_EQ(present_info.buffer_damage.damage->top, 150); ASSERT_EQ(present_info.buffer_damage.damage->right, 300); ASSERT_EQ(present_info.buffer_damage.damage->bottom, 350); latch.Signal(); }); ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, CanRenderWithImpellerOpenGL) { auto& context = GetEmbedderContext(EmbedderTestContextType::kOpenGLContext); EmbedderConfigBuilder builder(context); bool present_called = false; static_cast<EmbedderTestContextGL&>(context).SetGLPresentCallback( [&present_called](FlutterPresentInfo present_info) { present_called = true; }); builder.AddCommandLineArgument("--enable-impeller"); builder.SetDartEntrypoint("render_impeller_gl_test"); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture( FixtureNameForBackend(EmbedderTestContextType::kOpenGLContext, "impeller_gl_test.png"), rendered_scene)); // The scene will be rendered by the compositor, and the surface present // callback should not be invoked. ASSERT_FALSE(present_called); } INSTANTIATE_TEST_SUITE_P( EmbedderTestGlVk, EmbedderTestMultiBackend, ::testing::Values(EmbedderTestContextType::kOpenGLContext, EmbedderTestContextType::kVulkanContext)); } // namespace testing } // namespace flutter // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/shell/platform/embedder/tests/embedder_gl_unittests.cc/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_gl_unittests.cc", "repo_id": "engine", "token_count": 71698 }
335
// 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. #include "flutter/shell/platform/embedder/tests/embedder_test_context.h" #include <utility> #include "flutter/fml/make_copyable.h" #include "flutter/fml/paths.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/platform/embedder/tests/embedder_assertions.h" #include "flutter/testing/testing.h" #include "third_party/dart/runtime/bin/elf_loader.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { namespace testing { EmbedderTestContext::EmbedderTestContext(std::string assets_path) : assets_path_(std::move(assets_path)), aot_symbols_( LoadELFSymbolFromFixturesIfNeccessary(kDefaultAOTAppELFFileName)), native_resolver_(std::make_shared<TestDartNativeResolver>()) { SetupAOTMappingsIfNecessary(); SetupAOTDataIfNecessary(); isolate_create_callbacks_.push_back( [weak_resolver = std::weak_ptr<TestDartNativeResolver>{native_resolver_}]() { if (auto resolver = weak_resolver.lock()) { resolver->SetNativeResolverForIsolate(); } }); } EmbedderTestContext::~EmbedderTestContext() = default; void EmbedderTestContext::SetupAOTMappingsIfNecessary() { if (!DartVM::IsRunningPrecompiledCode()) { return; } vm_snapshot_data_ = std::make_unique<fml::NonOwnedMapping>(aot_symbols_.vm_snapshot_data, 0u); vm_snapshot_instructions_ = std::make_unique<fml::NonOwnedMapping>( aot_symbols_.vm_snapshot_instrs, 0u); isolate_snapshot_data_ = std::make_unique<fml::NonOwnedMapping>(aot_symbols_.vm_isolate_data, 0u); isolate_snapshot_instructions_ = std::make_unique<fml::NonOwnedMapping>( aot_symbols_.vm_isolate_instrs, 0u); } void EmbedderTestContext::SetupAOTDataIfNecessary() { if (!DartVM::IsRunningPrecompiledCode()) { return; } FlutterEngineAOTDataSource data_in = {}; FlutterEngineAOTData data_out = nullptr; const auto elf_path = fml::paths::JoinPaths( {GetFixturesPath(), testing::kDefaultAOTAppELFFileName}); data_in.type = kFlutterEngineAOTDataSourceTypeElfPath; data_in.elf_path = elf_path.c_str(); ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kSuccess); aot_data_.reset(data_out); } const std::string& EmbedderTestContext::GetAssetsPath() const { return assets_path_; } const fml::Mapping* EmbedderTestContext::GetVMSnapshotData() const { return vm_snapshot_data_.get(); } const fml::Mapping* EmbedderTestContext::GetVMSnapshotInstructions() const { return vm_snapshot_instructions_.get(); } const fml::Mapping* EmbedderTestContext::GetIsolateSnapshotData() const { return isolate_snapshot_data_.get(); } const fml::Mapping* EmbedderTestContext::GetIsolateSnapshotInstructions() const { return isolate_snapshot_instructions_.get(); } FlutterEngineAOTData EmbedderTestContext::GetAOTData() const { return aot_data_.get(); } void EmbedderTestContext::SetRootSurfaceTransformation(SkMatrix matrix) { root_surface_transformation_ = matrix; } void EmbedderTestContext::AddIsolateCreateCallback( const fml::closure& closure) { if (closure) { isolate_create_callbacks_.push_back(closure); } } VoidCallback EmbedderTestContext::GetIsolateCreateCallbackHook() { return [](void* user_data) { reinterpret_cast<EmbedderTestContext*>(user_data) ->FireIsolateCreateCallbacks(); }; } void EmbedderTestContext::FireIsolateCreateCallbacks() { for (const auto& closure : isolate_create_callbacks_) { closure(); } } void EmbedderTestContext::AddNativeCallback(const char* name, Dart_NativeFunction function) { native_resolver_->AddNativeCallback({name}, function); } void EmbedderTestContext::SetSemanticsUpdateCallback2( SemanticsUpdateCallback2 update_semantics_callback) { update_semantics_callback2_ = std::move(update_semantics_callback); } void EmbedderTestContext::SetSemanticsUpdateCallback( SemanticsUpdateCallback update_semantics_callback) { update_semantics_callback_ = std::move(update_semantics_callback); } void EmbedderTestContext::SetSemanticsNodeCallback( SemanticsNodeCallback update_semantics_node_callback) { update_semantics_node_callback_ = std::move(update_semantics_node_callback); } void EmbedderTestContext::SetSemanticsCustomActionCallback( SemanticsActionCallback update_semantics_custom_action_callback) { update_semantics_custom_action_callback_ = std::move(update_semantics_custom_action_callback); } void EmbedderTestContext::SetPlatformMessageCallback( const std::function<void(const FlutterPlatformMessage*)>& callback) { platform_message_callback_ = callback; } void EmbedderTestContext::SetChannelUpdateCallback( const ChannelUpdateCallback& callback) { channel_update_callback_ = callback; } void EmbedderTestContext::PlatformMessageCallback( const FlutterPlatformMessage* message) { if (platform_message_callback_) { platform_message_callback_(message); } } void EmbedderTestContext::SetLogMessageCallback( const LogMessageCallback& callback) { log_message_callback_ = callback; } FlutterUpdateSemanticsCallback2 EmbedderTestContext::GetUpdateSemanticsCallback2Hook() { if (update_semantics_callback2_ == nullptr) { return nullptr; } return [](const FlutterSemanticsUpdate2* update, void* user_data) { auto context = reinterpret_cast<EmbedderTestContext*>(user_data); if (context->update_semantics_callback2_) { context->update_semantics_callback2_(update); } }; } FlutterUpdateSemanticsCallback EmbedderTestContext::GetUpdateSemanticsCallbackHook() { if (update_semantics_callback_ == nullptr) { return nullptr; } return [](const FlutterSemanticsUpdate* update, void* user_data) { auto context = reinterpret_cast<EmbedderTestContext*>(user_data); if (context->update_semantics_callback_) { context->update_semantics_callback_(update); } }; } FlutterUpdateSemanticsNodeCallback EmbedderTestContext::GetUpdateSemanticsNodeCallbackHook() { if (update_semantics_node_callback_ == nullptr) { return nullptr; } return [](const FlutterSemanticsNode* semantics_node, void* user_data) { auto context = reinterpret_cast<EmbedderTestContext*>(user_data); if (context->update_semantics_node_callback_) { context->update_semantics_node_callback_(semantics_node); } }; } FlutterUpdateSemanticsCustomActionCallback EmbedderTestContext::GetUpdateSemanticsCustomActionCallbackHook() { if (update_semantics_custom_action_callback_ == nullptr) { return nullptr; } return [](const FlutterSemanticsCustomAction* action, void* user_data) { auto context = reinterpret_cast<EmbedderTestContext*>(user_data); if (context->update_semantics_custom_action_callback_) { context->update_semantics_custom_action_callback_(action); } }; } FlutterLogMessageCallback EmbedderTestContext::GetLogMessageCallbackHook() { return [](const char* tag, const char* message, void* user_data) { auto context = reinterpret_cast<EmbedderTestContext*>(user_data); if (context->log_message_callback_) { context->log_message_callback_(tag, message); } }; } FlutterComputePlatformResolvedLocaleCallback EmbedderTestContext::GetComputePlatformResolvedLocaleCallbackHook() { return [](const FlutterLocale** supported_locales, size_t length) -> const FlutterLocale* { return supported_locales[0]; }; } FlutterChannelUpdateCallback EmbedderTestContext::GetChannelUpdateCallbackHook() { if (channel_update_callback_ == nullptr) { return nullptr; } return [](const FlutterChannelUpdate* update, void* user_data) { auto context = reinterpret_cast<EmbedderTestContext*>(user_data); if (context->channel_update_callback_) { context->channel_update_callback_(update); } }; } FlutterTransformation EmbedderTestContext::GetRootSurfaceTransformation() { return FlutterTransformationMake(root_surface_transformation_); } EmbedderTestCompositor& EmbedderTestContext::GetCompositor() { FML_CHECK(compositor_) << "Accessed the compositor on a context where one was not set up. Use " "the config builder to set up a context with a custom compositor."; return *compositor_; } void EmbedderTestContext::SetNextSceneCallback( const NextSceneCallback& next_scene_callback) { if (compositor_) { compositor_->SetNextSceneCallback(next_scene_callback); return; } next_scene_callback_ = next_scene_callback; } std::future<sk_sp<SkImage>> EmbedderTestContext::GetNextSceneImage() { std::promise<sk_sp<SkImage>> promise; auto future = promise.get_future(); SetNextSceneCallback( fml::MakeCopyable([promise = std::move(promise)](auto image) mutable { promise.set_value(image); })); return future; } /// @note Procedure doesn't copy all closures. void EmbedderTestContext::FireRootSurfacePresentCallbackIfPresent( const std::function<sk_sp<SkImage>(void)>& image_callback) { if (!next_scene_callback_) { return; } auto callback = next_scene_callback_; next_scene_callback_ = nullptr; callback(image_callback()); } void EmbedderTestContext::SetVsyncCallback( std::function<void(intptr_t)> callback) { vsync_callback_ = std::move(callback); } void EmbedderTestContext::RunVsyncCallback(intptr_t baton) { vsync_callback_(baton); } } // namespace testing } // namespace flutter
engine/shell/platform/embedder/tests/embedder_test_context.cc/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_context.cc", "repo_id": "engine", "token_count": 3348 }
336
// 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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_VSYNC_WAITER_EMBEDDER_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_VSYNC_WAITER_EMBEDDER_H_ #include "flutter/fml/macros.h" #include "flutter/shell/common/vsync_waiter.h" namespace flutter { class VsyncWaiterEmbedder final : public VsyncWaiter { public: using VsyncCallback = std::function<void(intptr_t)>; VsyncWaiterEmbedder(const VsyncCallback& callback, const flutter::TaskRunners& task_runners); ~VsyncWaiterEmbedder() override; static bool OnEmbedderVsync(const flutter::TaskRunners& task_runners, intptr_t baton, fml::TimePoint frame_start_time, fml::TimePoint frame_target_time); private: const VsyncCallback vsync_callback_; // |VsyncWaiter| void AwaitVSync() override; FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiterEmbedder); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_VSYNC_WAITER_EMBEDDER_H_
engine/shell/platform/embedder/vsync_waiter_embedder.h/0
{ "file_path": "engine/shell/platform/embedder/vsync_waiter_embedder.h", "repo_id": "engine", "token_count": 506 }
337
// 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. part of zircon; // ignore_for_file: native_function_body_in_non_sdk_code // ignore_for_file: public_member_api_docs @pragma('vm:entry-point') class _Namespace { // No public constructor - this only has static methods. _Namespace._(); // Library private variable set by the embedder used to cache the // namespace (as an fdio_ns_t*). @pragma('vm:entry-point') static int? _namespace; } /// An exception representing an error returned as an zx_status_t. class ZxStatusException implements Exception { final String? message; final int status; ZxStatusException(this.status, [this.message]); @override String toString() { if (message == null) return 'ZxStatusException: status = $status'; else return 'ZxStatusException: status = $status, "$message"'; } } /// Users of the [_Result] subclasses should check the status before /// trying to read any data. Attempting to use a value stored in a result /// when the status in not OK will result in an exception. class _Result { final int status; const _Result(this.status); } @pragma('vm:entry-point') class HandleResult extends _Result { final Handle? _handle; Handle get handle => _handle!; @pragma('vm:entry-point') const HandleResult(final int status, [this._handle]) : super(status); @override String toString() => 'HandleResult(status=$status, handle=$_handle)'; } @pragma('vm:entry-point') class HandlePairResult extends _Result { final Handle? _first; final Handle? _second; Handle get first => _first!; Handle get second => _second!; @pragma('vm:entry-point') const HandlePairResult(final int status, [this._first, this._second]) : super(status); @override String toString() => 'HandlePairResult(status=$status, first=$_first, second=$_second)'; } @pragma('vm:entry-point') class ReadResult extends _Result { final ByteData? _bytes; final int? _numBytes; final List<Handle>? _handles; ByteData get bytes => _bytes!; int get numBytes => _numBytes!; List<Handle> get handles => _handles!; @pragma('vm:entry-point') const ReadResult(final int status, [this._bytes, this._numBytes, this._handles]) : super(status); /// Returns the bytes as a Uint8List. If status != OK this will throw /// an exception. Uint8List bytesAsUint8List() { final lbytes = bytes; return lbytes.buffer.asUint8List(lbytes.offsetInBytes, _numBytes!); } /// Returns the bytes as a String. If status != OK this will throw /// an exception. String bytesAsUTF8String() => utf8.decode(bytesAsUint8List()); @override String toString() => 'ReadResult(status=$status, bytes=$_bytes, numBytes=$_numBytes, handles=$_handles)'; } @pragma('vm:entry-point') class HandleInfo { final Handle handle; final int type; final int rights; @pragma('vm:entry-point') const HandleInfo(this.handle, this.type, this.rights); @override String toString() => 'HandleInfo(handle=$handle, type=$type, rights=$rights)'; } @pragma('vm:entry-point') class ReadEtcResult extends _Result { final ByteData? _bytes; final int? _numBytes; final List<HandleInfo>? _handleInfos; ByteData get bytes => _bytes!; int get numBytes => _numBytes!; List<HandleInfo> get handleInfos => _handleInfos!; @pragma('vm:entry-point') const ReadEtcResult(final int status, [this._bytes, this._numBytes, this._handleInfos]) : super(status); /// Returns the bytes as a Uint8List. If status != OK this will throw /// an exception. Uint8List bytesAsUint8List() { final lbytes = bytes; return lbytes.buffer.asUint8List(lbytes.offsetInBytes, _numBytes!); } /// Returns the bytes as a String. If status != OK this will throw /// an exception. String bytesAsUTF8String() => utf8.decode(bytesAsUint8List()); @override String toString() => 'ReadEtcResult(status=$status, bytes=$_bytes, numBytes=$_numBytes, handleInfos=$_handleInfos)'; } @pragma('vm:entry-point') class WriteResult extends _Result { final int? _numBytes; int get numBytes => _numBytes!; @pragma('vm:entry-point') const WriteResult(final int status, [this._numBytes]) : super(status); @override String toString() => 'WriteResult(status=$status, numBytes=$_numBytes)'; } @pragma('vm:entry-point') class GetSizeResult extends _Result { final int? _size; int get size => _size!; @pragma('vm:entry-point') const GetSizeResult(final int status, [this._size]) : super(status); @override String toString() => 'GetSizeResult(status=$status, size=$_size)'; } @pragma('vm:entry-point') class FromFileResult extends _Result { final Handle? _handle; final int? _numBytes; Handle get handle => _handle!; int get numBytes => _numBytes!; @pragma('vm:entry-point') const FromFileResult(final int status, [this._handle, this._numBytes]) : super(status); @override String toString() => 'FromFileResult(status=$status, handle=$_handle, numBytes=$_numBytes)'; } @pragma('vm:entry-point') class MapResult extends _Result { final Uint8List? _data; Uint8List get data => _data!; @pragma('vm:entry-point') const MapResult(final int status, [this._data]) : super(status); @override String toString() => 'MapResult(status=$status, data=$_data)'; } @pragma('vm:entry-point') base class System extends NativeFieldWrapperClass1 { // No public constructor - this only has static methods. System._(); // Channel operations. @pragma('vm:external-name', 'System_ChannelCreate') external static HandlePairResult channelCreate([int options = 0]); @pragma('vm:external-name', 'System_ChannelFromFile') external static HandleResult channelFromFile(String path); @pragma('vm:external-name', 'System_ConnectToService') external static int connectToService(String path, Handle channel); @pragma('vm:external-name', 'System_ChannelWrite') external static int channelWrite(Handle channel, ByteData data, List<Handle> handles); @pragma('vm:external-name', 'System_ChannelWriteEtc') external static int channelWriteEtc(Handle channel, ByteData data, List<HandleDisposition> handleDispositions); @pragma('vm:external-name', 'System_ChannelQueryAndRead') external static ReadResult channelQueryAndRead(Handle channel); @pragma('vm:external-name', 'System_ChannelQueryAndReadEtc') external static ReadEtcResult channelQueryAndReadEtc(Handle channel); // Eventpair operations. @pragma('vm:external-name', 'System_EventpairCreate') external static HandlePairResult eventpairCreate([int options = 0]); // Socket operations. @pragma('vm:external-name', 'System_SocketCreate') external static HandlePairResult socketCreate([int options = 0]); @pragma('vm:external-name', 'System_SocketWrite') external static WriteResult socketWrite(Handle socket, ByteData data, int options); @pragma('vm:external-name', 'System_SocketRead') external static ReadResult socketRead(Handle socket, int size); // Vmo operations. @pragma('vm:external-name', 'System_VmoCreate') external static HandleResult vmoCreate(int size, [int options = 0]); @pragma('vm:external-name', 'System_VmoFromFile') external static FromFileResult vmoFromFile(String path); @pragma('vm:external-name', 'System_VmoGetSize') external static GetSizeResult vmoGetSize(Handle vmo); @pragma('vm:external-name', 'System_VmoSetSize') external static int vmoSetSize(Handle vmo, int size); @pragma('vm:external-name', 'System_VmoWrite') external static int vmoWrite(Handle vmo, int offset, ByteData bytes); @pragma('vm:external-name', 'System_VmoRead') external static ReadResult vmoRead(Handle vmo, int offset, int size); @pragma('vm:external-name', 'System_VmoMap') external static MapResult vmoMap(Handle vmo); // Time operations. static int clockGetMonotonic() { if (zirconFFIBindings == null) { return _nativeClockGetMonotonic(); } else { return zirconFFIBindings!.zircon_dart_clock_get_monotonic(); } } @pragma('vm:external-name', 'System_ClockGetMonotonic') external static int _nativeClockGetMonotonic(); // TODO(edcoyne): Remove this, it is required to safely do an API transition across repos. static int reboot() { return -2; /*ZX_ERR_NOT_SUPPORTED*/ } }
engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/system.dart/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/system.dart", "repo_id": "engine", "token_count": 2760 }
338
// 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:async'; import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'dart:zircon'; import 'package:litetest/litetest.dart'; /// Helper method to turn a [String] into a [ByteData] containing the /// text of the string encoded as UTF-8. ByteData utf8Bytes(final String text) { return ByteData.sublistView(utf8.encode(text)); } // Take from zircon constants in zircon/errors.h, zircon/rights.h, zircon/types.h abstract class ZX { ZX._(); static const int OK = 0; static const int KOID_INVALID = 0; static const int ERR_BAD_HANDLE = -11; static const int ERR_SHOULD_WAIT = -22; static const int ERR_PEER_CLOSED = -24; static const int ERR_ACCESS_DENIED = -30; static const int EVENTPAIR_PEER_CLOSED = __ZX_OBJECT_PEER_CLOSED; static const int CHANNEL_READABLE = __ZX_OBJECT_READABLE; static const int CHANNEL_PEER_CLOSED = __ZX_OBJECT_PEER_CLOSED; static const int SOCKET_READABLE = __ZX_OBJECT_READABLE; static const int SOCKET_PEER_CLOSED = __ZX_OBJECT_PEER_CLOSED; static const int RIGHT_DUPLICATE = 1 << 0; static const int RIGHT_TRANSFER = 1 << 1; static const int RIGHT_READ = 1 << 2; static const int RIGHT_WRITE = 1 << 3; static const int RIGHT_GET_PROPERTY = 1 << 6; static const int RIGHT_SET_PROPERTY = 1 << 7; static const int RIGHT_MAP = 1 << 5; static const int RIGHT_SIGNAL = 1 << 12; static const int RIGHT_WAIT = 1 << 14; static const int RIGHT_INSPECT = 1 << 15; static const int RIGHT_SAME_RIGHTS = 1 << 31; static const int RIGHTS_BASIC = RIGHT_TRANSFER | RIGHT_DUPLICATE | RIGHT_WAIT | RIGHT_INSPECT; static const int RIGHTS_IO = RIGHT_READ | RIGHT_WRITE; static const int RIGHTS_PROPERTY = RIGHT_GET_PROPERTY | RIGHT_SET_PROPERTY; static const int DEFAULT_VMO_RIGHTS = RIGHTS_BASIC | RIGHTS_IO | RIGHTS_PROPERTY | RIGHT_MAP | RIGHT_SIGNAL; static const int OBJ_TYPE_VMO = 3; static const int OBJ_TYPE_CHANNEL = 4; static const int HANDLE_OP_MOVE = 0; static const int HANDLE_OP_DUPLICATE = 1; static const int __ZX_OBJECT_READABLE = 1 << 0; static const int __ZX_OBJECT_PEER_CLOSED = 1 << 2; } void main() { group('handle', () { test('create and duplicate handles', () { final HandlePairResult pair = System.eventpairCreate(); expect(pair.status, equals(ZX.OK)); expect(pair.first.isValid, isTrue); expect(pair.second.isValid, isTrue); final Handle duplicate = pair.first.duplicate(ZX.RIGHT_SAME_RIGHTS); expect(duplicate.isValid, isTrue); final Handle failedDuplicate = pair.first.duplicate(-1); expect(failedDuplicate.isValid, isFalse); }); test('failure invalid rights', () { final HandleResult vmo = System.vmoCreate(0); expect(vmo.status, equals(ZX.OK)); final Handle failedDuplicate = vmo.handle.duplicate(-1); expect(failedDuplicate.isValid, isFalse); expect(vmo.handle.isValid, isTrue); }); test('failure invalid handle', () { final Handle handle = Handle.invalid(); final Handle duplicate = handle.duplicate(ZX.RIGHT_SAME_RIGHTS); expect(duplicate.isValid, isFalse); }); test('duplicated handle should have same koid', () { final HandlePairResult pair = System.eventpairCreate(); expect(pair.status, equals(ZX.OK)); expect(pair.first.isValid, isTrue); expect(pair.second.isValid, isTrue); final Handle duplicate = pair.first.duplicate(ZX.RIGHT_SAME_RIGHTS); expect(duplicate.isValid, isTrue); expect(pair.first.koid, duplicate.koid); }); // TODO(fxbug.dev/77599): Simplify once zx_object_get_info is available. test('reduced rights', () { // Set up handle. final HandleResult vmo = System.vmoCreate(2); expect(vmo.status, equals(ZX.OK)); // Duplicate the first handle. final Handle duplicate = vmo.handle.duplicate(ZX.RIGHTS_BASIC); expect(duplicate.isValid, isTrue); // Write bytes to the original handle. final ByteData data1 = utf8Bytes('a'); final int status1 = System.vmoWrite(vmo.handle, 0, data1); expect(status1, equals(ZX.OK)); // Write bytes to the duplicated handle. final ByteData data2 = utf8Bytes('b'); final int status2 = System.vmoWrite(duplicate, 1, data2); expect(status2, equals(ZX.ERR_ACCESS_DENIED)); // Read bytes. final ReadResult readResult = System.vmoRead(vmo.handle, 0, 2); expect(readResult.status, equals(ZX.OK)); expect(readResult.numBytes, equals(2)); expect(readResult.bytes.lengthInBytes, equals(2)); expect(readResult.bytesAsUTF8String(), equals('a\x00')); }); test('create and replace handles', () { final HandlePairResult pair = System.eventpairCreate(); expect(pair.status, equals(ZX.OK)); expect(pair.first.isValid, isTrue); expect(pair.second.isValid, isTrue); final Handle replaced = pair.first.replace(ZX.RIGHT_SAME_RIGHTS); expect(replaced.isValid, isTrue); expect(pair.first.isValid, isFalse); }); test('failure invalid rights', () { final HandleResult vmo = System.vmoCreate(0); expect(vmo.status, equals(ZX.OK)); final Handle failedDuplicate = vmo.handle.replace(-1); expect(failedDuplicate.isValid, isFalse); expect(vmo.handle.isValid, isFalse); }); test('failure invalid handle', () { final Handle handle = Handle.invalid(); final Handle replaced = handle.replace(ZX.RIGHT_SAME_RIGHTS); expect(handle.isValid, isFalse); expect(replaced.isValid, isFalse); }); test('transferred handle should have same koid', () { final HandlePairResult pair = System.eventpairCreate(); expect(pair.status, equals(ZX.OK)); expect(pair.first.isValid, isTrue); expect(pair.second.isValid, isTrue); final int koid = pair.first.koid; final Handle replaced = pair.first.replace(ZX.RIGHT_SAME_RIGHTS); expect(replaced.isValid, isTrue); expect(koid, replaced.koid); }); // TODO(fxbug.dev/77599): Simplify once zx_object_get_info is available. test('reduced rights', () { // Set up handle. final HandleResult vmo = System.vmoCreate(2); expect(vmo.status, equals(ZX.OK)); // Replace the first handle. final Handle duplicate = vmo.handle.replace(ZX.RIGHTS_BASIC | ZX.RIGHT_READ); expect(duplicate.isValid, isTrue); // Write bytes to the original handle. final ByteData data1 = utf8Bytes('a'); final int status1 = System.vmoWrite(vmo.handle, 0, data1); expect(status1, equals(ZX.ERR_BAD_HANDLE)); // Write bytes to the duplicated handle. final ByteData data2 = utf8Bytes('b'); final int status2 = System.vmoWrite(duplicate, 1, data2); expect(status2, equals(ZX.ERR_ACCESS_DENIED)); // Read bytes. final ReadResult readResult = System.vmoRead(duplicate, 0, 2); expect(readResult.status, equals(ZX.OK)); expect(readResult.numBytes, equals(2)); expect(readResult.bytes.lengthInBytes, equals(2)); expect(readResult.bytesAsUTF8String(), equals('\x00\x00')); }); test('cache koid and invalidate', () { final HandleResult vmo = System.vmoCreate(0); expect(vmo.status, equals(ZX.OK)); int originalKoid = vmo.handle.koid; expect(originalKoid, notEquals(ZX.KOID_INVALID)); // Cached koid should be same value. expect(originalKoid, equals(vmo.handle.koid)); vmo.handle.close(); // koid should be invalidated. expect(vmo.handle.koid, equals(ZX.KOID_INVALID)); }); test('store the disposition arguments correctly', () { final Handle handle = System.channelCreate().first; final HandleDisposition disposition = HandleDisposition(1, handle, 2, 3); expect(disposition.operation, equals(1)); expect(disposition.handle, equals(handle)); expect(disposition.type, equals(2)); expect(disposition.rights, equals(3)); expect(disposition.result, equals(ZX.OK)); }); }); group('channel', () { test('create channel', () { final HandlePairResult pair = System.channelCreate(); expect(pair.status, equals(ZX.OK)); expect(pair.first.isValid, isTrue); expect(pair.second.isValid, isTrue); }); test('close channel', () { final HandlePairResult pair = System.channelCreate(); expect(pair.first.close(), equals(0)); expect(pair.first.isValid, isFalse); expect(pair.second.isValid, isTrue); expect(System.channelWrite(pair.first, ByteData(1), <Handle>[]), equals(ZX.ERR_BAD_HANDLE)); expect(System.channelWrite(pair.second, ByteData(1), <Handle>[]), equals(ZX.ERR_PEER_CLOSED)); }); test('channel bytes', () { final HandlePairResult pair = System.channelCreate(); // When no data is available, ZX.ERR_SHOULD_WAIT is returned. expect(System.channelQueryAndRead(pair.second).status, equals(ZX.ERR_SHOULD_WAIT)); // Write bytes. final ByteData data = utf8Bytes('Hello, world'); final int status = System.channelWrite(pair.first, data, <Handle>[]); expect(status, equals(ZX.OK)); // Read bytes. final ReadResult readResult = System.channelQueryAndRead(pair.second); expect(readResult.status, equals(ZX.OK)); expect(readResult.numBytes, equals(data.lengthInBytes)); expect(readResult.bytes.lengthInBytes, equals(data.lengthInBytes)); expect(readResult.bytesAsUTF8String(), equals('Hello, world')); expect(readResult.handles.length, equals(0)); }); test('channel handles', () { final HandlePairResult pair = System.channelCreate(); final ByteData data = utf8Bytes(''); final HandlePairResult eventPair = System.eventpairCreate(); final int status = System.channelWrite(pair.first, data, <Handle>[eventPair.first]); expect(status, equals(ZX.OK)); expect(eventPair.first.isValid, isFalse); final ReadResult readResult = System.channelQueryAndRead(pair.second); expect(readResult.status, equals(ZX.OK)); expect(readResult.numBytes, equals(0)); expect(readResult.bytes.lengthInBytes, equals(0)); expect(readResult.bytesAsUTF8String(), equals('')); expect(readResult.handles.length, equals(1)); expect(readResult.handles[0].isValid, isTrue); }); test('async wait channel read', () async { final HandlePairResult pair = System.channelCreate(); final Completer<List<int>> completer = Completer<List<int>>(); pair.first.asyncWait(ZX.CHANNEL_READABLE, (int status, int pending) { completer.complete(<int>[status, pending]); }); expect(completer.isCompleted, isFalse); System.channelWrite(pair.second, utf8Bytes('Hi'), <Handle>[]); final List<int> result = await completer.future; expect(result[0], equals(ZX.OK)); // status expect(result[1] & ZX.CHANNEL_READABLE, equals(ZX.CHANNEL_READABLE)); // pending }); test('async wait channel closed', () async { final HandlePairResult pair = System.channelCreate(); final Completer<int> completer = Completer<int>(); pair.first.asyncWait(ZX.CHANNEL_PEER_CLOSED, (int status, int pending) { completer.complete(status); }); expect(completer.isCompleted, isFalse); pair.second.close(); final int status = await completer.future; expect(status, equals(ZX.OK)); }); }); group('channel etc functions', () { test('moved handle', () { final HandlePairResult pair = System.channelCreate(); final ByteData data = utf8Bytes(''); final HandlePairResult transferred = System.channelCreate(); final HandleDisposition disposition = HandleDisposition(ZX.HANDLE_OP_MOVE, transferred.first, ZX.OBJ_TYPE_CHANNEL, ZX.RIGHTS_IO); final int status = System.channelWriteEtc( pair.first, data, <HandleDisposition>[disposition]); expect(status, equals(ZX.OK)); expect(disposition.result, equals(ZX.OK)); expect(transferred.first.isValid, isFalse); final ReadEtcResult readResult = System.channelQueryAndReadEtc(pair.second); expect(readResult.status, equals(ZX.OK)); expect(readResult.numBytes, equals(0)); expect(readResult.bytes.lengthInBytes, equals(0)); expect(readResult.bytesAsUTF8String(), equals('')); expect(readResult.handleInfos.length, equals(1)); final HandleInfo handleInfo = readResult.handleInfos[0]; expect(handleInfo.handle.isValid, isTrue); expect(handleInfo.type, equals(ZX.OBJ_TYPE_CHANNEL)); expect(handleInfo.rights, equals(ZX.RIGHTS_IO)); }); test('copied handle', () { final HandlePairResult pair = System.channelCreate(); final ByteData data = utf8Bytes(''); final HandleResult vmo = System.vmoCreate(0); final HandleDisposition disposition = HandleDisposition( ZX.HANDLE_OP_DUPLICATE, vmo.handle, ZX.OBJ_TYPE_VMO, ZX.RIGHT_SAME_RIGHTS); final int status = System.channelWriteEtc( pair.first, data, <HandleDisposition>[disposition]); expect(status, equals(ZX.OK)); expect(disposition.result, equals(ZX.OK)); expect(vmo.handle.isValid, isTrue); final ReadEtcResult readResult = System.channelQueryAndReadEtc(pair.second); expect(readResult.status, equals(ZX.OK)); expect(readResult.numBytes, equals(0)); expect(readResult.bytes.lengthInBytes, equals(0)); expect(readResult.bytesAsUTF8String(), equals('')); expect(readResult.handleInfos.length, equals(1)); final HandleInfo handleInfo = readResult.handleInfos[0]; expect(handleInfo.handle.isValid, isTrue); expect(handleInfo.type, equals(ZX.OBJ_TYPE_VMO)); expect(handleInfo.rights, equals(ZX.DEFAULT_VMO_RIGHTS)); }); test('closed handle should error', () { final HandlePairResult pair = System.channelCreate(); final ByteData data = utf8Bytes(''); final HandlePairResult closed = System.channelCreate(); final HandleDisposition disposition = HandleDisposition(ZX.HANDLE_OP_MOVE, closed.first, ZX.OBJ_TYPE_CHANNEL, ZX.RIGHT_SAME_RIGHTS); closed.first.close(); final int status = System.channelWriteEtc( pair.first, data, <HandleDisposition>[disposition]); expect(status, equals(ZX.ERR_BAD_HANDLE)); expect(disposition.result, equals(ZX.ERR_BAD_HANDLE)); expect(closed.first.isValid, isFalse); final ReadEtcResult readResult = System.channelQueryAndReadEtc(pair.second); expect(readResult.status, equals(ZX.ERR_SHOULD_WAIT)); }); test('multiple handles', () { final HandlePairResult pair = System.channelCreate(); final ByteData data = utf8Bytes(''); final HandlePairResult transferred = System.channelCreate(); final HandleResult vmo = System.vmoCreate(0); final List<HandleDisposition> dispositions = [ HandleDisposition(ZX.HANDLE_OP_MOVE, transferred.first, ZX.OBJ_TYPE_CHANNEL, ZX.RIGHTS_IO), HandleDisposition(ZX.HANDLE_OP_DUPLICATE, vmo.handle, ZX.OBJ_TYPE_VMO, ZX.RIGHT_SAME_RIGHTS) ]; final int status = System.channelWriteEtc(pair.first, data, dispositions); expect(status, equals(ZX.OK)); expect(dispositions[0].result, equals(ZX.OK)); expect(dispositions[1].result, equals(ZX.OK)); expect(transferred.first.isValid, isFalse); expect(vmo.handle.isValid, isTrue); final ReadEtcResult readResult = System.channelQueryAndReadEtc(pair.second); expect(readResult.status, equals(ZX.OK)); expect(readResult.numBytes, equals(0)); expect(readResult.bytes.lengthInBytes, equals(0)); expect(readResult.bytesAsUTF8String(), equals('')); expect(readResult.handleInfos.length, equals(2)); final HandleInfo handleInfo = readResult.handleInfos[0]; expect(handleInfo.handle.isValid, isTrue); expect(handleInfo.type, equals(ZX.OBJ_TYPE_CHANNEL)); expect(handleInfo.rights, equals(ZX.RIGHTS_IO)); final HandleInfo vmoInfo = readResult.handleInfos[1]; expect(vmoInfo.handle.isValid, isTrue); expect(vmoInfo.type, equals(ZX.OBJ_TYPE_VMO)); expect(vmoInfo.rights, equals(ZX.DEFAULT_VMO_RIGHTS)); }); }); group('eventpair', () { test('create', () { final HandlePairResult pair = System.eventpairCreate(); expect(pair.status, equals(ZX.OK)); expect(pair.first.isValid, isTrue); expect(pair.second.isValid, isTrue); }); test('duplicate', () { final HandlePairResult pair = System.eventpairCreate(); expect(pair.status, equals(ZX.OK)); expect(pair.first.isValid, isTrue); expect(pair.second.isValid, isTrue); expect(pair.first.duplicate(ZX.RIGHT_SAME_RIGHTS).isValid, isTrue); expect(pair.second.duplicate(ZX.RIGHT_SAME_RIGHTS).isValid, isTrue); }); test('close', () { final HandlePairResult pair = System.eventpairCreate(); expect(pair.first.close(), equals(0)); expect(pair.first.isValid, isFalse); expect(pair.second.isValid, isTrue); expect(pair.second.close(), equals(0)); expect(pair.second.isValid, isFalse); }); test('async wait peer closed', () async { final HandlePairResult pair = System.eventpairCreate(); final Completer<int> completer = Completer<int>(); pair.first.asyncWait(ZX.EVENTPAIR_PEER_CLOSED, (int status, int pending) { completer.complete(status); }); expect(completer.isCompleted, isFalse); pair.second.close(); final int status = await completer.future; expect(status, equals(ZX.OK)); }); }); // NOTE: This only tests stream sockets. // We should add tests for datagram sockets. group('socket', () { test('create socket', () { final HandlePairResult pair = System.socketCreate(); expect(pair.status, equals(ZX.OK)); expect(pair.first.isValid, isTrue); expect(pair.second.isValid, isTrue); }); test('close socket', () { final HandlePairResult pair = System.socketCreate(); expect(pair.first.close(), equals(0)); expect(pair.first.isValid, isFalse); expect(pair.second.isValid, isTrue); final WriteResult firstResult = System.socketWrite(pair.first, ByteData(1), 0); expect(firstResult.status, equals(ZX.ERR_BAD_HANDLE)); final WriteResult secondResult = System.socketWrite(pair.second, ByteData(1), 0); expect(secondResult.status, equals(ZX.ERR_PEER_CLOSED)); }); test('read write socket', () { final HandlePairResult pair = System.socketCreate(); // When no data is available, ZX.ERR_SHOULD_WAIT is returned. expect( System.socketRead(pair.second, 1).status, equals(ZX.ERR_SHOULD_WAIT)); final ByteData data = utf8Bytes('Hello, world'); final WriteResult writeResult = System.socketWrite(pair.first, data, 0); expect(writeResult.status, equals(ZX.OK)); final ReadResult readResult = System.socketRead(pair.second, data.lengthInBytes); expect(readResult.status, equals(ZX.OK)); expect(readResult.numBytes, equals(data.lengthInBytes)); expect(readResult.bytes.lengthInBytes, equals(data.lengthInBytes)); expect(readResult.bytesAsUTF8String(), equals('Hello, world')); }); test('partial read socket', () { final HandlePairResult pair = System.socketCreate(); final ByteData data = utf8Bytes('Hello, world'); final WriteResult writeResult = System.socketWrite(pair.first, data, 0); expect(writeResult.status, equals(ZX.OK)); const int shortLength = 'Hello'.length; final ReadResult shortReadResult = System.socketRead(pair.second, shortLength); expect(shortReadResult.status, equals(ZX.OK)); expect(shortReadResult.numBytes, equals(shortLength)); expect(shortReadResult.bytes.lengthInBytes, equals(shortLength)); expect(shortReadResult.bytesAsUTF8String(), equals('Hello')); final int longLength = data.lengthInBytes * 2; final ReadResult longReadResult = System.socketRead(pair.second, longLength); expect(longReadResult.status, equals(ZX.OK)); expect(longReadResult.numBytes, equals(data.lengthInBytes - shortLength)); expect(longReadResult.bytes.lengthInBytes, equals(longLength)); expect(longReadResult.bytesAsUTF8String(), equals(', world')); }); test('partial write socket', () { final HandlePairResult pair = System.socketCreate(); final WriteResult writeResult1 = System.socketWrite(pair.first, utf8Bytes('Hello, '), 0); expect(writeResult1.status, equals(ZX.OK)); final WriteResult writeResult2 = System.socketWrite(pair.first, utf8Bytes('world'), 0); expect(writeResult2.status, equals(ZX.OK)); final ReadResult readResult = System.socketRead(pair.second, 100); expect(readResult.status, equals(ZX.OK)); expect(readResult.numBytes, equals('Hello, world'.length)); expect(readResult.bytes.lengthInBytes, equals(100)); expect(readResult.bytesAsUTF8String(), equals('Hello, world')); }); test('async wait socket read', () async { final HandlePairResult pair = System.socketCreate(); final Completer<int> completer = Completer<int>(); pair.first.asyncWait(ZX.SOCKET_READABLE, (int status, int pending) { completer.complete(status); }); expect(completer.isCompleted, isFalse); System.socketWrite(pair.second, utf8Bytes('Hi'), 0); final int status = await completer.future; expect(status, equals(ZX.OK)); }); test('async wait socket closed', () async { final HandlePairResult pair = System.socketCreate(); final Completer<int> completer = Completer<int>(); pair.first.asyncWait(ZX.SOCKET_PEER_CLOSED, (int status, int pending) { completer.complete(status); }); expect(completer.isCompleted, isFalse); pair.second.close(); final int status = await completer.future; expect(status, equals(ZX.OK)); }); }); group('vmo', () { test('fromFile', () { const String fuchsia = 'Fuchsia'; File f = File('tmp/testdata') ..createSync() ..writeAsStringSync(fuchsia); String readFuchsia = f.readAsStringSync(); expect(readFuchsia, equals(fuchsia)); FromFileResult fileResult = System.vmoFromFile('tmp/testdata'); expect(fileResult.status, equals(ZX.OK)); MapResult mapResult = System.vmoMap(fileResult.handle); expect(mapResult.status, equals(ZX.OK)); Uint8List fileData = mapResult.data.asUnmodifiableView(); String fileString = utf8.decode(fileData.sublist(0, fileResult.numBytes)); expect(fileString, equals(fuchsia)); }); test('duplicate', () { const String fuchsia = 'Fuchsia'; Uint8List data = Uint8List.fromList(fuchsia.codeUnits); HandleResult createResult = System.vmoCreate(data.length); expect(createResult.status, equals(ZX.OK)); int writeResult = System.vmoWrite(createResult.handle, 0, data.buffer.asByteData()); expect(writeResult, equals(ZX.OK)); Handle duplicate = createResult.handle.duplicate(ZX.RIGHTS_BASIC | ZX.RIGHT_READ | ZX.RIGHT_MAP); expect(duplicate.isValid, isTrue); // Read from the duplicate. MapResult mapResult = System.vmoMap(duplicate); expect(mapResult.status, equals(ZX.OK)); Uint8List vmoData = mapResult.data.asUnmodifiableView(); String vmoString = utf8.decode(vmoData.sublist(0, data.length)); expect(vmoString, equals(fuchsia)); }); }); }
engine/shell/platform/fuchsia/dart-pkg/zircon/test/zircon_tests.dart/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/test/zircon_tests.dart", "repo_id": "engine", "token_count": 9558 }
339
// 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:async'; import 'dart:io'; import 'package:args/args.dart'; import 'package:crypto/crypto.dart'; import 'package:vm/kernel_front_end.dart' show createCompilerArgParser, runCompiler, successExitCode; final ArgParser _argParser = createCompilerArgParser() ..addFlag('train', help: 'Run through sample command line to produce snapshot', negatable: false); String _usage = ''' Usage: compiler [options] input.dart Options: ${_argParser.usage} '''; Future<void> main(List<String> args) async { ArgResults options; try { options = _argParser.parse(args); if (options['train']) { final Directory temp = Directory.systemTemp.createTempSync('train_kernel_compiler'); try { options = _argParser.parse(<String>[ '--manifest=flutter', '--data-dir=${temp.absolute}', ]); await runCompiler(options, _usage); return; } finally { temp.deleteSync(recursive: true); } } if (!options.rest.isNotEmpty) { throw Exception('Must specify input.dart'); } } on Exception catch (error) { print('ERROR: $error\n'); print(_usage); exitCode = 1; return; } final compilerExitCode = await runCompiler(options, _usage); if (compilerExitCode != successExitCode) { exitCode = compilerExitCode; return; } }
engine/shell/platform/fuchsia/dart/compiler.dart/0
{ "file_path": "engine/shell/platform/fuchsia/dart/compiler.dart", "repo_id": "engine", "token_count": 578 }
340
// 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. // This file is linked into the dart executable when it has a snapshot // linked into it. #include "embedder/snapshot.h" namespace dart_runner { // The string on the next line will be filled in with the contents of the // generated snapshot binary file for the vm isolate. This string forms the // content of the dart vm isolate snapshot which is loaded into the vm isolate. static const uint8_t vm_isolate_snapshot_buffer_[] = { % s}; uint8_t const* const vm_isolate_snapshot_buffer = vm_isolate_snapshot_buffer_; // The string on the next line will be filled in with the contents of the // generated snapshot binary file for a regular dart isolate. // This string forms the content of a regular dart isolate snapshot which // is loaded into an isolate when it is created. static const uint8_t isolate_snapshot_buffer_[] = { % s}; uint8_t const* const isolate_snapshot_buffer = isolate_snapshot_buffer_; } // namespace dart_runner
engine/shell/platform/fuchsia/dart_runner/embedder/snapshot.cc.tmpl/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/embedder/snapshot.cc.tmpl", "repo_id": "engine", "token_count": 294 }
341
// 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. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_SERVICE_ISOLATE_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_SERVICE_ISOLATE_H_ #include "third_party/dart/runtime/include/dart_api.h" namespace dart_runner { Dart_Isolate CreateServiceIsolate(const char* uri, Dart_IsolateFlags* flags, char** error); Dart_Handle GetVMServiceAssetsArchiveCallback(); } // namespace dart_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_SERVICE_ISOLATE_H_
engine/shell/platform/fuchsia/dart_runner/service_isolate.h/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/service_isolate.h", "repo_id": "engine", "token_count": 307 }
342
// Copyright 2022 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. #include "dart_runner/dart_test_component_controller.h" #include "gtest/gtest.h" namespace dart_runner::testing { namespace { std::string GetCurrentTestName() { return ::testing::UnitTest::GetInstance()->current_test_info()->name(); } } // namespace // TODO(naudzghebre): Add unit tests for the dart_test_runner. TEST(SuiteImplTest, EQUALITY) { EXPECT_EQ(1, 1) << GetCurrentTestName(); } } // namespace dart_runner::testing
engine/shell/platform/fuchsia/dart_runner/tests/suite_impl_unittests.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/tests/suite_impl_unittests.cc", "repo_id": "engine", "token_count": 199 }
343
// 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. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_COMPONENT_V2_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_COMPONENT_V2_H_ #include <array> #include <memory> #include <set> #include <fuchsia/component/runner/cpp/fidl.h> #include <fuchsia/io/cpp/fidl.h> #include <fuchsia/ui/app/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async/default.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/fidl/cpp/interface_request.h> #include <lib/fit/function.h> #include <lib/sys/cpp/service_directory.h> #include <lib/vfs/cpp/pseudo_dir.h> #include <lib/zx/eventpair.h> #include "flutter/common/settings.h" #include "flutter/fml/macros.h" #include "engine.h" #include "flutter_runner_product_configuration.h" #include "program_metadata.h" #include "unique_fdio_ns.h" namespace flutter_runner { class ComponentV2; struct ActiveComponentV2 { std::unique_ptr<fml::Thread> platform_thread; std::unique_ptr<ComponentV2> component; ActiveComponentV2& operator=(ActiveComponentV2&& other) noexcept { if (this != &other) { this->platform_thread.reset(other.platform_thread.release()); this->component.reset(other.component.release()); } return *this; } ~ActiveComponentV2() = default; }; // Represents an instance of a CF v2 Flutter component that contains one or more // Flutter engine instances. // // TODO(fxb/50694): Add unit tests once we've verified that the current behavior // is working correctly. class ComponentV2 final : public Engine::Delegate, public fuchsia::component::runner::ComponentController, public fuchsia::ui::app::ViewProvider { public: using TerminationCallback = fit::function<void(const ComponentV2*)>; // Creates a dedicated thread to run the component and creates the // component on it. The component can be accessed only on this thread. // This is a synchronous operation. static ActiveComponentV2 Create( TerminationCallback termination_callback, fuchsia::component::runner::ComponentStartInfo start_info, std::shared_ptr<sys::ServiceDirectory> runner_incoming_services, fidl::InterfaceRequest<fuchsia::component::runner::ComponentController> controller); // Must be called on the same thread returned from the create call. The thread // may be collected after. ~ComponentV2(); /// Parses the program metadata that was provided for the component. /// /// |old_gen_heap_size| will be set to -1 if no value was specified. static ProgramMetadata ParseProgramMetadata( const fuchsia::data::Dictionary& program_metadata); const std::string& GetDebugLabel() const; #if !defined(DART_PRODUCT) void WriteProfileToTrace() const; #endif // !defined(DART_PRODUCT) private: ComponentV2( TerminationCallback termination_callback, fuchsia::component::runner::ComponentStartInfo start_info, std::shared_ptr<sys::ServiceDirectory> runner_incoming_services, fidl::InterfaceRequest<fuchsia::component::runner::ComponentController> controller); // |fuchsia::component::runner::ComponentController| void Kill() override; /// Helper to actually |Kill| the component, closing the connection via an /// epitaph with the given |epitaph_status|. Call this instead of /// Kill() in the implementation of this class, as |Kill| is only intended for /// clients of the ComponentController protocol to call. /// /// To determine what |epitaph_status| is appropriate for your situation, /// see the documentation for |fuchsia.component.runner.ComponentController|. void KillWithEpitaph(zx_status_t epitaph_status); // |fuchsia::component::runner::ComponentController| void Stop() override; // |fuchsia::ui::app::ViewProvider| void CreateView2(fuchsia::ui::app::CreateView2Args view_args) override; void CreateViewWithViewRef( ::zx::eventpair token, ::fuchsia::ui::views::ViewRefControl view_ref_control, ::fuchsia::ui::views::ViewRef view_ref) override {} // |flutter::Engine::Delegate| void OnEngineTerminate(const Engine* holder) override; flutter::Settings settings_; FlutterRunnerProductConfiguration product_config_; TerminationCallback termination_callback_; const std::string debug_label_; UniqueFDIONS fdio_ns_ = UniqueFDIONSCreate(); fml::UniqueFD component_data_directory_; fml::UniqueFD component_assets_directory_; fidl::Binding<fuchsia::component::runner::ComponentController> component_controller_; fuchsia::io::DirectoryPtr directory_ptr_; fuchsia::io::NodePtr cloned_directory_ptr_; fidl::InterfaceRequest<fuchsia::io::Directory> directory_request_; std::unique_ptr<vfs::PseudoDir> outgoing_dir_; std::unique_ptr<vfs::PseudoDir> runtime_dir_; std::shared_ptr<sys::ServiceDirectory> svc_; std::shared_ptr<sys::ServiceDirectory> runner_incoming_services_; fidl::BindingSet<fuchsia::ui::app::ViewProvider> shells_bindings_; fml::RefPtr<flutter::DartSnapshot> isolate_snapshot_; std::set<std::unique_ptr<Engine>> shell_holders_; std::pair<bool, uint32_t> last_return_code_; fml::WeakPtrFactory<ComponentV2> weak_factory_; // Must be the last member. FML_DISALLOW_COPY_AND_ASSIGN(ComponentV2); }; } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_COMPONENT_V2_H_
engine/shell/platform/fuchsia/flutter/component_v2.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/component_v2.h", "repo_id": "engine", "token_count": 1828 }
344
// 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. #include "fuchsia_intl.h" #include <sstream> #include <string> #include <vector> #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "runner.h" #include "runtime/dart/utils/tempfs.h" #include "third_party/icu/source/common/unicode/bytestream.h" #include "third_party/icu/source/common/unicode/errorcode.h" #include "third_party/icu/source/common/unicode/locid.h" #include "third_party/icu/source/common/unicode/strenum.h" #include "third_party/icu/source/common/unicode/stringpiece.h" #include "third_party/icu/source/common/unicode/uloc.h" using icu::Locale; namespace flutter_runner { using fuchsia::intl::Profile; fml::MallocMapping MakeLocalizationPlatformMessageData( const Profile& intl_profile) { rapidjson::Document document; auto& allocator = document.GetAllocator(); document.SetObject(); document.AddMember("method", "setLocale", allocator); rapidjson::Value args(rapidjson::kArrayType); for (const auto& locale_id : intl_profile.locales()) { UErrorCode error_code = U_ZERO_ERROR; icu::Locale locale = icu::Locale::forLanguageTag(locale_id.id, error_code); if (U_FAILURE(error_code)) { FML_LOG(ERROR) << "Error parsing locale ID \"" << locale_id.id << "\""; continue; } args.PushBack(rapidjson::Value().SetString(locale.getLanguage(), allocator), allocator); auto country = locale.getCountry() != nullptr ? locale.getCountry() : ""; args.PushBack(rapidjson::Value().SetString(country, allocator), allocator); auto script = locale.getScript() != nullptr ? locale.getScript() : ""; args.PushBack(rapidjson::Value().SetString(script, allocator), allocator); std::string variant = locale.getVariant() != nullptr ? locale.getVariant() : ""; // ICU4C capitalizes the variant for backward compatibility, even though // the preferred form is lowercase. So we lowercase here. std::transform(begin(variant), end(variant), begin(variant), [](unsigned char c) { return std::tolower(c); }); args.PushBack(rapidjson::Value().SetString(variant, allocator), allocator); } document.AddMember("args", args, allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); document.Accept(writer); auto data = reinterpret_cast<const uint8_t*>(buffer.GetString()); return fml::MallocMapping::Copy(data, buffer.GetSize()); } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/fuchsia_intl.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/fuchsia_intl.cc", "repo_id": "engine", "token_count": 941 }
345
// 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 { use: [ // This is used by the Dart VM to communicate from Dart code to C++ code. { storage: "tmp", path: "/tmp", }, // This is used by the Dart VM to load i18n data. { directory: "config-data", rights: [ "r*" ], path: "/config/data", }, // The ICU time zone data, factored out of `config-data`. // See: // https://fuchsia.dev/fuchsia-src/concepts/process/namespaces?typical_directory_structure { directory: "tzdata-icu", rights: [ "r*" ], path: "/config/tzdata/icu", }, { directory: "root-ssl-certificates", rights: [ "r*" ], path: "/config/ssl", }, { protocol: [ "fuchsia.accessibility.semantics.SemanticsManager", "fuchsia.device.NameProvider", "fuchsia.feedback.CrashReporter", "fuchsia.fonts.Provider", "fuchsia.inspect.InspectSink", // Copied from inspect/client.shard.cml. "fuchsia.intl.PropertyProvider", "fuchsia.logger.LogSink", // Copied from syslog/client.shard.cml. "fuchsia.media.ProfileProvider", "fuchsia.memorypressure.Provider", "fuchsia.net.name.Lookup", "fuchsia.posix.socket.Provider", "fuchsia.sysmem.Allocator", "fuchsia.ui.composition.Allocator", "fuchsia.ui.composition.Flatland", "fuchsia.ui.input.ImeService", "fuchsia.ui.input3.Keyboard", "fuchsia.ui.pointerinjector.Registry", "fuchsia.vulkan.loader.Loader", // Copied from vulkan/client.shard.cml. ], }, { protocol: [ "fuchsia.tracing.provider.Registry", // Copied from vulkan/client.shard.cml. ], availability: "optional", }, ] }
engine/shell/platform/fuchsia/flutter/meta/common.shard.cml/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/meta/common.shard.cml", "repo_id": "engine", "token_count": 1175 }
346
// 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. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RTREE_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RTREE_H_ #include <list> #include <map> #include "third_party/skia/include/core/SkBBHFactory.h" #include "third_party/skia/include/core/SkTypes.h" namespace flutter { /** * An R-Tree implementation that forwards calls to an SkRTree. * * This implementation provides a searchNonOverlappingDrawnRects method, * which can be used to query the rects for the operations recorded in the tree. */ class RTree : public SkBBoxHierarchy { public: RTree(); void insert(const SkRect[], const SkBBoxHierarchy::Metadata[], int N) override; void insert(const SkRect[], int N) override; void search(const SkRect& query, std::vector<int>* results) const override; size_t bytesUsed() const override; // Finds the rects in the tree that represent drawing operations and intersect // with the query rect. // // When two rects intersect with each other, they are joined into a single // rect which also intersects with the query rect. In other words, the bounds // of each rect in the result list are mutually exclusive. std::list<SkRect> searchNonOverlappingDrawnRects(const SkRect& query) const; // Insertion count (not overall node count, which may be greater). int getCount() const { return all_ops_count_; } private: // A map containing the draw operation rects keyed off the operation index // in the insert call. std::map<int, SkRect> draw_op_; sk_sp<SkBBoxHierarchy> bbh_; int all_ops_count_; }; class RTreeFactory : public SkBBHFactory { public: RTreeFactory(); // Gets the instance to the R-tree. sk_sp<RTree> getInstance(); sk_sp<SkBBoxHierarchy> operator()() const override; private: sk_sp<RTree> r_tree_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RTREE_H_
engine/shell/platform/fuchsia/flutter/rtree.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/rtree.h", "repo_id": "engine", "token_count": 682 }
347
// 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. #include "flutter/shell/platform/fuchsia/flutter/external_view_embedder.h" #include <fuchsia/math/cpp/fidl.h> #include <fuchsia/sysmem/cpp/fidl.h> #include <fuchsia/ui/composition/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/async-testing/test_loop.h> #include <lib/zx/event.h> #include <lib/zx/eventpair.h> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <vector> #include "flutter/flow/embedded_views.h" #include "flutter/fml/logging.h" #include "flutter/fml/time/time_delta.h" #include "flutter/fml/time/time_point.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkSurface.h" #include "fakes/scenic/fake_flatland.h" #include "fakes/scenic/fake_flatland_types.h" #include "flutter/shell/platform/fuchsia/flutter/surface_producer.h" #include "gmock/gmock.h" // For EXPECT_THAT and matchers #include "gtest/gtest.h" using fuchsia::scenic::scheduling::FramePresentedInfo; using fuchsia::scenic::scheduling::FuturePresentationTimes; using fuchsia::scenic::scheduling::PresentReceivedInfo; using ::testing::_; using ::testing::AllOf; using ::testing::Contains; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Field; using ::testing::FieldsAre; using ::testing::IsEmpty; using ::testing::Matcher; using ::testing::Pointee; using ::testing::Property; using ::testing::SizeIs; using ::testing::VariantWith; namespace flutter_runner::testing { namespace { constexpr static fuchsia::ui::composition::BlendMode kFirstLayerBlendMode{ fuchsia::ui::composition::BlendMode::SRC}; constexpr static fuchsia::ui::composition::BlendMode kUpperLayerBlendMode{ fuchsia::ui::composition::BlendMode::SRC_OVER}; constexpr static int64_t kImplicitViewId = 0; class FakeSurfaceProducerSurface : public SurfaceProducerSurface { public: explicit FakeSurfaceProducerSurface( fidl::InterfaceRequest<fuchsia::sysmem::BufferCollectionToken> sysmem_token_request, fuchsia::ui::composition::BufferCollectionImportToken buffer_import_token, const SkISize& size) : sysmem_token_request_(std::move(sysmem_token_request)), buffer_import_token_(std::move(buffer_import_token)), surface_(SkSurfaces::Null(size.width(), size.height())) { zx_status_t acquire_status = zx::event::create(0, &acquire_fence_); if (acquire_status != ZX_OK) { FML_LOG(ERROR) << "FakeSurfaceProducerSurface: Failed to create acquire event"; } zx_status_t release_status = zx::event::create(0, &release_fence_); if (release_status != ZX_OK) { FML_LOG(ERROR) << "FakeSurfaceProducerSurface: Failed to create release event"; } } ~FakeSurfaceProducerSurface() override {} bool IsValid() const override { return true; } SkISize GetSize() const override { return SkISize::Make(surface_->width(), surface_->height()); } void SetImageId(uint32_t image_id) override { image_id_ = image_id; } uint32_t GetImageId() override { return image_id_; } sk_sp<SkSurface> GetSkiaSurface() const override { return surface_; } fuchsia::ui::composition::BufferCollectionImportToken GetBufferCollectionImportToken() override { return std::move(buffer_import_token_); } zx::event GetAcquireFence() override { zx::event fence; acquire_fence_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); return fence; } zx::event GetReleaseFence() override { zx::event fence; release_fence_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); return fence; } void SetReleaseImageCallback( ReleaseImageCallback release_image_callback) override {} size_t AdvanceAndGetAge() override { return 0; } bool FlushSessionAcquireAndReleaseEvents() override { return true; } void SignalWritesFinished( const std::function<void(void)>& on_writes_committed) override {} private: fidl::InterfaceRequest<fuchsia::sysmem::BufferCollectionToken> sysmem_token_request_; fuchsia::ui::composition::BufferCollectionImportToken buffer_import_token_; zx::event acquire_fence_; zx::event release_fence_; sk_sp<SkSurface> surface_; uint32_t image_id_{0}; }; class FakeSurfaceProducer : public SurfaceProducer { public: explicit FakeSurfaceProducer( fuchsia::ui::composition::AllocatorHandle flatland_allocator) : flatland_allocator_(flatland_allocator.Bind()) {} ~FakeSurfaceProducer() override = default; // |SurfaceProducer| GrDirectContext* gr_context() const override { return nullptr; } // |SurfaceProducer| std::unique_ptr<SurfaceProducerSurface> ProduceOffscreenSurface( const SkISize& size) override { return nullptr; } // |SurfaceProducer| std::unique_ptr<SurfaceProducerSurface> ProduceSurface( const SkISize& size) override { auto [buffer_export_token, buffer_import_token] = BufferCollectionTokenPair::New(); fuchsia::sysmem::BufferCollectionTokenHandle sysmem_token; auto sysmem_token_request = sysmem_token.NewRequest(); fuchsia::ui::composition::RegisterBufferCollectionArgs buffer_collection_args; buffer_collection_args.set_export_token(std::move(buffer_export_token)); buffer_collection_args.set_buffer_collection_token(std::move(sysmem_token)); buffer_collection_args.set_usage( fuchsia::ui::composition::RegisterBufferCollectionUsage::DEFAULT); flatland_allocator_->RegisterBufferCollection( std::move(buffer_collection_args), [](fuchsia::ui::composition::Allocator_RegisterBufferCollection_Result result) { if (result.is_err()) { FAIL() << "fuhsia::ui::composition::RegisterBufferCollection error: " << static_cast<uint32_t>(result.err()); } }); return std::make_unique<FakeSurfaceProducerSurface>( std::move(sysmem_token_request), std::move(buffer_import_token), size); } // |SurfaceProducer| void SubmitSurfaces( std::vector<std::unique_ptr<SurfaceProducerSurface>> surfaces) override {} fuchsia::ui::composition::AllocatorPtr flatland_allocator_; }; Matcher<fuchsia::ui::composition::ImageProperties> IsImageProperties( const fuchsia::math::SizeU& size) { return AllOf( Property("has_size", &fuchsia::ui::composition::ImageProperties::has_size, true), Property("size", &fuchsia::ui::composition::ImageProperties::size, size)); } Matcher<fuchsia::ui::composition::ViewportProperties> IsViewportProperties( const fuchsia::math::SizeU& logical_size, const fuchsia::math::Inset& inset) { return AllOf( Property("has_logical_size", &fuchsia::ui::composition::ViewportProperties::has_logical_size, true), Property("logical_size", &fuchsia::ui::composition::ViewportProperties::logical_size, logical_size), Property("has_inset", &fuchsia::ui::composition::ViewportProperties::has_inset, true), Property("inset", &fuchsia::ui::composition::ViewportProperties::inset, inset)); } Matcher<fuchsia::ui::composition::HitRegion> IsHitRegion( const float x, const float y, const float width, const float height, const fuchsia::ui::composition::HitTestInteraction hit_test) { return FieldsAre(FieldsAre(x, y, width, height), hit_test); } Matcher<FakeGraph> IsEmptyGraph() { return FieldsAre(IsEmpty(), IsEmpty(), Eq(nullptr), Eq(std::nullopt)); } Matcher<FakeGraph> IsFlutterGraph( const fuchsia::ui::composition::ParentViewportWatcherPtr& parent_viewport_watcher, const fuchsia::ui::views::ViewportCreationToken& viewport_creation_token, const fuchsia::ui::views::ViewRef& view_ref, std::vector<Matcher<std::shared_ptr<FakeTransform>>> layer_matchers = {}, fuchsia::math::VecF scale = FakeTransform::kDefaultScale) { auto viewport_token_koids = GetKoids(viewport_creation_token); auto view_ref_koids = GetKoids(view_ref); auto watcher_koids = GetKoids(parent_viewport_watcher); return FieldsAre( /*content_map*/ _, /*transform_map*/ _, Pointee(FieldsAre( /*id*/ _, FakeTransform::kDefaultTranslation, /*scale*/ scale, FakeTransform::kDefaultOrientation, /*clip_bounds*/ _, FakeTransform::kDefaultOpacity, /*children*/ ElementsAreArray(layer_matchers), /*content*/ Eq(nullptr), /*hit_regions*/ _)), Eq(FakeView{ .view_token = viewport_token_koids.second, .view_ref = view_ref_koids.first, .view_ref_control = view_ref_koids.second, .view_ref_focused = ZX_KOID_INVALID, .focuser = ZX_KOID_INVALID, .touch_source = ZX_KOID_INVALID, .mouse_source = ZX_KOID_INVALID, .parent_viewport_watcher = watcher_koids.second, })); } Matcher<std::shared_ptr<FakeTransform>> IsImageLayer( const fuchsia::math::SizeU& layer_size, fuchsia::ui::composition::BlendMode blend_mode, std::vector<Matcher<fuchsia::ui::composition::HitRegion>> hit_region_matchers) { return Pointee(FieldsAre( /*id*/ _, FakeTransform::kDefaultTranslation, FakeTransform::kDefaultScale, FakeTransform::kDefaultOrientation, /*clip_bounds*/ _, FakeTransform::kDefaultOpacity, /*children*/ IsEmpty(), /*content*/ Pointee(VariantWith<FakeImage>(FieldsAre( /*id*/ _, IsImageProperties(layer_size), FakeImage::kDefaultSampleRegion, layer_size, FakeImage::kDefaultOpacity, blend_mode, /*buffer_import_token*/ _, /*vmo_index*/ 0))), /* hit_regions*/ ElementsAreArray(hit_region_matchers))); } Matcher<std::shared_ptr<FakeTransform>> IsViewportLayer( const fuchsia::ui::views::ViewCreationToken& view_token, const fuchsia::math::SizeU& view_logical_size, const fuchsia::math::Inset& view_inset, const fuchsia::math::Vec& view_translation, const fuchsia::math::VecF& view_scale, const float view_opacity) { return Pointee(FieldsAre( /* id */ _, view_translation, view_scale, FakeTransform::kDefaultOrientation, /*clip_bounds*/ _, view_opacity, /*children*/ IsEmpty(), /*content*/ Pointee(VariantWith<FakeViewport>(FieldsAre( /* id */ _, IsViewportProperties(view_logical_size, view_inset), /* viewport_token */ GetKoids(view_token).second, /* child_view_watcher */ _))), /*hit_regions*/ _)); } Matcher<std::shared_ptr<FakeTransform>> IsClipTransformLayer( const fuchsia::math::Vec& transform_translation, const fuchsia::math::VecF& transform_scale, std::optional<fuchsia::math::Rect> clip_bounds, Matcher<std::shared_ptr<FakeTransform>> viewport_matcher) { return Pointee(FieldsAre( /* id */ _, transform_translation, transform_scale, FakeTransform::kDefaultOrientation, /*clip_bounds*/ clip_bounds, FakeTransform::kDefaultOpacity, /*children*/ ElementsAre(viewport_matcher), /*content*/ _, /*hit_regions*/ _)); } Matcher<std::shared_ptr<FakeTransform>> IsInputShield() { return Pointee(AllOf( // Must not clip the hit region. Field("clip_bounds", &FakeTransform::clip_bounds, Eq(std::nullopt)), // Hit region must be "infinite". Field("hit_regions", &FakeTransform::hit_regions, Contains(flutter_runner::testing::kInfiniteHitRegion)))); } fuchsia::ui::composition::OnNextFrameBeginValues WithPresentCredits( uint32_t additional_present_credits) { fuchsia::ui::composition::OnNextFrameBeginValues values; values.set_additional_present_credits(additional_present_credits); fuchsia::scenic::scheduling::PresentationInfo info_1; info_1.set_presentation_time(123); std::vector<fuchsia::scenic::scheduling::PresentationInfo> infos; infos.push_back(std::move(info_1)); values.set_future_presentation_infos(std::move(infos)); return values; } void DrawSimpleFrame(ExternalViewEmbedder& external_view_embedder, SkISize frame_size, float frame_dpr, std::function<void(flutter::DlCanvas*)> draw_callback) { external_view_embedder.BeginFrame(nullptr, nullptr); external_view_embedder.PrepareFlutterView(kImplicitViewId, frame_size, frame_dpr); { flutter::DlCanvas* root_canvas = external_view_embedder.GetRootCanvas(); external_view_embedder.PostPrerollAction(nullptr); draw_callback(root_canvas); } external_view_embedder.EndFrame(false, nullptr); flutter::SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true; external_view_embedder.SubmitFlutterView( nullptr, nullptr, std::make_unique<flutter::SurfaceFrame>( nullptr, std::move(framebuffer_info), [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, frame_size)); } void DrawFrameWithView( ExternalViewEmbedder& external_view_embedder, SkISize frame_size, float frame_dpr, int view_id, flutter::EmbeddedViewParams& view_params, std::function<void(flutter::DlCanvas*)> background_draw_callback, std::function<void(flutter::DlCanvas*)> overlay_draw_callback) { external_view_embedder.BeginFrame(nullptr, nullptr); external_view_embedder.PrepareFlutterView(kImplicitViewId, frame_size, frame_dpr); { flutter::DlCanvas* root_canvas = external_view_embedder.GetRootCanvas(); external_view_embedder.PrerollCompositeEmbeddedView( view_id, std::make_unique<flutter::EmbeddedViewParams>(view_params)); external_view_embedder.PostPrerollAction(nullptr); background_draw_callback(root_canvas); flutter::DlCanvas* overlay_canvas = external_view_embedder.CompositeEmbeddedView(view_id); overlay_draw_callback(overlay_canvas); } external_view_embedder.EndFrame(false, nullptr); flutter::SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true; external_view_embedder.SubmitFlutterView( nullptr, nullptr, std::make_unique<flutter::SurfaceFrame>( nullptr, std::move(framebuffer_info), [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, frame_size)); } }; // namespace class ExternalViewEmbedderTest : public ::testing::Test { protected: ExternalViewEmbedderTest() : session_subloop_(loop_.StartNewLoop()), flatland_connection_(CreateFlatlandConnection()), fake_surface_producer_( std::make_shared<FakeSurfaceProducer>(CreateFlatlandAllocator())) {} ~ExternalViewEmbedderTest() override = default; async::TestLoop& loop() { return loop_; } std::shared_ptr<FakeSurfaceProducer> fake_surface_producer() { return fake_surface_producer_; } FakeFlatland& fake_flatland() { return fake_flatland_; } std::shared_ptr<FlatlandConnection> flatland_connection() { return flatland_connection_; } private: fuchsia::ui::composition::AllocatorHandle CreateFlatlandAllocator() { FML_CHECK(!fake_flatland_.is_allocator_connected()); fuchsia::ui::composition::AllocatorHandle flatland_allocator = fake_flatland_.ConnectAllocator(session_subloop_->dispatcher()); return flatland_allocator; } std::shared_ptr<FlatlandConnection> CreateFlatlandConnection() { FML_CHECK(!fake_flatland_.is_flatland_connected()); fuchsia::ui::composition::FlatlandHandle flatland = fake_flatland_.ConnectFlatland(session_subloop_->dispatcher()); const auto test_name = ::testing::UnitTest::GetInstance()->current_test_info()->name(); return std::make_shared<FlatlandConnection>( std::move(test_name), std::move(flatland), /*error_callback=*/[] { FAIL(); }, /*ofpe_callback=*/[](auto...) {}); } // Primary loop and subloop for the FakeFlatland instance to process its // messages. The subloop allocates its own zx_port_t, allowing us to use a // separate port for each end of the message channel, rather than sharing a // single one. Dual ports allow messages and responses to be intermingled, // which is how production code behaves; this improves test realism. async::TestLoop loop_; std::unique_ptr<async::LoopInterface> session_subloop_; FakeFlatland fake_flatland_; std::shared_ptr<FlatlandConnection> flatland_connection_; std::shared_ptr<FakeSurfaceProducer> fake_surface_producer_; }; TEST_F(ExternalViewEmbedderTest, RootScene) { fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; fuchsia::ui::views::ViewRef view_ref_clone; auto view_creation_token_status = zx::channel::create( 0u, &viewport_creation_token.value, &view_creation_token.value); ASSERT_EQ(view_creation_token_status, ZX_OK); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); view_ref.Clone(&view_ref_clone); ExternalViewEmbedder external_view_embedder( std::move(view_creation_token), fuchsia::ui::views::ViewIdentityOnCreation{ .view_ref = std::move(view_ref), .view_ref_control = std::move(view_ref_control), }, fuchsia::ui::composition::ViewBoundProtocols{}, parent_viewport_watcher.NewRequest(), flatland_connection(), fake_surface_producer()); EXPECT_THAT(fake_flatland().graph(), IsEmptyGraph()); // Pump the loop; the graph should still be empty because nothing called // `Present` yet. loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsEmptyGraph()); // Pump the loop; the contents of the initial `Present` should be processed. flatland_connection()->Present(); loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); } TEST_F(ExternalViewEmbedderTest, SimpleScene) { fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; fuchsia::ui::views::ViewRef view_ref_clone; auto view_creation_token_status = zx::channel::create( 0u, &viewport_creation_token.value, &view_creation_token.value); ASSERT_EQ(view_creation_token_status, ZX_OK); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); view_ref.Clone(&view_ref_clone); // Create the `ExternalViewEmbedder` and pump the message loop until // the initial scene graph is setup. ExternalViewEmbedder external_view_embedder( std::move(view_creation_token), fuchsia::ui::views::ViewIdentityOnCreation{ .view_ref = std::move(view_ref), .view_ref_control = std::move(view_ref_control), }, fuchsia::ui::composition::ViewBoundProtocols{}, parent_viewport_watcher.NewRequest(), flatland_connection(), fake_surface_producer()); flatland_connection()->Present(); loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Draw the scene. The scene graph shouldn't change yet. const SkISize frame_size_signed = SkISize::Make(512, 512); const fuchsia::math::SizeU frame_size{ static_cast<uint32_t>(frame_size_signed.width()), static_cast<uint32_t>(frame_size_signed.height())}; DrawSimpleFrame(external_view_embedder, frame_size_signed, 1.f, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect( SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); } TEST_F(ExternalViewEmbedderTest, SceneWithOneView) { fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; fuchsia::ui::views::ViewRef view_ref_clone; auto view_creation_token_status = zx::channel::create( 0u, &viewport_creation_token.value, &view_creation_token.value); ASSERT_EQ(view_creation_token_status, ZX_OK); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); view_ref.Clone(&view_ref_clone); // Create the `ExternalViewEmbedder` and pump the message loop until // the initial scene graph is setup. ExternalViewEmbedder external_view_embedder( std::move(view_creation_token), fuchsia::ui::views::ViewIdentityOnCreation{ .view_ref = std::move(view_ref), .view_ref_control = std::move(view_ref_control), }, fuchsia::ui::composition::ViewBoundProtocols{}, parent_viewport_watcher.NewRequest(), flatland_connection(), fake_surface_producer()); flatland_connection()->Present(); loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Create the view before drawing the scene. const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f); const fuchsia::math::SizeU child_view_size{ static_cast<uint32_t>(child_view_size_signed.width()), static_cast<uint32_t>(child_view_size_signed.height())}; auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); const uint32_t child_view_id = child_viewport_token.value.get(); const int kOpacity = 200; const float kOpacityFloat = 200 / 255.0f; const fuchsia::math::VecF kScale{3.0f, 4.0f}; auto matrix = SkMatrix::I(); matrix.setScaleX(kScale.x); matrix.setScaleY(kScale.y); auto mutators_stack = flutter::MutatorsStack(); mutators_stack.PushOpacity(kOpacity); mutators_stack.PushTransform(matrix); flutter::EmbeddedViewParams child_view_params(matrix, child_view_size_signed, mutators_stack); external_view_embedder.CreateView( child_view_id, []() {}, [](fuchsia::ui::composition::ContentId, fuchsia::ui::composition::ChildViewWatcherHandle) {}); const SkRect child_view_occlusion_hint = SkRect::MakeLTRB(1, 2, 3, 4); const fuchsia::math::Inset child_view_inset{ static_cast<int32_t>(child_view_occlusion_hint.top()), static_cast<int32_t>(child_view_occlusion_hint.right()), static_cast<int32_t>(child_view_occlusion_hint.bottom()), static_cast<int32_t>(child_view_occlusion_hint.left())}; external_view_embedder.SetViewProperties( child_view_id, child_view_occlusion_hint, /*hit_testable=*/false, /*focusable=*/false); // We must take into account the effect of DPR on the view scale. const float kDPR = 2.0f; const float kInvDPR = 1.f / kDPR; // Draw the scene. The scene graph shouldn't change yet. const SkISize frame_size_signed = SkISize::Make(512, 512); const fuchsia::math::SizeU frame_size{ static_cast<uint32_t>(frame_size_signed.width()), static_cast<uint32_t>(frame_size_signed.height())}; DrawFrameWithView( external_view_embedder, frame_size_signed, kDPR, child_view_id, child_view_params, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect(SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kRed()); canvas->Translate(canvas_size.width() * 3.f / 4.f, canvas_size.height() / 2.f); canvas->DrawRect(SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsViewportLayer(child_view_token, child_view_size, child_view_inset, {0, 0}, kScale, kOpacityFloat), IsImageLayer( frame_size, kUpperLayerBlendMode, {IsHitRegion( /* x */ 384.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, {kInvDPR, kInvDPR})); // Destroy the view. The scene graph shouldn't change yet. external_view_embedder.DestroyView( child_view_id, [](fuchsia::ui::composition::ContentId) {}); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsViewportLayer(child_view_token, child_view_size, child_view_inset, {0, 0}, kScale, kOpacityFloat), IsImageLayer( frame_size, kUpperLayerBlendMode, {IsHitRegion( /* x */ 384.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, {kInvDPR, kInvDPR})); // Draw another frame without the view. The scene graph shouldn't change yet. DrawSimpleFrame(external_view_embedder, frame_size_signed, 1.f, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect( SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsViewportLayer(child_view_token, child_view_size, child_view_inset, {0, 0}, kScale, kOpacityFloat), IsImageLayer( frame_size, kUpperLayerBlendMode, {IsHitRegion( /* x */ 384.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, {kInvDPR, kInvDPR})); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); } TEST_F(ExternalViewEmbedderTest, SceneWithOneClippedView) { fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; fuchsia::ui::views::ViewRef view_ref_clone; auto view_creation_token_status = zx::channel::create( 0u, &viewport_creation_token.value, &view_creation_token.value); ASSERT_EQ(view_creation_token_status, ZX_OK); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); view_ref.Clone(&view_ref_clone); // Create the `ExternalViewEmbedder` and pump the message loop until // the initial scene graph is setup. ExternalViewEmbedder external_view_embedder( std::move(view_creation_token), fuchsia::ui::views::ViewIdentityOnCreation{ .view_ref = std::move(view_ref), .view_ref_control = std::move(view_ref_control), }, fuchsia::ui::composition::ViewBoundProtocols{}, parent_viewport_watcher.NewRequest(), flatland_connection(), fake_surface_producer()); flatland_connection()->Present(); loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Create the view before drawing the scene. const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f); const fuchsia::math::SizeU child_view_size{ static_cast<uint32_t>(child_view_size_signed.width()), static_cast<uint32_t>(child_view_size_signed.height())}; auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); const uint32_t child_view_id = child_viewport_token.value.get(); const int kOpacity = 200; const float kOpacityFloat = 200 / 255.0f; const fuchsia::math::VecF kScale{3.0f, 4.0f}; const int kTranslateX = 10; const int kTranslateY = 20; auto matrix = SkMatrix::I(); matrix.setScaleX(kScale.x); matrix.setScaleY(kScale.y); matrix.setTranslateX(kTranslateX); matrix.setTranslateY(kTranslateY); SkRect kClipRect = SkRect::MakeXYWH(30, 40, child_view_size_signed.width() - 50, child_view_size_signed.height() - 60); fuchsia::math::Rect kClipInMathRect = { static_cast<int32_t>(kClipRect.x()), static_cast<int32_t>(kClipRect.y()), static_cast<int32_t>(kClipRect.width()), static_cast<int32_t>(kClipRect.height())}; auto mutators_stack = flutter::MutatorsStack(); mutators_stack.PushOpacity(kOpacity); mutators_stack.PushTransform(matrix); mutators_stack.PushClipRect(kClipRect); flutter::EmbeddedViewParams child_view_params(matrix, child_view_size_signed, mutators_stack); external_view_embedder.CreateView( child_view_id, []() {}, [](fuchsia::ui::composition::ContentId, fuchsia::ui::composition::ChildViewWatcherHandle) {}); const SkRect child_view_occlusion_hint = SkRect::MakeLTRB(1, 2, 3, 4); const fuchsia::math::Inset child_view_inset{ static_cast<int32_t>(child_view_occlusion_hint.top()), static_cast<int32_t>(child_view_occlusion_hint.right()), static_cast<int32_t>(child_view_occlusion_hint.bottom()), static_cast<int32_t>(child_view_occlusion_hint.left())}; external_view_embedder.SetViewProperties( child_view_id, child_view_occlusion_hint, /*hit_testable=*/false, /*focusable=*/false); // We must take into account the effect of DPR on the view scale. const float kDPR = 2.0f; const float kInvDPR = 1.f / kDPR; // Draw the scene. The scene graph shouldn't change yet. const SkISize frame_size_signed = SkISize::Make(512, 512); const fuchsia::math::SizeU frame_size{ static_cast<uint32_t>(frame_size_signed.width()), static_cast<uint32_t>(frame_size_signed.height())}; DrawFrameWithView( external_view_embedder, frame_size_signed, kDPR, child_view_id, child_view_params, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect(SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kRed()); canvas->Translate(canvas_size.width() * 3.f / 4.f, canvas_size.height() / 2.f); canvas->DrawRect(SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsClipTransformLayer( {kTranslateX, kTranslateY}, kScale, kClipInMathRect, IsViewportLayer(child_view_token, child_view_size, child_view_inset, {0, 0}, FakeTransform::kDefaultScale, kOpacityFloat)), IsImageLayer( frame_size, kUpperLayerBlendMode, {IsHitRegion( /* x */ 384.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, {kInvDPR, kInvDPR})); // Draw another frame with view, but get rid of the clips this time. This // should remove all ClipTransformLayer instances. auto new_matrix = SkMatrix::I(); new_matrix.setScaleX(kScale.x); new_matrix.setScaleY(kScale.y); auto new_mutators_stack = flutter::MutatorsStack(); new_mutators_stack.PushOpacity(kOpacity); new_mutators_stack.PushTransform(new_matrix); flutter::EmbeddedViewParams new_child_view_params( new_matrix, child_view_size_signed, new_mutators_stack); DrawFrameWithView( external_view_embedder, frame_size_signed, kDPR, child_view_id, new_child_view_params, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect(SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kRed()); canvas->Translate(canvas_size.width() * 3.f / 4.f, canvas_size.height() / 2.f); canvas->DrawRect(SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsViewportLayer(child_view_token, child_view_size, child_view_inset, {0, 0}, kScale, kOpacityFloat), IsImageLayer( frame_size, kUpperLayerBlendMode, {IsHitRegion( /* x */ 384.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, {kInvDPR, kInvDPR})); // Destroy the view and draw another frame without the view. external_view_embedder.DestroyView( child_view_id, [](fuchsia::ui::composition::ContentId) {}); DrawSimpleFrame(external_view_embedder, frame_size_signed, 1.f, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect( SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); } TEST_F(ExternalViewEmbedderTest, SceneWithOneView_NoOverlay) { fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; fuchsia::ui::views::ViewRef view_ref_clone; auto view_creation_token_status = zx::channel::create( 0u, &viewport_creation_token.value, &view_creation_token.value); ASSERT_EQ(view_creation_token_status, ZX_OK); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); view_ref.Clone(&view_ref_clone); // Create the `ExternalViewEmbedder` and pump the message loop until // the initial scene graph is setup. ExternalViewEmbedder external_view_embedder( std::move(view_creation_token), fuchsia::ui::views::ViewIdentityOnCreation{ .view_ref = std::move(view_ref), .view_ref_control = std::move(view_ref_control), }, fuchsia::ui::composition::ViewBoundProtocols{}, parent_viewport_watcher.NewRequest(), flatland_connection(), fake_surface_producer()); flatland_connection()->Present(); loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Create the view before drawing the scene. const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f); const fuchsia::math::SizeU child_view_size{ static_cast<uint32_t>(child_view_size_signed.width()), static_cast<uint32_t>(child_view_size_signed.height())}; auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); const uint32_t child_view_id = child_viewport_token.value.get(); const int kOpacity = 125; const float kOpacityFloat = 125 / 255.0f; const fuchsia::math::VecF kScale{2.f, 3.0f}; auto matrix = SkMatrix::I(); matrix.setScaleX(kScale.x); matrix.setScaleY(kScale.y); auto mutators_stack = flutter::MutatorsStack(); mutators_stack.PushOpacity(kOpacity); mutators_stack.PushTransform(matrix); flutter::EmbeddedViewParams child_view_params(matrix, child_view_size_signed, mutators_stack); external_view_embedder.CreateView( child_view_id, []() {}, [](fuchsia::ui::composition::ContentId, fuchsia::ui::composition::ChildViewWatcherHandle) {}); // Draw the scene. The scene graph shouldn't change yet. const SkISize frame_size_signed = SkISize::Make(512, 512); const fuchsia::math::SizeU frame_size{ static_cast<uint32_t>(frame_size_signed.width()), static_cast<uint32_t>(frame_size_signed.height())}; DrawFrameWithView( external_view_embedder, frame_size_signed, 1.f, child_view_id, child_view_params, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect(SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }, [](flutter::DlCanvas* canvas) {}); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsViewportLayer(child_view_token, child_view_size, FakeViewport::kDefaultViewportInset, {0, 0}, kScale, kOpacityFloat)})); // Destroy the view. The scene graph shouldn't change yet. external_view_embedder.DestroyView( child_view_id, [](fuchsia::ui::composition::ContentId) {}); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsViewportLayer(child_view_token, child_view_size, FakeViewport::kDefaultViewportInset, {0, 0}, kScale, kOpacityFloat)})); // Draw another frame without the view. The scene graph shouldn't change yet. DrawSimpleFrame(external_view_embedder, frame_size_signed, 1.f, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect( SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsViewportLayer(child_view_token, child_view_size, FakeViewport::kDefaultViewportInset, {0, 0}, kScale, kOpacityFloat)})); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); } TEST_F(ExternalViewEmbedderTest, SceneWithOneView_DestroyBeforeDrawing) { fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; fuchsia::ui::views::ViewRef view_ref_clone; auto view_creation_token_status = zx::channel::create( 0u, &viewport_creation_token.value, &view_creation_token.value); ASSERT_EQ(view_creation_token_status, ZX_OK); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); view_ref.Clone(&view_ref_clone); // Create the `ExternalViewEmbedder` and pump the message loop until // the initial scene graph is setup. ExternalViewEmbedder external_view_embedder( std::move(view_creation_token), fuchsia::ui::views::ViewIdentityOnCreation{ .view_ref = std::move(view_ref), .view_ref_control = std::move(view_ref_control), }, fuchsia::ui::composition::ViewBoundProtocols{}, parent_viewport_watcher.NewRequest(), flatland_connection(), fake_surface_producer()); flatland_connection()->Present(); loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Create the view before drawing the scene. auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); const uint32_t child_view_id = child_viewport_token.value.get(); external_view_embedder.CreateView( child_view_id, []() {}, [](fuchsia::ui::composition::ContentId, fuchsia::ui::composition::ChildViewWatcherHandle) {}); // Draw the scene without the view. The scene graph shouldn't change yet. const SkISize frame_size_signed = SkISize::Make(512, 512); const fuchsia::math::SizeU frame_size{ static_cast<uint32_t>(frame_size_signed.width()), static_cast<uint32_t>(frame_size_signed.height())}; DrawSimpleFrame(external_view_embedder, frame_size_signed, 1.f, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor().kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect( SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); // Destroy the view. The scene graph shouldn't change yet. external_view_embedder.DestroyView( child_view_id, [](fuchsia::ui::composition::ContentId) {}); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); // Draw another frame without the view and change the size. The scene graph // shouldn't change yet. const SkISize new_frame_size_signed = SkISize::Make(256, 256); const fuchsia::math::SizeU new_frame_size{ static_cast<uint32_t>(new_frame_size_signed.width()), static_cast<uint32_t>(new_frame_size_signed.height())}; DrawSimpleFrame(external_view_embedder, new_frame_size_signed, 1.f, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect( SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( new_frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 64.f, /* y */ 128.f, /* width */ 8.f, /* height */ 8.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); } // This test case exercises the scenario in which the view contains two disjoint // regions with painted content; we should generate two separate hit regions // matching the bounds of the painted regions in this case. TEST_F(ExternalViewEmbedderTest, SimpleScene_DisjointHitRegions) { fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; fuchsia::ui::views::ViewRef view_ref_clone; auto view_creation_token_status = zx::channel::create( 0u, &viewport_creation_token.value, &view_creation_token.value); ASSERT_EQ(view_creation_token_status, ZX_OK); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); view_ref.Clone(&view_ref_clone); // Create the `ExternalViewEmbedder` and pump the message loop until // the initial scene graph is setup. ExternalViewEmbedder external_view_embedder( std::move(view_creation_token), fuchsia::ui::views::ViewIdentityOnCreation{ .view_ref = std::move(view_ref), .view_ref_control = std::move(view_ref_control), }, fuchsia::ui::composition::ViewBoundProtocols{}, parent_viewport_watcher.NewRequest(), flatland_connection(), fake_surface_producer()); flatland_connection()->Present(); loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Draw the scene. The scene graph shouldn't change yet. const SkISize frame_size_signed = SkISize::Make(512, 512); const fuchsia::math::SizeU frame_size{ static_cast<uint32_t>(frame_size_signed.width()), static_cast<uint32_t>(frame_size_signed.height())}; DrawSimpleFrame( external_view_embedder, frame_size_signed, 1.f, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); SkRect paint_region_1, paint_region_2; paint_region_1 = SkRect::MakeXYWH( canvas_size.width() / 4.f, canvas_size.height() / 2.f, canvas_size.width() / 32.f, canvas_size.height() / 32.f); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->DrawRect(paint_region_1, rect_paint); paint_region_2 = SkRect::MakeXYWH( canvas_size.width() * 3.f / 4.f, canvas_size.height() / 2.f, canvas_size.width() / 32.f, canvas_size.height() / 32.f); rect_paint.setColor(flutter::DlColor::kRed()); canvas->DrawRect(paint_region_2, rect_paint); }); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT), IsHitRegion( /* x */ 384.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); } // This test case exercises the scenario in which the view contains two // overlapping regions with painted content; we should generate one hit // region matching the union of the bounds of the two painted regions in // this case. TEST_F(ExternalViewEmbedderTest, SimpleScene_OverlappingHitRegions) { fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; fuchsia::ui::views::ViewRef view_ref_clone; auto view_creation_token_status = zx::channel::create( 0u, &viewport_creation_token.value, &view_creation_token.value); ASSERT_EQ(view_creation_token_status, ZX_OK); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); view_ref.Clone(&view_ref_clone); // Create the `ExternalViewEmbedder` and pump the message loop until // the initial scene graph is setup. ExternalViewEmbedder external_view_embedder( std::move(view_creation_token), fuchsia::ui::views::ViewIdentityOnCreation{ .view_ref = std::move(view_ref), .view_ref_control = std::move(view_ref_control), }, fuchsia::ui::composition::ViewBoundProtocols{}, parent_viewport_watcher.NewRequest(), flatland_connection(), fake_surface_producer()); flatland_connection()->Present(); loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Draw the scene. The scene graph shouldn't change yet. const SkISize frame_size_signed = SkISize::Make(512, 512); const fuchsia::math::SizeU frame_size{ static_cast<uint32_t>(frame_size_signed.width()), static_cast<uint32_t>(frame_size_signed.height())}; DrawSimpleFrame( external_view_embedder, frame_size_signed, 1.f, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); SkRect paint_region_1, paint_region_2; paint_region_1 = SkRect::MakeXYWH( canvas_size.width() / 4.f, canvas_size.height() / 2.f, 3.f * canvas_size.width() / 8.f, canvas_size.height() / 4.f); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->DrawRect(paint_region_1, rect_paint); paint_region_2 = SkRect::MakeXYWH( canvas_size.width() * 3.f / 8.f, canvas_size.height() / 2.f, 3.f * canvas_size.width() / 8.f, canvas_size.height() / 4.f); rect_paint.setColor(flutter::DlColor::kRed()); canvas->DrawRect(paint_region_2, rect_paint); }); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone)); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 256.f, /* height */ 128.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); } TEST_F(ExternalViewEmbedderTest, ViewportCoveredWithInputInterceptor) { fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; fuchsia::ui::views::ViewRef view_ref_clone; auto view_creation_token_status = zx::channel::create( 0u, &viewport_creation_token.value, &view_creation_token.value); ASSERT_EQ(view_creation_token_status, ZX_OK); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); view_ref.Clone(&view_ref_clone); // Create the `ExternalViewEmbedder` and pump the message loop until // the initial scene graph is setup. ExternalViewEmbedder external_view_embedder( std::move(view_creation_token), fuchsia::ui::views::ViewIdentityOnCreation{ .view_ref = std::move(view_ref), .view_ref_control = std::move(view_ref_control), }, fuchsia::ui::composition::ViewBoundProtocols{}, parent_viewport_watcher.NewRequest(), flatland_connection(), fake_surface_producer(), /*intercept_all_input=*/true // Enables the interceptor. ); flatland_connection()->Present(); loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone, {IsInputShield()})); // Create the view before drawing the scene. const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f); const fuchsia::math::SizeU child_view_size{ static_cast<uint32_t>(child_view_size_signed.width()), static_cast<uint32_t>(child_view_size_signed.height())}; auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); const uint32_t child_view_id = child_viewport_token.value.get(); const int kOpacity = 200; const float kOpacityFloat = 200 / 255.0f; const fuchsia::math::VecF kScale{3.0f, 4.0f}; auto matrix = SkMatrix::I(); matrix.setScaleX(kScale.x); matrix.setScaleY(kScale.y); auto mutators_stack = flutter::MutatorsStack(); mutators_stack.PushOpacity(kOpacity); mutators_stack.PushTransform(matrix); flutter::EmbeddedViewParams child_view_params(matrix, child_view_size_signed, mutators_stack); external_view_embedder.CreateView( child_view_id, []() {}, [](fuchsia::ui::composition::ContentId, fuchsia::ui::composition::ChildViewWatcherHandle) {}); const SkRect child_view_occlusion_hint = SkRect::MakeLTRB(1, 2, 3, 4); const fuchsia::math::Inset child_view_inset{ static_cast<int32_t>(child_view_occlusion_hint.top()), static_cast<int32_t>(child_view_occlusion_hint.right()), static_cast<int32_t>(child_view_occlusion_hint.bottom()), static_cast<int32_t>(child_view_occlusion_hint.left())}; external_view_embedder.SetViewProperties( child_view_id, child_view_occlusion_hint, /*hit_testable=*/false, /*focusable=*/false); // We must take into account the effect of DPR on the view scale. const float kDPR = 2.0f; const float kInvDPR = 1.f / kDPR; // Draw the scene. The scene graph shouldn't change yet. const SkISize frame_size_signed = SkISize::Make(512, 512); const fuchsia::math::SizeU frame_size{ static_cast<uint32_t>(frame_size_signed.width()), static_cast<uint32_t>(frame_size_signed.height())}; DrawFrameWithView( external_view_embedder, frame_size_signed, kDPR, child_view_id, child_view_params, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kGreen()); canvas->Translate(canvas_size.width() / 4.f, canvas_size.height() / 2.f); canvas->DrawRect(SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }, [](flutter::DlCanvas* canvas) { const SkISize layer_size = canvas->GetBaseLayerSize(); const SkSize canvas_size = SkSize::Make(layer_size.width(), layer_size.height()); flutter::DlPaint rect_paint; rect_paint.setColor(flutter::DlColor::kRed()); canvas->Translate(canvas_size.width() * 3.f / 4.f, canvas_size.height() / 2.f); canvas->DrawRect(SkRect::MakeWH(canvas_size.width() / 32.f, canvas_size.height() / 32.f), rect_paint); }); EXPECT_THAT(fake_flatland().graph(), IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, view_ref_clone, {IsInputShield()})); // Pump the message loop. The scene updates should propagate to flatland. loop().RunUntilIdle(); fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); loop().RunUntilIdle(); EXPECT_THAT( fake_flatland().graph(), IsFlutterGraph( parent_viewport_watcher, viewport_creation_token, view_ref_clone, /*layers*/ {IsImageLayer( frame_size, kFirstLayerBlendMode, {IsHitRegion( /* x */ 128.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsViewportLayer(child_view_token, child_view_size, child_view_inset, {0, 0}, kScale, kOpacityFloat), IsImageLayer( frame_size, kUpperLayerBlendMode, {IsHitRegion( /* x */ 384.f, /* y */ 256.f, /* width */ 16.f, /* height */ 16.f, /* hit_test */ fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), IsInputShield()}, {kInvDPR, kInvDPR})); } } // namespace flutter_runner::testing
engine/shell/platform/fuchsia/flutter/tests/external_view_embedder_unittests.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/external_view_embedder_unittests.cc", "repo_id": "engine", "token_count": 33371 }
348
# 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. assert(is_fuchsia) import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") group("integration") { testonly = true deps = [ "embedder:tests", "mouse-input:tests", "text-input:tests", "touch-input:tests", ] }
engine/shell/platform/fuchsia/flutter/tests/integration/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/BUILD.gn", "repo_id": "engine", "token_count": 148 }
349
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fuchsia/accessibility/semantics/cpp/fidl.h> #include <fuchsia/buildinfo/cpp/fidl.h> #include <fuchsia/component/cpp/fidl.h> #include <fuchsia/fonts/cpp/fidl.h> #include <fuchsia/input/report/cpp/fidl.h> #include <fuchsia/kernel/cpp/fidl.h> #include <fuchsia/logger/cpp/fidl.h> #include <fuchsia/memorypressure/cpp/fidl.h> #include <fuchsia/metrics/cpp/fidl.h> #include <fuchsia/net/interfaces/cpp/fidl.h> #include <fuchsia/tracing/provider/cpp/fidl.h> #include <fuchsia/ui/app/cpp/fidl.h> #include <fuchsia/ui/display/singleton/cpp/fidl.h> #include <fuchsia/ui/input/cpp/fidl.h> #include <fuchsia/ui/test/input/cpp/fidl.h> #include <fuchsia/web/cpp/fidl.h> #include <lib/async/cpp/task.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/sys/component/cpp/testing/realm_builder.h> #include <lib/sys/component/cpp/testing/realm_builder_types.h> #include <zircon/status.h> #include <zircon/types.h> #include <zircon/utc.h> #include <cstddef> #include <cstdint> #include <iostream> #include <memory> #include <optional> #include <queue> #include <string> #include <type_traits> #include <utility> #include <vector> #include <gtest/gtest.h> #include "flutter/fml/logging.h" #include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h" #include "lib/fidl/cpp/interface_ptr.h" namespace mouse_input_test::testing { namespace { // Types imported for the realm_builder library. using component_testing::ChildRef; using component_testing::ConfigValue; using component_testing::LocalComponentImpl; using component_testing::ParentRef; using component_testing::Protocol; using component_testing::Realm; using component_testing::Route; using fuchsia_test_utils::PortableUITest; using RealmBuilder = component_testing::RealmBuilder; // Alias for Component child name as provided to Realm Builder. using ChildName = std::string; // Alias for Component Legacy URL as provided to Realm Builder. using LegacyUrl = std::string; // Maximum pointer movement during a clickpad press for the gesture to // be guaranteed to be interpreted as a click. For movement greater than // this value, upper layers may, e.g., interpret the gesture as a drag. // // This value corresponds to the one used to instantiate the ClickDragHandler // registered by Input Pipeline in Scene Manager. constexpr int64_t kClickToDragThreshold = 16.0; constexpr auto kMouseInputListener = "mouse_input_listener"; constexpr auto kMouseInputListenerRef = ChildRef{kMouseInputListener}; constexpr auto kMouseInputView = "mouse-input-view"; constexpr auto kMouseInputViewRef = ChildRef{kMouseInputView}; constexpr auto kMouseInputViewUrl = "fuchsia-pkg://fuchsia.com/mouse-input-view#meta/mouse-input-view.cm"; struct Position { double x = 0.0; double y = 0.0; }; // Combines all vectors in `vecs` into one. template <typename T> std::vector<T> merge(std::initializer_list<std::vector<T>> vecs) { std::vector<T> result; for (auto v : vecs) { result.insert(result.end(), v.begin(), v.end()); } return result; } int ButtonsToInt( const std::vector<fuchsia::ui::test::input::MouseButton>& buttons) { int result = 0; for (const auto& button : buttons) { result |= (0x1 >> button); } return result; } // `MouseInputListener` is a local test protocol that our test apps use to let // us know what position and button press state the mouse cursor has. class MouseInputListenerServer : public fuchsia::ui::test::input::MouseInputListener, public LocalComponentImpl { public: explicit MouseInputListenerServer(async_dispatcher_t* dispatcher) : dispatcher_(dispatcher) {} void ReportMouseInput( fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest request) override { FML_LOG(INFO) << "Received MouseInput event"; events_.push(std::move(request)); } // |MockComponent::OnStart| // When the component framework requests for this component to start, this // method will be invoked by the realm_builder library. void OnStart() override { FML_LOG(INFO) << "Starting MouseInputServer"; ASSERT_EQ(ZX_OK, outgoing()->AddPublicService( fidl::InterfaceRequestHandler< fuchsia::ui::test::input::MouseInputListener>( [this](auto request) { bindings_.AddBinding(this, std::move(request), dispatcher_); }))); } size_t SizeOfEvents() const { return events_.size(); } fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest PopEvent() { auto e = std::move(events_.front()); events_.pop(); return e; } const fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest& LastEvent() const { return events_.back(); } void ClearEvents() { events_ = {}; } private: // Not owned. async_dispatcher_t* dispatcher_ = nullptr; fidl::BindingSet<fuchsia::ui::test::input::MouseInputListener> bindings_; std::queue< fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest> events_; }; class MouseInputTest : public PortableUITest, public ::testing::Test, public ::testing::WithParamInterface<std::string> { protected: void SetUp() override { PortableUITest::SetUp(); // Register fake mouse device. RegisterMouse(); // Get the display dimensions. FML_LOG(INFO) << "Waiting for display info from fuchsia.ui.display.singleton.Info"; fuchsia::ui::display::singleton::InfoPtr display_info = realm_root() ->component() .Connect<fuchsia::ui::display::singleton::Info>(); display_info->GetMetrics( [this](fuchsia::ui::display::singleton::Metrics metrics) { display_width_ = metrics.extent_in_px().width; display_height_ = metrics.extent_in_px().height; FML_LOG(INFO) << "Got display_width = " << display_width_ << " and display_height = " << display_height_; }); RunLoopUntil( [this] { return display_width_ != 0 && display_height_ != 0; }); } void TearDown() override { // at the end of test, ensure event queue is empty. ASSERT_EQ(mouse_input_listener_->SizeOfEvents(), 0u); } MouseInputListenerServer* mouse_input_listener() { return mouse_input_listener_; } // Helper method for checking the test.mouse.MouseInputListener response from // the client app. void VerifyEvent( fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest& pointer_data, double expected_x, double expected_y, std::vector<fuchsia::ui::test::input::MouseButton> expected_buttons, const fuchsia::ui::test::input::MouseEventPhase expected_phase, const std::string& component_name) { FML_LOG(INFO) << "Client received mouse change at (" << pointer_data.local_x() << ", " << pointer_data.local_y() << ") with buttons " << ButtonsToInt(pointer_data.buttons()) << "."; FML_LOG(INFO) << "Expected mouse change is at approximately (" << expected_x << ", " << expected_y << ") with buttons " << ButtonsToInt(expected_buttons) << "."; // Allow for minor rounding differences in coordinates. // Note: These approximations don't account for // `PointerMotionDisplayScaleHandler` or `PointerMotionSensorScaleHandler`. // We will need to do so in order to validate larger motion or different // sized displays. EXPECT_NEAR(pointer_data.local_x(), expected_x, 1); EXPECT_NEAR(pointer_data.local_y(), expected_y, 1); EXPECT_EQ(pointer_data.buttons(), expected_buttons); EXPECT_EQ(pointer_data.phase(), expected_phase); EXPECT_EQ(pointer_data.component_name(), component_name); } void VerifyEventLocationOnTheRightOfExpectation( fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest& pointer_data, double expected_x_min, double expected_y, std::vector<fuchsia::ui::test::input::MouseButton> expected_buttons, const fuchsia::ui::test::input::MouseEventPhase expected_phase, const std::string& component_name) { FML_LOG(INFO) << "Client received mouse change at (" << pointer_data.local_x() << ", " << pointer_data.local_y() << ") with buttons " << ButtonsToInt(pointer_data.buttons()) << "."; FML_LOG(INFO) << "Expected mouse change is at approximately (>" << expected_x_min << ", " << expected_y << ") with buttons " << ButtonsToInt(expected_buttons) << "."; EXPECT_GT(pointer_data.local_x(), expected_x_min); EXPECT_NEAR(pointer_data.local_y(), expected_y, 1); EXPECT_EQ(pointer_data.buttons(), expected_buttons); EXPECT_EQ(pointer_data.phase(), expected_phase); EXPECT_EQ(pointer_data.component_name(), component_name); } // Guaranteed to be initialized after SetUp(). uint32_t display_width() const { return display_width_; } uint32_t display_height() const { return display_height_; } private: void ExtendRealm() override { FML_LOG(INFO) << "Extending realm"; // Key part of service setup: have this test component vend the // |MouseInputListener| service in the constructed realm. auto mouse_input_listener = std::make_unique<MouseInputListenerServer>(dispatcher()); mouse_input_listener_ = mouse_input_listener.get(); realm_builder()->AddLocalChild( kMouseInputListener, [mouse_input_listener = std::move(mouse_input_listener)]() mutable { return std::move(mouse_input_listener); }); realm_builder()->AddChild(kMouseInputView, kMouseInputViewUrl, component_testing::ChildOptions{ .environment = kFlutterRunnerEnvironment, }); realm_builder()->AddRoute( Route{.capabilities = {Protocol{ fuchsia::ui::test::input::MouseInputListener::Name_}}, .source = kMouseInputListenerRef, .targets = {kFlutterJitRunnerRef, kMouseInputViewRef}}); realm_builder()->AddRoute( Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, .source = kMouseInputViewRef, .targets = {ParentRef()}}); } ParamType GetTestUIStackUrl() override { return GetParam(); }; MouseInputListenerServer* mouse_input_listener_; uint32_t display_width_ = 0; uint32_t display_height_ = 0; }; // Makes use of gtest's parameterized testing, allowing us // to test different combinations of test-ui-stack + runners. Currently, there // is just one combination. Documentation: // http://go/gunitadvanced#value-parameterized-tests INSTANTIATE_TEST_SUITE_P( MouseInputTestParameterized, MouseInputTest, ::testing::Values( "fuchsia-pkg://fuchsia.com/flatland-scene-manager-test-ui-stack#meta/" "test-ui-stack.cm")); TEST_P(MouseInputTest, DISABLED_FlutterMouseMove) { LaunchClient(); SimulateMouseEvent(/* pressed_buttons = */ {}, /* movement_x = */ 1, /* movement_y = */ 2); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 1u); auto e = mouse_input_listener()->PopEvent(); // If the first mouse event is cursor movement, Flutter first sends an ADD // event with updated location. VerifyEvent(e, /*expected_x=*/static_cast<double>(display_width()) / 2.f + 1, /*expected_y=*/static_cast<double>(display_height()) / 2.f + 2, /*expected_buttons=*/{}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, /*component_name=*/"mouse-input-view"); } TEST_P(MouseInputTest, DISABLED_FlutterMouseDown) { LaunchClient(); SimulateMouseEvent( /* pressed_buttons = */ {fuchsia::ui::test::input::MouseButton::FIRST}, /* movement_x = */ 0, /* movement_y = */ 0); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 3; }); ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 3u); auto event_add = mouse_input_listener()->PopEvent(); auto event_down = mouse_input_listener()->PopEvent(); auto event_noop_move = mouse_input_listener()->PopEvent(); // If the first mouse event is a button press, Flutter first sends an ADD // event with no buttons. VerifyEvent(event_add, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, /*component_name=*/"mouse-input-view"); // Then Flutter sends a DOWN pointer event with the buttons we care about. VerifyEvent( event_down, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::DOWN, /*component_name=*/"mouse-input-view"); // Then Flutter sends a MOVE pointer event with no new information. VerifyEvent( event_noop_move, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::MOVE, /*component_name=*/"mouse-input-view"); } TEST_P(MouseInputTest, DISABLED_FlutterMouseDownUp) { LaunchClient(); SimulateMouseEvent( /* pressed_buttons = */ {fuchsia::ui::test::input::MouseButton::FIRST}, /* movement_x = */ 0, /* movement_y = */ 0); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 3; }); ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 3u); auto event_add = mouse_input_listener()->PopEvent(); auto event_down = mouse_input_listener()->PopEvent(); auto event_noop_move = mouse_input_listener()->PopEvent(); // If the first mouse event is a button press, Flutter first sends an ADD // event with no buttons. VerifyEvent(event_add, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, /*component_name=*/"mouse-input-view"); // Then Flutter sends a DOWN pointer event with the buttons we care about. VerifyEvent( event_down, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::DOWN, /*component_name=*/"mouse-input-view"); // Then Flutter sends a MOVE pointer event with no new information. VerifyEvent( event_noop_move, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::MOVE, /*component_name=*/"mouse-input-view"); SimulateMouseEvent(/* pressed_buttons = */ {}, /* movement_x = */ 0, /* movement_y = */ 0); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 1u); auto event_up = mouse_input_listener()->PopEvent(); VerifyEvent(event_up, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::UP, /*component_name=*/"mouse-input-view"); } TEST_P(MouseInputTest, DISABLED_FlutterMouseDownMoveUp) { LaunchClient(); SimulateMouseEvent( /* pressed_buttons = */ {fuchsia::ui::test::input::MouseButton::FIRST}, /* movement_x = */ 0, /* movement_y = */ 0); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 3; }); ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 3u); auto event_add = mouse_input_listener()->PopEvent(); auto event_down = mouse_input_listener()->PopEvent(); auto event_noop_move = mouse_input_listener()->PopEvent(); // If the first mouse event is a button press, Flutter first sends an ADD // event with no buttons. VerifyEvent(event_add, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, /*component_name=*/"mouse-input-view"); // Then Flutter sends a DOWN pointer event with the buttons we care about. VerifyEvent( event_down, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::DOWN, /*component_name=*/"mouse-input-view"); // Then Flutter sends a MOVE pointer event with no new information. VerifyEvent( event_noop_move, /*expected_x=*/static_cast<double>(display_width()) / 2.f, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::MOVE, /*component_name=*/"mouse-input-view"); SimulateMouseEvent( /* pressed_buttons = */ {fuchsia::ui::test::input::MouseButton::FIRST}, /* movement_x = */ kClickToDragThreshold, /* movement_y = */ 0); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 1u); auto event_move = mouse_input_listener()->PopEvent(); VerifyEventLocationOnTheRightOfExpectation( event_move, /*expected_x_min=*/static_cast<double>(display_width()) / 2.f + 1, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::MOVE, /*component_name=*/"mouse-input-view"); SimulateMouseEvent(/* pressed_buttons = */ {}, /* movement_x = */ 0, /* movement_y = */ 0); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 1u); auto event_up = mouse_input_listener()->PopEvent(); VerifyEventLocationOnTheRightOfExpectation( event_up, /*expected_x_min=*/static_cast<double>(display_width()) / 2.f + 1, /*expected_y=*/static_cast<double>(display_height()) / 2.f, /*expected_buttons=*/{}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::UP, /*component_name=*/"mouse-input-view"); } // TODO(fxbug.dev/103098): This test shows the issue when sending mouse wheel as // the first event to Flutter. // 1. expect Flutter app receive 2 events: ADD - Scroll, but got 3 events: Move // - Scroll - Scroll. // 2. the first event flutter app received has random value in buttons field // Disabled until flutter rolls, since it changes the behavior of this issue. TEST_P(MouseInputTest, DISABLED_FlutterMouseWheelIssue103098) { LaunchClient(); SimulateMouseScroll(/* pressed_buttons = */ {}, /* scroll_x = */ 1, /* scroll_y = */ 0); // Here we expected 2 events, ADD - Scroll, but got 3, Move - Scroll - Scroll. RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 3; }); double initial_x = static_cast<double>(display_width()) / 2.f; double initial_y = static_cast<double>(display_height()) / 2.f; auto event_1 = mouse_input_listener()->PopEvent(); EXPECT_NEAR(event_1.local_x(), initial_x, 1); EXPECT_NEAR(event_1.local_y(), initial_y, 1); // Flutter will scale the count of ticks to pixel. EXPECT_GT(event_1.wheel_x_physical_pixel(), 0); EXPECT_EQ(event_1.wheel_y_physical_pixel(), 0); EXPECT_EQ(event_1.phase(), fuchsia::ui::test::input::MouseEventPhase::MOVE); auto event_2 = mouse_input_listener()->PopEvent(); VerifyEvent( event_2, /*expected_x=*/initial_x, /*expected_y=*/initial_y, /*expected_buttons=*/{}, /*expected_phase=*/fuchsia::ui::test::input::MouseEventPhase::HOVER, /*component_name=*/"mouse-input-view"); // Flutter will scale the count of ticks to pixel. EXPECT_GT(event_2.wheel_x_physical_pixel(), 0); EXPECT_EQ(event_2.wheel_y_physical_pixel(), 0); auto event_3 = mouse_input_listener()->PopEvent(); VerifyEvent( event_3, /*expected_x=*/initial_x, /*expected_y=*/initial_y, /*expected_buttons=*/{}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::HOVER, /*component_name=*/"mouse-input-view"); // Flutter will scale the count of ticks to pixel. EXPECT_GT(event_3.wheel_x_physical_pixel(), 0); EXPECT_EQ(event_3.wheel_y_physical_pixel(), 0); } TEST_P(MouseInputTest, DISABLED_FlutterMouseWheel) { LaunchClient(); double initial_x = static_cast<double>(display_width()) / 2.f + 1; double initial_y = static_cast<double>(display_height()) / 2.f + 2; // TODO(fxbug.dev/103098): Send a mouse move as the first event to workaround. SimulateMouseEvent(/* pressed_buttons = */ {}, /* movement_x = */ 1, /* movement_y = */ 2); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); auto event_add = mouse_input_listener()->PopEvent(); VerifyEvent(event_add, /*expected_x=*/initial_x, /*expected_y=*/initial_y, /*expected_buttons=*/{}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, /*component_name=*/"mouse-input-view"); SimulateMouseScroll(/* pressed_buttons = */ {}, /* scroll_x = */ 1, /* scroll_y = */ 0); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); auto event_wheel_h = mouse_input_listener()->PopEvent(); VerifyEvent( event_wheel_h, /*expected_x=*/initial_x, /*expected_y=*/initial_y, /*expected_buttons=*/{}, /*expected_phase=*/fuchsia::ui::test::input::MouseEventPhase::HOVER, /*component_name=*/"mouse-input-view"); // Flutter will scale the count of ticks to pixel. EXPECT_GT(event_wheel_h.wheel_x_physical_pixel(), 0); EXPECT_EQ(event_wheel_h.wheel_y_physical_pixel(), 0); SimulateMouseScroll(/* pressed_buttons = */ {}, /* scroll_x = */ 0, /* scroll_y = */ 1); RunLoopUntil( [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); auto event_wheel_v = mouse_input_listener()->PopEvent(); VerifyEvent( event_wheel_v, /*expected_x=*/initial_x, /*expected_y=*/initial_y, /*expected_buttons=*/{}, /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::HOVER, /*component_name=*/"mouse-input-view"); // Flutter will scale the count of ticks to pixel. EXPECT_LT(event_wheel_v.wheel_y_physical_pixel(), 0); EXPECT_EQ(event_wheel_v.wheel_x_physical_pixel(), 0); } } // namespace } // namespace mouse_input_test::testing
engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-test.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-test.cc", "repo_id": "engine", "token_count": 9453 }
350
// 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. #include "pointer_event_utility.h" namespace flutter_runner::testing { using fup_EventPhase = fuchsia::ui::pointer::EventPhase; using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; using fup_TouchIxnId = fuchsia::ui::pointer::TouchInteractionId; using fup_TouchIxnResult = fuchsia::ui::pointer::TouchInteractionResult; using fup_TouchPointerSample = fuchsia::ui::pointer::TouchPointerSample; using fup_ViewParameters = fuchsia::ui::pointer::ViewParameters; using fup_MouseEvent = fuchsia::ui::pointer::MouseEvent; using fup_MousePointerSample = fuchsia::ui::pointer::MousePointerSample; using fup_MouseDeviceInfo = fuchsia::ui::pointer::MouseDeviceInfo; namespace { fup_ViewParameters CreateViewParameters( std::array<std::array<float, 2>, 2> view, std::array<std::array<float, 2>, 2> viewport, std::array<float, 9> transform) { fup_ViewParameters params; fuchsia::ui::pointer::Rectangle view_rect; view_rect.min = view[0]; view_rect.max = view[1]; params.view = view_rect; fuchsia::ui::pointer::Rectangle viewport_rect; viewport_rect.min = viewport[0]; viewport_rect.max = viewport[1]; params.viewport = viewport_rect; params.viewport_to_view_transform = transform; return params; } } // namespace TouchEventBuilder TouchEventBuilder::New() { return TouchEventBuilder(); } TouchEventBuilder& TouchEventBuilder::AddTime(zx_time_t time) { time_ = time; return *this; } TouchEventBuilder& TouchEventBuilder::AddSample(fup_TouchIxnId id, fup_EventPhase phase, std::array<float, 2> position) { sample_ = std::make_optional<fup_TouchPointerSample>(); sample_->set_interaction(id); sample_->set_phase(phase); sample_->set_position_in_viewport(position); return *this; } TouchEventBuilder& TouchEventBuilder::AddViewParameters( std::array<std::array<float, 2>, 2> view, std::array<std::array<float, 2>, 2> viewport, std::array<float, 9> transform) { params_ = CreateViewParameters(std::move(view), std::move(viewport), std::move(transform)); return *this; } TouchEventBuilder& TouchEventBuilder::AddResult(fup_TouchIxnResult result) { result_ = result; return *this; } fup_TouchEvent TouchEventBuilder::Build() { fup_TouchEvent event; if (time_) { event.set_timestamp(time_.value()); } if (params_) { event.set_view_parameters(std::move(params_.value())); } if (sample_) { event.set_pointer_sample(std::move(sample_.value())); } if (result_) { event.set_interaction_result(std::move(result_.value())); } return event; } std::vector<fup_TouchEvent> TouchEventBuilder::BuildAsVector() { std::vector<fup_TouchEvent> events; events.emplace_back(Build()); return events; } MouseEventBuilder MouseEventBuilder::New() { return MouseEventBuilder(); } MouseEventBuilder& MouseEventBuilder::AddTime(zx_time_t time) { time_ = time; return *this; } MouseEventBuilder& MouseEventBuilder::AddSample( uint32_t id, std::array<float, 2> position, std::vector<uint8_t> pressed_buttons, std::array<int64_t, 2> scroll, std::array<int64_t, 2> scroll_in_physical_pixel, bool is_precision_scroll) { sample_ = std::make_optional<fup_MousePointerSample>(); sample_->set_device_id(id); if (!pressed_buttons.empty()) { sample_->set_pressed_buttons(pressed_buttons); } sample_->set_position_in_viewport(position); if (scroll[0] != 0) { sample_->set_scroll_h(scroll[0]); } if (scroll[1] != 0) { sample_->set_scroll_v(scroll[1]); } if (scroll_in_physical_pixel[0] != 0) { sample_->set_scroll_h_physical_pixel(scroll_in_physical_pixel[0]); } if (scroll_in_physical_pixel[1] != 0) { sample_->set_scroll_v_physical_pixel(scroll_in_physical_pixel[1]); } sample_->set_is_precision_scroll(is_precision_scroll); return *this; } MouseEventBuilder& MouseEventBuilder::AddViewParameters( std::array<std::array<float, 2>, 2> view, std::array<std::array<float, 2>, 2> viewport, std::array<float, 9> transform) { params_ = CreateViewParameters(std::move(view), std::move(viewport), std::move(transform)); return *this; } MouseEventBuilder& MouseEventBuilder::AddMouseDeviceInfo( uint32_t id, std::vector<uint8_t> buttons) { device_info_ = std::make_optional<fup_MouseDeviceInfo>(); device_info_->set_id(id); device_info_->set_buttons(buttons); return *this; } fup_MouseEvent MouseEventBuilder::Build() { fup_MouseEvent event; if (time_) { event.set_timestamp(time_.value()); } if (params_) { event.set_view_parameters(std::move(params_.value())); } if (sample_) { event.set_pointer_sample(std::move(sample_.value())); } if (device_info_) { event.set_device_info(std::move(device_info_.value())); } event.set_trace_flow_id(123); return event; } std::vector<fup_MouseEvent> MouseEventBuilder::BuildAsVector() { std::vector<fup_MouseEvent> events; events.emplace_back(Build()); return events; } } // namespace flutter_runner::testing
engine/shell/platform/fuchsia/flutter/tests/pointer_event_utility.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/pointer_event_utility.cc", "repo_id": "engine", "token_count": 2030 }
351
// 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. #include "vulkan_surface_pool.h" #include <lib/fdio/directory.h> #include <lib/zx/process.h> #include <algorithm> #include <string> #include "flutter/fml/trace_event.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter_runner { static std::string GetCurrentProcessName() { char name[ZX_MAX_NAME_LEN]; zx_status_t status = zx::process::self()->get_property(ZX_PROP_NAME, name, sizeof(name)); return status == ZX_OK ? std::string(name) : std::string(); } static zx_koid_t GetCurrentProcessId() { zx_info_handle_basic_t info; zx_status_t status = zx::process::self()->get_info( ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); return status == ZX_OK ? info.koid : ZX_KOID_INVALID; } VulkanSurfacePool::VulkanSurfacePool(vulkan::VulkanProvider& vulkan_provider, sk_sp<GrDirectContext> context) : vulkan_provider_(vulkan_provider), context_(std::move(context)) { FML_CHECK(context_ != nullptr); zx_status_t status = fdio_service_connect( "/svc/fuchsia.sysmem.Allocator", sysmem_allocator_.NewRequest().TakeChannel().release()); sysmem_allocator_->SetDebugClientInfo(GetCurrentProcessName(), GetCurrentProcessId()); FML_DCHECK(status == ZX_OK); status = fdio_service_connect( "/svc/fuchsia.ui.composition.Allocator", flatland_allocator_.NewRequest().TakeChannel().release()); FML_DCHECK(status == ZX_OK); } VulkanSurfacePool::~VulkanSurfacePool() {} std::unique_ptr<VulkanSurface> VulkanSurfacePool::AcquireSurface( const SkISize& size) { auto surface = GetCachedOrCreateSurface(size); if (surface == nullptr) { FML_LOG(ERROR) << "VulkanSurfaceProducer: Could not acquire surface"; return nullptr; } if (!surface->FlushSessionAcquireAndReleaseEvents()) { FML_LOG(ERROR) << "VulkanSurfaceProducer: Could not flush acquire/release " "events for buffer."; return nullptr; } return surface; } std::unique_ptr<VulkanSurface> VulkanSurfacePool::GetCachedOrCreateSurface( const SkISize& size) { TRACE_EVENT2("flutter", "VulkanSurfacePool::GetCachedOrCreateSurface", "width", size.width(), "height", size.height()); // First try to find a surface that exactly matches |size|. { auto exact_match_it = std::find_if(available_surfaces_.begin(), available_surfaces_.end(), [&size](const auto& surface) { return surface->IsValid() && surface->GetSize() == size; }); if (exact_match_it != available_surfaces_.end()) { auto acquired_surface = std::move(*exact_match_it); available_surfaces_.erase(exact_match_it); TRACE_EVENT_INSTANT0("flutter", "Exact match found"); return acquired_surface; } } return CreateSurface(size); } void VulkanSurfacePool::SubmitSurface( std::unique_ptr<SurfaceProducerSurface> p_surface) { TRACE_EVENT0("flutter", "VulkanSurfacePool::SubmitSurface"); // This cast is safe because |VulkanSurface| is the only implementation of // |SurfaceProducerSurface| for Flutter on Fuchsia. Additionally, it is // required, because we need to access |VulkanSurface| specific information // of the surface (such as the amount of VkDeviceMemory it contains). auto vulkan_surface = std::unique_ptr<VulkanSurface>( static_cast<VulkanSurface*>(p_surface.release())); if (!vulkan_surface) { return; } uintptr_t surface_key = reinterpret_cast<uintptr_t>(vulkan_surface.get()); auto insert_iterator = pending_surfaces_.insert(std::make_pair( surface_key, // key std::move(vulkan_surface) // value )); if (insert_iterator.second) { insert_iterator.first->second->SignalWritesFinished(std::bind( &VulkanSurfacePool::RecyclePendingSurface, this, surface_key)); } } std::unique_ptr<VulkanSurface> VulkanSurfacePool::CreateSurface( const SkISize& size) { TRACE_EVENT2("flutter", "VulkanSurfacePool::CreateSurface", "width", size.width(), "height", size.height()); auto surface = std::make_unique<VulkanSurface>( vulkan_provider_, sysmem_allocator_, flatland_allocator_, context_, size); if (!surface->IsValid()) { FML_LOG(ERROR) << "VulkanSurfaceProducer: Created surface is invalid"; return nullptr; } trace_surfaces_created_++; return surface; } void VulkanSurfacePool::RecyclePendingSurface(uintptr_t surface_key) { // Before we do anything, we must clear the surface from the collection of // pending surfaces. auto found_in_pending = pending_surfaces_.find(surface_key); if (found_in_pending == pending_surfaces_.end()) { return; } // Grab a hold of the surface to recycle and clear the entry in the pending // surfaces collection. auto surface_to_recycle = std::move(found_in_pending->second); pending_surfaces_.erase(found_in_pending); RecycleSurface(std::move(surface_to_recycle)); } void VulkanSurfacePool::RecycleSurface(std::unique_ptr<VulkanSurface> surface) { // The surface may have become invalid (for example it the fences could // not be reset). if (!surface->IsValid()) { return; } TRACE_EVENT0("flutter", "VulkanSurfacePool::RecycleSurface"); // Recycle the buffer by putting it in the list of available surfaces if we // have not reached the maximum amount of cached surfaces. if (available_surfaces_.size() < kMaxSurfaces) { available_surfaces_.push_back(std::move(surface)); } else { TRACE_EVENT_INSTANT0("flutter", "Too many surfaces in pool, dropping"); } TraceStats(); } void VulkanSurfacePool::AgeAndCollectOldBuffers() { TRACE_EVENT0("flutter", "VulkanSurfacePool::AgeAndCollectOldBuffers"); // Remove all surfaces that are no longer valid or are too old. size_t size_before = available_surfaces_.size(); available_surfaces_.erase( std::remove_if(available_surfaces_.begin(), available_surfaces_.end(), [&](auto& surface) { return !surface->IsValid() || surface->AdvanceAndGetAge() >= kMaxSurfaceAge; }), available_surfaces_.end()); TRACE_EVENT1("flutter", "AgeAndCollect", "aged surfaces", (size_before - available_surfaces_.size())); // Look for a surface that has both a larger |VkDeviceMemory| allocation // than is necessary for its |VkImage|, and has a stable size history. auto surface_to_remove_it = std::find_if( available_surfaces_.begin(), available_surfaces_.end(), [](const auto& surface) { return surface->IsOversized() && surface->HasStableSizeHistory(); }); // If we found such a surface, then destroy it and cache a new one that only // uses a necessary amount of memory. if (surface_to_remove_it != available_surfaces_.end()) { TRACE_EVENT_INSTANT0("flutter", "replacing surface with smaller one"); auto size = (*surface_to_remove_it)->GetSize(); available_surfaces_.erase(surface_to_remove_it); auto new_surface = CreateSurface(size); if (new_surface != nullptr) { available_surfaces_.push_back(std::move(new_surface)); } else { FML_LOG(ERROR) << "VulkanSurfaceProducer: Failed to create a new shrunk surface"; } } TraceStats(); } void VulkanSurfacePool::ShrinkToFit() { TRACE_EVENT0("flutter", "VulkanSurfacePool::ShrinkToFit"); // Reset all oversized surfaces in |available_surfaces_| so that the old // surfaces and new surfaces don't exist at the same time at any point, // reducing our peak memory footprint. std::vector<SkISize> sizes_to_recreate; for (auto& surface : available_surfaces_) { if (surface->IsOversized()) { sizes_to_recreate.push_back(surface->GetSize()); surface.reset(); } } available_surfaces_.erase(std::remove(available_surfaces_.begin(), available_surfaces_.end(), nullptr), available_surfaces_.end()); for (const auto& size : sizes_to_recreate) { auto surface = CreateSurface(size); if (surface != nullptr) { available_surfaces_.push_back(std::move(surface)); } else { FML_LOG(ERROR) << "VulkanSurfaceProducer: Failed to create resized surface"; } } TraceStats(); } void VulkanSurfacePool::TraceStats() { // Resources held in cached buffers. size_t cached_surfaces_bytes = 0; for (const auto& surface : available_surfaces_) { cached_surfaces_bytes += surface->GetAllocationSize(); } // Resources held by Skia. int skia_resources = 0; size_t skia_bytes = 0; context_->getResourceCacheUsage(&skia_resources, &skia_bytes); const size_t skia_cache_purgeable = context_->getResourceCachePurgeableBytes(); TRACE_COUNTER("flutter", "SurfacePoolCounts", 0u, "CachedCount", available_surfaces_.size(), // "Created", trace_surfaces_created_, // "Reused", trace_surfaces_reused_, // "PendingInCompositor", pending_surfaces_.size(), // "Retained", 0, // "SkiaCacheResources", skia_resources // ); TRACE_COUNTER("flutter", "SurfacePoolBytes", 0u, // "CachedBytes", cached_surfaces_bytes, // "RetainedBytes", 0, // "SkiaCacheBytes", skia_bytes, // "SkiaCachePurgeable", skia_cache_purgeable // ); // Reset per present/frame stats. trace_surfaces_created_ = 0; trace_surfaces_reused_ = 0; } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/vulkan_surface_pool.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/vulkan_surface_pool.cc", "repo_id": "engine", "token_count": 3909 }
352
// 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. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_INLINES_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_INLINES_H_ namespace dart_utils { template <size_t SIZE, typename T> inline size_t ArraySize(T (&array)[SIZE]) { return SIZE; } } // namespace dart_utils #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_INLINES_H_
engine/shell/platform/fuchsia/runtime/dart/utils/inlines.h/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/inlines.h", "repo_id": "engine", "token_count": 206 }
353