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 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
class SurfaceScene implements ui.Scene {
/// This class is created by the engine, and should not be instantiated
/// or extended directly.
///
/// To create a Scene object, use a [SceneBuilder].
SurfaceScene(this.webOnlyRootElement, {
required this.timingRecorder,
});
final DomElement? webOnlyRootElement;
final FrameTimingRecorder? timingRecorder;
/// Creates a raster image representation of the current state of the scene.
/// This is a slow operation that is performed on a background thread.
@override
Future<ui.Image> toImage(int width, int height) {
throw UnsupportedError('toImage is not supported on the Web');
}
@override
ui.Image toImageSync(int width, int height) {
throw UnsupportedError('toImageSync is not supported on the Web');
}
/// Releases the resources used by this scene.
///
/// After calling this function, the scene is cannot be used further.
@override
void dispose() {}
}
/// A surface that creates a DOM element for whole app.
class PersistedScene extends PersistedContainerSurface {
PersistedScene(PersistedScene? super.oldLayer) {
transform = Matrix4.identity();
}
@override
void recomputeTransformAndClip() {
// Must be the true DPR from the browser, nothing overridable.
// See: https://github.com/flutter/flutter/issues/143124
final double browserDpr = EngineFlutterDisplay.instance.browserDevicePixelRatio;
// The scene clip is the size of the entire window **in Logical pixels**.
//
// Even though the majority of the engine uses `physicalSize`, there are some
// bits (like the HTML renderer, or dynamic view sizing) that are implemented
// using CSS, and CSS operates in logical pixels.
//
// See also: [EngineFlutterView.resize].
final ui.Size bounds = window.physicalSize / browserDpr;
localClipBounds = ui.Rect.fromLTRB(0, 0, bounds.width, bounds.height);
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.identity();
@override
DomElement createElement() {
return defaultCreateElement('flt-scene');
}
@override
void apply() {}
}
| engine/lib/web_ui/lib/src/engine/html/scene.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html/scene.dart",
"repo_id": "engine",
"token_count": 770
} | 400 |
// 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.
@JS()
library js_promise;
import 'dart:js_interop';
import 'package:js/js_util.dart' as js_util;
import '../util.dart';
extension CallExtension on JSFunction {
external void call(JSAny? this_, JSAny? object);
}
@JS('Promise')
external JSAny get _promiseConstructor;
JSPromise<JSAny?> createPromise(JSFunction executor) =>
js_util.callConstructor(
_promiseConstructor,
<Object>[executor],
);
JSPromise<JSAny?> futureToPromise<T extends JSAny?>(Future<T> future) {
return createPromise((JSFunction resolver, JSFunction rejecter) {
future.then(
(T value) => resolver.call(null, value),
onError: (Object? error) {
printWarning('Rejecting promise with error: $error');
rejecter.call(null, null);
});
}.toJS);
}
| engine/lib/web_ui/lib/src/engine/js_interop/js_promise.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/js_interop/js_promise.dart",
"repo_id": "engine",
"token_count": 344
} | 401 |
// 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.
// TODO(yjbanov): The code in this file was temporarily moved to lib/web_ui/lib/ui.dart
// during the NNBD migration so that `dart:ui` does not have to export
// `dart:_engine`. NNBD does not allow exported non-migrated libraries
// from migrated libraries.
| engine/lib/web_ui/lib/src/engine/platform_views.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/platform_views.dart",
"repo_id": "engine",
"token_count": 166
} | 402 |
// 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.
export 'semantics/accessibility.dart';
export 'semantics/checkable.dart';
export 'semantics/focusable.dart';
export 'semantics/image.dart';
export 'semantics/incrementable.dart';
export 'semantics/label_and_value.dart';
export 'semantics/link.dart';
export 'semantics/live_region.dart';
export 'semantics/platform_view.dart';
export 'semantics/scrollable.dart';
export 'semantics/semantics.dart';
export 'semantics/semantics_helper.dart';
export 'semantics/tappable.dart';
export 'semantics/text_field.dart';
| engine/lib/web_ui/lib/src/engine/semantics.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/semantics.dart",
"repo_id": "engine",
"token_count": 219
} | 403 |
// 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:ffi';
import 'dart:js_interop';
import 'package:ui/src/engine.dart';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
import 'package:ui/ui.dart' as ui;
const int _kSoftLineBreak = 0;
const int _kHardLineBreak = 100;
class SkwasmLineMetrics extends SkwasmObjectWrapper<RawLineMetrics> implements ui.LineMetrics {
factory SkwasmLineMetrics({
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._(lineMetricsCreate(
hardBreak,
ascent,
descent,
unscaledAscent,
height,
width,
left,
baseline,
lineNumber,
));
SkwasmLineMetrics._(LineMetricsHandle handle) : super(handle, _registry);
static final SkwasmFinalizationRegistry<RawLineMetrics> _registry =
SkwasmFinalizationRegistry<RawLineMetrics>(lineMetricsDispose);
@override
bool get hardBreak => lineMetricsGetHardBreak(handle);
@override
double get ascent => lineMetricsGetAscent(handle);
@override
double get descent => lineMetricsGetDescent(handle);
@override
double get unscaledAscent => lineMetricsGetUnscaledAscent(handle);
@override
double get height => lineMetricsGetHeight(handle);
@override
double get width => lineMetricsGetWidth(handle);
@override
double get left => lineMetricsGetLeft(handle);
@override
double get baseline => lineMetricsGetBaseline(handle);
@override
int get lineNumber => lineMetricsGetLineNumber(handle);
}
class SkwasmParagraph extends SkwasmObjectWrapper<RawParagraph> implements ui.Paragraph {
SkwasmParagraph(ParagraphHandle handle) : super(handle, _registry);
static final SkwasmFinalizationRegistry<RawParagraph> _registry =
SkwasmFinalizationRegistry<RawParagraph>(paragraphDispose);
bool _hasCheckedForMissingCodePoints = false;
@override
double get width => paragraphGetWidth(handle);
@override
double get height => paragraphGetHeight(handle);
@override
double get longestLine => paragraphGetLongestLine(handle);
@override
double get minIntrinsicWidth => paragraphGetMinIntrinsicWidth(handle);
@override
double get maxIntrinsicWidth => paragraphGetMaxIntrinsicWidth(handle);
@override
double get alphabeticBaseline => paragraphGetAlphabeticBaseline(handle);
@override
double get ideographicBaseline => paragraphGetIdeographicBaseline(handle);
@override
bool get didExceedMaxLines => paragraphGetDidExceedMaxLines(handle);
@override
int get numberOfLines => paragraphGetLineCount(handle);
@override
int? getLineNumberAt(int codeUnitOffset) {
final int lineNumber = paragraphGetLineNumberAt(handle, codeUnitOffset);
return lineNumber >= 0 ? lineNumber : null;
}
@override
void layout(ui.ParagraphConstraints constraints) {
paragraphLayout(handle, constraints.width);
if (!_hasCheckedForMissingCodePoints) {
_hasCheckedForMissingCodePoints = true;
final int missingCodePointCount = paragraphGetUnresolvedCodePoints(handle, nullptr, 0);
if (missingCodePointCount > 0) {
withStackScope((StackScope scope) {
final Pointer<Uint32> codePointBuffer = scope.allocUint32Array(missingCodePointCount);
final int returnedCodePointCount = paragraphGetUnresolvedCodePoints(
handle,
codePointBuffer,
missingCodePointCount
);
assert(missingCodePointCount == returnedCodePointCount);
renderer.fontCollection.fontFallbackManager!.addMissingCodePoints(
List<int>.generate(
missingCodePointCount,
(int index) => codePointBuffer[index]
)
);
});
}
}
}
List<ui.TextBox> _convertTextBoxList(TextBoxListHandle listHandle) {
final int length = textBoxListGetLength(listHandle);
return withStackScope((StackScope scope) {
final RawRect tempRect = scope.allocFloatArray(4);
return List<ui.TextBox>.generate(length, (int index) {
final int textDirectionIndex =
textBoxListGetBoxAtIndex(listHandle, index, tempRect);
return ui.TextBox.fromLTRBD(
tempRect[0],
tempRect[1],
tempRect[2],
tempRect[3],
ui.TextDirection.values[textDirectionIndex],
);
});
});
}
@override
List<ui.TextBox> getBoxesForRange(
int start,
int end, {
ui.BoxHeightStyle boxHeightStyle = ui.BoxHeightStyle.tight,
ui.BoxWidthStyle boxWidthStyle = ui.BoxWidthStyle.tight
}) {
final TextBoxListHandle listHandle = paragraphGetBoxesForRange(
handle,
start,
end,
boxHeightStyle.index,
boxWidthStyle.index
);
final List<ui.TextBox> boxes = _convertTextBoxList(listHandle);
textBoxListDispose(listHandle);
return boxes;
}
@override
ui.TextPosition getPositionForOffset(ui.Offset offset) => withStackScope((StackScope scope) {
final Pointer<Int32> outAffinity = scope.allocInt32Array(1);
final int position = paragraphGetPositionForOffset(
handle,
offset.dx,
offset.dy,
outAffinity
);
return ui.TextPosition(
offset: position,
affinity: ui.TextAffinity.values[outAffinity[0]],
);
});
@override
ui.GlyphInfo? getGlyphInfoAt(int codeUnitOffset) {
return withStackScope((StackScope scope) {
final Pointer<Float> outRect = scope.allocFloatArray(4);
final Pointer<Uint32> outRange = scope.allocUint32Array(2);
final Pointer<Bool> outBooleanFlags = scope.allocBoolArray(1);
return paragraphGetGlyphInfoAt(handle, codeUnitOffset, outRect, outRange, outBooleanFlags)
? ui.GlyphInfo(
scope.convertRectFromNative(outRect),
ui.TextRange(start: outRange[0], end: outRange[1]),
outBooleanFlags[0] ? ui.TextDirection.ltr : ui.TextDirection.rtl,
)
: null;
});
}
@override
ui.GlyphInfo? getClosestGlyphInfoForOffset(ui.Offset offset) {
return withStackScope((StackScope scope) {
final Pointer<Float> outRect = scope.allocFloatArray(4);
final Pointer<Uint32> outRange = scope.allocUint32Array(2);
final Pointer<Bool> outBooleanFlags = scope.allocBoolArray(1);
return paragraphGetClosestGlyphInfoAtCoordinate(handle, offset.dx, offset.dy, outRect, outRange, outBooleanFlags)
? ui.GlyphInfo(
scope.convertRectFromNative(outRect),
ui.TextRange(start: outRange[0], end: outRange[1]),
outBooleanFlags[0] ? ui.TextDirection.ltr : ui.TextDirection.rtl,
)
: null;
});
}
@override
ui.TextRange getWordBoundary(ui.TextPosition position) => withStackScope((StackScope scope) {
final Pointer<Int32> outRange = scope.allocInt32Array(2);
paragraphGetWordBoundary(handle, position.offset, outRange);
return ui.TextRange(start: outRange[0], end: outRange[1]);
});
@override
ui.TextRange getLineBoundary(ui.TextPosition position) {
final int lineNumber = paragraphGetLineNumberAt(handle, position.offset);
final LineMetricsHandle metricsHandle =
paragraphGetLineMetricsAtIndex(handle, lineNumber);
final ui.TextRange range = ui.TextRange(
start: lineMetricsGetStartIndex(metricsHandle),
end: lineMetricsGetEndIndex(metricsHandle),
);
lineMetricsDispose(metricsHandle);
return range;
}
@override
List<ui.TextBox> getBoxesForPlaceholders() {
final TextBoxListHandle listHandle = paragraphGetBoxesForPlaceholders(handle);
final List<ui.TextBox> boxes = _convertTextBoxList(listHandle);
textBoxListDispose(listHandle);
return boxes;
}
@override
List<SkwasmLineMetrics> computeLineMetrics() {
final int lineCount = paragraphGetLineCount(handle);
return List<SkwasmLineMetrics>.generate(lineCount,
(int index) => SkwasmLineMetrics._(paragraphGetLineMetricsAtIndex(handle, index))
);
}
@override
ui.LineMetrics? getLineMetricsAt(int index) {
final LineMetricsHandle lineMetrics = paragraphGetLineMetricsAtIndex(handle, index);
return lineMetrics != nullptr ? SkwasmLineMetrics._(lineMetrics) : null;
}
}
void withScopedFontList(
List<String> fontFamilies,
void Function(Pointer<SkStringHandle>, int) callback) {
withStackScope((StackScope scope) {
final Pointer<SkStringHandle> familiesPtr =
scope.allocPointerArray(fontFamilies.length).cast<SkStringHandle>();
int nativeIndex = 0;
for (int i = 0; i < fontFamilies.length; i++) {
familiesPtr[nativeIndex] = skStringFromDartString(fontFamilies[i]);
nativeIndex++;
}
callback(familiesPtr, fontFamilies.length);
for (int i = 0; i < fontFamilies.length; i++) {
skStringFree(familiesPtr[i]);
}
});
}
class SkwasmNativeTextStyle extends SkwasmObjectWrapper<RawTextStyle> {
SkwasmNativeTextStyle(TextStyleHandle handle) : super(handle, _registry);
factory SkwasmNativeTextStyle.defaultTextStyle() => SkwasmNativeTextStyle(textStyleCreate());
static final SkwasmFinalizationRegistry<RawTextStyle> _registry =
SkwasmFinalizationRegistry<RawTextStyle>(textStyleDispose);
SkwasmNativeTextStyle copy() {
return SkwasmNativeTextStyle(textStyleCopy(handle));
}
}
class SkwasmTextStyle implements ui.TextStyle {
SkwasmTextStyle({
this.color,
this.decoration,
this.decorationColor,
this.decorationStyle,
this.decorationThickness,
this.fontWeight,
this.fontStyle,
this.textBaseline,
this.fontFamily,
this.fontFamilyFallback,
this.fontSize,
this.letterSpacing,
this.wordSpacing,
this.height,
this.leadingDistribution,
this.locale,
this.background,
this.foreground,
this.shadows,
this.fontFeatures,
this.fontVariations,
}) : assert(
color == null || foreground == null,
'Cannot provide both a color and a foreground\n'
'The color argument is just a shorthand for "foreground: Paint()..color = color".',
);
void applyToNative(SkwasmNativeTextStyle style) {
final TextStyleHandle handle = style.handle;
if (color != null) {
textStyleSetColor(handle, color!.value);
}
if (decoration != null) {
textStyleSetDecoration(handle, decoration!.maskValue);
}
if (decorationColor != null) {
textStyleSetDecorationColor(handle, decorationColor!.value);
}
if (decorationStyle != null) {
textStyleSetDecorationStyle(handle, decorationStyle!.index);
}
if (decorationThickness != null) {
textStyleSetDecorationThickness(handle, decorationThickness!);
}
if (fontWeight != null || fontStyle != null) {
textStyleSetFontStyle(
handle,
(fontWeight ?? ui.FontWeight.normal).value,
(fontStyle ?? ui.FontStyle.normal).index
);
}
if (textBaseline != null) {
textStyleSetTextBaseline(handle, textBaseline!.index);
}
final List<String> effectiveFontFamilies = fontFamilies;
if (effectiveFontFamilies.isNotEmpty) {
withScopedFontList(effectiveFontFamilies,
(Pointer<SkStringHandle> families, int count) =>
textStyleAddFontFamilies(handle, families, count));
}
if (fontSize != null) {
textStyleSetFontSize(handle, fontSize!);
}
if (letterSpacing != null) {
textStyleSetLetterSpacing(handle, letterSpacing!);
}
if (wordSpacing != null) {
textStyleSetWordSpacing(handle, wordSpacing!);
}
if (height != null) {
textStyleSetHeight(handle, height!);
}
if (leadingDistribution != null) {
textStyleSetHalfLeading(
handle,
leadingDistribution == ui.TextLeadingDistribution.even
);
}
if (locale != null) {
final SkStringHandle localeHandle =
skStringFromDartString(locale!.toLanguageTag());
textStyleSetLocale(handle, localeHandle);
skStringFree(localeHandle);
}
if (background != null) {
textStyleSetBackground(handle, (background! as SkwasmPaint).handle);
}
if (foreground != null) {
textStyleSetForeground(handle, (foreground! as SkwasmPaint).handle);
}
if (shadows != null) {
for (final ui.Shadow shadow in shadows!) {
textStyleAddShadow(
handle,
shadow.color.value,
shadow.offset.dx,
shadow.offset.dy,
shadow.blurSigma,
);
}
}
if (fontFeatures != null) {
for (final ui.FontFeature feature in fontFeatures!) {
final SkStringHandle featureName = skStringFromDartString(feature.feature);
textStyleAddFontFeature(handle, featureName, feature.value);
skStringFree(featureName);
}
}
if (fontVariations != null && fontVariations!.isNotEmpty) {
final int variationCount = fontVariations!.length;
withStackScope((StackScope scope) {
final Pointer<Uint32> axisBuffer = scope.allocUint32Array(variationCount);
final Pointer<Float> valueBuffer = scope.allocFloatArray(variationCount);
for (int i = 0; i < variationCount; i++) {
final ui.FontVariation variation = fontVariations![i];
final String axis = variation.axis;
assert(axis.length == 4); // 4 byte code
final int axisNumber =
axis.codeUnitAt(0) << 24 |
axis.codeUnitAt(1) << 16 |
axis.codeUnitAt(2) << 8 |
axis.codeUnitAt(3);
axisBuffer[i] = axisNumber;
valueBuffer[i] = variation.value;
}
textStyleSetFontVariations(handle, axisBuffer, valueBuffer, variationCount);
});
}
}
List<String> get fontFamilies => <String>[
if (fontFamily != null) fontFamily!,
if (fontFamilyFallback != null) ...fontFamilyFallback!,
];
final ui.Color? color;
final ui.TextDecoration? decoration;
final ui.Color? decorationColor;
final ui.TextDecorationStyle? decorationStyle;
final double? decorationThickness;
final ui.FontWeight? fontWeight;
final ui.FontStyle? fontStyle;
final ui.TextBaseline? textBaseline;
final String? fontFamily;
final List<String>? fontFamilyFallback;
final double? fontSize;
final double? letterSpacing;
final double? wordSpacing;
final double? height;
final ui.TextLeadingDistribution? leadingDistribution;
final ui.Locale? locale;
final ui.Paint? background;
final ui.Paint? foreground;
final List<ui.Shadow>? shadows;
final List<ui.FontFeature>? fontFeatures;
final List<ui.FontVariation>? fontVariations;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is SkwasmTextStyle
&& other.color == color
&& other.decoration == decoration
&& other.decorationColor == decorationColor
&& other.decorationStyle == decorationStyle
&& other.fontWeight == fontWeight
&& other.fontStyle == fontStyle
&& other.textBaseline == textBaseline
&& other.leadingDistribution == leadingDistribution
&& other.fontFamily == fontFamily
&& other.fontSize == fontSize
&& other.letterSpacing == letterSpacing
&& other.wordSpacing == wordSpacing
&& other.height == height
&& other.decorationThickness == decorationThickness
&& other.locale == locale
&& other.background == background
&& other.foreground == foreground
&& listEquals<ui.Shadow>(other.shadows, shadows)
&& listEquals<String>(other.fontFamilyFallback, fontFamilyFallback)
&& listEquals<ui.FontFeature>(other.fontFeatures, fontFeatures)
&& listEquals<ui.FontVariation>(other.fontVariations, fontVariations);
}
@override
int get hashCode {
final List<ui.Shadow>? shadows = this.shadows;
final List<ui.FontFeature>? fontFeatures = this.fontFeatures;
final List<ui.FontVariation>? fontVariations = this.fontVariations;
final List<String>? fontFamilyFallback = this.fontFamilyFallback;
return Object.hash(
color,
decoration,
decorationColor,
decorationStyle,
fontWeight,
fontStyle,
textBaseline,
leadingDistribution,
fontFamily,
fontFamilyFallback == null ? null : Object.hashAll(fontFamilyFallback),
fontSize,
letterSpacing,
wordSpacing,
height,
locale,
background,
foreground,
shadows == null ? null : Object.hashAll(shadows),
decorationThickness,
// Object.hash goes up to 20 arguments, but we have 21
Object.hash(
fontFeatures == null ? null : Object.hashAll(fontFeatures),
fontVariations == null ? null : Object.hashAll(fontVariations),
)
);
}
@override
String toString() {
String result = super.toString();
assert(() {
final List<String>? fontFamilyFallback = this.fontFamilyFallback;
final double? fontSize = this.fontSize;
final double? height = this.height;
result = 'TextStyle('
'color: ${color ?? "unspecified"}, '
'decoration: ${decoration ?? "unspecified"}, '
'decorationColor: ${decorationColor ?? "unspecified"}, '
'decorationStyle: ${decorationStyle ?? "unspecified"}, '
'decorationThickness: ${decorationThickness ?? "unspecified"}, '
'fontWeight: ${fontWeight ?? "unspecified"}, '
'fontStyle: ${fontStyle ?? "unspecified"}, '
'textBaseline: ${textBaseline ?? "unspecified"}, '
'fontFamily: ${fontFamily ?? "unspecified"}, '
'fontFamilyFallback: ${fontFamilyFallback != null && fontFamilyFallback.isNotEmpty ? fontFamilyFallback : "unspecified"}, '
'fontSize: ${fontSize != null ? fontSize.toStringAsFixed(1) : "unspecified"}, '
'letterSpacing: ${letterSpacing != null ? "${letterSpacing}x" : "unspecified"}, '
'wordSpacing: ${wordSpacing != null ? "${wordSpacing}x" : "unspecified"}, '
'height: ${height != null ? "${height.toStringAsFixed(1)}x" : "unspecified"}, '
'leadingDistribution: ${leadingDistribution ?? "unspecified"}, '
'locale: ${locale ?? "unspecified"}, '
'background: ${background ?? "unspecified"}, '
'foreground: ${foreground ?? "unspecified"}, '
'shadows: ${shadows ?? "unspecified"}, '
'fontFeatures: ${fontFeatures ?? "unspecified"}, '
'fontVariations: ${fontVariations ?? "unspecified"}'
')';
return true;
}());
return result;
}
}
final class SkwasmStrutStyle extends SkwasmObjectWrapper<RawStrutStyle> implements ui.StrutStyle {
factory SkwasmStrutStyle({
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? height,
double? leading,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
bool? forceStrutHeight,
ui.TextLeadingDistribution? leadingDistribution,
}) {
final StrutStyleHandle handle = strutStyleCreate();
if (fontFamily != null || fontFamilyFallback != null) {
final List<String> fontFamilies = <String>[
if (fontFamily != null) fontFamily,
if (fontFamilyFallback != null) ...fontFamilyFallback,
];
if (fontFamilies.isNotEmpty) {
withScopedFontList(fontFamilies,
(Pointer<SkStringHandle> families, int count) =>
strutStyleSetFontFamilies(handle, families, count));
}
}
if (fontSize != null) {
strutStyleSetFontSize(handle, fontSize);
}
if (height != null) {
strutStyleSetHeight(handle, height);
}
if (leadingDistribution != null) {
strutStyleSetHalfLeading(
handle,
leadingDistribution == ui.TextLeadingDistribution.even);
}
if (leading != null) {
strutStyleSetLeading(handle, leading);
}
if (fontWeight != null || fontStyle != null) {
fontWeight ??= ui.FontWeight.normal;
fontStyle ??= ui.FontStyle.normal;
strutStyleSetFontStyle(handle, fontWeight.value, fontStyle.index);
}
if (forceStrutHeight != null) {
strutStyleSetForceStrutHeight(handle, forceStrutHeight);
}
return SkwasmStrutStyle._(
handle,
fontFamily,
fontFamilyFallback,
fontSize,
height,
leadingDistribution,
leading,
fontWeight,
fontStyle,
forceStrutHeight,
);
}
SkwasmStrutStyle._(
StrutStyleHandle handle,
this._fontFamily,
this._fontFamilyFallback,
this._fontSize,
this._height,
this._leadingDistribution,
this._leading,
this._fontWeight,
this._fontStyle,
this._forceStrutHeight,
) : super(handle, _registry);
static final SkwasmFinalizationRegistry<RawStrutStyle> _registry =
SkwasmFinalizationRegistry<RawStrutStyle>(strutStyleDispose);
final String? _fontFamily;
final List<String>? _fontFamilyFallback;
final double? _fontSize;
final double? _height;
final double? _leading;
final ui.FontWeight? _fontWeight;
final ui.FontStyle? _fontStyle;
final bool? _forceStrutHeight;
final ui.TextLeadingDistribution? _leadingDistribution;
@override
bool operator ==(Object other) {
return other is SkwasmStrutStyle &&
other._fontFamily == _fontFamily &&
other._fontSize == _fontSize &&
other._height == _height &&
other._leading == _leading &&
other._leadingDistribution == _leadingDistribution &&
other._fontWeight == _fontWeight &&
other._fontStyle == _fontStyle &&
other._forceStrutHeight == _forceStrutHeight &&
listEquals<String>(other._fontFamilyFallback, _fontFamilyFallback);
}
@override
int get hashCode {
final List<String>? fontFamilyFallback = _fontFamilyFallback;
return Object.hash(
_fontFamily,
fontFamilyFallback != null ? Object.hashAll(fontFamilyFallback) : null,
_fontSize,
_height,
_leading,
_leadingDistribution,
_fontWeight,
_fontStyle,
_forceStrutHeight,
);
}
}
class SkwasmParagraphStyle extends SkwasmObjectWrapper<RawParagraphStyle> implements ui.ParagraphStyle {
factory SkwasmParagraphStyle({
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,
}) {
final ParagraphStyleHandle handle = paragraphStyleCreate();
if (textAlign != null) {
paragraphStyleSetTextAlign(handle, textAlign.index);
}
if (textDirection != null) {
paragraphStyleSetTextDirection(handle, textDirection.index);
}
if (maxLines != null) {
paragraphStyleSetMaxLines(handle, maxLines);
}
if (height != null) {
paragraphStyleSetHeight(handle, height);
}
if (textHeightBehavior != null) {
paragraphStyleSetTextHeightBehavior(
handle,
textHeightBehavior.applyHeightToFirstAscent,
textHeightBehavior.applyHeightToLastDescent,
);
}
if (ellipsis != null) {
final SkStringHandle ellipsisHandle = skStringFromDartString(ellipsis);
paragraphStyleSetEllipsis(handle, ellipsisHandle);
skStringFree(ellipsisHandle);
}
if (strutStyle != null) {
strutStyle as SkwasmStrutStyle;
paragraphStyleSetStrutStyle(handle, strutStyle.handle);
}
final SkwasmNativeTextStyle textStyle =
(renderer.fontCollection as SkwasmFontCollection).defaultTextStyle.copy();
final TextStyleHandle textStyleHandle = textStyle.handle;
if (fontFamily != null) {
withScopedFontList(<String>[fontFamily],
(Pointer<SkStringHandle> families, int count) =>
textStyleAddFontFamilies(textStyleHandle, families, count));
}
if (fontSize != null) {
textStyleSetFontSize(textStyleHandle, fontSize);
}
if (fontWeight != null || fontStyle != null) {
fontWeight ??= ui.FontWeight.normal;
fontStyle ??= ui.FontStyle.normal;
textStyleSetFontStyle(textStyleHandle, fontWeight.value, fontStyle.index);
}
if (textHeightBehavior != null) {
textStyleSetHalfLeading(
textStyleHandle,
textHeightBehavior.leadingDistribution == ui.TextLeadingDistribution.even,
);
}
if (locale != null) {
final SkStringHandle localeHandle =
skStringFromDartString(locale.toLanguageTag());
textStyleSetLocale(textStyleHandle, localeHandle);
skStringFree(localeHandle);
}
paragraphStyleSetTextStyle(handle, textStyleHandle);
paragraphStyleSetApplyRoundingHack(handle, false);
return SkwasmParagraphStyle._(
handle,
textStyle,
fontFamily,
textAlign,
textDirection,
fontWeight,
fontStyle,
maxLines,
fontFamily,
fontSize,
height,
textHeightBehavior,
strutStyle,
ellipsis,
locale,
);
}
SkwasmParagraphStyle._(
ParagraphStyleHandle handle,
this.textStyle,
this.defaultFontFamily,
this._textAlign,
this._textDirection,
this._fontWeight,
this._fontStyle,
this._maxLines,
this._fontFamily,
this._fontSize,
this._height,
this._textHeightBehavior,
this._strutStyle,
this._ellipsis,
this._locale,
) : super(handle, _registry);
static final SkwasmFinalizationRegistry<RawParagraphStyle> _registry =
SkwasmFinalizationRegistry<RawParagraphStyle>(paragraphStyleDispose);
final SkwasmNativeTextStyle textStyle;
final String? defaultFontFamily;
final ui.TextAlign? _textAlign;
final ui.TextDirection? _textDirection;
final ui.FontWeight? _fontWeight;
final ui.FontStyle? _fontStyle;
final int? _maxLines;
final String? _fontFamily;
final double? _fontSize;
final double? _height;
final ui.TextHeightBehavior? _textHeightBehavior;
final ui.StrutStyle? _strutStyle;
final String? _ellipsis;
final ui.Locale? _locale;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is SkwasmParagraphStyle &&
other._textAlign == _textAlign &&
other._textDirection == _textDirection &&
other._fontWeight == _fontWeight &&
other._fontStyle == _fontStyle &&
other._maxLines == _maxLines &&
other._fontFamily == _fontFamily &&
other._fontSize == _fontSize &&
other._height == _height &&
other._textHeightBehavior == _textHeightBehavior &&
other._strutStyle == _strutStyle &&
other._ellipsis == _ellipsis &&
other._locale == _locale;
}
@override
int get hashCode {
return Object.hash(
_textAlign,
_textDirection,
_fontWeight,
_fontStyle,
_maxLines,
_fontFamily,
_fontSize,
_height,
_textHeightBehavior,
_strutStyle,
_ellipsis,
_locale,
);
}
@override
String toString() {
String result = super.toString();
assert(() {
final double? fontSize = _fontSize;
final double? height = _height;
result = 'ParagraphStyle('
'textAlign: ${_textAlign ?? "unspecified"}, '
'textDirection: ${_textDirection ?? "unspecified"}, '
'fontWeight: ${_fontWeight ?? "unspecified"}, '
'fontStyle: ${_fontStyle ?? "unspecified"}, '
'maxLines: ${_maxLines ?? "unspecified"}, '
'textHeightBehavior: ${_textHeightBehavior ?? "unspecified"}, '
'fontFamily: ${_fontFamily ?? "unspecified"}, '
'fontSize: ${fontSize != null ? fontSize.toStringAsFixed(1) : "unspecified"}, '
'height: ${height != null ? "${height.toStringAsFixed(1)}x" : "unspecified"}, '
'strutStyle: ${_strutStyle ?? "unspecified"}, '
'ellipsis: ${_ellipsis != null ? '"$_ellipsis"' : "unspecified"}, '
'locale: ${_locale ?? "unspecified"}'
')';
return true;
}());
return result;
}
}
class SkwasmParagraphBuilder extends SkwasmObjectWrapper<RawParagraphBuilder> implements ui.ParagraphBuilder {
factory SkwasmParagraphBuilder(
SkwasmParagraphStyle style,
SkwasmFontCollection collection,
) => SkwasmParagraphBuilder._(paragraphBuilderCreate(
style.handle,
collection.handle,
), style);
SkwasmParagraphBuilder._(ParagraphBuilderHandle handle, this.style) : super(handle, _registry);
static final SkwasmFinalizationRegistry<RawParagraphBuilder> _registry =
SkwasmFinalizationRegistry<RawParagraphBuilder>(paragraphBuilderDispose);
final SkwasmParagraphStyle style;
final List<SkwasmNativeTextStyle> textStyleStack = <SkwasmNativeTextStyle>[];
@override
List<double> placeholderScales = <double>[];
@override
void addPlaceholder(
double width,
double height,
ui.PlaceholderAlignment alignment, {
double scale = 1.0,
double? baselineOffset,
ui.TextBaseline? baseline
}) {
paragraphBuilderAddPlaceholder(
handle,
width * scale,
height * scale,
alignment.index,
(baselineOffset ?? height) * scale,
(baseline ?? ui.TextBaseline.alphabetic).index,
);
placeholderScales.add(scale);
}
@override
void addText(String text) {
final SkString16Handle stringHandle = skString16FromDartString(text);
paragraphBuilderAddText(handle, stringHandle);
skString16Free(stringHandle);
}
static final DomV8BreakIterator _v8BreakIterator = createV8BreakIterator();
static final DomSegmenter _graphemeSegmenter = createIntlSegmenter(granularity: 'grapheme');
static final DomSegmenter _wordSegmenter = createIntlSegmenter(granularity: 'word');
static final DomTextDecoder _utf8Decoder = DomTextDecoder();
void _addSegmenterData() => withStackScope((StackScope scope) {
// Because some of the string processing is dealt with manually in dart,
// and some is handled by the browser, we actually need both a dart string
// and a JS string. Converting from linear memory to Dart strings or JS
// strings is more efficient than directly converting to each other, so we
// just create both up front here.
final Pointer<Uint32> outSize = scope.allocUint32Array(1);
final Pointer<Uint8> utf8Data = paragraphBuilderGetUtf8Text(handle, outSize);
if (utf8Data == nullptr) {
return;
}
// TODO(jacksongardner): We could make a subclass of `List<int>` here to
// avoid this copy.
final List<int> codeUnitList = List<int>.generate(
outSize.value,
(int index) => utf8Data[index]
);
final String text = utf8.decode(codeUnitList);
final JSString jsText = _utf8Decoder.decode(
// In an ideal world we would just use a subview of wasm memory rather
// than a slice, but the TextDecoder API doesn't work on shared buffer
// sources yet.
// See https://bugs.chromium.org/p/chromium/issues/detail?id=1012656
createUint8ArrayFromBuffer(skwasmInstance.wasmMemory.buffer).slice(
utf8Data.address.toJS,
(utf8Data.address + outSize.value).toJS
));
_addGraphemeBreakData(text, jsText);
_addWordBreakData(text, jsText);
_addLineBreakData(text, jsText);
});
UnicodePositionBufferHandle _createBreakPositionBuffer(String text, JSString jsText, DomSegmenter segmenter) {
final DomIteratorWrapper<DomSegment> iterator = segmenter.segmentRaw(jsText).iterator();
final List<int> breaks = <int>[];
while (iterator.moveNext()) {
breaks.add(iterator.current.index);
}
breaks.add(text.length);
final UnicodePositionBufferHandle positionBuffer = unicodePositionBufferCreate(breaks.length);
final Pointer<Uint32> buffer = unicodePositionBufferGetDataPointer(positionBuffer);
for (int i = 0; i < breaks.length; i++) {
buffer[i] = breaks[i];
}
return positionBuffer;
}
void _addGraphemeBreakData(String text, JSString jsText) {
final UnicodePositionBufferHandle positionBuffer =
_createBreakPositionBuffer(text, jsText, _graphemeSegmenter);
paragraphBuilderSetGraphemeBreaksUtf16(handle, positionBuffer);
unicodePositionBufferFree(positionBuffer);
}
void _addWordBreakData(String text, JSString jsText) {
final UnicodePositionBufferHandle positionBuffer =
_createBreakPositionBuffer(text, jsText, _wordSegmenter);
paragraphBuilderSetWordBreaksUtf16(handle, positionBuffer);
unicodePositionBufferFree(positionBuffer);
}
void _addLineBreakData(String text, JSString jsText) {
final List<LineBreakFragment> lineBreaks = breakLinesUsingV8BreakIterator(text, jsText, _v8BreakIterator);
final LineBreakBufferHandle lineBreakBuffer = lineBreakBufferCreate(lineBreaks.length + 1);
final Pointer<LineBreak> lineBreakPointer = lineBreakBufferGetDataPointer(lineBreakBuffer);
// First line break is always zero. The buffer is zero initialized, so we can just
// skip the first one.
for (int i = 0; i < lineBreaks.length; i++) {
final LineBreakFragment fragment = lineBreaks[i];
lineBreakPointer[i + 1].position = fragment.end;
lineBreakPointer[i + 1].lineBreakType = fragment.type == LineBreakType.mandatory
? _kHardLineBreak
: _kSoftLineBreak;
}
paragraphBuilderSetLineBreaksUtf16(handle, lineBreakBuffer);
lineBreakBufferFree(lineBreakBuffer);
}
@override
ui.Paragraph build() {
_addSegmenterData();
return SkwasmParagraph(paragraphBuilderBuild(handle));
}
@override
int get placeholderCount => placeholderScales.length;
@override
void pop() {
final SkwasmNativeTextStyle style = textStyleStack.removeLast();
style.dispose();
paragraphBuilderPop(handle);
}
@override
void pushStyle(ui.TextStyle textStyle) {
textStyle as SkwasmTextStyle;
final SkwasmNativeTextStyle baseStyle = textStyleStack.isNotEmpty
? textStyleStack.last
: style.textStyle;
final SkwasmNativeTextStyle nativeStyle = baseStyle.copy();
textStyle.applyToNative(nativeStyle);
textStyleStack.add(nativeStyle);
paragraphBuilderPushStyle(handle, nativeStyle.handle);
}
}
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/paragraph.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/paragraph.dart",
"repo_id": "engine",
"token_count": 13025
} | 404 |
// 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:convert';
import 'dart:ffi';
final class RawSkString extends Opaque {}
typedef SkStringHandle = Pointer<RawSkString>;
final class RawSkString16 extends Opaque {}
typedef SkString16Handle = Pointer<RawSkString16>;
@Native<SkStringHandle Function(Size)>(symbol: 'skString_allocate', isLeaf: true)
external SkStringHandle skStringAllocate(int size);
@Native<Pointer<Int8> Function(SkStringHandle)>(symbol: 'skString_getData', isLeaf: true)
external Pointer<Int8> skStringGetData(SkStringHandle handle);
@Native<Void Function(SkStringHandle)>(symbol: 'skString_free', isLeaf: true)
external void skStringFree(SkStringHandle handle);
@Native<SkString16Handle Function(Size)>(symbol: 'skString16_allocate', isLeaf: true)
external SkString16Handle skString16Allocate(int size);
@Native<Pointer<Int16> Function(SkString16Handle)>(symbol: 'skString16_getData', isLeaf: true)
external Pointer<Int16> skString16GetData(SkString16Handle handle);
@Native<Void Function(SkString16Handle)>(symbol: 'skString16_free', isLeaf: true)
external void skString16Free(SkString16Handle handle);
SkStringHandle skStringFromDartString(String string) {
final List<int> rawUtf8Bytes = utf8.encode(string);
final SkStringHandle stringHandle = skStringAllocate(rawUtf8Bytes.length);
final Pointer<Int8> stringDataPointer = skStringGetData(stringHandle);
for (int i = 0; i < rawUtf8Bytes.length; i++) {
stringDataPointer[i] = rawUtf8Bytes[i];
}
return stringHandle;
}
SkString16Handle skString16FromDartString(String string) {
final SkString16Handle stringHandle = skString16Allocate(string.length);
final Pointer<Int16> stringDataPointer = skString16GetData(stringHandle);
for (int i = 0; i < string.length; i++) {
stringDataPointer[i] = string.codeUnitAt(i);
}
return stringHandle;
}
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_skstring.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_skstring.dart",
"repo_id": "engine",
"token_count": 662
} | 405 |
// 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/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
class SkwasmRenderer implements Renderer {
@override
ui.Path combinePaths(ui.PathOperation op, ui.Path path1, ui.Path path2) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.ImageFilter composeImageFilters({required ui.ImageFilter outer, required ui.ImageFilter inner}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.Path copyPath(ui.Path src) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.ImageFilter createBlurImageFilter({double sigmaX = 0.0, double sigmaY = 0.0, ui.TileMode tileMode = ui.TileMode.clamp}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.Canvas createCanvas(ui.PictureRecorder recorder, [ui.Rect? cullRect]) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@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]) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.ImageFilter createDilateImageFilter({double radiusX = 0.0, double radiusY = 0.0}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.ImageFilter createErodeImageFilter({double radiusX = 0.0, double radiusY = 0.0}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.ImageShader createImageShader(ui.Image image, ui.TileMode tmx, ui.TileMode tmy, Float64List matrix4, ui.FilterQuality? filterQuality) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@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]) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.ImageFilter createMatrixImageFilter(Float64List matrix4, {ui.FilterQuality filterQuality = ui.FilterQuality.low}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.Paint createPaint() {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.ParagraphBuilder createParagraphBuilder(ui.ParagraphStyle style) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@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}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.Path createPath() {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.PictureRecorder createPictureRecorder() {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.Gradient createRadialGradient(ui.Offset center, double radius, List<ui.Color> colors, [List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix4]) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.SceneBuilder createSceneBuilder() {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@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}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@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]) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@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}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.Vertices createVertices(ui.VertexMode mode, List<ui.Offset> positions, {List<ui.Offset>? textureCoordinates, List<ui.Color>? colors, List<int>? indices}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
ui.Vertices createVerticesRaw(ui.VertexMode mode, Float32List positions, {Float32List? textureCoordinates, Int32List? colors, Uint16List? indices}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
void decodeImageFromPixels(Uint8List pixels, int width, int height, ui.PixelFormat format, ui.ImageDecoderCallback callback, {int? rowBytes, int? targetWidth, int? targetHeight, bool allowUpscaling = true}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
FlutterFontCollection get fontCollection => throw UnimplementedError('Skwasm not implemented on this platform.');
@override
FutureOr<void> initialize() {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
Future<ui.Codec> instantiateImageCodec(Uint8List list, {int? targetWidth, int? targetHeight, bool allowUpscaling = true}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
Future<ui.Codec> instantiateImageCodecFromUrl(Uri uri, {ui_web.ImageCodecChunkCallback? chunkCallback}) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
Future<void> renderScene(ui.Scene scene, ui.FlutterView view) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
@override
String get rendererTag => throw UnimplementedError('Skwasm not implemented on this platform.');
@override
void clearFragmentProgramCache() => _programs.clear();
static final Map<String, Future<ui.FragmentProgram>> _programs = <String, Future<ui.FragmentProgram>>{};
@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 CkFragmentProgram.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
}) => throw UnimplementedError('Skwasm not implemented on this platform.');
@override
ui.Image createImageFromImageBitmap(DomImageBitmap imageSource) {
throw UnimplementedError('Skwasm not implemented on this platform.');
}
}
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_stub/renderer.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_stub/renderer.dart",
"repo_id": "engine",
"token_count": 2686
} | 406 |
// 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:web_unicode/web_unicode.dart';
import 'unicode_range.dart';
export 'package:web_unicode/web_unicode.dart' show WordCharProperty;
UnicodePropertyLookup<WordCharProperty> wordLookup =
UnicodePropertyLookup<WordCharProperty>.fromPackedData(
packedWordBreakProperties,
singleWordBreakRangesCount,
WordCharProperty.values,
defaultWordCharProperty,
);
| engine/lib/web_ui/lib/src/engine/text/word_break_properties.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/text/word_break_properties.dart",
"repo_id": "engine",
"token_count": 165
} | 407 |
// 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:ui/src/engine/dom.dart';
import '../hot_restart_cache_handler.dart' show registerElementForCleanup;
import 'embedding_strategy.dart';
/// An [EmbeddingStrategy] that renders flutter inside a target host element.
///
/// This strategy attempts to minimize DOM modifications outside of the host
/// element, so it plays "nice" with other web frameworks.
class CustomElementEmbeddingStrategy implements EmbeddingStrategy {
/// Creates a [CustomElementEmbeddingStrategy] to embed a Flutter view into [_hostElement].
CustomElementEmbeddingStrategy(this.hostElement) {
hostElement.clearChildren();
hostElement.setAttribute('flt-embedding', 'custom-element');
}
@override
DomEventTarget get globalEventTarget => _rootElement;
@override
final DomElement hostElement;
/// The root element of the Flutter view.
late final DomElement _rootElement;
@override
void attachViewRoot(DomElement rootElement) {
rootElement
..style.width = '100%'
..style.height = '100%'
..style.display = 'block'
..style.overflow = 'hidden'
..style.position = 'relative';
hostElement.appendChild(rootElement);
registerElementForCleanup(rootElement);
_rootElement = rootElement;
}
}
| engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/custom_element_embedding_strategy.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/custom_element_embedding_strategy.dart",
"repo_id": "engine",
"token_count": 431
} | 408 |
// 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:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
/// Bootstraps the Flutter Web engine and app.
///
/// If the app uses plugins, then the [registerPlugins] callback can be provided
/// to register those plugins. This is done typically by calling
/// `registerPlugins` from the auto-generated `web_plugin_registrant.dart` file.
///
/// The [runApp] callback is invoked to run the app after the engine is fully
/// initialized.
///
/// For more information, see what the `flutter_tools` does in the entrypoint
/// that it generates around the app's main method:
///
/// * https://github.com/flutter/flutter/blob/95be76ab7e3dca2def54454313e97f94f4ac4582/packages/flutter_tools/lib/src/web/file_generators/main_dart.dart#L14-L43
///
/// By default, engine initialization and app startup occur immediately and back
/// to back. They can be programmatically controlled by setting
/// `FlutterLoader.didCreateEngineInitializer`. For more information, see how
/// `flutter.js` does it:
///
/// * https://github.com/flutter/flutter/blob/95be76ab7e3dca2def54454313e97f94f4ac4582/packages/flutter_tools/lib/src/web/file_generators/js/flutter.js
Future<void> bootstrapEngine({
ui.VoidCallback? registerPlugins,
ui.VoidCallback? runApp,
}) async {
// Create the object that knows how to bootstrap an app from JS and Dart.
final AppBootstrap bootstrap = AppBootstrap(
initializeEngine: ([JsFlutterConfiguration? configuration]) async {
await initializeEngineServices(jsConfiguration: configuration);
}, runApp: () async {
if (registerPlugins != null) {
registerPlugins();
}
await initializeEngineUi();
if (runApp != null) {
runApp();
}
},
);
final FlutterLoader? loader = flutter?.loader;
if (loader == null || loader.isAutoStart) {
// The user does not want control of the app, bootstrap immediately.
await bootstrap.autoStart();
} else {
// Yield control of the bootstrap procedure to the user.
loader.didCreateEngineInitializer(bootstrap.prepareEngineInitializer());
}
}
| engine/lib/web_ui/lib/ui_web/src/ui_web/initialization.dart/0 | {
"file_path": "engine/lib/web_ui/lib/ui_web/src/ui_web/initialization.dart",
"repo_id": "engine",
"token_count": 717
} | 409 |
// 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 "skwasm_support.h"
#include "surface.h"
#include "wrappers.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "third_party/skia/include/gpu/GpuTypes.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "third_party/skia/include/gpu/ganesh/GrExternalTextureGenerator.h"
#include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h"
#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h"
#include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
#include "third_party/skia/include/gpu/gl/GrGLTypes.h"
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <emscripten/html5_webgl.h>
using namespace SkImages;
namespace {
enum class PixelFormat {
rgba8888,
bgra8888,
rgbaFloat32,
};
SkColorType colorTypeForPixelFormat(PixelFormat format) {
switch (format) {
case PixelFormat::rgba8888:
return SkColorType::kRGBA_8888_SkColorType;
case PixelFormat::bgra8888:
return SkColorType::kBGRA_8888_SkColorType;
case PixelFormat::rgbaFloat32:
return SkColorType::kRGBA_F32_SkColorType;
}
}
SkAlphaType alphaTypeForPixelFormat(PixelFormat format) {
switch (format) {
case PixelFormat::rgba8888:
case PixelFormat::bgra8888:
return SkAlphaType::kPremul_SkAlphaType;
case PixelFormat::rgbaFloat32:
return SkAlphaType::kUnpremul_SkAlphaType;
}
}
class ExternalWebGLTexture : public GrExternalTexture {
public:
ExternalWebGLTexture(GrBackendTexture backendTexture,
GLuint textureId,
EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context)
: _backendTexture(backendTexture),
_textureId(textureId),
_webGLContext(context) {}
GrBackendTexture getBackendTexture() override { return _backendTexture; }
void dispose() override {
Skwasm::makeCurrent(_webGLContext);
glDeleteTextures(1, &_textureId);
}
private:
GrBackendTexture _backendTexture;
GLuint _textureId;
EMSCRIPTEN_WEBGL_CONTEXT_HANDLE _webGLContext;
};
} // namespace
class TextureSourceImageGenerator : public GrExternalTextureGenerator {
public:
TextureSourceImageGenerator(SkImageInfo ii,
SkwasmObject textureSource,
Skwasm::Surface* surface)
: GrExternalTextureGenerator(ii),
_textureSourceWrapper(
surface->createTextureSourceWrapper(textureSource)) {}
std::unique_ptr<GrExternalTexture> generateExternalTexture(
GrRecordingContext* context,
skgpu::Mipmapped mipmapped) override {
GrGLTextureInfo glInfo;
glInfo.fID = skwasm_createGlTextureFromTextureSource(
_textureSourceWrapper->getTextureSource(), fInfo.width(),
fInfo.height());
glInfo.fFormat = GL_RGBA8_OES;
glInfo.fTarget = GL_TEXTURE_2D;
auto backendTexture = GrBackendTextures::MakeGL(
fInfo.width(), fInfo.height(), mipmapped, glInfo);
// In order to bind the image source to the texture, makeTexture has changed
// which texture is "in focus" for the WebGL context.
GrAsDirectContext(context)->resetContext(kTextureBinding_GrGLBackendState);
return std::make_unique<ExternalWebGLTexture>(
backendTexture, glInfo.fID, emscripten_webgl_get_current_context());
}
private:
std::unique_ptr<Skwasm::TextureSourceWrapper> _textureSourceWrapper;
};
SKWASM_EXPORT SkImage* image_createFromPicture(SkPicture* picture,
int32_t width,
int32_t height) {
return DeferredFromPicture(sk_ref_sp<SkPicture>(picture), {width, height},
nullptr, nullptr, BitDepth::kU8,
SkColorSpace::MakeSRGB())
.release();
}
SKWASM_EXPORT SkImage* image_createFromPixels(SkData* data,
int width,
int height,
PixelFormat pixelFormat,
size_t rowByteCount) {
return SkImages::RasterFromData(
SkImageInfo::Make(width, height,
colorTypeForPixelFormat(pixelFormat),
alphaTypeForPixelFormat(pixelFormat),
SkColorSpace::MakeSRGB()),
sk_ref_sp(data), rowByteCount)
.release();
}
SKWASM_EXPORT SkImage* image_createFromTextureSource(SkwasmObject textureSource,
int width,
int height,
Skwasm::Surface* surface) {
return SkImages::DeferredFromTextureGenerator(
std::unique_ptr<TextureSourceImageGenerator>(
new TextureSourceImageGenerator(
SkImageInfo::Make(width, height,
SkColorType::kRGBA_8888_SkColorType,
SkAlphaType::kPremul_SkAlphaType),
textureSource, surface)))
.release();
}
SKWASM_EXPORT void image_ref(SkImage* image) {
image->ref();
}
SKWASM_EXPORT void image_dispose(SkImage* image) {
image->unref();
}
SKWASM_EXPORT int image_getWidth(SkImage* image) {
return image->width();
}
SKWASM_EXPORT int image_getHeight(SkImage* image) {
return image->height();
}
| engine/lib/web_ui/skwasm/image.cpp/0 | {
"file_path": "engine/lib/web_ui/skwasm/image.cpp",
"repo_id": "engine",
"token_count": 2694
} | 410 |
// 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/include/core/SkVertices.h"
SKWASM_EXPORT SkVertices* vertices_create(SkVertices::VertexMode vertexMode,
int vertexCount,
SkPoint* positions,
SkPoint* textureCoordinates,
SkColor* colors,
int indexCount,
uint16_t* indices) {
return SkVertices::MakeCopy(vertexMode, vertexCount, positions,
textureCoordinates, colors, indexCount, indices)
.release();
}
SKWASM_EXPORT void vertices_dispose(SkVertices* vertices) {
vertices->unref();
}
| engine/lib/web_ui/skwasm/vertices.cpp/0 | {
"file_path": "engine/lib/web_ui/skwasm/vertices.cpp",
"repo_id": "engine",
"token_count": 492
} | 411 |
// 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:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../common/matchers.dart';
import 'common.dart';
import 'test_data.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('CanvasKit Images', () {
setUpCanvasKitTest(withImplicitView: true);
tearDown(() {
mockHttpFetchResponseFactory = null;
});
_testCkAnimatedImage();
_testForImageCodecs(useBrowserImageDecoder: false);
if (browserSupportsImageDecoder) {
_testForImageCodecs(useBrowserImageDecoder: true);
_testCkBrowserImageDecoder();
}
test('isAvif', () {
expect(isAvif(Uint8List.fromList(<int>[])), isFalse);
expect(isAvif(Uint8List.fromList(<int>[1, 2, 3])), isFalse);
expect(
isAvif(Uint8List.fromList(<int>[
0x00, 0x00, 0x00, 0x1c, 0x66, 0x74, 0x79, 0x70,
0x61, 0x76, 0x69, 0x66, 0x00, 0x00, 0x00, 0x00,
])),
isTrue,
);
expect(
isAvif(Uint8List.fromList(<int>[
0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70,
0x61, 0x76, 0x69, 0x66, 0x00, 0x00, 0x00, 0x00,
])),
isTrue,
);
});
}, skip: isSafari);
}
void _testForImageCodecs({required bool useBrowserImageDecoder}) {
final String mode = useBrowserImageDecoder ? 'webcodecs' : 'wasm';
final List<String> warnings = <String>[];
late void Function(String) oldPrintWarning;
group('($mode)', () {
setUp(() {
browserSupportsImageDecoder = useBrowserImageDecoder;
warnings.clear();
});
setUpAll(() {
oldPrintWarning = printWarning;
printWarning = (String warning) {
warnings.add(warning);
};
});
tearDown(() {
debugResetBrowserSupportsImageDecoder();
});
tearDownAll(() {
printWarning = oldPrintWarning;
});
test('CkAnimatedImage can be explicitly disposed of', () {
final CkAnimatedImage image = CkAnimatedImage.decodeFromBytes(kTransparentImage, 'test');
expect(image.debugDisposed, isFalse);
image.dispose();
expect(image.debugDisposed, isTrue);
// Disallow usage after disposal
expect(() => image.frameCount, throwsAssertionError);
expect(() => image.repetitionCount, throwsAssertionError);
expect(() => image.getNextFrame(), throwsAssertionError);
// Disallow double-dispose.
expect(() => image.dispose(), throwsAssertionError);
});
test('CkAnimatedImage iterates frames correctly', () async {
final CkAnimatedImage image = CkAnimatedImage.decodeFromBytes(kAnimatedGif, 'test');
expect(image.frameCount, 3);
expect(image.repetitionCount, -1);
final ui.FrameInfo frame1 = await image.getNextFrame();
await expectFrameData(frame1, <int>[255, 0, 0, 255]);
final ui.FrameInfo frame2 = await image.getNextFrame();
await expectFrameData(frame2, <int>[0, 255, 0, 255]);
final ui.FrameInfo frame3 = await image.getNextFrame();
await expectFrameData(frame3, <int>[0, 0, 255, 255]);
});
test('CkImage toString', () {
final SkImage skImage =
canvasKit.MakeAnimatedImageFromEncoded(kTransparentImage)!
.makeImageAtCurrentFrame();
final CkImage image = CkImage(skImage);
expect(image.toString(), '[1×1]');
image.dispose();
});
test('CkImage can be explicitly disposed of', () {
final SkImage skImage =
canvasKit.MakeAnimatedImageFromEncoded(kTransparentImage)!
.makeImageAtCurrentFrame();
final CkImage image = CkImage(skImage);
expect(image.debugDisposed, isFalse);
expect(image.box.isDisposed, isFalse);
image.dispose();
expect(image.debugDisposed, isTrue);
expect(image.box.isDisposed, isTrue);
// Disallow double-dispose.
expect(() => image.dispose(), throwsAssertionError);
});
test('CkImage can be explicitly disposed of when cloned', () async {
final SkImage skImage =
canvasKit.MakeAnimatedImageFromEncoded(kTransparentImage)!
.makeImageAtCurrentFrame();
final CkImage image = CkImage(skImage);
final CountedRef<CkImage, SkImage> box = image.box;
expect(box.refCount, 1);
expect(box.debugGetStackTraces().length, 1);
final CkImage clone = image.clone();
expect(box.refCount, 2);
expect(box.debugGetStackTraces().length, 2);
expect(image.isCloneOf(clone), isTrue);
expect(box.isDisposed, isFalse);
expect(skImage.isDeleted(), isFalse);
image.dispose();
expect(box.refCount, 1);
expect(box.isDisposed, isFalse);
expect(skImage.isDeleted(), isFalse);
clone.dispose();
expect(box.refCount, 0);
expect(box.isDisposed, isTrue);
expect(skImage.isDeleted(), isTrue);
expect(box.debugGetStackTraces().length, 0);
});
test('CkImage toByteData', () async {
final SkImage skImage =
canvasKit.MakeAnimatedImageFromEncoded(kTransparentImage)!
.makeImageAtCurrentFrame();
final CkImage image = CkImage(skImage);
expect((await image.toByteData()).lengthInBytes, greaterThan(0));
expect((await image.toByteData(format: ui.ImageByteFormat.png)).lengthInBytes, greaterThan(0));
});
test('toByteData with decodeImageFromPixels on videoFrame formats', () async {
// This test ensures that toByteData() returns pixels that can be used by decodeImageFromPixels
// for the following videoFrame formats:
// [BGRX, I422, I420, I444, BGRA]
final HttpFetchResponse listingResponse = await httpFetch('/test_images/');
final List<String> testFiles = (await listingResponse.json() as List<dynamic>).cast<String>();
Future<ui.Image> testDecodeFromPixels(Uint8List pixels, int width, int height) async {
final Completer<ui.Image> completer = Completer<ui.Image>();
ui.decodeImageFromPixels(
pixels,
width,
height,
ui.PixelFormat.rgba8888,
(ui.Image image) {
completer.complete(image);
},
);
return completer.future;
}
// Sanity-check the test file list. If suddenly test files are moved or
// deleted, and the test server returns an empty list, or is missing some
// important test files, we want to know.
expect(testFiles, isNotEmpty);
expect(testFiles, contains(matches(RegExp(r'.*\.jpg'))));
expect(testFiles, contains(matches(RegExp(r'.*\.png'))));
expect(testFiles, contains(matches(RegExp(r'.*\.gif'))));
expect(testFiles, contains(matches(RegExp(r'.*\.webp'))));
expect(testFiles, contains(matches(RegExp(r'.*\.bmp'))));
for (final String testFile in testFiles) {
final HttpFetchResponse imageResponse = await httpFetch('/test_images/$testFile');
final Uint8List imageData = await imageResponse.asUint8List();
final ui.Codec codec = await skiaInstantiateImageCodec(imageData);
expect(codec.frameCount, greaterThan(0));
expect(codec.repetitionCount, isNotNull);
final ui.FrameInfo frame = await codec.getNextFrame();
final CkImage ckImage = frame.image as CkImage;
final ByteData imageBytes = await ckImage.toByteData();
expect(imageBytes.lengthInBytes, greaterThan(0));
final Uint8List pixels = imageBytes.buffer.asUint8List();
final ui.Image testImage = await testDecodeFromPixels(pixels, ckImage.width, ckImage.height);
expect(testImage, isNotNull);
codec.dispose();
}
// TODO(hterkelsen): Firefox and Safari do not currently support ImageDecoder.
// TODO(jacksongardner): enable on wasm
// see https://github.com/flutter/flutter/issues/118334
}, skip: isFirefox || isSafari || isWasm);
test('CkImage.clone also clones the VideoFrame', () async {
final CkBrowserImageDecoder image = await CkBrowserImageDecoder.create(
data: kAnimatedGif,
debugSource: 'test',
);
final ui.FrameInfo frame = await image.getNextFrame();
final CkImage ckImage = frame.image as CkImage;
expect(ckImage.videoFrame, isNotNull);
final CkImage imageClone = ckImage.clone();
expect(imageClone.videoFrame, isNotNull);
final ByteData png = await imageClone.toByteData(format: ui.ImageByteFormat.png);
expect(png, isNotNull);
// The precise PNG encoding is browser-specific, but we can check the file
// signature.
expect(detectContentType(png.buffer.asUint8List()), 'image/png');
// TODO(hterkelsen): Firefox and Safari do not currently support ImageDecoder.
}, skip: isFirefox || isSafari);
test('skiaInstantiateWebImageCodec loads an image from the network',
() async {
mockHttpFetchResponseFactory = (String url) async {
return MockHttpFetchResponse(
url: url,
status: 200,
payload: MockHttpFetchPayload(byteBuffer: kTransparentImage.buffer),
);
};
final ui.Codec codec = await skiaInstantiateWebImageCodec(
'http://image-server.com/picture.jpg', null);
expect(codec.frameCount, 1);
final ui.Image image = (await codec.getNextFrame()).image;
expect(image.height, 1);
expect(image.width, 1);
});
test('instantiateImageCodec respects target image size',
() async {
const List<List<int>> targetSizes = <List<int>>[
<int>[1, 1],
<int>[1, 2],
<int>[2, 3],
<int>[3, 4],
<int>[4, 4],
<int>[10, 20],
];
for (final List<int> targetSize in targetSizes) {
final int targetWidth = targetSize[0];
final int targetHeight = targetSize[1];
final ui.Codec codec = await ui.instantiateImageCodec(
k4x4PngImage,
targetWidth: targetWidth,
targetHeight: targetHeight,
);
final ui.Image image = (await codec.getNextFrame()).image;
expect(image.width, targetWidth);
expect(image.height, targetHeight);
image.dispose();
codec.dispose();
}
});
test('instantiateImageCodec with multi-frame image does not support targetWidth/targetHeight',
() async {
final ui.Codec codec = await ui.instantiateImageCodec(
kAnimatedGif,
targetWidth: 2,
targetHeight: 3,
);
final ui.Image image = (await codec.getNextFrame()).image;
expect(
warnings,
containsAllInOrder(
<String>[
'targetWidth and targetHeight for multi-frame images not supported',
],
),
);
// expect the re-size did not happen, kAnimatedGif is [1x1]
expect(image.width, 1);
expect(image.height, 1);
image.dispose();
codec.dispose();
});
test('skiaInstantiateWebImageCodec throws exception on request error',
() async {
mockHttpFetchResponseFactory = (String url) async {
throw HttpFetchError(url, requestError: 'This is a test request error.');
};
try {
await skiaInstantiateWebImageCodec('url-does-not-matter', null);
fail('Expected to throw');
} on ImageCodecException catch (exception) {
expect(
exception.toString(),
'ImageCodecException: Failed to load network image.\n'
'Image URL: url-does-not-matter\n'
'Trying to load an image from another domain? Find answers at:\n'
'https://flutter.dev/docs/development/platform-integration/web-images',
);
}
});
test('skiaInstantiateWebImageCodec throws exception on HTTP error',
() async {
try {
await skiaInstantiateWebImageCodec('/does-not-exist.jpg', null);
fail('Expected to throw');
} on ImageCodecException catch (exception) {
expect(
exception.toString(),
'ImageCodecException: Failed to load network image.\n'
'Image URL: /does-not-exist.jpg\n'
'Server response code: 404',
);
}
});
test('skiaInstantiateWebImageCodec includes URL in the error for malformed image',
() async {
mockHttpFetchResponseFactory = (String url) async {
return MockHttpFetchResponse(
url: url,
status: 200,
payload: MockHttpFetchPayload(byteBuffer: Uint8List(0).buffer),
);
};
try {
await skiaInstantiateWebImageCodec('http://image-server.com/picture.jpg', null);
fail('Expected to throw');
} on ImageCodecException catch (exception) {
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: http://image-server.com/picture.jpg',
);
} else {
expect(
exception.toString(),
'ImageCodecException: Failed to detect image file format using the file header.\n'
'File header was empty.\n'
'Image source: http://image-server.com/picture.jpg',
);
}
}
});
test('Reports error when failing to decode empty image data', () async {
try {
await ui.instantiateImageCodec(Uint8List(0));
fail('Expected to throw');
} on ImageCodecException catch (exception) {
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: encoded image bytes',
);
} else {
expect(
exception.toString(),
'ImageCodecException: Failed to detect image file format using the file header.\n'
'File header was empty.\n'
'Image source: encoded image bytes',
);
}
}
});
test('Reports error when failing to decode malformed image data', () async {
try {
await ui.instantiateImageCodec(Uint8List.fromList(<int>[
0xFF, 0xD8, 0xFF, 0xDB, 0x00, 0x00, 0x00,
]));
fail('Expected to throw');
} on ImageCodecException catch (exception) {
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: encoded image bytes'
);
} else {
expect(
exception.toString(),
// Browser error message is not checked as it can depend on the
// browser engine and version.
matches(RegExp(
r"ImageCodecException: Failed to decode image using the browser's ImageDecoder API.\n"
r'Image source: encoded image bytes\n'
r'Original browser error: .+'
))
);
}
}
});
test('Includes file header in the error message when fails to detect file type', () async {
try {
await ui.instantiateImageCodec(Uint8List.fromList(<int>[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
]));
fail('Expected to throw');
} on ImageCodecException catch (exception) {
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: encoded image bytes'
);
} else {
expect(
exception.toString(),
'ImageCodecException: Failed to detect image file format using the file header.\n'
'File header was [0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x00].\n'
'Image source: encoded image bytes'
);
}
}
});
test('Provides readable error message when image type is unsupported', () async {
addTearDown(() {
debugContentTypeDetector = null;
});
debugContentTypeDetector = (_) {
return 'unsupported/image-type';
};
try {
await ui.instantiateImageCodec(Uint8List.fromList(<int>[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
]));
fail('Expected to throw');
} on ImageCodecException catch (exception) {
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: encoded image bytes'
);
} else {
expect(
exception.toString(),
"ImageCodecException: Image file format (unsupported/image-type) is not supported by this browser's ImageDecoder API.\n"
'Image source: encoded image bytes'
);
}
}
});
test('decodeImageFromPixels', () async {
Future<ui.Image> testDecodeFromPixels(int width, int height) async {
final Completer<ui.Image> completer = Completer<ui.Image>();
ui.decodeImageFromPixels(
Uint8List.fromList(List<int>.filled(width * height * 4, 0)),
width,
height,
ui.PixelFormat.rgba8888,
(ui.Image image) {
completer.complete(image);
},
);
return completer.future;
}
final ui.Image image1 = await testDecodeFromPixels(10, 20);
expect(image1, isNotNull);
expect(image1.width, 10);
expect(image1.height, 20);
final ui.Image image2 = await testDecodeFromPixels(40, 100);
expect(image2, isNotNull);
expect(image2.width, 40);
expect(image2.height, 100);
});
test('decodeImageFromPixels respects target image size', () async {
Future<ui.Image> testDecodeFromPixels(int width, int height, int targetWidth, int targetHeight) async {
final Completer<ui.Image> completer = Completer<ui.Image>();
ui.decodeImageFromPixels(
Uint8List.fromList(List<int>.filled(width * height * 4, 0)),
width,
height,
ui.PixelFormat.rgba8888,
(ui.Image image) {
completer.complete(image);
},
targetWidth: targetWidth,
targetHeight: targetHeight,
);
return completer.future;
}
const List<List<int>> targetSizes = <List<int>>[
<int>[1, 1],
<int>[1, 2],
<int>[2, 3],
<int>[3, 4],
<int>[4, 4],
<int>[10, 20],
];
for (final List<int> targetSize in targetSizes) {
final int targetWidth = targetSize[0];
final int targetHeight = targetSize[1];
final ui.Image image = await testDecodeFromPixels(10, 20, targetWidth, targetHeight);
expect(image.width, targetWidth);
expect(image.height, targetHeight);
image.dispose();
}
});
test('decodeImageFromPixels upscale when allowUpscaling is false', () async {
Future<ui.Image> testDecodeFromPixels(int width, int height) async {
final Completer<ui.Image> completer = Completer<ui.Image>();
ui.decodeImageFromPixels(
Uint8List.fromList(List<int>.filled(width * height * 4, 0)),
width,
height,
ui.PixelFormat.rgba8888,
(ui.Image image) {
completer.complete(image);
},
targetWidth: 20,
targetHeight: 30,
allowUpscaling: false
);
return completer.future;
}
expect(() async => testDecodeFromPixels(10, 20), throwsAssertionError);
});
test('Decode test images', () async {
final HttpFetchResponse listingResponse = await httpFetch('/test_images/');
final List<String> testFiles = (await listingResponse.json() as List<dynamic>).cast<String>();
// Sanity-check the test file list. If suddenly test files are moved or
// deleted, and the test server returns an empty list, or is missing some
// important test files, we want to know.
expect(testFiles, isNotEmpty);
expect(testFiles, contains(matches(RegExp(r'.*\.jpg'))));
expect(testFiles, contains(matches(RegExp(r'.*\.png'))));
expect(testFiles, contains(matches(RegExp(r'.*\.gif'))));
expect(testFiles, contains(matches(RegExp(r'.*\.webp'))));
expect(testFiles, contains(matches(RegExp(r'.*\.bmp'))));
for (final String testFile in testFiles) {
final HttpFetchResponse imageResponse = await httpFetch('/test_images/$testFile');
final Uint8List imageData = await imageResponse.asUint8List();
final ui.Codec codec = await skiaInstantiateImageCodec(imageData);
expect(codec.frameCount, greaterThan(0));
expect(codec.repetitionCount, isNotNull);
for (int i = 0; i < codec.frameCount; i++) {
final ui.FrameInfo frame = await codec.getNextFrame();
expect(frame.duration, isNotNull);
expect(frame.image, isNotNull);
}
codec.dispose();
}
});
// Reproduces https://skbug.com/12721
test('decoded image can be read back from picture', () async {
final HttpFetchResponse imageResponse = await httpFetch('/test_images/mandrill_128.png');
final Uint8List imageData = await imageResponse.asUint8List();
final ui.Codec codec = await skiaInstantiateImageCodec(imageData);
final ui.FrameInfo frame = await codec.getNextFrame();
final CkImage image = frame.image as CkImage;
final CkImage snapshot;
{
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(10, 10);
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.drawRect(
const ui.Rect.fromLTRB(5, 5, 20, 20),
CkPaint(),
);
canvas.drawImage(image, ui.Offset.zero, CkPaint());
canvas.drawRect(
const ui.Rect.fromLTRB(90, 90, 105, 105),
CkPaint(),
);
sb.addPicture(ui.Offset.zero, recorder.endRecording());
sb.pop();
snapshot = await sb.build().toImage(150, 150) as CkImage;
}
{
final LayerSceneBuilder sb = LayerSceneBuilder();
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.drawImage(snapshot, ui.Offset.zero, CkPaint());
sb.addPicture(ui.Offset.zero, recorder.endRecording());
await matchSceneGolden(
'canvaskit_read_back_decoded_image_$mode.png', sb.build(),
region: const ui.Rect.fromLTRB(0, 0, 150, 150));
}
image.dispose();
codec.dispose();
});
// This is a regression test for the issues with transferring textures from
// one GL context to another, such as:
//
// * https://github.com/flutter/flutter/issues/86809
// * https://github.com/flutter/flutter/issues/91881
test('the same image can be rendered on difference surfaces', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final ui.Codec codec = await ui.instantiateImageCodec(k4x4PngImage);
final CkImage image = (await codec.getNextFrame()).image as CkImage;
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(4, 4);
{
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.save();
canvas.scale(16, 16);
canvas.drawImage(image, ui.Offset.zero, CkPaint());
canvas.restore();
canvas.drawParagraph(makeSimpleText('1'), const ui.Offset(4, 4));
sb.addPicture(ui.Offset.zero, recorder.endRecording());
}
sb.addPlatformView(0, width: 100, height: 100);
sb.pushOffset(20, 20);
{
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.save();
canvas.scale(16, 16);
canvas.drawImage(image, ui.Offset.zero, CkPaint());
canvas.restore();
canvas.drawParagraph(makeSimpleText('2'), const ui.Offset(2, 2));
sb.addPicture(ui.Offset.zero, recorder.endRecording());
}
await matchSceneGolden(
'canvaskit_cross_gl_context_image_$mode.png', sb.build(),
region: const ui.Rect.fromLTRB(0, 0, 100, 100));
await disposePlatformView(0);
});
test('toImageSync with texture-backed image', () async {
final HttpFetchResponse imageResponse = await httpFetch('/test_images/mandrill_128.png');
final Uint8List imageData = await imageResponse.asUint8List();
final ui.Codec codec = await skiaInstantiateImageCodec(imageData);
final ui.FrameInfo frame = await codec.getNextFrame();
final CkImage mandrill = frame.image as CkImage;
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawImageRect(
mandrill,
const ui.Rect.fromLTWH(0, 0, 128, 128),
const ui.Rect.fromLTWH(0, 0, 128, 128),
ui.Paint(),
);
final ui.Picture picture = recorder.endRecording();
final ui.Image image = picture.toImageSync(50, 50);
expect(image.width, 50);
expect(image.height, 50);
final ByteData? data = await image.toByteData();
expect(data, isNotNull);
expect(data!.lengthInBytes, 50 * 50 * 4);
expect(data.buffer.asUint32List().any((int byte) => byte != 0), isTrue);
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
{
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.save();
canvas.drawImage(image as CkImage, ui.Offset.zero, CkPaint());
canvas.restore();
sb.addPicture(ui.Offset.zero, recorder.endRecording());
}
await matchSceneGolden(
'canvaskit_picture_texture_toimage.png', sb.build(),
region: const ui.Rect.fromLTRB(0, 0, 128, 128));
mandrill.dispose();
codec.dispose();
});
test('decoded image can be read back from picture', () async {
final HttpFetchResponse imageResponse = await httpFetch('/test_images/mandrill_128.png');
final Uint8List imageData = await imageResponse.asUint8List();
final ui.Codec codec = await skiaInstantiateImageCodec(imageData);
final ui.FrameInfo frame = await codec.getNextFrame();
final CkImage image = frame.image as CkImage;
final CkImage snapshot;
{
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(10, 10);
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.drawRect(
const ui.Rect.fromLTRB(5, 5, 20, 20),
CkPaint(),
);
canvas.drawImage(image, ui.Offset.zero, CkPaint());
canvas.drawRect(
const ui.Rect.fromLTRB(90, 90, 105, 105),
CkPaint(),
);
sb.addPicture(ui.Offset.zero, recorder.endRecording());
sb.pop();
snapshot = await sb.build().toImage(150, 150) as CkImage;
}
{
final LayerSceneBuilder sb = LayerSceneBuilder();
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.drawImage(snapshot, ui.Offset.zero, CkPaint());
sb.addPicture(ui.Offset.zero, recorder.endRecording());
await matchSceneGolden(
'canvaskit_read_back_decoded_image_$mode.png', sb.build(),
region: const ui.Rect.fromLTRB(0, 0, 150, 150));
}
image.dispose();
codec.dispose();
});
test('can detect JPEG from just magic number', () async {
expect(
detectContentType(
Uint8List.fromList(<int>[0xff, 0xd8, 0xff, 0xe2, 0x0c, 0x58, 0x49, 0x43, 0x43, 0x5f])),
'image/jpeg');
});
}, timeout: const Timeout.factor(10)); // These tests can take a while. Allow for a longer timeout.
}
/// Tests specific to WASM codecs bundled with CanvasKit.
void _testCkAnimatedImage() {
test('ImageDecoder toByteData(PNG)', () async {
final CkAnimatedImage image = CkAnimatedImage.decodeFromBytes(kAnimatedGif, 'test');
final ui.FrameInfo frame = await image.getNextFrame();
final ByteData? png = await frame.image.toByteData(format: ui.ImageByteFormat.png);
expect(png, isNotNull);
// The precise PNG encoding is browser-specific, but we can check the file
// signature.
expect(detectContentType(png!.buffer.asUint8List()), 'image/png');
});
test('CkAnimatedImage toByteData(RGBA)', () async {
final CkAnimatedImage image = CkAnimatedImage.decodeFromBytes(kAnimatedGif, 'test');
const List<List<int>> expectedColors = <List<int>>[
<int>[255, 0, 0, 255],
<int>[0, 255, 0, 255],
<int>[0, 0, 255, 255],
];
for (int i = 0; i < image.frameCount; i++) {
final ui.FrameInfo frame = await image.getNextFrame();
final ByteData? rgba = await frame.image.toByteData();
expect(rgba, isNotNull);
expect(rgba!.buffer.asUint8List(), expectedColors[i]);
}
});
}
/// Tests specific to browser image codecs based functionality.
void _testCkBrowserImageDecoder() {
assert(browserSupportsImageDecoder);
test('ImageDecoder toByteData(PNG)', () async {
final CkBrowserImageDecoder image = await CkBrowserImageDecoder.create(
data: kAnimatedGif,
debugSource: 'test',
);
final ui.FrameInfo frame = await image.getNextFrame();
final ByteData? png = await frame.image.toByteData(format: ui.ImageByteFormat.png);
expect(png, isNotNull);
// The precise PNG encoding is browser-specific, but we can check the file
// signature.
expect(detectContentType(png!.buffer.asUint8List()), 'image/png');
});
test('ImageDecoder toByteData(RGBA)', () async {
final CkBrowserImageDecoder image = await CkBrowserImageDecoder.create(
data: kAnimatedGif,
debugSource: 'test',
);
const List<List<int>> expectedColors = <List<int>>[
<int>[255, 0, 0, 255],
<int>[0, 255, 0, 255],
<int>[0, 0, 255, 255],
];
for (int i = 0; i < image.frameCount; i++) {
final ui.FrameInfo frame = await image.getNextFrame();
final ByteData? rgba = await frame.image.toByteData();
expect(rgba, isNotNull);
expect(rgba!.buffer.asUint8List(), expectedColors[i]);
}
});
test('ImageDecoder expires after inactivity', () async {
const Duration testExpireDuration = Duration(milliseconds: 100);
debugOverrideWebDecoderExpireDuration(testExpireDuration);
final CkBrowserImageDecoder image = await CkBrowserImageDecoder.create(
data: kAnimatedGif,
debugSource: 'test',
);
// ImageDecoder is initialized eagerly to populate `frameCount` and
// `repetitionCount`.
final ImageDecoder? decoder1 = image.debugCachedWebDecoder;
expect(decoder1, isNotNull);
expect(image.frameCount, 3);
expect(image.repetitionCount, -1);
// A frame can be decoded right away.
final ui.FrameInfo frame1 = await image.getNextFrame();
await expectFrameData(frame1, <int>[255, 0, 0, 255]);
expect(frame1, isNotNull);
// The cached decoder should not yet expire.
await Future<void>.delayed(testExpireDuration ~/ 2);
expect(image.debugCachedWebDecoder, same(decoder1));
// Now it expires.
await Future<void>.delayed(testExpireDuration);
expect(image.debugCachedWebDecoder, isNull);
// A new decoder should be created upon the next frame request.
final ui.FrameInfo frame2 = await image.getNextFrame();
// Check that the cached decoder is indeed new.
final ImageDecoder? decoder2 = image.debugCachedWebDecoder;
expect(decoder2, isNot(same(decoder1)));
await expectFrameData(frame2, <int>[0, 255, 0, 255]);
// Check that the new decoder remembers the last frame index.
final ui.FrameInfo frame3 = await image.getNextFrame();
await expectFrameData(frame3, <int>[0, 0, 255, 255]);
debugRestoreWebDecoderExpireDuration();
});
}
Future<void> expectFrameData(ui.FrameInfo frame, List<int> data) async {
final ByteData frameData = (await frame.image.toByteData())!;
expect(frameData.buffer.asUint8List(), Uint8List.fromList(data));
}
| engine/lib/web_ui/test/canvaskit/image_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/image_golden_test.dart",
"repo_id": "engine",
"token_count": 13897
} | 412 |
// 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;
import '../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('$LayerScene', () {
setUpAll(() async {
await bootstrapAndRunApp();
});
test('toImage returns an image', () async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
expect(recorder, isA<CkPictureRecorder>());
final ui.Canvas canvas = ui.Canvas(recorder);
expect(canvas, isA<CanvasKitCanvas>());
final ui.Paint paint = ui.Paint();
expect(paint, isA<CkPaint>());
paint.color = const ui.Color.fromARGB(255, 255, 0, 0);
// Draw a red circle.
canvas.drawCircle(const ui.Offset(20, 20), 10, paint);
final ui.Picture picture = recorder.endRecording();
expect(picture, isA<CkPicture>());
final ui.SceneBuilder builder = ui.SceneBuilder();
expect(builder, isA<LayerSceneBuilder>());
builder.pushOffset(0, 0);
builder.addPicture(ui.Offset.zero, picture);
final ui.Scene scene = builder.build();
final ui.Image sceneImage = await scene.toImage(100, 100);
expect(sceneImage, isA<CkImage>());
});
test('pushColorFilter does not throw', () async {
final ui.SceneBuilder builder = ui.SceneBuilder();
expect(builder, isA<LayerSceneBuilder>());
builder.pushOffset(0, 0);
builder.pushColorFilter(const ui.ColorFilter.srgbToLinearGamma());
final ui.Scene scene = builder.build();
expect(scene, isNotNull);
});
});
}
| engine/lib/web_ui/test/canvaskit/scene_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/scene_test.dart",
"repo_id": "engine",
"token_count": 701
} | 413 |
// 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/test.dart';
import 'package:ui/src/engine.dart' as engine;
import 'package:ui/src/engine/initialization.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import 'fake_asset_manager.dart';
import 'rendering.dart';
void setUpUnitTests({
bool withImplicitView = false,
bool emulateTesterEnvironment = true,
bool setUpTestViewDimensions = true,
}) {
late final FakeAssetScope debugFontsScope;
setUpAll(() async {
if (emulateTesterEnvironment) {
ui_web.debugEmulateFlutterTesterEnvironment = true;
}
debugFontsScope = configureDebugFontsAssetScope(fakeAssetManager);
debugOnlyAssetManager = fakeAssetManager;
await bootstrapAndRunApp(withImplicitView: withImplicitView);
engine.renderer.fontCollection.fontFallbackManager?.downloadQueue.fallbackFontUrlPrefixOverride = 'assets/fallback_fonts/';
if (setUpTestViewDimensions) {
// The following parameters are hard-coded in Flutter's test embedder. Since
// we don't have an embedder yet this is the lowest-most layer we can put
// this stuff in.
const double devicePixelRatio = 3.0;
engine.EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(devicePixelRatio);
engine.EnginePlatformDispatcher.instance.implicitView?.debugPhysicalSizeOverride =
const ui.Size(800 * devicePixelRatio, 600 * devicePixelRatio);
engine.scheduleFrameCallback = () {};
}
setUpRenderingForTests();
});
tearDownAll(() async {
fakeAssetManager.popAssetScope(debugFontsScope);
});
}
Future<void> bootstrapAndRunApp({bool withImplicitView = false}) async {
final Completer<void> completer = Completer<void>();
await ui_web.bootstrapEngine(runApp: () => completer.complete());
await completer.future;
if (!withImplicitView) {
_disableImplicitView();
}
}
void _disableImplicitView() {
// TODO(mdebbar): Instead of disabling the implicit view, we should be able to
// initialize tests without an implicit view to begin with.
// https://github.com/flutter/flutter/issues/138906
final engine.EngineFlutterWindow? implicitView = engine.EnginePlatformDispatcher.instance.implicitView;
if (implicitView != null) {
engine.EnginePlatformDispatcher.instance.viewManager.disposeAndUnregisterView(implicitView.viewId);
}
}
| engine/lib/web_ui/test/common/test_initialization.dart/0 | {
"file_path": "engine/lib/web_ui/test/common/test_initialization.dart",
"repo_id": "engine",
"token_count": 867
} | 414 |
// 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';
// The biggest integer value that can be represented in JavaScript is 1 << 53.
// However, the 1 << 53 expression cannot be used in JavaScript because that
// would apply the bitwise shift to a "number" (i.e. float64), which is
// meaningless. Instead, a decimal literal is used here.
const int _kBiggestExactJavaScriptInt = 9007199254740992;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
// Ignoring the deprecated member use because we're specifically testing
// deprecated API.
// ignore: deprecated_member_use
void testMain() {
test('hashValues and hashList can hash lots of huge values effectively', () {
final int hashValueFromArgs = hashValues(
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
);
// Hash the same values via a list
final int hashValueFromList = hashList(<int>[
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
]);
// Hash a slightly smaller number to verify that the hash code is different.
final int slightlyDifferentHashValueFromArgs = hashValues(
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt - 1,
);
final int slightlyDifferentHashValueFromList = hashList(<int>[
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt,
_kBiggestExactJavaScriptInt - 1,
]);
expect(hashValueFromArgs, equals(hashValueFromList));
expect(slightlyDifferentHashValueFromArgs, equals(slightlyDifferentHashValueFromList));
expect(hashValueFromArgs, isNot(equals(slightlyDifferentHashValueFromArgs)));
});
}
| engine/lib/web_ui/test/engine/hash_codes_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/hash_codes_test.dart",
"repo_id": "engine",
"token_count": 1803
} | 415 |
// 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;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
const MethodCodec codec = JSONMethodCodec();
void sendSetSystemUIOverlayStyle({ui.Color? statusBarColor}) {
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/platform',
codec.encodeMethodCall(MethodCall(
'SystemChrome.setSystemUIOverlayStyle',
<String, dynamic>{
'statusBarColor': statusBarColor?.value,
},
)),
null,
);
}
String? getCssThemeColor() {
final DomHTMLMetaElement? theme =
domDocument.querySelector('#flutterweb-theme') as DomHTMLMetaElement?;
return theme?.content;
}
group('SystemUIOverlayStyle', () {
test('theme color is set / removed by platform message', () {
// Run the unit test without emulating Flutter tester environment.
ui_web.debugEmulateFlutterTesterEnvironment = false;
expect(getCssThemeColor(), null);
const ui.Color statusBarColor = ui.Color(0xFFF44336);
sendSetSystemUIOverlayStyle(statusBarColor: statusBarColor);
expect(getCssThemeColor(), statusBarColor.toCssString());
sendSetSystemUIOverlayStyle();
expect(getCssThemeColor(), null);
});
});
}
| engine/lib/web_ui/test/engine/platform_dispatcher/system_ui_overlay_style_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/platform_dispatcher/system_ui_overlay_style_test.dart",
"repo_id": "engine",
"token_count": 586
} | 416 |
// 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';
import '../../common/test_initialization.dart';
import 'semantics_tester.dart';
EngineSemantics semantics() => EngineSemantics.instance;
EngineSemanticsOwner owner() => EnginePlatformDispatcher.instance.implicitView!.semantics;
void main() {
internalBootstrapBrowserTest(() {
return testMain;
});
}
Future<void> testMain() async {
await bootstrapAndRunApp(withImplicitView: true);
test('EngineSemanticsOwner auto-enables semantics on update', () async {
expect(semantics().semanticsEnabled, isFalse);
expect(
EnginePlatformDispatcher
.instance.accessibilityFeatures.accessibleNavigation,
isFalse);
final DomElement placeholder = domDocument.querySelector('flt-semantics-placeholder')!;
expect(placeholder.isConnected, isTrue);
// Sending a semantics update should auto-enable engine semantics.
final SemanticsTester tester = SemanticsTester(owner());
tester.updateNode(id: 0);
tester.apply();
expect(semantics().semanticsEnabled, isTrue);
expect(
EnginePlatformDispatcher.instance.accessibilityFeatures.accessibleNavigation,
isTrue,
);
// The placeholder should be removed
expect(placeholder.isConnected, isFalse);
});
}
| engine/lib/web_ui/test/engine/semantics/semantics_auto_enable_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/semantics/semantics_auto_enable_test.dart",
"repo_id": "engine",
"token_count": 493
} | 417 |
// 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';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('Surface', () {
setUpAll(() async {
await bootstrapAndRunApp(withImplicitView: true);
});
setUp(() {
SurfaceSceneBuilder.debugForgetFrameScene();
});
test('debugAssertSurfaceState produces a human-readable message', () {
final SceneBuilder builder = SceneBuilder();
final PersistedOpacity opacityLayer = builder.pushOpacity(100) as PersistedOpacity;
try {
debugAssertSurfaceState(opacityLayer, PersistedSurfaceState.active, PersistedSurfaceState.pendingRetention);
fail('Expected $PersistedSurfaceException');
} on PersistedSurfaceException catch (exception) {
expect(
'$exception',
'PersistedOpacity: is in an unexpected state.\n'
'Expected one of: PersistedSurfaceState.active, PersistedSurfaceState.pendingRetention\n'
'But was: PersistedSurfaceState.created',
);
}
});
test('is created', () {
final SceneBuilder builder = SceneBuilder();
final PersistedOpacity opacityLayer = builder.pushOpacity(100) as PersistedOpacity;
builder.pop();
expect(opacityLayer, isNotNull);
expect(opacityLayer.rootElement, isNull);
expect(opacityLayer.isCreated, isTrue);
builder.build();
expect(opacityLayer.rootElement!.tagName.toLowerCase(), 'flt-opacity');
expect(opacityLayer.isActive, isTrue);
});
test('is released', () {
final SceneBuilder builder1 = SceneBuilder();
final PersistedOpacity opacityLayer = builder1.pushOpacity(100) as PersistedOpacity;
builder1.pop();
builder1.build();
expect(opacityLayer.isActive, isTrue);
SceneBuilder().build();
expect(opacityLayer.isReleased, isTrue);
expect(opacityLayer.rootElement, isNull);
});
test('discarding is recursive', () {
final SceneBuilder builder1 = SceneBuilder();
final PersistedOpacity opacityLayer = builder1.pushOpacity(100) as PersistedOpacity;
final PersistedTransform transformLayer =
builder1.pushTransform(Matrix4.identity().toFloat64()) as PersistedTransform;
builder1.pop();
builder1.pop();
builder1.build();
expect(opacityLayer.isActive, isTrue);
expect(transformLayer.isActive, isTrue);
SceneBuilder().build();
expect(opacityLayer.isReleased, isTrue);
expect(transformLayer.isReleased, isTrue);
expect(opacityLayer.rootElement, isNull);
expect(transformLayer.rootElement, isNull);
});
test('is updated', () {
final SceneBuilder builder1 = SceneBuilder();
final PersistedOpacity opacityLayer1 = builder1.pushOpacity(100) as PersistedOpacity;
builder1.pop();
builder1.build();
expect(opacityLayer1.isActive, isTrue);
final DomElement element = opacityLayer1.rootElement!;
final SceneBuilder builder2 = SceneBuilder();
final PersistedOpacity opacityLayer2 =
builder2.pushOpacity(200, oldLayer: opacityLayer1) as PersistedOpacity;
expect(opacityLayer1.isPendingUpdate, isTrue);
expect(opacityLayer2.isCreated, isTrue);
expect(opacityLayer2.oldLayer, same(opacityLayer1));
builder2.pop();
builder2.build();
expect(opacityLayer1.isReleased, isTrue);
expect(opacityLayer1.rootElement, isNull);
expect(opacityLayer2.isActive, isTrue);
expect(
opacityLayer2.rootElement, element); // adopts old surface's element
expect(opacityLayer2.oldLayer, isNull);
});
test('ignores released surface when updated', () {
// Build a surface
final SceneBuilder builder1 = SceneBuilder();
final PersistedOpacity opacityLayer1 = builder1.pushOpacity(100) as PersistedOpacity;
builder1.pop();
builder1.build();
expect(opacityLayer1.isActive, isTrue);
final DomElement element = opacityLayer1.rootElement!;
// Release it
SceneBuilder().build();
expect(opacityLayer1.isReleased, isTrue);
expect(opacityLayer1.rootElement, isNull);
// Attempt to update it
final SceneBuilder builder2 = SceneBuilder();
final PersistedOpacity opacityLayer2 =
builder2.pushOpacity(200, oldLayer: opacityLayer1) as PersistedOpacity;
builder2.pop();
expect(opacityLayer1.isReleased, isTrue);
expect(opacityLayer2.isCreated, isTrue);
builder2.build();
expect(opacityLayer1.isReleased, isTrue);
expect(opacityLayer2.isActive, isTrue);
expect(opacityLayer2.rootElement, isNot(equals(element)));
});
// This test creates a situation when an intermediate layer disappears,
// causing its child to become a direct child of the common ancestor. This
// often happens with opacity layers. When opacity reaches 1.0, the
// framework removes that layer (as it is no longer necessary). This test
// makes sure we reuse the child layer's DOM nodes. Here's the illustration
// of what's happening:
//
// Frame 1 Frame 2
//
// A A
// | |
// B ┌──>C
// | │ |
// C ────┘ L
// |
// L
//
// Layer "L" is a logging layer used to track what would happen to the
// child of "C" as it's being dragged around the tree. For example, we
// check that the child doesn't get discarded by mistake.
test('reparents DOM element when updated', () {
final _LoggingTestSurface logger = _LoggingTestSurface();
final SurfaceSceneBuilder builder1 = SurfaceSceneBuilder();
final PersistedTransform a1 =
builder1.pushTransform(
(Matrix4.identity()..scale(EngineFlutterDisplay.instance.browserDevicePixelRatio)).toFloat64()) as PersistedTransform;
final PersistedOpacity b1 = builder1.pushOpacity(100) as PersistedOpacity;
final PersistedTransform c1 =
builder1.pushTransform(Matrix4.identity().toFloat64()) as PersistedTransform;
builder1.debugAddSurface(logger);
builder1.pop();
builder1.pop();
builder1.pop();
builder1.build();
expect(logger.log, <String>['build', 'createElement', 'apply']);
final DomElement elementA = a1.rootElement!;
final DomElement elementB = b1.rootElement!;
final DomElement elementC = c1.rootElement!;
expect(elementC.parent, elementB);
expect(elementB.parent, elementA);
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
final PersistedTransform a2 =
builder2.pushTransform(
(Matrix4.identity()..scale(EngineFlutterDisplay.instance.browserDevicePixelRatio)).toFloat64(),
oldLayer: a1) as PersistedTransform;
final PersistedTransform c2 =
builder2.pushTransform(Matrix4.identity().toFloat64(), oldLayer: c1) as PersistedTransform;
builder2.addRetained(logger);
builder2.pop();
builder2.pop();
expect(c1.isPendingUpdate, isTrue);
expect(c2.isCreated, isTrue);
builder2.build();
expect(logger.log, <String>['build', 'createElement', 'apply', 'retain']);
expect(c1.isReleased, isTrue);
expect(c2.isActive, isTrue);
expect(a2.rootElement, elementA);
expect(b1.rootElement, isNull);
expect(c2.rootElement, elementC);
expect(elementC.parent, elementA);
expect(elementB.parent, null);
},
// This method failed on iOS Safari.
// TODO(ferhat): https://github.com/flutter/flutter/issues/60036
skip: browserEngine == BrowserEngine.webkit &&
operatingSystem == OperatingSystem.iOs);
test('is retained', () {
final SceneBuilder builder1 = SceneBuilder();
final PersistedOpacity opacityLayer = builder1.pushOpacity(100) as PersistedOpacity;
builder1.pop();
builder1.build();
expect(opacityLayer.isActive, isTrue);
final DomElement element = opacityLayer.rootElement!;
final SceneBuilder builder2 = SceneBuilder();
expect(opacityLayer.isActive, isTrue);
builder2.addRetained(opacityLayer);
expect(opacityLayer.isPendingRetention, isTrue);
builder2.build();
expect(opacityLayer.isActive, isTrue);
expect(opacityLayer.rootElement, element);
});
test('revives released surface when retained', () {
final SurfaceSceneBuilder builder1 = SurfaceSceneBuilder();
final PersistedOpacity opacityLayer = builder1.pushOpacity(100) as PersistedOpacity;
final _LoggingTestSurface logger = _LoggingTestSurface();
builder1.debugAddSurface(logger);
builder1.pop();
builder1.build();
expect(opacityLayer.isActive, isTrue);
expect(logger.log, <String>['build', 'createElement', 'apply']);
final DomElement element = opacityLayer.rootElement!;
SceneBuilder().build();
expect(opacityLayer.isReleased, isTrue);
expect(opacityLayer.rootElement, isNull);
expect(logger.log, <String>['build', 'createElement', 'apply', 'discard']);
final SceneBuilder builder2 = SceneBuilder();
builder2.addRetained(opacityLayer);
expect(opacityLayer.isCreated, isTrue); // revived
expect(logger.log, <String>['build', 'createElement', 'apply', 'discard', 'revive']);
builder2.build();
expect(opacityLayer.isActive, isTrue);
expect(opacityLayer.rootElement, isNot(equals(element)));
});
test('reviving is recursive', () {
final SceneBuilder builder1 = SceneBuilder();
final PersistedOpacity opacityLayer = builder1.pushOpacity(100) as PersistedOpacity;
final PersistedTransform transformLayer =
builder1.pushTransform(Matrix4.identity().toFloat64()) as PersistedTransform;
builder1.pop();
builder1.pop();
builder1.build();
expect(opacityLayer.isActive, isTrue);
expect(transformLayer.isActive, isTrue);
final DomElement opacityElement = opacityLayer.rootElement!;
final DomElement transformElement = transformLayer.rootElement!;
SceneBuilder().build();
final SceneBuilder builder2 = SceneBuilder();
builder2.addRetained(opacityLayer);
expect(opacityLayer.isCreated, isTrue); // revived
expect(transformLayer.isCreated, isTrue); // revived
builder2.build();
expect(opacityLayer.isActive, isTrue);
expect(transformLayer.isActive, isTrue);
expect(opacityLayer.rootElement, isNot(equals(opacityElement)));
expect(transformLayer.rootElement, isNot(equals(transformElement)));
});
// This test creates a situation when a retained layer is moved to another
// parent. We want to make sure that we move the retained layer's elements
// without rebuilding from scratch. No new elements are created in this
// situation.
//
// Here's an illustrated example where layer C is reparented onto B along
// with D:
//
// Frame 1 Frame 2
//
// A A
// ╱ ╲ |
// B C ──┐ B
// | │ |
// D └──>C
// |
// D
test('reparents DOM elements when retained', () {
final SceneBuilder builder1 = SceneBuilder();
final PersistedOpacity a1 = builder1.pushOpacity(10) as PersistedOpacity;
final PersistedOpacity b1 = builder1.pushOpacity(20) as PersistedOpacity;
builder1.pop();
final PersistedOpacity c1 = builder1.pushOpacity(30) as PersistedOpacity;
final PersistedOpacity d1 = builder1.pushOpacity(40) as PersistedOpacity;
builder1.pop();
builder1.pop();
builder1.pop();
builder1.build();
final DomElement elementA = a1.rootElement!;
final DomElement elementB = b1.rootElement!;
final DomElement elementC = c1.rootElement!;
final DomElement elementD = d1.rootElement!;
expect(elementB.parent, elementA);
expect(elementC.parent, elementA);
expect(elementD.parent, elementC);
final SceneBuilder builder2 = SceneBuilder();
final PersistedOpacity a2 = builder2.pushOpacity(10, oldLayer: a1) as PersistedOpacity;
final PersistedOpacity b2 = builder2.pushOpacity(20, oldLayer: b1) as PersistedOpacity;
builder2.addRetained(c1);
builder2.pop();
builder2.pop();
builder2.build();
expect(a2.rootElement, elementA);
expect(b2.rootElement, elementB);
expect(c1.rootElement, elementC);
expect(d1.rootElement, elementD);
expect(
<DomElement>[
elementD.parent!,
elementC.parent!,
elementB.parent!,
],
<DomElement>[elementC, elementB, elementA],
);
});
test('is updated by matching', () {
final SceneBuilder builder1 = SceneBuilder();
final PersistedOpacity opacityLayer1 = builder1.pushOpacity(100) as PersistedOpacity;
builder1.pop();
builder1.build();
expect(opacityLayer1.isActive, isTrue);
final DomElement element = opacityLayer1.rootElement!;
final SceneBuilder builder2 = SceneBuilder();
final PersistedOpacity opacityLayer2 = builder2.pushOpacity(200) as PersistedOpacity;
expect(opacityLayer1.isActive, isTrue);
expect(opacityLayer2.isCreated, isTrue);
builder2.pop();
builder2.build();
expect(opacityLayer1.isReleased, isTrue);
expect(opacityLayer1.rootElement, isNull);
expect(opacityLayer2.isActive, isTrue);
expect(
opacityLayer2.rootElement, element); // adopts old surface's element
});
});
final Map<String, TestEngineLayerFactory> layerFactories = <String, TestEngineLayerFactory>{
'ColorFilterEngineLayer': (SurfaceSceneBuilder builder) => builder.pushColorFilter(const ColorFilter.mode(
Color(0xFFFF0000),
BlendMode.srcIn,
)),
'OffsetEngineLayer': (SurfaceSceneBuilder builder) => builder.pushOffset(1, 2),
'TransformEngineLayer': (SurfaceSceneBuilder builder) => builder.pushTransform(Matrix4.identity().toFloat64()),
'ClipRectEngineLayer': (SurfaceSceneBuilder builder) => builder.pushClipRect(const Rect.fromLTRB(0, 0, 10, 10)),
'ClipRRectEngineLayer': (SurfaceSceneBuilder builder) => builder.pushClipRRect(RRect.fromRectXY(const Rect.fromLTRB(0, 0, 10, 10), 1, 2)),
'ClipPathEngineLayer': (SurfaceSceneBuilder builder) => builder.pushClipPath(Path()..addRect(const Rect.fromLTRB(0, 0, 10, 10))),
'OpacityEngineLayer': (SurfaceSceneBuilder builder) => builder.pushOpacity(100),
'ImageFilterEngineLayer': (SurfaceSceneBuilder builder) => builder.pushImageFilter(ImageFilter.blur(sigmaX: 0.1, sigmaY: 0.2)),
'BackdropEngineLayer': (SurfaceSceneBuilder builder) => builder.pushBackdropFilter(ImageFilter.blur(sigmaX: 0.1, sigmaY: 0.2)),
// Firefox does not support WebGL in headless mode.
if (!isFirefox)
'ShaderMaskEngineLayer': (SurfaceSceneBuilder builder) {
const List<Color> colors = <Color>[Color(0xFF000000), Color(0xFFFF3C38)];
const List<double> stops = <double>[0.0, 1.0];
const Rect shaderBounds = Rect.fromLTWH(180, 10, 140, 140);
final EngineGradient shader = GradientLinear(
Offset(200 - shaderBounds.left, 30 - shaderBounds.top),
Offset(320 - shaderBounds.left, 150 - shaderBounds.top),
colors, stops, TileMode.clamp, Matrix4.identity().storage,
);
return builder.pushShaderMask(shader, shaderBounds, BlendMode.srcOver);
},
};
// Regression test for https://github.com/flutter/flutter/issues/104305
for (final MapEntry<String, TestEngineLayerFactory> layerFactory in layerFactories.entries) {
test('${layerFactory.key} supports addRetained after being discarded', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushOffset(0, 0);
final PersistedSurface oldLayer = layerFactory.value(builder) as PersistedSurface;
builder.pop();
builder.pop();
builder.build();
expect(oldLayer.isActive, isTrue);
// Pump an empty frame so the `oldLayer` is discarded before it's reused.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.build();
expect(oldLayer.isReleased, isTrue);
// At this point the `oldLayer` needs to be revived.
final SurfaceSceneBuilder builder3 = SurfaceSceneBuilder();
builder3.addRetained(oldLayer);
builder3.build();
expect(oldLayer.isActive, isTrue);
});
}
}
typedef TestEngineLayerFactory = EngineLayer Function(SurfaceSceneBuilder builder);
class _LoggingTestSurface extends PersistedContainerSurface {
_LoggingTestSurface() : super(null);
final List<String> log = <String>[];
@override
void build() {
log.add('build');
super.build();
}
@override
void apply() {
log.add('apply');
}
@override
DomElement createElement() {
log.add('createElement');
return createDomElement('flt-test-layer');
}
@override
void update(_LoggingTestSurface oldSurface) {
log.add('update');
super.update(oldSurface);
}
@override
void adoptElements(covariant PersistedSurface oldSurface) {
log.add('adoptElements');
super.adoptElements(oldSurface);
}
@override
void retain() {
log.add('retain');
super.retain();
}
@override
void discard() {
log.add('discard');
super.discard();
}
@override
void revive() {
log.add('revive');
super.revive();
}
@override
double matchForUpdate(PersistedSurface? existingSurface) {
return 1.0;
}
}
| engine/lib/web_ui/test/engine/surface/surface_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/surface/surface_test.dart",
"repo_id": "engine",
"token_count": 6664
} | 418 |
// 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 'dart:js_interop';
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/hot_restart_cache_handler.dart';
@JS('window.__flutterState')
external JSArray<JSAny?>? get _jsHotRestartStore;
@JS('window.__flutterState')
external set _jsHotRestartStore(JSArray<JSAny?>? nodes);
void main() {
internalBootstrapBrowserTest(() => doTests);
}
void doTests() {
tearDown(() {
_jsHotRestartStore = null;
});
group('registerElementForCleanup', () {
test('stores elements in a global cache', () async {
final DomElement toBeCached = createDomElement('some-element-to-cache');
final DomElement other = createDomElement('other-element-to-cache');
final DomElement another = createDomElement('another-element-to-cache');
registerElementForCleanup(toBeCached);
registerElementForCleanup(other);
registerElementForCleanup(another);
expect(_jsHotRestartStore!.toDart, <DomElement>[
toBeCached,
other,
another,
]);
});
});
group('HotRestartCacheHandler Constructor', () {
test('Creates a cache in the JS environment', () async {
HotRestartCacheHandler();
expect(_jsHotRestartStore, isNotNull);
// For dart2wasm, we have to check the length this way.
expect(_jsHotRestartStore!.length, 0.toJS);
});
});
group('HotRestartCacheHandler.registerElement', () {
late HotRestartCacheHandler cache;
setUp(() {
cache = HotRestartCacheHandler();
});
test('Registers an element in the DOM cache', () async {
final DomElement element = createDomElement('for-test');
cache.registerElement(element);
expect(_jsHotRestartStore!.toDart, <DomElement>[element]);
});
test('Registers elements in the DOM cache', () async {
final DomElement element = createDomElement('for-test');
domDocument.body!.append(element);
cache.registerElement(element);
expect(_jsHotRestartStore!.toDart, <DomElement>[element]);
});
test('Clears registered elements from the DOM and the cache upon restart',
() async {
final DomElement element = createDomElement('for-test');
final DomElement element2 = createDomElement('for-test-two');
domDocument.body!.append(element);
domDocument.body!.append(element2);
cache.registerElement(element);
expect(element.isConnected, isTrue);
expect(element2.isConnected, isTrue);
// Simulate a hot restart...
cache = HotRestartCacheHandler();
// For dart2wasm, we have to check the length this way.
expect(_jsHotRestartStore!.length, 0.toJS);
expect(element.isConnected, isFalse); // Removed
expect(element2.isConnected, isTrue);
});
});
}
| engine/lib/web_ui/test/engine/view_embedder/hot_restart_cache_handler_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/view_embedder/hot_restart_cache_handler_test.dart",
"repo_id": "engine",
"token_count": 1074
} | 419 |
// 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 Rect region = Rect.fromLTWH(0, 0, 500, 500);
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
setUp(() async {
debugShowClipLayers = true;
SurfaceSceneBuilder.debugForgetFrameScene();
for (final DomNode scene in domDocument.querySelectorAll('flt-scene')) {
scene.remove();
}
});
test('Should apply color filter to image', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final Picture backgroundPicture = _drawBackground();
builder.addPicture(Offset.zero, backgroundPicture);
builder.pushColorFilter(
const EngineColorFilter.mode(Color(0xF0000080), BlendMode.color));
final Picture circles1 = _drawTestPictureWithCircles(30, 30);
builder.addPicture(Offset.zero, circles1);
builder.pop();
domDocument.body!.append(builder.build().webOnlyRootElement!);
// TODO(ferhat): update golden for this test after canvas sandwich detection is
// added to RecordingCanvas.
await matchGoldenFile('color_filter_blendMode_color.png', region: region);
});
test('Should apply matrix color filter to image', () async {
final List<double> colorMatrix = <double>[
0.2126, 0.7152, 0.0722, 0, 0, //
0.2126, 0.7152, 0.0722, 0, 0, //
0.2126, 0.7152, 0.0722, 0, 0, //
0, 0, 0, 1, 0, //
];
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final Picture backgroundPicture = _drawBackground();
builder.addPicture(Offset.zero, backgroundPicture);
builder.pushColorFilter(
EngineColorFilter.matrix(colorMatrix));
final Picture circles1 = _drawTestPictureWithCircles(30, 30);
builder.addPicture(Offset.zero, circles1);
builder.pop();
domDocument.body!.append(builder.build().webOnlyRootElement!);
await matchGoldenFile('color_filter_matrix.png', region: region);
});
/// Regression test for https://github.com/flutter/flutter/issues/85733
test('Should apply mode color filter to circles', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final Picture backgroundPicture = _drawBackground();
builder.addPicture(Offset.zero, backgroundPicture);
builder.pushColorFilter(
const ColorFilter.mode(
Color(0xFFFF0000),
BlendMode.srcIn,
));
final Picture circles1 = _drawTestPictureWithCircles(30, 30);
builder.addPicture(Offset.zero, circles1);
builder.pop();
domDocument.body!.append(builder.build().webOnlyRootElement!);
await matchGoldenFile('color_filter_mode.png', region: region);
});
}
Picture _drawTestPictureWithCircles(double offsetX, double offsetY) {
final EnginePictureRecorder recorder =
PictureRecorder() as EnginePictureRecorder;
final RecordingCanvas canvas =
recorder.beginRecording(const Rect.fromLTRB(0, 0, 400, 400));
canvas.drawCircle(Offset(offsetX + 10, offsetY + 10), 10,
(Paint()..style = PaintingStyle.fill) as SurfacePaint);
canvas.drawCircle(
Offset(offsetX + 60, offsetY + 10),
10,
(Paint()
..style = PaintingStyle.fill
..color = const Color.fromRGBO(255, 0, 0, 1)) as SurfacePaint);
canvas.drawCircle(
Offset(offsetX + 10, offsetY + 60),
10,
(Paint()
..style = PaintingStyle.fill
..color = const Color.fromRGBO(0, 255, 0, 1)) as SurfacePaint);
canvas.drawCircle(
Offset(offsetX + 60, offsetY + 60),
10,
(Paint()
..style = PaintingStyle.fill
..color = const Color.fromRGBO(0, 0, 255, 1)) as SurfacePaint);
return recorder.endRecording();
}
Picture _drawBackground() {
final EnginePictureRecorder recorder =
PictureRecorder() as EnginePictureRecorder;
final RecordingCanvas canvas =
recorder.beginRecording(const Rect.fromLTRB(0, 0, 400, 400));
canvas.drawRect(
const Rect.fromLTWH(8, 8, 400.0 - 16, 400.0 - 16),
(Paint()
..style = PaintingStyle.fill
..color = const Color(0xFFE0FFE0)) as SurfacePaint);
return recorder.endRecording();
}
| engine/lib/web_ui/test/html/compositing/color_filter_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/compositing/color_filter_golden_test.dart",
"repo_id": "engine",
"token_count": 1646
} | 420 |
// 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';
import 'package:ui/ui.dart' hide TextStyle;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Matcher listEqual(List<int> source, {int tolerance = 0}) {
return predicate(
(List<int> target) {
if (source.length != target.length) {
return false;
}
for (int i = 0; i < source.length; i += 1) {
if ((source[i] - target[i]).abs() > tolerance) {
return false;
}
}
return true;
},
source.toString(),
);
}
// Converts `rawPixels` into a list of bytes that represent raw pixels in rgba8888.
//
// Each element of `rawPixels` represents a bytes in order 0xRRGGBBAA, with
// pixel order Left to right, then top to bottom.
Uint8List _pixelsToBytes(List<int> rawPixels) {
return Uint8List.fromList(<int>[
for (final int pixel in rawPixels)
...<int>[
(pixel >> 24) & 0xff, // r
(pixel >> 16) & 0xff, // g
(pixel >> 8) & 0xff, // b
(pixel >> 0) & 0xff, // a
]
]);
}
Future<Image> _encodeToHtmlThenDecode(
Uint8List rawBytes,
int width,
int height, {
PixelFormat pixelFormat = PixelFormat.rgba8888,
}) async {
final ImageDescriptor descriptor = ImageDescriptor.raw(
await ImmutableBuffer.fromUint8List(rawBytes),
width: width,
height: height,
pixelFormat: pixelFormat,
);
return (await (await descriptor.instantiateCodec()).getNextFrame()).image;
}
// This utility function detects how the current Web engine decodes pixel data.
//
// The HTML renderer uses the BMP format to display pixel data, but it used to
// use a wrong implementation. The bug has been fixed, but the fix breaks apps
// that had to provide incorrect data to work around this issue. This function
// is used in the migration guide to assist libraries that would like to run on
// both pre- and post-patch engines by testing the current behavior on a single
// pixel, making use the fact that the patch fixes the pixel order.
//
// The `format` argument is used for testing. In the actual code it should be
// replaced by `PixelFormat.rgba8888`.
//
// See also:
//
// * Patch: https://github.com/flutter/engine/pull/29448
// * Migration guide: https://docs.flutter.dev/release/breaking-changes/raw-images-on-web-uses-correct-origin-and-colors
Future<bool> rawImageUsesCorrectBehavior(PixelFormat format) async {
final ImageDescriptor descriptor = ImageDescriptor.raw(
await ImmutableBuffer.fromUint8List(Uint8List.fromList(<int>[0xED, 0, 0, 0xFF])),
width: 1, height: 1, pixelFormat: format);
final Image image = (await (await descriptor.instantiateCodec()).getNextFrame()).image;
final Uint8List resultPixels = Uint8List.sublistView(
(await image.toByteData(format: ImageByteFormat.rawStraightRgba))!);
return resultPixels[0] == 0xED;
}
Future<void> testMain() async {
test('Correctly encodes an opaque image', () async {
// A 2x2 testing image without transparency.
final Image sourceImage = await _encodeToHtmlThenDecode(
_pixelsToBytes(
<int>[0xFF0102FF, 0x04FE05FF, 0x0708FDFF, 0x0A0B0C00],
), 2, 2,
);
final Uint8List actualPixels = Uint8List.sublistView(
(await sourceImage.toByteData(format: ImageByteFormat.rawStraightRgba))!);
// The `benchmarkPixels` is identical to `sourceImage` except for the fully
// transparent last pixel, whose channels are turned 0.
final Uint8List benchmarkPixels = _pixelsToBytes(
<int>[0xFF0102FF, 0x04FE05FF, 0x0708FDFF, 0x00000000],
);
expect(actualPixels, listEqual(benchmarkPixels));
});
test('Correctly encodes an opaque image in bgra8888', () async {
// A 2x2 testing image without transparency.
final Image sourceImage = await _encodeToHtmlThenDecode(
_pixelsToBytes(
<int>[0xFF0102FF, 0x04FE05FF, 0x0708FDFF, 0x0A0B0C00],
), 2, 2, pixelFormat: PixelFormat.bgra8888,
);
final Uint8List actualPixels = Uint8List.sublistView(
(await sourceImage.toByteData(format: ImageByteFormat.rawStraightRgba))!);
// The `benchmarkPixels` is the same as `sourceImage` except that the R and
// G channels are swapped and the fully transparent last pixel is turned 0.
final Uint8List benchmarkPixels = _pixelsToBytes(
<int>[0x0201FFFF, 0x05FE04FF, 0xFD0807FF, 0x00000000],
);
expect(actualPixels, listEqual(benchmarkPixels));
});
test('Correctly encodes a transparent image', () async {
// A 2x2 testing image with transparency.
final Image sourceImage = await _encodeToHtmlThenDecode(
_pixelsToBytes(
<int>[0xFF800006, 0xFF800080, 0xFF8000C0, 0xFF8000FF],
), 2, 2,
);
final Image blueBackground = await _encodeToHtmlThenDecode(
_pixelsToBytes(
<int>[0x0000FFFF, 0x0000FFFF, 0x0000FFFF, 0x0000FFFF],
), 2, 2,
);
// The standard way of testing the raw bytes of `sourceImage` is to draw
// the image onto a canvas and fetch its data (see HtmlImage.toByteData).
// But here, we draw an opaque background first before drawing the image,
// and test if the blended result is expected.
//
// This is because, if we only draw the `sourceImage`, the resulting pixels
// will be slightly off from the raw pixels. The reason is unknown, but
// very likely because the canvas.getImageData introduces rounding errors
// if any pixels are left semi-transparent, which might be caused by
// converting to and from pre-multiplied values. See
// https://github.com/flutter/flutter/issues/92958 .
final DomCanvasElement canvas = createDomCanvasElement()
..width = 2
..height = 2;
final DomCanvasRenderingContext2D ctx = canvas.context2D;
ctx.drawImage((blueBackground as HtmlImage).imgElement, 0, 0);
ctx.drawImage((sourceImage as HtmlImage).imgElement, 0, 0);
final DomImageData imageData = ctx.getImageData(0, 0, 2, 2);
final List<int> actualPixels = imageData.data;
final Uint8List benchmarkPixels = _pixelsToBytes(
<int>[0x0603F9FF, 0x80407FFF, 0xC0603FFF, 0xFF8000FF],
);
expect(actualPixels, listEqual(benchmarkPixels, tolerance: 1));
});
test('The behavior detector works correctly', () async {
expect(await rawImageUsesCorrectBehavior(PixelFormat.rgba8888), true);
expect(await rawImageUsesCorrectBehavior(PixelFormat.bgra8888), false);
});
}
| engine/lib/web_ui/test/html/image_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/image_test.dart",
"repo_id": "engine",
"token_count": 2402
} | 421 |
// 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 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide TextStyle;
import '../common/test_initialization.dart';
import 'screenshot.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
const double screenWidth = 600.0;
const double screenHeight = 800.0;
const Rect screenRect = Rect.fromLTWH(0, 0, screenWidth, screenHeight);
setUpUnitTests(
setUpTestViewDimensions: false,
);
test('Should draw transformed line.', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500));
final Path path = Path();
path.moveTo(0, 0);
path.lineTo(300, 200);
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFF404000));
final Path transformedPath = Path();
final Matrix4 testMatrixTranslateRotate =
Matrix4.rotationZ(math.pi * 30.0 / 180.0)..translate(100, 20);
transformedPath.addPath(path, Offset.zero,
matrix4: testMatrixTranslateRotate.toFloat64());
rc.drawPath(
transformedPath,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color.fromRGBO(0, 128, 255, 1.0));
await canvasScreenshot(rc, 'path_transform_with_line', canvasRect: screenRect);
});
test('Should draw transformed line.', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500));
final Path path = Path();
path.addRect(const Rect.fromLTRB(50, 40, 300, 100));
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFF404000));
final Path transformedPath = Path();
final Matrix4 testMatrixTranslateRotate =
Matrix4.rotationZ(math.pi * 30.0 / 180.0)..translate(100, 20);
transformedPath.addPath(path, Offset.zero,
matrix4: testMatrixTranslateRotate.toFloat64());
rc.drawPath(
transformedPath,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color.fromRGBO(0, 128, 255, 1.0));
await canvasScreenshot(rc, 'path_transform_with_rect', canvasRect: screenRect);
});
test('Should draw transformed quadratic curve.', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500));
final Path path = Path();
path.moveTo(100, 100);
path.quadraticBezierTo(100, 300, 400, 300);
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFF404000));
final Path transformedPath = Path();
final Matrix4 testMatrixTranslateRotate =
Matrix4.rotationZ(math.pi * 30.0 / 180.0)..translate(100, -80);
transformedPath.addPath(path, Offset.zero,
matrix4: testMatrixTranslateRotate.toFloat64());
rc.drawPath(
transformedPath,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color.fromRGBO(0, 128, 255, 1.0));
await canvasScreenshot(rc, 'path_transform_with_quadratic_curve', canvasRect: screenRect);
});
test('Should draw transformed conic.', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500));
const double yStart = 20;
const Offset p0 = Offset(25, yStart + 25);
const Offset pc = Offset(60, yStart + 150);
const Offset p2 = Offset(100, yStart + 50);
final Path path = Path();
path.moveTo(p0.dx, p0.dy);
path.conicTo(pc.dx, pc.dy, p2.dx, p2.dy, 0.5);
path.close();
path.moveTo(p0.dx, p0.dy + 100);
path.conicTo(pc.dx, pc.dy + 100, p2.dx, p2.dy + 100, 10);
path.close();
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFF404000));
final Path transformedPath = Path();
final Matrix4 testMatrixTranslateRotate =
Matrix4.rotationZ(math.pi * 30.0 / 180.0)..translate(100, -80);
transformedPath.addPath(path, Offset.zero,
matrix4: testMatrixTranslateRotate.toFloat64());
rc.drawPath(
transformedPath,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color.fromRGBO(0, 128, 255, 1.0));
await canvasScreenshot(rc, 'path_transform_with_conic', canvasRect: screenRect);
});
test('Should draw transformed arc.', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500));
final Path path = Path();
path.moveTo(350, 280);
path.arcToPoint(const Offset(450, 90),
radius: const Radius.elliptical(200, 50),
rotation: -math.pi / 6.0,
largeArc: true);
path.close();
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFF404000));
final Path transformedPath = Path();
final Matrix4 testMatrixTranslateRotate =
Matrix4.rotationZ(math.pi * 30.0 / 180.0)..translate(100, 10);
transformedPath.addPath(path, Offset.zero,
matrix4: testMatrixTranslateRotate.toFloat64());
rc.drawPath(
transformedPath,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color.fromRGBO(0, 128, 255, 1.0));
await canvasScreenshot(rc, 'path_transform_with_arc', canvasRect: screenRect);
});
test('Should draw transformed rrect.', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500));
final Path path = Path();
path.addRRect(RRect.fromLTRBR(50, 50, 300, 200, const Radius.elliptical(4, 8)));
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFF404000));
final Path transformedPath = Path();
final Matrix4 testMatrixTranslateRotate =
Matrix4.rotationZ(math.pi * 30.0 / 180.0)..translate(100, -80);
transformedPath.addPath(path, Offset.zero,
matrix4: testMatrixTranslateRotate.toFloat64());
rc.drawPath(
transformedPath,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color.fromRGBO(0, 128, 255, 1.0));
await canvasScreenshot(rc, 'path_transform_with_rrect', canvasRect: screenRect);
});
}
| engine/lib/web_ui/test/html/path_transform_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/path_transform_golden_test.dart",
"repo_id": "engine",
"token_count": 2887
} | 422 |
// 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 '../paragraph/helper.dart';
final EngineTextStyle defaultStyle = EngineTextStyle.only(
fontFamily: StyleManager.defaultFontFamily,
fontSize: StyleManager.defaultFontSize,
);
final EngineTextStyle style1 = defaultStyle.copyWith(fontSize: 20);
final EngineTextStyle style2 = defaultStyle.copyWith(color: blue);
final EngineTextStyle style3 = defaultStyle.copyWith(fontFamily: 'Roboto');
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
group('$LayoutFragmenter', () {
test('empty paragraph', () {
final CanvasParagraph paragraph1 = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {},
);
expect(split(paragraph1), <_Fragment>[
_Fragment('', endOfText, null, ffPrevious, defaultStyle),
]);
final CanvasParagraph paragraph2 = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {
builder.addText('');
},
);
expect(split(paragraph2), <_Fragment>[
_Fragment('', endOfText, null, ffPrevious, defaultStyle),
]);
final CanvasParagraph paragraph3 = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {
builder.pushStyle(style1);
builder.addText('');
},
);
expect(split(paragraph3), <_Fragment>[
_Fragment('', endOfText, null, ffPrevious, style1),
]);
});
test('single span', () {
final CanvasParagraph paragraph =
plain(EngineParagraphStyle(), 'Lorem 12 $rtlWord1 ipsum34');
expect(split(paragraph), <_Fragment>[
_Fragment('Lorem', prohibited, ltr, ffLtr, defaultStyle),
_Fragment(' ', opportunity, null, ffSandwich, defaultStyle, sp: 1),
_Fragment('12', prohibited, ltr, ffPrevious, defaultStyle),
_Fragment(' ', opportunity, null, ffSandwich, defaultStyle, sp: 1),
_Fragment(rtlWord1, prohibited, rtl, ffRtl, defaultStyle),
_Fragment(' ', opportunity, null, ffSandwich, defaultStyle, sp: 3),
_Fragment('ipsum34', endOfText, ltr, ffLtr, defaultStyle),
]);
});
test('multi span', () {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {
builder.pushStyle(style1);
builder.addText('Lorem');
builder.pop();
builder.pushStyle(style2);
builder.addText(' ipsum 12 ');
builder.pop();
builder.pushStyle(style3);
builder.addText(' $rtlWord1 foo.');
builder.pop();
},
);
expect(split(paragraph), <_Fragment>[
_Fragment('Lorem', prohibited, ltr, ffLtr, style1),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 1),
_Fragment('ipsum', prohibited, ltr, ffLtr, style2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 1),
_Fragment('12', prohibited, ltr, ffPrevious, style2),
_Fragment(' ', prohibited, null, ffSandwich, style2, sp: 1),
_Fragment(' ', opportunity, null, ffSandwich, style3, sp: 1),
_Fragment(rtlWord1, prohibited, rtl, ffRtl, style3),
_Fragment(' ', opportunity, null, ffSandwich, style3, sp: 1),
_Fragment('foo', prohibited, ltr, ffLtr, style3),
_Fragment('.', endOfText, null, ffSandwich, style3),
]);
});
test('new lines', () {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {
builder.pushStyle(style1);
builder.addText('Lor\nem \n');
builder.pop();
builder.pushStyle(style2);
builder.addText(' \n ipsum 12 ');
builder.pop();
builder.pushStyle(style3);
builder.addText(' $rtlWord1 fo');
builder.pop();
builder.pushStyle(style1);
builder.addText('o.');
builder.pop();
},
);
expect(split(paragraph), <_Fragment>[
_Fragment('Lor', prohibited, ltr, ffLtr, style1),
_Fragment('\n', mandatory, null, ffSandwich, style1, nl: 1, sp: 1),
_Fragment('em', prohibited, ltr, ffLtr, style1),
_Fragment(' \n', mandatory, null, ffSandwich, style1, nl: 1, sp: 2),
_Fragment(' \n', mandatory, null, ffSandwich, style2, nl: 1, sp: 2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 2),
_Fragment('ipsum', prohibited, ltr, ffLtr, style2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 1),
_Fragment('12', prohibited, ltr, ffPrevious, style2),
_Fragment(' ', prohibited, null, ffSandwich, style2, sp: 1),
_Fragment(' ', opportunity, null, ffSandwich, style3, sp: 1),
_Fragment(rtlWord1, prohibited, rtl, ffRtl, style3),
_Fragment(' ', opportunity, null, ffSandwich, style3, sp: 1),
_Fragment('fo', prohibited, ltr, ffLtr, style3),
_Fragment('o', prohibited, ltr, ffLtr, style1),
_Fragment('.', endOfText, null, ffSandwich, style1),
]);
});
test('last line is empty', () {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {
builder.pushStyle(style1);
builder.addText('Lorem \n');
builder.pop();
builder.pushStyle(style2);
builder.addText(' \n ipsum \n');
builder.pop();
},
);
expect(split(paragraph), <_Fragment>[
_Fragment('Lorem', prohibited, ltr, ffLtr, style1),
_Fragment(' \n', mandatory, null, ffSandwich, style1, nl: 1, sp: 2),
_Fragment(' \n', mandatory, null, ffSandwich, style2, nl: 1, sp: 2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 2),
_Fragment('ipsum', prohibited, ltr, ffLtr, style2),
_Fragment(' \n', mandatory, null, ffSandwich, style2, nl: 1, sp: 2),
_Fragment('', endOfText, null, ffSandwich, style2),
]);
});
test('space-only spans', () {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {
builder.addText('Lorem ');
builder.pushStyle(style1);
builder.addText(' ');
builder.pop();
builder.pushStyle(style2);
builder.addText(' ');
builder.pop();
builder.addText('ipsum');
},
);
expect(split(paragraph), <_Fragment>[
_Fragment('Lorem', prohibited, ltr, ffLtr, defaultStyle),
_Fragment(' ', prohibited, null, ffSandwich, defaultStyle, sp: 1),
_Fragment(' ', prohibited, null, ffSandwich, style1, sp: 3),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 2),
_Fragment('ipsum', endOfText, ltr, ffLtr, defaultStyle),
]);
});
test('placeholders', () {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {
builder.pushStyle(style1);
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('Lorem');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('ipsum\n');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.pop();
builder.pushStyle(style2);
builder.addText('$rtlWord1 ');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('\nsit');
builder.pop();
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
},
);
expect(split(paragraph), <_Fragment>[
_Fragment(placeholderChar, opportunity, ltr, ffLtr, style1),
_Fragment('Lorem', opportunity, ltr, ffLtr, style1),
_Fragment(placeholderChar, opportunity, ltr, ffLtr, style1),
_Fragment('ipsum', prohibited, ltr, ffLtr, style1),
_Fragment('\n', mandatory, null, ffSandwich, style1, nl: 1, sp: 1),
_Fragment(placeholderChar, opportunity, ltr, ffLtr, style1),
_Fragment(rtlWord1, prohibited, rtl, ffRtl, style2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 1),
_Fragment(placeholderChar, prohibited, ltr, ffLtr, style2),
_Fragment('\n', mandatory, null, ffSandwich, style2, nl: 1, sp: 1),
_Fragment('sit', opportunity, ltr, ffLtr, style2),
_Fragment(placeholderChar, endOfText, ltr, ffLtr, defaultStyle),
]);
});
});
}
/// Holds information about how a fragment.
class _Fragment {
_Fragment(this.text, this.type, this.textDirection, this.fragmentFlow, this.style, {
this.nl = 0,
this.sp = 0,
});
factory _Fragment._fromLayoutFragment(String text, LayoutFragment layoutFragment) {
return _Fragment(
text.substring(layoutFragment.start, layoutFragment.end),
layoutFragment.type,
layoutFragment.textDirection,
layoutFragment.fragmentFlow,
layoutFragment.style,
nl: layoutFragment.trailingNewlines,
sp: layoutFragment.trailingSpaces,
);
}
final String text;
final LineBreakType type;
final TextDirection? textDirection;
final FragmentFlow fragmentFlow;
final EngineTextStyle style;
/// The number of trailing new line characters.
final int nl;
/// The number of trailing spaces.
final int sp;
@override
int get hashCode => Object.hash(text, type, textDirection, fragmentFlow, style, nl, sp);
@override
bool operator ==(Object other) {
return other is _Fragment &&
other.text == text &&
other.type == type &&
other.textDirection == textDirection &&
other.fragmentFlow == fragmentFlow &&
other.style == style &&
other.nl == nl &&
other.sp == sp;
}
@override
String toString() {
return '"$text" ($type, $textDirection, $fragmentFlow, nl: $nl, sp: $sp)';
}
}
List<_Fragment> split(CanvasParagraph paragraph) {
return <_Fragment>[
for (final LayoutFragment layoutFragment
in computeLayoutFragments(paragraph))
_Fragment._fromLayoutFragment(paragraph.plainText, layoutFragment)
];
}
List<LayoutFragment> computeLayoutFragments(CanvasParagraph paragraph) {
return LayoutFragmenter(paragraph.plainText, paragraph.spans).fragment();
}
extension _EngineTextStyle on EngineTextStyle {
EngineTextStyle copyWith({
Color? color,
TextDecoration? decoration,
Color? decorationColor,
TextDecorationStyle? decorationStyle,
double? decorationThickness,
FontWeight? fontWeight,
FontStyle? fontStyle,
TextBaseline? textBaseline,
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? letterSpacing,
double? wordSpacing,
double? height,
TextLeadingDistribution? leadingDistribution,
Locale? locale,
Paint? background,
Paint? foreground,
List<Shadow>? shadows,
List<FontFeature>? fontFeatures,
List<FontVariation>? fontVariations,
}) {
return EngineTextStyle(
color: color ?? this.color,
decoration: decoration ?? this.decoration,
decorationColor: decorationColor ?? this.decorationColor,
decorationStyle: decorationStyle ?? this.decorationStyle,
decorationThickness: decorationThickness ?? this.decorationThickness,
fontWeight: fontWeight ?? this.fontWeight,
fontStyle: fontStyle ?? this.fontStyle,
textBaseline: textBaseline ?? this.textBaseline,
fontFamily: fontFamily ?? this.fontFamily,
fontFamilyFallback: fontFamilyFallback ?? this.fontFamilyFallback,
fontSize: fontSize ?? this.fontSize,
letterSpacing: letterSpacing ?? this.letterSpacing,
wordSpacing: wordSpacing ?? this.wordSpacing,
height: height ?? this.height,
leadingDistribution: leadingDistribution,
locale: locale ?? this.locale,
background: background ?? this.background,
foreground: foreground ?? this.foreground,
shadows: shadows ?? this.shadows,
fontFeatures: fontFeatures ?? this.fontFeatures,
fontVariations: fontVariations ?? this.fontVariations,
);
}
}
| engine/lib/web_ui/test/html/text/layout_fragmenter_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/text/layout_fragmenter_test.dart",
"repo_id": "engine",
"token_count": 5091
} | 423 |
// 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:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
import '../common/test_initialization.dart';
import 'utils.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
const ui.Rect kBlueSquareRegion = ui.Rect.fromLTRB(0, 0, 25, 25);
const ui.Rect kRedCircleRegion = ui.Rect.fromLTRB(25, 0, 50, 25);
const ui.Rect kMagentaStarRegion = ui.Rect.fromLTRB(0, 25, 30, 55);
const ui.Rect kGreenSquiggleRegion = ui.Rect.fromLTRB(30, 25, 50, 55);
const ui.Rect kTotalAtlasRegion = ui.Rect.fromLTRB(0, 0, 55, 55);
ui.Image generateAtlas() {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawColor(const ui.Color(0), ui.BlendMode.src);
// Draw the square
canvas.save();
canvas.clipRect(kBlueSquareRegion);
canvas.drawRect(
// Inset the square by one pixel so it doesn't bleed into the other sprites.
kBlueSquareRegion.deflate(1.0),
ui.Paint()..color = const ui.Color(0xFF0000FF)
);
canvas.restore();
// Draw the circle
canvas.save();
canvas.clipRect(kRedCircleRegion);
canvas.drawCircle(
kRedCircleRegion.center,
// Make the circle one pixel smaller than the bounds to it doesn't bleed
// into the other shapes.
(kRedCircleRegion.width / 2.0) - 1.0,
ui.Paint()..color = const ui.Color(0xFFFF0000));
canvas.restore();
// Draw the star
canvas.save();
canvas.clipRect(kMagentaStarRegion);
final ui.Offset starCenter = kMagentaStarRegion.center;
// Make the star one pixel smaller than the bounds so that it doesn't bleed
// into the other shapes.
final double radius = (kMagentaStarRegion.height / 2.0) - 1.0;
// Start at the top (rotated 90 degrees)
double theta = -math.pi / 2.0;
// Rotate two fifths of the circle each time
const double rotation = 4.0 * math.pi / 5.0;
final ui.Path starPath = ui.Path();
starPath.moveTo(
starCenter.dx + radius * math.cos(theta),
starCenter.dy + radius * math.sin(theta)
);
for (int i = 0; i < 5; i++) {
theta += rotation;
starPath.lineTo(
starCenter.dx + radius * math.cos(theta),
starCenter.dy + radius * math.sin(theta)
);
}
canvas.drawPath(
starPath,
ui.Paint()
..color = const ui.Color(0xFFFF00FF)
..style = ui.PaintingStyle.fill
);
canvas.restore();
// Draw the Squiggle
canvas.save();
canvas.clipRect(kGreenSquiggleRegion);
final ui.Path squigglePath = ui.Path();
squigglePath.moveTo(kGreenSquiggleRegion.topCenter.dx, kGreenSquiggleRegion.topCenter.dy + 2.0);
squigglePath.cubicTo(
kGreenSquiggleRegion.left - 10.0, kGreenSquiggleRegion.top + kGreenSquiggleRegion.height * 0.33,
kGreenSquiggleRegion.right + 10.0, kGreenSquiggleRegion.top + kGreenSquiggleRegion.height * 0.66,
kGreenSquiggleRegion.bottomCenter.dx, kGreenSquiggleRegion.bottomCenter.dy - 2.0
);
canvas.drawPath(
squigglePath,
ui.Paint()
..color = const ui.Color(0xFF00FF00)
..style = ui.PaintingStyle.stroke
..strokeWidth = 5.0
);
canvas.restore();
final ui.Picture picture = recorder.endRecording();
return picture.toImageSync(
kTotalAtlasRegion.width.toInt(),
kTotalAtlasRegion.height.toInt()
);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
setUpTestViewDimensions: false,
);
const ui.Rect region = ui.Rect.fromLTWH(0, 0, 300, 300);
test('render atlas', () async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder, region);
final ui.Image atlas = generateAtlas();
canvas.drawImage(atlas, ui.Offset.zero, ui.Paint());
await drawPictureUsingCurrentRenderer(recorder.endRecording());
await matchGoldenFile('ui_atlas.png', region: region);
}, skip: isHtml); // HTML renderer doesn't support drawAtlas
test('drawAtlas', () async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder, region);
final ui.Image atlas = generateAtlas();
final List<ui.RSTransform> transforms = List<ui.RSTransform>.generate(
12, (int index) {
const double radius = 100;
const double rotation = math.pi / 6.0;
final double angle = rotation * index;
final double scos = math.sin(angle);
final double ssin = math.cos(angle);
return ui.RSTransform(
scos,
ssin,
region.center.dx + radius * scos,
region.center.dy + radius * ssin,
);
}
);
final List<ui.Rect> rects = <ui.Rect>[
kBlueSquareRegion,
kRedCircleRegion,
kMagentaStarRegion,
kGreenSquiggleRegion,
kBlueSquareRegion,
kRedCircleRegion,
kMagentaStarRegion,
kGreenSquiggleRegion,
kBlueSquareRegion,
kRedCircleRegion,
kMagentaStarRegion,
kGreenSquiggleRegion,
];
canvas.drawAtlas(
atlas, transforms, rects, null, null, null, ui.Paint());
await drawPictureUsingCurrentRenderer(recorder.endRecording());
await matchGoldenFile('ui_draw_atlas.png', region: region);
}, skip: isHtml); // HTML renderer doesn't support drawAtlas
test('drawAtlasRaw', () async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder, region);
final ui.Image atlas = generateAtlas();
final Float32List transforms = Float32List(12 * 4);
for (int i = 0; i < 12; i++) {
const double radius = 100;
const double rotation = math.pi / 6.0;
final double angle = rotation * i;
final double scos = math.sin(angle);
final double ssin = math.cos(angle);
transforms[i * 4] = scos;
transforms[i * 4 + 1] = ssin;
transforms[i * 4 + 2] = region.center.dx + radius * scos;
transforms[i * 4 + 3] = region.center.dy + radius * ssin;
}
final List<ui.Rect> rects = <ui.Rect>[
kBlueSquareRegion,
kRedCircleRegion,
kMagentaStarRegion,
kGreenSquiggleRegion,
kBlueSquareRegion,
kRedCircleRegion,
kMagentaStarRegion,
kGreenSquiggleRegion,
kBlueSquareRegion,
kRedCircleRegion,
kMagentaStarRegion,
kGreenSquiggleRegion,
];
final Float32List rawRects = Float32List(rects.length * 4);
for (int i = 0; i < rects.length; i++) {
rawRects[i * 4] = rects[i].left;
rawRects[i * 4 + 1] = rects[i].top;
rawRects[i * 4 + 2] = rects[i].right;
rawRects[i * 4 + 3] = rects[i].bottom;
}
final Int32List colors = Int32List(12);
for (int i = 0; i < 12; i++) {
final int rgb = 0xFF << (8 * (i % 3));
colors[i] = 0xFF000000 | rgb;
}
canvas.drawRawAtlas(
atlas,
transforms,
rawRects,
colors,
ui.BlendMode.dstIn,
null,
ui.Paint()
);
await drawPictureUsingCurrentRenderer(recorder.endRecording());
await matchGoldenFile('ui_draw_atlas_raw.png', region: region);
}, skip: isHtml); // HTML renderer doesn't support drawAtlas
}
| engine/lib/web_ui/test/ui/draw_atlas_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/ui/draw_atlas_golden_test.dart",
"repo_id": "engine",
"token_count": 2941
} | 424 |
// 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';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import 'package:web_engine_tester/golden_tester.dart';
import '../common/rendering.dart';
import '../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
const ui.Rect region = ui.Rect.fromLTWH(0, 0, 300, 300);
const String platformViewType = 'test-platform-view';
setUp(() {
ui_web.platformViewRegistry.registerViewFactory(
platformViewType,
(int viewId) {
final DomElement element = createDomHTMLDivElement();
element.style.backgroundColor = 'blue';
return element;
}
);
});
tearDown(() {
PlatformViewManager.instance.debugClear();
});
test('picture + overlapping platformView', () async {
await _createPlatformView(1, platformViewType);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawCircle(
const ui.Offset(50, 50),
50,
ui.Paint()
..style = ui.PaintingStyle.fill
..color = const ui.Color(0xFFFF0000)
);
final ui.SceneBuilder sb = ui.SceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(const ui.Offset(100, 100), recorder.endRecording());
sb.addPlatformView(
1,
offset: const ui.Offset(125, 125),
width: 50,
height: 50,
);
await renderScene(sb.build());
await matchGoldenFile('picture_platformview_overlap.png', region: region);
});
test('platformView sandwich', () async {
await _createPlatformView(1, platformViewType);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawCircle(
const ui.Offset(50, 50),
50,
ui.Paint()
..style = ui.PaintingStyle.fill
..color = const ui.Color(0xFF00FF00)
);
final ui.Picture picture = recorder.endRecording();
final ui.SceneBuilder sb = ui.SceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(const ui.Offset(75, 75), picture);
sb.addPlatformView(
1,
offset: const ui.Offset(100, 100),
width: 100,
height: 100,
);
sb.addPicture(const ui.Offset(125, 125), picture);
await renderScene(sb.build());
await matchGoldenFile('picture_platformview_sandwich.png', region: region);
});
test('transformed platformview', () async {
await _createPlatformView(1, platformViewType);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawCircle(
const ui.Offset(50, 50),
50,
ui.Paint()
..style = ui.PaintingStyle.fill
..color = const ui.Color(0xFFFF0000)
);
final ui.SceneBuilder sb = ui.SceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(const ui.Offset(100, 100), recorder.endRecording());
sb.pushTransform(Matrix4.rotationZ(0.1).toFloat64());
sb.addPlatformView(
1,
offset: const ui.Offset(125, 125),
width: 50,
height: 50,
);
await renderScene(sb.build());
await matchGoldenFile('platformview_transformed.png', region: region);
});
test('platformview with opacity', () async {
await _createPlatformView(1, platformViewType);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawCircle(
const ui.Offset(50, 50),
50,
ui.Paint()
..style = ui.PaintingStyle.fill
..color = const ui.Color(0xFFFF0000)
);
final ui.SceneBuilder sb = ui.SceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(const ui.Offset(100, 100), recorder.endRecording());
sb.pushOpacity(127);
sb.addPlatformView(
1,
offset: const ui.Offset(125, 125),
width: 50,
height: 50,
);
await renderScene(sb.build());
await matchGoldenFile('platformview_opacity.png', region: region);
});
}
// Sends a platform message to create a Platform View with the given id and viewType.
Future<void> _createPlatformView(int id, String viewType) {
final Completer<void> completer = Completer<void>();
const MethodCodec codec = StandardMethodCodec();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/platform_views',
codec.encodeMethodCall(MethodCall(
'create',
<String, dynamic>{
'id': id,
'viewType': viewType,
},
)),
(dynamic _) => completer.complete(),
);
return completer.future;
}
| engine/lib/web_ui/test/ui/platform_view_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/ui/platform_view_test.dart",
"repo_id": "engine",
"token_count": 1991
} | 425 |
// 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_ISOLATE_GROUP_DATA_H_
#define FLUTTER_RUNTIME_DART_ISOLATE_GROUP_DATA_H_
#include <map>
#include <mutex>
#include <string>
#include "flutter/common/settings.h"
#include "flutter/fml/closure.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "flutter/lib/ui/window/platform_configuration.h"
namespace flutter {
class DartIsolate;
class DartSnapshot;
class PlatformMessageHandler;
using ChildIsolatePreparer = std::function<bool(DartIsolate*)>;
// Object holding state associated with a Dart isolate group. An instance of
// this class will be provided to Dart_CreateIsolateGroup as the
// isolate_group_data.
//
// This object must be thread safe because the Dart VM can invoke the isolate
// group cleanup callback on any thread.
class DartIsolateGroupData : public PlatformMessageHandlerStorage {
public:
DartIsolateGroupData(const Settings& settings,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
std::string advisory_script_uri,
std::string advisory_script_entrypoint,
const ChildIsolatePreparer& child_isolate_preparer,
const fml::closure& isolate_create_callback,
const fml::closure& isolate_shutdown_callback);
~DartIsolateGroupData();
const Settings& GetSettings() const;
fml::RefPtr<const DartSnapshot> GetIsolateSnapshot() const;
const std::string& GetAdvisoryScriptURI() const;
const std::string& GetAdvisoryScriptEntrypoint() const;
ChildIsolatePreparer GetChildIsolatePreparer() const;
const fml::closure& GetIsolateCreateCallback() const;
const fml::closure& GetIsolateShutdownCallback() const;
void SetChildIsolatePreparer(const ChildIsolatePreparer& value);
/// Adds a kernel buffer mapping to the kernels loaded for this isolate group.
void AddKernelBuffer(const std::shared_ptr<const fml::Mapping>& buffer);
/// A copy of the mappings for all kernel buffer objects loaded into this
/// isolate group.
std::vector<std::shared_ptr<const fml::Mapping>> GetKernelBuffers() const;
// |PlatformMessageHandlerStorage|
void SetPlatformMessageHandler(
int64_t root_isolate_token,
std::weak_ptr<PlatformMessageHandler> handler) override;
// |PlatformMessageHandlerStorage|
std::weak_ptr<PlatformMessageHandler> GetPlatformMessageHandler(
int64_t root_isolate_token) const override;
private:
std::vector<std::shared_ptr<const fml::Mapping>> kernel_buffers_;
const Settings settings_;
const fml::RefPtr<const DartSnapshot> isolate_snapshot_;
const std::string advisory_script_uri_;
const std::string advisory_script_entrypoint_;
mutable std::mutex child_isolate_preparer_mutex_;
ChildIsolatePreparer child_isolate_preparer_;
const fml::closure isolate_create_callback_;
const fml::closure isolate_shutdown_callback_;
std::map<int64_t, std::weak_ptr<PlatformMessageHandler>>
platform_message_handlers_;
mutable std::mutex platform_message_handlers_mutex_;
FML_DISALLOW_COPY_AND_ASSIGN(DartIsolateGroupData);
};
} // namespace flutter
#endif // FLUTTER_RUNTIME_DART_ISOLATE_GROUP_DATA_H_
| engine/runtime/dart_isolate_group_data.h/0 | {
"file_path": "engine/runtime/dart_isolate_group_data.h",
"repo_id": "engine",
"token_count": 1129
} | 426 |
// 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_VM_DATA_H_
#define FLUTTER_RUNTIME_DART_VM_DATA_H_
#include "flutter/fml/macros.h"
#include "flutter/runtime/dart_snapshot.h"
namespace flutter {
//------------------------------------------------------------------------------
/// @brief Provides thread-safe access to data that is necessary to
/// bootstrap a new Dart VM instance. All snapshots referenced by
/// this object are read-only.
///
class DartVMData {
public:
//----------------------------------------------------------------------------
/// @brief Creates a new instance of `DartVMData`. Both the VM and
/// isolate snapshot members are optional and may be `nullptr`. If
/// `nullptr`, the snapshot resolvers present in the settings
/// object are used to infer the snapshots. If the snapshots
/// cannot be inferred from the settings object, this method
/// return `nullptr`.
///
/// @param[in] settings The settings used to infer the VM and
/// isolate snapshots if they are not provided
/// directly.
/// @param[in] vm_snapshot The VM snapshot or `nullptr`.
/// @param[in] isolate_snapshot The isolate snapshot or `nullptr`.
///
/// @return A new instance of VM data that can be used to bootstrap a Dart
/// VM. `nullptr` if the snapshots are not provided and cannot be
/// inferred from the settings object.
///
static std::shared_ptr<const DartVMData> Create(
const Settings& settings,
fml::RefPtr<const DartSnapshot> vm_snapshot,
fml::RefPtr<const DartSnapshot> isolate_snapshot);
//----------------------------------------------------------------------------
/// @brief Collect the DartVMData instance.
///
~DartVMData();
//----------------------------------------------------------------------------
/// @brief The settings object from which the Dart snapshots were
/// inferred.
///
/// @return The settings.
///
const Settings& GetSettings() const;
//----------------------------------------------------------------------------
/// @brief Gets the VM snapshot. This can be in the call to bootstrap
/// the Dart VM via `Dart_Initialize`.
///
/// @return The VM snapshot.
///
const DartSnapshot& GetVMSnapshot() const;
//----------------------------------------------------------------------------
/// @brief Get the isolate snapshot necessary to launch isolates in the
/// Dart VM. The Dart VM instance in which these isolates are
/// launched must be the same as the VM created using snapshot
/// accessed via `GetVMSnapshot`.
///
/// @return The isolate snapshot.
///
fml::RefPtr<const DartSnapshot> GetIsolateSnapshot() const;
//----------------------------------------------------------------------------
/// @brief Get the isolate snapshot used to launch the service isolate
/// in the Dart VM.
///
/// @return The service isolate snapshot.
///
fml::RefPtr<const DartSnapshot> GetServiceIsolateSnapshot() const;
//----------------------------------------------------------------------------
/// @brief Returns whether the service isolate snapshot requires null
/// safety in the Dart_IsolateFlags used to create the isolate.
///
/// @return True if the snapshot requires null safety.
///
bool GetServiceIsolateSnapshotNullSafety() const;
private:
const Settings settings_;
const fml::RefPtr<const DartSnapshot> vm_snapshot_;
const fml::RefPtr<const DartSnapshot> isolate_snapshot_;
const fml::RefPtr<const DartSnapshot> service_isolate_snapshot_;
DartVMData(const Settings& settings,
fml::RefPtr<const DartSnapshot> vm_snapshot,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
fml::RefPtr<const DartSnapshot> service_isolate_snapshot);
FML_DISALLOW_COPY_AND_ASSIGN(DartVMData);
};
} // namespace flutter
#endif // FLUTTER_RUNTIME_DART_VM_DATA_H_
| engine/runtime/dart_vm_data.h/0 | {
"file_path": "engine/runtime/dart_vm_data.h",
"repo_id": "engine",
"token_count": 1420
} | 427 |
// 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_PLATFORM_DATA_H_
#define FLUTTER_RUNTIME_PLATFORM_DATA_H_
#include <memory>
#include <string>
#include <vector>
#include "flutter/lib/ui/window/viewport_metrics.h"
#include "flutter/shell/common/display.h"
namespace flutter {
//------------------------------------------------------------------------------
/// The struct of platform-specific data used for initializing
/// ui.PlatformDispatcher.
///
/// The framework may request data from ui.PlatformDispatcher before the
/// platform is properly configured. When creating the Shell, the engine sets
/// this struct to default values until the platform is ready to send the real
/// data.
///
/// See also:
///
/// * flutter::Shell::Create, which takes a platform_data to initialize the
/// ui.PlatformDispatcher attached to it.
struct PlatformData {
PlatformData();
~PlatformData();
// A map from view IDs of existing views to their viewport metrics.
std::unordered_map<int64_t, ViewportMetrics> viewport_metrics_for_views;
std::string language_code;
std::string country_code;
std::string script_code;
std::string variant_code;
std::vector<std::string> locale_data;
std::string user_settings_data = "{}";
std::string lifecycle_state;
bool semantics_enabled = false;
bool assistive_technology_enabled = false;
int32_t accessibility_feature_flags_ = 0;
std::vector<DisplayData> displays;
};
} // namespace flutter
#endif // FLUTTER_RUNTIME_PLATFORM_DATA_H_
| engine/runtime/platform_data.h/0 | {
"file_path": "engine/runtime/platform_data.h",
"repo_id": "engine",
"token_count": 487
} | 428 |
// 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/runtime/dart_vm_lifecycle.h"
#include "flutter/testing/dart_isolate_runner.h"
#include "flutter/testing/fixture_test.h"
#include "flutter/testing/testing.h"
#include "flutter/third_party/tonic/converter/dart_converter.h"
// CREATE_NATIVE_ENTRY is leaky by design
// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape)
namespace flutter {
namespace testing {
class TypeConversionsTest : public FixtureTest {
public:
TypeConversionsTest()
: settings_(CreateSettingsForFixture()),
vm_(DartVMRef::Create(settings_)) {}
~TypeConversionsTest() = default;
[[nodiscard]] bool RunWithEntrypoint(const std::string& entrypoint) {
if (running_isolate_) {
return false;
}
auto thread = CreateNewThread();
TaskRunners single_threaded_task_runner(GetCurrentTestName(), thread,
thread, thread, thread);
auto isolate =
RunDartCodeInIsolate(vm_, settings_, single_threaded_task_runner,
entrypoint, {}, GetDefaultKernelFilePath());
if (!isolate || isolate->get()->GetPhase() != DartIsolate::Phase::Running) {
return false;
}
running_isolate_ = std::move(isolate);
return true;
}
private:
Settings settings_;
DartVMRef vm_;
std::unique_ptr<AutoIsolateShutdown> running_isolate_;
FML_DISALLOW_COPY_AND_ASSIGN(TypeConversionsTest);
};
TEST_F(TypeConversionsTest, TestFixture) {
ASSERT_TRUE(RunWithEntrypoint("main"));
}
TEST_F(TypeConversionsTest, CanConvertEmptyList) {
fml::AutoResetWaitableEvent event;
AddNativeCallback(
"NotifySuccess", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto bool_handle = Dart_GetNativeArgument(args, 0);
ASSERT_FALSE(tonic::CheckAndHandleError(bool_handle));
ASSERT_TRUE(tonic::DartConverter<bool>::FromDart(bool_handle));
event.Signal();
}));
AddNativeCallback(
"NotifyNative", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments) {
std::vector<int64_t> items;
auto items_handle = tonic::ToDart(items);
ASSERT_FALSE(tonic::CheckAndHandleError(items_handle));
tonic::DartInvokeField(::Dart_RootLibrary(), "testCanConvertEmptyList",
{items_handle});
}));
ASSERT_TRUE(RunWithEntrypoint("trampoline"));
event.Wait();
}
TEST_F(TypeConversionsTest, CanConvertListOfStrings) {
fml::AutoResetWaitableEvent event;
AddNativeCallback(
"NotifySuccess", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto bool_handle = Dart_GetNativeArgument(args, 0);
ASSERT_FALSE(tonic::CheckAndHandleError(bool_handle));
ASSERT_TRUE(tonic::DartConverter<bool>::FromDart(bool_handle));
event.Signal();
}));
AddNativeCallback(
"NotifyNative", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments) {
std::vector<std::string> items;
items.push_back("tinker");
items.push_back("tailor");
items.push_back("soldier");
items.push_back("sailor");
auto items_handle = tonic::ToDart(items);
ASSERT_FALSE(tonic::CheckAndHandleError(items_handle));
tonic::DartInvokeField(::Dart_RootLibrary(),
"testCanConvertListOfStrings", {items_handle});
}));
ASSERT_TRUE(RunWithEntrypoint("trampoline"));
event.Wait();
}
TEST_F(TypeConversionsTest, CanConvertListOfDoubles) {
fml::AutoResetWaitableEvent event;
AddNativeCallback(
"NotifySuccess", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto bool_handle = Dart_GetNativeArgument(args, 0);
ASSERT_FALSE(tonic::CheckAndHandleError(bool_handle));
ASSERT_TRUE(tonic::DartConverter<bool>::FromDart(bool_handle));
event.Signal();
}));
AddNativeCallback(
"NotifyNative", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments) {
std::vector<double> items;
items.push_back(1.0);
items.push_back(2.0);
items.push_back(3.0);
items.push_back(4.0);
auto items_handle = tonic::ToDart(items);
ASSERT_FALSE(tonic::CheckAndHandleError(items_handle));
tonic::DartInvokeField(::Dart_RootLibrary(),
"testCanConvertListOfDoubles", {items_handle});
}));
ASSERT_TRUE(RunWithEntrypoint("trampoline"));
event.Wait();
}
TEST_F(TypeConversionsTest, CanConvertListOfInts) {
fml::AutoResetWaitableEvent event;
AddNativeCallback(
"NotifySuccess", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto bool_handle = Dart_GetNativeArgument(args, 0);
ASSERT_FALSE(tonic::CheckAndHandleError(bool_handle));
ASSERT_TRUE(tonic::DartConverter<bool>::FromDart(bool_handle));
event.Signal();
}));
AddNativeCallback(
"NotifyNative", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments) {
std::vector<int32_t> items;
items.push_back(1);
items.push_back(2);
items.push_back(3);
items.push_back(4);
auto items_handle = tonic::ToDart(items);
ASSERT_FALSE(tonic::CheckAndHandleError(items_handle));
tonic::DartInvokeField(::Dart_RootLibrary(), "testCanConvertListOfInts",
{items_handle});
}));
ASSERT_TRUE(RunWithEntrypoint("trampoline"));
event.Wait();
}
} // namespace testing
} // namespace flutter
// NOLINTEND(clang-analyzer-core.StackAddressEscape)
| engine/runtime/type_conversions_unittests.cc/0 | {
"file_path": "engine/runtime/type_conversions_unittests.cc",
"repo_id": "engine",
"token_count": 2397
} | 429 |
// 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_DISPLAY_MANAGER_H_
#define FLUTTER_SHELL_COMMON_DISPLAY_MANAGER_H_
#include <mutex>
#include <vector>
#include "flutter/shell/common/display.h"
namespace flutter {
/// Manages lifecycle of the connected displays. This class is thread-safe.
class DisplayManager {
public:
DisplayManager();
~DisplayManager();
/// Returns the display refresh rate of the main display. In cases where there
/// is only one display connected, it will return that. We do not yet support
/// cases where there are multiple displays.
///
/// When there are no registered displays, it returns
/// `kUnknownDisplayRefreshRate`.
double GetMainDisplayRefreshRate() const;
/// Handles the display updates.
void HandleDisplayUpdates(std::vector<std::unique_ptr<Display>> displays);
private:
/// Guards `displays_` vector.
mutable std::mutex displays_mutex_;
std::vector<std::unique_ptr<Display>> displays_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_DISPLAY_MANAGER_H_
| engine/shell/common/display_manager.h/0 | {
"file_path": "engine/shell/common/display_manager.h",
"repo_id": "engine",
"token_count": 358
} | 430 |
// 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_PLATFORM_MESSAGE_HANDLER_H_
#define FLUTTER_SHELL_COMMON_PLATFORM_MESSAGE_HANDLER_H_
#include <memory>
#include "flutter/fml/mapping.h"
namespace flutter {
class PlatformMessage;
/// An interface over the ability to handle PlatformMessages that are being sent
/// from Flutter to the host platform.
class PlatformMessageHandler {
public:
virtual ~PlatformMessageHandler() = default;
/// Ultimately sends the PlatformMessage to the host platform.
/// This method is invoked on the ui thread.
virtual void HandlePlatformMessage(
std::unique_ptr<PlatformMessage> message) = 0;
/// Returns true if the platform message will ALWAYS be dispatched to the
/// platform thread.
///
/// Platforms that support Background Platform Channels will return
/// false.
virtual bool DoesHandlePlatformMessageOnPlatformThread() const = 0;
/// Performs the return procedure for an associated call to
/// HandlePlatformMessage.
/// This method should be thread-safe and able to be invoked on any thread.
virtual void InvokePlatformMessageResponseCallback(
int response_id,
std::unique_ptr<fml::Mapping> mapping) = 0;
/// Performs the return procedure for an associated call to
/// HandlePlatformMessage where there is no return value.
/// This method should be thread-safe and able to be invoked on any thread.
virtual void InvokePlatformMessageEmptyResponseCallback(int response_id) = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_PLATFORM_MESSAGE_HANDLER_H_
| engine/shell/common/platform_message_handler.h/0 | {
"file_path": "engine/shell/common/platform_message_handler.h",
"repo_id": "engine",
"token_count": 482
} | 431 |
// 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_SHELL_H_
#define FLUTTER_SHELL_COMMON_SHELL_H_
#include <functional>
#include <mutex>
#include <string_view>
#include <unordered_map>
#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/common/graphics/texture.h"
#include "flutter/common/settings.h"
#include "flutter/common/task_runners.h"
#include "flutter/flow/surface.h"
#include "flutter/fml/closure.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "flutter/fml/memory/thread_checker.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/status.h"
#include "flutter/fml/synchronization/sync_switch.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/thread.h"
#include "flutter/fml/time/time_point.h"
#include "flutter/lib/ui/painting/image_generator_registry.h"
#include "flutter/lib/ui/semantics/custom_accessibility_action.h"
#include "flutter/lib/ui/semantics/semantics_node.h"
#include "flutter/lib/ui/volatile_path_tracker.h"
#include "flutter/lib/ui/window/platform_message.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
#include "flutter/runtime/platform_data.h"
#include "flutter/runtime/service_protocol.h"
#include "flutter/shell/common/animator.h"
#include "flutter/shell/common/display_manager.h"
#include "flutter/shell/common/engine.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/resource_cache_limit_calculator.h"
#include "flutter/shell/common/shell_io_manager.h"
#include "impeller/runtime_stage/runtime_stage.h"
namespace flutter {
/// Error exit codes for the Dart isolate.
enum class DartErrorCode {
// NOLINTBEGIN(readability-identifier-naming)
/// No error has occurred.
NoError = 0,
/// The Dart error code for an API error.
ApiError = 253,
/// The Dart error code for a compilation error.
CompilationError = 254,
/// The Dart error code for an unknown error.
UnknownError = 255
// NOLINTEND(readability-identifier-naming)
};
/// Values for |Shell::SetGpuAvailability|.
enum class GpuAvailability {
/// Indicates that GPU operations should be permitted.
kAvailable = 0,
/// Indicates that the GPU is about to become unavailable, and to attempt to
/// flush any GPU related resources now.
kFlushAndMakeUnavailable = 1,
/// Indicates that the GPU is unavailable, and that no attempt should be made
/// to even flush GPU objects until it is available again.
kUnavailable = 2
};
//------------------------------------------------------------------------------
/// Perhaps the single most important class in the Flutter engine repository.
/// When embedders create a Flutter application, they are referring to the
/// creation of an instance of a shell. Creation and destruction of the shell is
/// synchronous and the embedder only holds a unique pointer to the shell. The
/// shell does not create the threads its primary components run on. Instead, it
/// is the embedder's responsibility to create threads and give the shell task
/// runners for those threads. Due to deterministic destruction of the shell,
/// the embedder can terminate all threads immediately after collecting the
/// shell. The shell must be created and destroyed on the same thread, but,
/// different shells (i.e. a separate instances of a Flutter application) may be
/// run on different threads simultaneously. The task runners themselves do not
/// have to be unique. If all task runner references given to the shell during
/// shell creation point to the same task runner, the Flutter application is
/// effectively single threaded.
///
/// The shell is the central nervous system of the Flutter application. None of
/// the shell components are thread safe and must be created, accessed and
/// destroyed on the same thread. To interact with one another, the various
/// components delegate to the shell for communication. Instead of using back
/// pointers to the shell, a delegation pattern is used by all components that
/// want to communicate with one another. Because of this, the shell implements
/// the delegate interface for all these components.
///
/// All shell methods accessed by the embedder may only be called on the
/// platform task runner. In case the embedder wants to directly access a shell
/// subcomponent, it is the embedder's responsibility to acquire a weak pointer
/// to that component and post a task to the task runner used by the component
/// to access its methods. The shell must also be destroyed on the platform
/// task runner.
///
/// There is no explicit API to bootstrap and shutdown the Dart VM. The first
/// instance of the shell in the process bootstraps the Dart VM and the
/// destruction of the last shell instance destroys the same. Since different
/// shells may be created and destroyed on different threads. VM bootstrap may
/// happen on one thread but its collection on another. This behavior is thread
/// safe.
///
class Shell final : public PlatformView::Delegate,
public Animator::Delegate,
public Engine::Delegate,
public Rasterizer::Delegate,
public ServiceProtocol::Handler,
public ResourceCacheLimitItem {
public:
template <class T>
using CreateCallback = std::function<std::unique_ptr<T>(Shell&)>;
typedef std::function<std::unique_ptr<Engine>(
Engine::Delegate& delegate,
const PointerDataDispatcherMaker& dispatcher_maker,
DartVM& vm,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
TaskRunners task_runners,
const PlatformData& platform_data,
Settings settings,
std::unique_ptr<Animator> animator,
fml::WeakPtr<IOManager> io_manager,
fml::RefPtr<SkiaUnrefQueue> unref_queue,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch,
impeller::RuntimeStageBackend runtime_stage_type)>
EngineCreateCallback;
using RemoveViewCallback = std::function<void(bool removed)>;
//----------------------------------------------------------------------------
/// @brief Creates a shell instance using the provided settings. The
/// callbacks to create the various shell subcomponents will be
/// called on the appropriate threads before this method returns.
/// If this is the first instance of a shell in the process, this
/// call also bootstraps the Dart VM.
/// @note The root isolate which will run this Shell's Dart code takes
/// its instructions from the passed in settings. This allows
/// embedders to host multiple Shells with different Dart code.
///
/// @param[in] task_runners The task runners
/// @param[in] settings The settings
/// @param[in] on_create_platform_view The callback that must return a
/// platform view. This will be called on
/// the platform task runner before this
/// method returns.
/// @param[in] on_create_rasterizer That callback that must provide a
/// valid rasterizer. This will be called
/// on the render task runner before this
/// method returns.
/// @param[in] is_gpu_disabled The default value for the switch that
/// turns off the GPU.
///
/// @return A full initialized shell if the settings and callbacks are
/// valid. The root isolate has been created but not yet launched.
/// It may be launched by obtaining the engine weak pointer and
/// posting a task onto the UI task runner with a valid run
/// configuration to run the isolate. The embedder must always
/// check the validity of the shell (using the IsSetup call)
/// immediately after getting a pointer to it.
///
static std::unique_ptr<Shell> Create(
const PlatformData& platform_data,
const TaskRunners& task_runners,
Settings settings,
const CreateCallback<PlatformView>& on_create_platform_view,
const CreateCallback<Rasterizer>& on_create_rasterizer,
bool is_gpu_disabled = false);
//----------------------------------------------------------------------------
/// @brief Destroys the shell. This is a synchronous operation and
/// synchronous barrier blocks are introduced on the various
/// threads to ensure shutdown of all shell sub-components before
/// this method returns.
///
~Shell();
//----------------------------------------------------------------------------
/// @brief Creates one Shell from another Shell where the created Shell
/// takes the opportunity to share any internal components it can.
/// This results is a Shell that has a smaller startup time cost
/// and a smaller memory footprint than an Shell created with the
/// Create function.
///
/// The new Shell is returned in a running state so RunEngine
/// shouldn't be called again on the Shell. Once running, the
/// second Shell is mostly independent from the original Shell
/// and the original Shell doesn't need to keep running for the
/// spawned Shell to keep functioning.
/// @param[in] run_configuration A RunConfiguration used to run the Isolate
/// associated with this new Shell. It doesn't have to be the same
/// configuration as the current Shell but it needs to be in the
/// same snapshot or AOT.
///
/// @see http://flutter.dev/go/multiple-engines
std::unique_ptr<Shell> Spawn(
RunConfiguration run_configuration,
const std::string& initial_route,
const CreateCallback<PlatformView>& on_create_platform_view,
const CreateCallback<Rasterizer>& on_create_rasterizer) const;
//----------------------------------------------------------------------------
/// @brief Starts an isolate for the given RunConfiguration.
///
void RunEngine(RunConfiguration run_configuration);
//----------------------------------------------------------------------------
/// @brief Starts an isolate for the given RunConfiguration. The
/// result_callback will be called with the status of the
/// operation.
///
void RunEngine(RunConfiguration run_configuration,
const std::function<void(Engine::RunStatus)>& result_callback);
//------------------------------------------------------------------------------
/// @return The settings used to launch this shell.
///
const Settings& GetSettings() const override;
//------------------------------------------------------------------------------
/// @brief If callers wish to interact directly with any shell
/// subcomponents, they must (on the platform thread) obtain a
/// task runner that the component is designed to run on and a
/// weak pointer to that component. They may then post a task to
/// that task runner, do the validity check on that task runner
/// before performing any operation on that component. This
/// accessor allows callers to access the task runners for this
/// shell.
///
/// @return The task runners current in use by the shell.
///
const TaskRunners& GetTaskRunners() const override;
//------------------------------------------------------------------------------
/// @brief Getting the raster thread merger from parent shell, it can be
/// a null RefPtr when it's a root Shell or the
/// embedder_->SupportsDynamicThreadMerging() returns false.
///
/// @return The raster thread merger used by the parent shell.
///
const fml::RefPtr<fml::RasterThreadMerger> GetParentRasterThreadMerger()
const override;
//----------------------------------------------------------------------------
/// @brief Rasterizers may only be accessed on the raster task runner.
///
/// @return A weak pointer to the rasterizer.
///
fml::TaskRunnerAffineWeakPtr<Rasterizer> GetRasterizer() const;
//------------------------------------------------------------------------------
/// @brief Engines may only be accessed on the UI thread. This method is
/// deprecated, and implementers should instead use other API
/// available on the Shell or the PlatformView.
///
/// @return A weak pointer to the engine.
///
fml::WeakPtr<Engine> GetEngine();
//----------------------------------------------------------------------------
/// @brief Platform views may only be accessed on the platform task
/// runner.
///
/// @return A weak pointer to the platform view.
///
fml::WeakPtr<PlatformView> GetPlatformView();
//----------------------------------------------------------------------------
/// @brief The IO Manager may only be accessed on the IO task runner.
///
/// @return A weak pointer to the IO manager.
///
fml::WeakPtr<ShellIOManager> GetIOManager();
// Embedders should call this under low memory conditions to free up
// internal caches used.
//
// This method posts a task to the raster threads to signal the Rasterizer to
// free resources.
//----------------------------------------------------------------------------
/// @brief Used by embedders to notify that there is a low memory
/// warning. The shell will attempt to purge caches. Current, only
/// the rasterizer cache is purged.
void NotifyLowMemoryWarning() const;
//----------------------------------------------------------------------------
/// @brief Used by embedders to check if all shell subcomponents are
/// initialized. It is the embedder's responsibility to make this
/// call before accessing any other shell method. A shell that is
/// not set up must be discarded and another one created with
/// updated settings.
///
/// @return Returns if the shell has been set up. Once set up, this does
/// not change for the life-cycle of the shell.
///
bool IsSetup() const;
/// @brief Allocates resources for a new non-implicit view.
///
/// This method returns immediately and does not wait for the task on
/// the UI thread to finish. This is safe because operations are
/// either initiated from the UI thread (such as rendering), or are
/// sent as posted tasks that are queued. In either case, it's ok for
/// the engine to have views that the Dart VM doesn't.
///
/// The implicit view should never be added with this function.
/// Instead, it is added internally on Shell initialization. Trying to
/// add `kFlutterImplicitViewId` triggers an assertion.
///
/// @param[in] view_id The view ID of the new view.
/// @param[in] viewport_metrics The initial viewport metrics for the view.
///
void AddView(int64_t view_id, const ViewportMetrics& viewport_metrics);
/// @brief Deallocates resources for a non-implicit view.
///
/// This method returns immediately and does not wait for the task on
/// the UI thread to finish. This means that the Dart VM might still
/// send messages regarding this view ID for a short while, even
/// though this view ID is already invalid.
///
/// The implicit view should never be removed. Trying to remove
/// `kFlutterImplicitViewId` triggers an assertion.
///
/// @param[in] view_id The view ID of the view to be removed.
/// @param[in] callback The callback that's invoked once the engine has
/// attempted to remove the view.
///
void RemoveView(int64_t view_id, RemoveViewCallback callback);
//----------------------------------------------------------------------------
/// @brief Captures a screenshot and optionally Base64 encodes the data
/// of the last layer tree rendered by the rasterizer in this
/// shell.
///
/// @param[in] type The type of screenshot to capture.
/// @param[in] base64_encode If the screenshot data should be base64
/// encoded.
///
/// @return The screenshot result.
///
Rasterizer::Screenshot Screenshot(Rasterizer::ScreenshotType type,
bool base64_encode);
//----------------------------------------------------------------------------
/// @brief Pauses the calling thread until the first frame is presented.
///
/// @param[in] timeout The duration to wait before timing out. If this
/// duration would cause an overflow when added to
/// std::chrono::steady_clock::now(), this method will
/// wait indefinitely for the first frame.
///
/// @return 'kOk' when the first frame has been presented before the
/// timeout successfully, 'kFailedPrecondition' if called from the
/// GPU or UI thread, 'kDeadlineExceeded' if there is a timeout.
///
fml::Status WaitForFirstFrame(fml::TimeDelta timeout);
//----------------------------------------------------------------------------
/// @brief Used by embedders to reload the system fonts in
/// FontCollection.
/// It also clears the cached font families and send system
/// channel message to framework to rebuild affected widgets.
///
/// @return Returns if shell reloads system fonts successfully.
///
bool ReloadSystemFonts();
//----------------------------------------------------------------------------
/// @brief Used by embedders to get the last error from the Dart UI
/// Isolate, if one exists.
///
/// @return Returns the last error code from the UI Isolate.
///
std::optional<DartErrorCode> GetUIIsolateLastError() const;
//----------------------------------------------------------------------------
/// @brief Used by embedders to check if the Engine is running and has
/// any live ports remaining. For example, the Flutter tester uses
/// this method to check whether it should continue to wait for
/// a running test or not.
///
/// @return Returns if the shell has an engine and the engine has any live
/// Dart ports.
///
bool EngineHasLivePorts() const;
//----------------------------------------------------------------------------
/// @brief Accessor for the disable GPU SyncSwitch.
// |Rasterizer::Delegate|
std::shared_ptr<const fml::SyncSwitch> GetIsGpuDisabledSyncSwitch()
const override;
//----------------------------------------------------------------------------
/// @brief Marks the GPU as available or unavailable.
void SetGpuAvailability(GpuAvailability availability);
//----------------------------------------------------------------------------
/// @brief Get a pointer to the Dart VM used by this running shell
/// instance.
///
/// @return The Dart VM pointer.
///
DartVM* GetDartVM();
//----------------------------------------------------------------------------
/// @brief Notifies the display manager of the updates.
///
void OnDisplayUpdates(std::vector<std::unique_ptr<Display>> displays);
//----------------------------------------------------------------------------
/// @brief Queries the `DisplayManager` for the main display refresh rate.
///
double GetMainDisplayRefreshRate();
//----------------------------------------------------------------------------
/// @brief Install a new factory that can match against and decode image
/// data.
/// @param[in] factory Callback that produces `ImageGenerator`s for
/// compatible input data.
/// @param[in] priority The priority used to determine the order in which
/// factories are tried. Higher values mean higher
/// priority. The built-in Skia decoders are installed
/// at priority 0, and so a priority > 0 takes precedent
/// over the builtin decoders. When multiple decoders
/// are added with the same priority, those which are
/// added earlier take precedent.
/// @see `CreateCompatibleGenerator`
void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority);
// |Engine::Delegate|
const std::shared_ptr<PlatformMessageHandler>& GetPlatformMessageHandler()
const override;
const std::weak_ptr<VsyncWaiter> GetVsyncWaiter() const;
const std::shared_ptr<fml::ConcurrentTaskRunner>
GetConcurrentWorkerTaskRunner() const;
// Infer the VM ref and the isolate snapshot based on the settings.
//
// If the VM is already running, the settings are ignored, but the returned
// isolate snapshot always prioritize what is specified by the settings, and
// falls back to the one VM was launched with.
//
// This function is what Shell::Create uses to infer snapshot settings.
//
// TODO(dkwingsmt): Extracting this method is part of a bigger change. If the
// entire change is not eventually landed, we should merge this method back
// to Create. https://github.com/flutter/flutter/issues/136826
static std::pair<DartVMRef, fml::RefPtr<const DartSnapshot>>
InferVmInitDataFromSettings(Settings& settings);
private:
using ServiceProtocolHandler =
std::function<bool(const ServiceProtocol::Handler::ServiceProtocolMap&,
rapidjson::Document*)>;
/// A collection of message channels (by name) that have sent at least one
/// message from a non-platform thread. Used to prevent printing the error
/// log more than once per channel, as a badly behaving plugin may send
/// multiple messages per second indefinitely.
std::mutex misbehaving_message_channels_mutex_;
std::set<std::string> misbehaving_message_channels_;
const TaskRunners task_runners_;
const fml::RefPtr<fml::RasterThreadMerger> parent_raster_thread_merger_;
std::shared_ptr<ResourceCacheLimitCalculator>
resource_cache_limit_calculator_;
size_t resource_cache_limit_;
const Settings settings_;
DartVMRef vm_;
mutable std::mutex time_recorder_mutex_;
std::optional<fml::TimePoint> latest_frame_target_time_;
std::unique_ptr<PlatformView> platform_view_; // on platform task runner
std::unique_ptr<Engine> engine_; // on UI task runner
std::unique_ptr<Rasterizer> rasterizer_; // on raster task runner
std::shared_ptr<ShellIOManager> io_manager_; // on IO task runner
std::shared_ptr<fml::SyncSwitch> is_gpu_disabled_sync_switch_;
std::shared_ptr<VolatilePathTracker> volatile_path_tracker_;
std::shared_ptr<PlatformMessageHandler> platform_message_handler_;
std::atomic<bool> route_messages_through_platform_thread_ = false;
fml::WeakPtr<Engine> weak_engine_; // to be shared across threads
fml::TaskRunnerAffineWeakPtr<Rasterizer>
weak_rasterizer_; // to be shared across threads
fml::WeakPtr<PlatformView>
weak_platform_view_; // to be shared across threads
std::unordered_map<std::string_view, // method
std::pair<fml::RefPtr<fml::TaskRunner>,
ServiceProtocolHandler> // task-runner/function
// pair
>
service_protocol_handlers_;
bool is_set_up_ = false;
bool is_added_to_service_protocol_ = false;
uint64_t next_pointer_flow_id_ = 0;
bool first_frame_rasterized_ = false;
std::atomic<bool> waiting_for_first_frame_ = true;
std::mutex waiting_for_first_frame_mutex_;
std::condition_variable waiting_for_first_frame_condition_;
// Written in the UI thread and read from the raster thread. Hence make it
// atomic.
std::atomic<bool> needs_report_timings_{false};
// Whether there's a task scheduled to report the timings to Dart through
// ui.PlatformDispatcher.onReportTimings.
bool frame_timings_report_scheduled_ = false;
// Vector of FrameTiming::kCount * n timestamps for n frames whose timings
// have not been reported yet. Vector of ints instead of FrameTiming is
// stored here for easier conversions to Dart objects.
std::vector<int64_t> unreported_timings_;
/// Manages the displays. This class is thread safe, can be accessed from
/// any of the threads.
std::unique_ptr<DisplayManager> display_manager_;
// protects expected_frame_size_ which is set on platform thread and read on
// raster thread
std::mutex resize_mutex_;
// used to discard wrong size layer tree produced during interactive
// resizing
std::unordered_map<int64_t, SkISize> expected_frame_sizes_;
// Used to communicate the right frame bounds via service protocol.
double device_pixel_ratio_ = 0.0;
// How many frames have been timed since last report.
size_t UnreportedFramesCount() const;
Shell(DartVMRef vm,
const TaskRunners& task_runners,
fml::RefPtr<fml::RasterThreadMerger> parent_merger,
const std::shared_ptr<ResourceCacheLimitCalculator>&
resource_cache_limit_calculator,
const Settings& settings,
std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
bool is_gpu_disabled);
static std::unique_ptr<Shell> CreateShellOnPlatformThread(
DartVMRef vm,
fml::RefPtr<fml::RasterThreadMerger> parent_merger,
std::shared_ptr<ShellIOManager> parent_io_manager,
const std::shared_ptr<ResourceCacheLimitCalculator>&
resource_cache_limit_calculator,
const TaskRunners& task_runners,
const PlatformData& platform_data,
const Settings& settings,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
const Shell::CreateCallback<PlatformView>& on_create_platform_view,
const Shell::CreateCallback<Rasterizer>& on_create_rasterizer,
const EngineCreateCallback& on_create_engine,
bool is_gpu_disabled);
static std::unique_ptr<Shell> CreateWithSnapshot(
const PlatformData& platform_data,
const TaskRunners& task_runners,
const fml::RefPtr<fml::RasterThreadMerger>& parent_thread_merger,
const std::shared_ptr<ShellIOManager>& parent_io_manager,
const std::shared_ptr<ResourceCacheLimitCalculator>&
resource_cache_limit_calculator,
Settings settings,
DartVMRef vm,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
const CreateCallback<PlatformView>& on_create_platform_view,
const CreateCallback<Rasterizer>& on_create_rasterizer,
const EngineCreateCallback& on_create_engine,
bool is_gpu_disabled);
bool Setup(std::unique_ptr<PlatformView> platform_view,
std::unique_ptr<Engine> engine,
std::unique_ptr<Rasterizer> rasterizer,
const std::shared_ptr<ShellIOManager>& io_manager);
void ReportTimings();
// |PlatformView::Delegate|
void OnPlatformViewCreated(std::unique_ptr<Surface> surface) override;
// |PlatformView::Delegate|
void OnPlatformViewDestroyed() override;
// |PlatformView::Delegate|
void OnPlatformViewScheduleFrame() override;
// |PlatformView::Delegate|
void OnPlatformViewSetViewportMetrics(
int64_t view_id,
const ViewportMetrics& metrics) override;
// |PlatformView::Delegate|
void OnPlatformViewDispatchPlatformMessage(
std::unique_ptr<PlatformMessage> message) override;
// |PlatformView::Delegate|
void OnPlatformViewDispatchPointerDataPacket(
std::unique_ptr<PointerDataPacket> packet) override;
// |PlatformView::Delegate|
void OnPlatformViewDispatchSemanticsAction(int32_t node_id,
SemanticsAction action,
fml::MallocMapping args) override;
// |PlatformView::Delegate|
void OnPlatformViewSetSemanticsEnabled(bool enabled) override;
// |shell:PlatformView::Delegate|
void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override;
// |PlatformView::Delegate|
void OnPlatformViewRegisterTexture(
std::shared_ptr<flutter::Texture> texture) override;
// |PlatformView::Delegate|
void OnPlatformViewUnregisterTexture(int64_t texture_id) override;
// |PlatformView::Delegate|
void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override;
// |PlatformView::Delegate|
void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override;
// |PlatformView::Delegate|
const Settings& OnPlatformViewGetSettings() const override;
// |PlatformView::Delegate|
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;
// |PlatformView::Delegate|
void UpdateAssetResolverByType(
std::unique_ptr<AssetResolver> updated_asset_resolver,
AssetResolver::AssetResolverType type) override;
// |Animator::Delegate|
void OnAnimatorBeginFrame(fml::TimePoint frame_target_time,
uint64_t frame_number) override;
// |Animator::Delegate|
void OnAnimatorNotifyIdle(fml::TimeDelta deadline) override;
// |Animator::Delegate|
void OnAnimatorUpdateLatestFrameTargetTime(
fml::TimePoint frame_target_time) override;
// |Animator::Delegate|
void OnAnimatorDraw(std::shared_ptr<FramePipeline> pipeline) override;
// |Animator::Delegate|
void OnAnimatorDrawLastLayerTrees(
std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) override;
// |Engine::Delegate|
void OnEngineUpdateSemantics(
SemanticsNodeUpdates update,
CustomAccessibilityActionUpdates actions) override;
// |Engine::Delegate|
void OnEngineHandlePlatformMessage(
std::unique_ptr<PlatformMessage> message) override;
void HandleEngineSkiaMessage(std::unique_ptr<PlatformMessage> message);
// |Engine::Delegate|
void OnPreEngineRestart() override;
// |Engine::Delegate|
void OnRootIsolateCreated() override;
// |Engine::Delegate|
void UpdateIsolateDescription(const std::string isolate_name,
int64_t isolate_port) override;
// |Engine::Delegate|
void SetNeedsReportTimings(bool value) override;
// |Engine::Delegate|
std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocale(
const std::vector<std::string>& supported_locale_data) override;
// |Engine::Delegate|
void RequestDartDeferredLibrary(intptr_t loading_unit_id) override;
// |Engine::Delegate|
fml::TimePoint GetCurrentTimePoint() override;
// |Engine::Delegate|
void OnEngineChannelUpdate(std::string name, bool listening) override;
// |Engine::Delegate|
double GetScaledFontSize(double unscaled_font_size,
int configuration_id) const override;
// |Rasterizer::Delegate|
void OnFrameRasterized(const FrameTiming&) override;
// |Rasterizer::Delegate|
fml::Milliseconds GetFrameBudget() override;
// |Rasterizer::Delegate|
fml::TimePoint GetLatestFrameTargetTime() const override;
// |Rasterizer::Delegate|
bool ShouldDiscardLayerTree(int64_t view_id,
const flutter::LayerTree& tree) override;
// |ServiceProtocol::Handler|
fml::RefPtr<fml::TaskRunner> GetServiceProtocolHandlerTaskRunner(
std::string_view method) const override;
// |ServiceProtocol::Handler|
bool HandleServiceProtocolMessage(
std::string_view method, // one if the extension names specified above.
const ServiceProtocolMap& params,
rapidjson::Document* response) override;
// |ServiceProtocol::Handler|
ServiceProtocol::Handler::Description GetServiceProtocolDescription()
const override;
// Service protocol handler
bool OnServiceProtocolScreenshot(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
bool OnServiceProtocolScreenshotSKP(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
bool OnServiceProtocolRunInView(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
bool OnServiceProtocolFlushUIThreadTasks(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
bool OnServiceProtocolSetAssetBundlePath(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
bool OnServiceProtocolGetDisplayRefreshRate(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
//
// The returned SkSLs are base64 encoded. Decode before storing them to
// files.
bool OnServiceProtocolGetSkSLs(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
bool OnServiceProtocolEstimateRasterCacheMemory(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
//
// Renders a frame and responds with various statistics pertaining to the
// raster call. These include time taken to raster every leaf layer and also
// leaf layer snapshots.
bool OnServiceProtocolRenderFrameWithRasterStats(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
//
// Forces the FontCollection to reload the font manifest. Used to support
// hot reload for fonts.
bool OnServiceProtocolReloadAssetFonts(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Send a system font change notification.
void SendFontChangeNotification();
// |ResourceCacheLimitItem|
size_t GetResourceCacheLimit() override { return resource_cache_limit_; };
// Creates an asset bundle from the original settings asset path or
// directory.
std::unique_ptr<DirectoryAssetBundle> RestoreOriginalAssetResolver();
SkISize ExpectedFrameSize(int64_t view_id);
// For accessing the Shell via the raster thread, necessary for various
// rasterizer callbacks.
std::unique_ptr<fml::TaskRunnerAffineWeakPtrFactory<Shell>> weak_factory_gpu_;
fml::WeakPtrFactory<Shell> weak_factory_;
friend class testing::ShellTest;
FML_DISALLOW_COPY_AND_ASSIGN(Shell);
};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_SHELL_H_
| engine/shell/common/shell.h/0 | {
"file_path": "engine/shell/common/shell.h",
"repo_id": "engine",
"token_count": 11690
} | 432 |
// 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_vulkan.h"
#include <utility>
#include "flutter/common/graphics/persistent_cache.h"
#include "flutter/flutter_vma/flutter_skia_vma.h"
#include "flutter/shell/common/context_options.h"
#include "flutter/vulkan/vulkan_skia_proc_table.h"
#include "flutter/vulkan/vulkan_utilities.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h"
#include "third_party/skia/include/gpu/ganesh/vk/GrVkDirectContext.h"
#if OS_FUCHSIA
#define VULKAN_SO_PATH "libvulkan.so"
#else
#include "flutter/vulkan/swiftshader_path.h"
#endif
namespace flutter {
namespace testing {
ShellTestPlatformViewVulkan::ShellTestPlatformViewVulkan(
PlatformView::Delegate& delegate,
const TaskRunners& task_runners,
std::shared_ptr<ShellTestVsyncClock> vsync_clock,
CreateVsyncWaiter create_vsync_waiter,
std::shared_ptr<ShellTestExternalViewEmbedder>
shell_test_external_view_embedder)
: ShellTestPlatformView(delegate, task_runners),
create_vsync_waiter_(std::move(create_vsync_waiter)),
vsync_clock_(std::move(vsync_clock)),
proc_table_(fml::MakeRefCounted<vulkan::VulkanProcTable>(VULKAN_SO_PATH)),
shell_test_external_view_embedder_(
std::move(shell_test_external_view_embedder)) {}
ShellTestPlatformViewVulkan::~ShellTestPlatformViewVulkan() = default;
std::unique_ptr<VsyncWaiter> ShellTestPlatformViewVulkan::CreateVSyncWaiter() {
return create_vsync_waiter_();
}
void ShellTestPlatformViewVulkan::SimulateVSync() {
vsync_clock_->SimulateVSync();
}
// |PlatformView|
std::unique_ptr<Surface> ShellTestPlatformViewVulkan::CreateRenderingSurface() {
return std::make_unique<OffScreenSurface>(proc_table_,
shell_test_external_view_embedder_);
}
// |PlatformView|
std::shared_ptr<ExternalViewEmbedder>
ShellTestPlatformViewVulkan::CreateExternalViewEmbedder() {
return shell_test_external_view_embedder_;
}
// |PlatformView|
PointerDataDispatcherMaker ShellTestPlatformViewVulkan::GetDispatcherMaker() {
return [](DefaultPointerDataDispatcher::Delegate& delegate) {
return std::make_unique<SmoothPointerDataDispatcher>(delegate);
};
}
// TODO(gw280): This code was forked from vulkan_window.cc specifically for
// shell_test.
// We need to merge this functionality back into //vulkan.
// https://github.com/flutter/flutter/issues/51132
ShellTestPlatformViewVulkan::OffScreenSurface::OffScreenSurface(
fml::RefPtr<vulkan::VulkanProcTable> vk,
std::shared_ptr<ShellTestExternalViewEmbedder>
shell_test_external_view_embedder)
: vk_(std::move(vk)),
shell_test_external_view_embedder_(
std::move(shell_test_external_view_embedder)) {
if (!vk_ || !vk_->HasAcquiredMandatoryProcAddresses()) {
FML_DLOG(ERROR) << "Proc table has not acquired mandatory proc addresses.";
return;
}
// Create the application instance.
std::vector<std::string> extensions = {
VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME,
};
application_ = std::make_unique<vulkan::VulkanApplication>(
*vk_, "FlutterTest", std::move(extensions), VK_MAKE_VERSION(1, 0, 0),
VK_MAKE_VERSION(1, 1, 0), true);
if (!application_->IsValid() || !vk_->AreInstanceProcsSetup()) {
// Make certain the application instance was created and it set up the
// instance proc table entries.
FML_DLOG(ERROR) << "Instance proc addresses have not been set up.";
return;
}
// Create the device.
logical_device_ = application_->AcquireFirstCompatibleLogicalDevice();
if (logical_device_ == nullptr || !logical_device_->IsValid() ||
!vk_->AreDeviceProcsSetup()) {
// Make certain the device was created and it set up the device proc table
// entries.
FML_DLOG(ERROR) << "Device proc addresses have not been set up.";
return;
}
memory_allocator_ = FlutterSkiaVulkanMemoryAllocator::Make(
application_->GetAPIVersion(), application_->GetInstance(),
logical_device_->GetPhysicalDeviceHandle(), logical_device_->GetHandle(),
vk_, true);
// Create the Skia GrContext.
if (!CreateSkiaGrContext()) {
FML_DLOG(ERROR) << "Could not create Skia context.";
return;
}
valid_ = true;
}
bool ShellTestPlatformViewVulkan::OffScreenSurface::CreateSkiaGrContext() {
GrVkBackendContext backend_context;
if (!CreateSkiaBackendContext(&backend_context)) {
FML_DLOG(ERROR) << "Could not create Skia backend context.";
return false;
}
const auto options =
MakeDefaultContextOptions(ContextType::kRender, GrBackendApi::kVulkan);
sk_sp<GrDirectContext> context =
GrDirectContexts::MakeVulkan(backend_context, options);
if (context == nullptr) {
FML_DLOG(ERROR) << "Failed to create GrDirectContext";
return false;
}
context->setResourceCacheLimit(vulkan::kGrCacheMaxByteSize);
context_ = context;
return true;
}
bool ShellTestPlatformViewVulkan::OffScreenSurface::CreateSkiaBackendContext(
GrVkBackendContext* context) {
auto getProc = CreateSkiaGetProc(vk_);
if (getProc == nullptr) {
FML_DLOG(ERROR) << "GetProcAddress is null";
return false;
}
uint32_t skia_features = 0;
if (!logical_device_->GetPhysicalDeviceFeaturesSkia(&skia_features)) {
FML_DLOG(ERROR) << "Failed to get Physical Device features";
return false;
}
context->fInstance = application_->GetInstance();
context->fPhysicalDevice = logical_device_->GetPhysicalDeviceHandle();
context->fDevice = logical_device_->GetHandle();
context->fQueue = logical_device_->GetQueueHandle();
context->fGraphicsQueueIndex = logical_device_->GetGraphicsQueueIndex();
context->fMinAPIVersion = application_->GetAPIVersion();
context->fMaxAPIVersion = application_->GetAPIVersion();
context->fFeatures = skia_features;
context->fGetProc = std::move(getProc);
context->fOwnsInstanceAndDevice = false;
context->fMemoryAllocator = memory_allocator_;
return true;
}
ShellTestPlatformViewVulkan::OffScreenSurface::~OffScreenSurface() {}
bool ShellTestPlatformViewVulkan::OffScreenSurface::IsValid() {
return valid_;
}
std::unique_ptr<SurfaceFrame>
ShellTestPlatformViewVulkan::OffScreenSurface::AcquireFrame(
const SkISize& size) {
auto image_info = SkImageInfo::Make(size, SkColorType::kRGBA_8888_SkColorType,
SkAlphaType::kOpaque_SkAlphaType);
auto surface = SkSurfaces::RenderTarget(context_.get(), skgpu::Budgeted::kNo,
image_info, 0, nullptr);
SurfaceFrame::SubmitCallback callback = [](const SurfaceFrame&,
DlCanvas* canvas) -> bool {
canvas->Flush();
return true;
};
SurfaceFrame::FramebufferInfo framebuffer_info;
framebuffer_info.supports_readback = true;
return std::make_unique<SurfaceFrame>(std::move(surface), framebuffer_info,
std::move(callback),
/*frame_size=*/SkISize::Make(800, 600));
}
GrDirectContext* ShellTestPlatformViewVulkan::OffScreenSurface::GetContext() {
return context_.get();
}
SkMatrix ShellTestPlatformViewVulkan::OffScreenSurface::GetRootTransformation()
const {
SkMatrix matrix;
matrix.reset();
return matrix;
}
} // namespace testing
} // namespace flutter
| engine/shell/common/shell_test_platform_view_vulkan.cc/0 | {
"file_path": "engine/shell/common/shell_test_platform_view_vulkan.cc",
"repo_id": "engine",
"token_count": 2813
} | 433 |
// 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_THREAD_HOST_H_
#define FLUTTER_SHELL_COMMON_THREAD_HOST_H_
#include <memory>
#include <optional>
#include <string>
#include "flutter/fml/macros.h"
#include "flutter/fml/thread.h"
namespace flutter {
using ThreadConfig = fml::Thread::ThreadConfig;
using ThreadConfigSetter = fml::Thread::ThreadConfigSetter;
/// The collection of all the threads used by the engine.
struct ThreadHost {
enum Type {
kPlatform = 1 << 0,
kUi = 1 << 1,
kRaster = 1 << 2,
kIo = 1 << 3,
kProfiler = 1 << 4,
};
/// The collection of all the thread configures, and we create custom thread
/// configure in engine to info the thread.
struct ThreadHostConfig {
explicit ThreadHostConfig(
const ThreadConfigSetter& setter = fml::Thread::SetCurrentThreadName)
: type_mask(0), config_setter(setter) {}
ThreadHostConfig(
const std::string& name_prefix,
uint64_t mask,
const ThreadConfigSetter& setter = fml::Thread::SetCurrentThreadName)
: type_mask(mask), name_prefix(name_prefix), config_setter(setter) {}
explicit ThreadHostConfig(
uint64_t mask,
const ThreadConfigSetter& setter = fml::Thread::SetCurrentThreadName)
: ThreadHostConfig("", mask, setter) {}
/// Check if need to create thread.
bool isThreadNeeded(Type type) const { return type_mask & type; }
/// Use the prefix and thread type to generator a thread name.
static std::string MakeThreadName(Type type, const std::string& prefix);
/// Specified the UI Thread Config, meanwhile set the mask.
void SetUIConfig(const ThreadConfig&);
/// Specified the Platform Thread Config, meanwhile set the mask.
void SetPlatformConfig(const ThreadConfig&);
/// Specified the IO Thread Config, meanwhile set the mask.
void SetRasterConfig(const ThreadConfig&);
/// Specified the IO Thread Config, meanwhile set the mask.
void SetIOConfig(const ThreadConfig&);
/// Specified the ProfilerThread Config, meanwhile set the mask.
void SetProfilerConfig(const ThreadConfig&);
uint64_t type_mask;
std::string name_prefix = "";
const ThreadConfigSetter config_setter;
std::optional<ThreadConfig> platform_config;
std::optional<ThreadConfig> ui_config;
std::optional<ThreadConfig> raster_config;
std::optional<ThreadConfig> io_config;
std::optional<ThreadConfig> profiler_config;
};
std::string name_prefix;
std::unique_ptr<fml::Thread> platform_thread;
std::unique_ptr<fml::Thread> ui_thread;
std::unique_ptr<fml::Thread> raster_thread;
std::unique_ptr<fml::Thread> io_thread;
std::unique_ptr<fml::Thread> profiler_thread;
ThreadHost();
ThreadHost(ThreadHost&&);
ThreadHost& operator=(ThreadHost&&) = default;
ThreadHost(const std::string& name_prefix, uint64_t mask);
explicit ThreadHost(const ThreadHostConfig& host_config);
~ThreadHost();
private:
std::unique_ptr<fml::Thread> CreateThread(
Type type,
std::optional<ThreadConfig> thread_config,
const ThreadHostConfig& host_config) const;
};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_THREAD_HOST_H_
| engine/shell/common/thread_host.h/0 | {
"file_path": "engine/shell/common/thread_host.h",
"repo_id": "engine",
"token_count": 1131
} | 434 |
// 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_GL_DELEGATE_H_
#define FLUTTER_SHELL_GPU_GPU_SURFACE_GL_DELEGATE_H_
#include <optional>
#include "flutter/common/graphics/gl_context_switch.h"
#include "flutter/flow/embedded_views.h"
#include "flutter/fml/macros.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
namespace flutter {
// A structure to represent the frame information which is passed to the
// embedder when requesting a frame buffer object.
struct GLFrameInfo {
uint32_t width;
uint32_t height;
};
// A structure to represent the frame buffer information which is returned to
// the rendering backend after requesting a frame buffer object.
struct GLFBOInfo {
// The frame buffer's ID.
uint32_t fbo_id;
// The frame buffer's existing damage (i.e. damage since it was last used).
const std::optional<SkIRect> existing_damage;
};
// Information passed during presentation of a frame.
struct GLPresentInfo {
uint32_t fbo_id;
// The frame damage is a hint to compositor telling it which parts of front
// buffer need to be updated.
const std::optional<SkIRect>& frame_damage;
// Time at which this frame is scheduled to be presented. This is a hint
// that can be passed to the platform to drop queued frames.
std::optional<fml::TimePoint> presentation_time = std::nullopt;
// The buffer damage refers to the region that needs to be set as damaged
// within the frame buffer.
const std::optional<SkIRect>& buffer_damage;
};
class GPUSurfaceGLDelegate {
public:
~GPUSurfaceGLDelegate();
// Called to make the main GL context current on the current thread.
virtual std::unique_ptr<GLContextResult> GLContextMakeCurrent() = 0;
// Called to clear the current GL context on the thread. This may be called on
// either the Raster or IO threads.
virtual bool GLContextClearCurrent() = 0;
// Inform the GL Context that there's going to be no writing beyond
// the specified region
virtual void GLContextSetDamageRegion(const std::optional<SkIRect>& region) {}
// Called to present the main GL surface. This is only called for the main GL
// context and not any of the contexts dedicated for IO.
virtual bool GLContextPresent(const GLPresentInfo& present_info) = 0;
// The information about the main window bound framebuffer. ID is Typically
// FBO0.
virtual GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const = 0;
// The rendering subsystem assumes that the ID of the main window bound
// framebuffer remains constant throughout. If this assumption in incorrect,
// embedders are required to return true from this method. In such cases,
// GLContextFBO(frame_info) will be called again to acquire the new FBO ID for
// rendering subsequent frames.
virtual bool GLContextFBOResetAfterPresent() const;
// Returns framebuffer info for current backbuffer
virtual SurfaceFrame::FramebufferInfo GLContextFramebufferInfo() const;
// A transformation applied to the onscreen surface before the canvas is
// flushed.
virtual SkMatrix GLContextSurfaceTransformation() const;
virtual sk_sp<const GrGLInterface> GetGLInterface() const;
// TODO(chinmaygarde): The presence of this method is to work around the fact
// that not all platforms can accept a custom GL proc table. Migrate all
// platforms to move GL proc resolution to the embedder and remove this
// method.
static sk_sp<const GrGLInterface> GetDefaultPlatformGLInterface();
using GLProcResolver =
std::function<void* /* proc name */ (const char* /* proc address */)>;
// Provide a custom GL proc resolver. If no such resolver is present, Skia
// will attempt to do GL proc address resolution on its own. Embedders that
// have specific opinions on GL API selection or need to add their own
// instrumentation to specific GL calls can specify custom GL functions
// here.
virtual GLProcResolver GetGLProcResolver() const;
// Whether to allow drawing to the surface when the GPU is disabled
virtual bool AllowsDrawingWhenGpuDisabled() const;
};
} // namespace flutter
#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_GL_DELEGATE_H_
| engine/shell/gpu/gpu_surface_gl_delegate.h/0 | {
"file_path": "engine/shell/gpu/gpu_surface_gl_delegate.h",
"repo_id": "engine",
"token_count": 1216
} | 435 |
// 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/gpu/gpu_surface_vulkan.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h"
#include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h"
#include "vulkan/vulkan_core.h"
namespace flutter {
GPUSurfaceVulkan::GPUSurfaceVulkan(GPUSurfaceVulkanDelegate* delegate,
const sk_sp<GrDirectContext>& skia_context,
bool render_to_surface)
: delegate_(delegate),
skia_context_(skia_context),
render_to_surface_(render_to_surface),
weak_factory_(this) {}
GPUSurfaceVulkan::~GPUSurfaceVulkan() = default;
bool GPUSurfaceVulkan::IsValid() {
return skia_context_ != nullptr;
}
std::unique_ptr<SurfaceFrame> GPUSurfaceVulkan::AcquireFrame(
const SkISize& frame_size) {
if (!IsValid()) {
FML_LOG(ERROR) << "Vulkan surface was invalid.";
return nullptr;
}
if (frame_size.isEmpty()) {
FML_LOG(ERROR) << "Vulkan surface was asked for an empty frame.";
return nullptr;
}
if (!render_to_surface_) {
return std::make_unique<SurfaceFrame>(
nullptr, SurfaceFrame::FramebufferInfo(),
[](const SurfaceFrame& surface_frame, DlCanvas* canvas) {
return true;
},
frame_size);
}
FlutterVulkanImage image = delegate_->AcquireImage(frame_size);
if (!image.image) {
FML_LOG(ERROR) << "Invalid VkImage given by the embedder.";
return nullptr;
}
sk_sp<SkSurface> surface = CreateSurfaceFromVulkanImage(
reinterpret_cast<VkImage>(image.image),
static_cast<VkFormat>(image.format), frame_size);
if (!surface) {
FML_LOG(ERROR) << "Could not create the SkSurface from the Vulkan image.";
return nullptr;
}
SurfaceFrame::SubmitCallback callback = [image = image, delegate = delegate_](
const SurfaceFrame&,
DlCanvas* canvas) -> bool {
TRACE_EVENT0("flutter", "GPUSurfaceVulkan::PresentImage");
if (canvas == nullptr) {
FML_DLOG(ERROR) << "Canvas not available.";
return false;
}
canvas->Flush();
return delegate->PresentImage(reinterpret_cast<VkImage>(image.image),
static_cast<VkFormat>(image.format));
};
SurfaceFrame::FramebufferInfo framebuffer_info{.supports_readback = true};
return std::make_unique<SurfaceFrame>(std::move(surface), framebuffer_info,
std::move(callback), frame_size);
}
SkMatrix GPUSurfaceVulkan::GetRootTransformation() const {
// This backend does not support delegating to the underlying platform to
// query for root surface transformations. Just return identity.
SkMatrix matrix;
matrix.reset();
return matrix;
}
GrDirectContext* GPUSurfaceVulkan::GetContext() {
return skia_context_.get();
}
sk_sp<SkSurface> GPUSurfaceVulkan::CreateSurfaceFromVulkanImage(
const VkImage image,
const VkFormat format,
const SkISize& size) {
#ifdef SK_VULKAN
GrVkImageInfo image_info = {
.fImage = image,
.fImageTiling = VK_IMAGE_TILING_OPTIMAL,
.fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.fFormat = format,
.fImageUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
VK_IMAGE_USAGE_TRANSFER_DST_BIT |
VK_IMAGE_USAGE_SAMPLED_BIT,
.fSampleCount = 1,
.fLevelCount = 1,
};
auto backend_texture =
GrBackendTextures::MakeVk(size.width(), size.height(), image_info);
SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
return SkSurfaces::WrapBackendTexture(
skia_context_.get(), // context
backend_texture, // back-end texture
kTopLeft_GrSurfaceOrigin, // surface origin
1, // sample count
ColorTypeFromFormat(format), // color type
SkColorSpace::MakeSRGB(), // color space
&surface_properties // surface properties
);
#else
return nullptr;
#endif // SK_VULKAN
}
SkColorType GPUSurfaceVulkan::ColorTypeFromFormat(const VkFormat format) {
switch (format) {
case VK_FORMAT_R8G8B8A8_UNORM:
case VK_FORMAT_R8G8B8A8_SRGB:
return SkColorType::kRGBA_8888_SkColorType;
case VK_FORMAT_B8G8R8A8_UNORM:
case VK_FORMAT_B8G8R8A8_SRGB:
return SkColorType::kBGRA_8888_SkColorType;
default:
return SkColorType::kUnknown_SkColorType;
}
}
} // namespace flutter
| engine/shell/gpu/gpu_surface_vulkan.cc/0 | {
"file_path": "engine/shell/gpu/gpu_surface_vulkan.cc",
"repo_id": "engine",
"token_count": 2176
} | 436 |
// 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 <memory>
#include "flutter/shell/common/thread_host.h"
#include "flutter/shell/platform/android/android_context_gl_skia.h"
#include "flutter/shell/platform/android/android_egl_surface.h"
#include "flutter/shell/platform/android/android_environment_gl.h"
#include "flutter/shell/platform/android/android_surface_gl_skia.h"
#include "fml/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "shell/platform/android/context/android_context.h"
namespace flutter {
namespace testing {
namespace android {
namespace {
TaskRunners MakeTaskRunners(const std::string& thread_label,
const ThreadHost& thread_host) {
fml::MessageLoop::EnsureInitializedForCurrentThread();
fml::RefPtr<fml::TaskRunner> platform_runner =
fml::MessageLoop::GetCurrent().GetTaskRunner();
return TaskRunners(thread_label, platform_runner,
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
}
} // namespace
class TestImpellerContext : public impeller::Context {
public:
TestImpellerContext() {}
~TestImpellerContext() {}
impeller::Context::BackendType GetBackendType() const override {
return impeller::Context::BackendType::kOpenGLES;
}
std::string DescribeGpuModel() const override { return ""; }
bool IsValid() const override { return true; }
const std::shared_ptr<const impeller::Capabilities>& GetCapabilities()
const override {
FML_UNREACHABLE();
}
bool UpdateOffscreenLayerPixelFormat(impeller::PixelFormat format) override {
FML_UNREACHABLE();
}
std::shared_ptr<impeller::Allocator> GetResourceAllocator() const override {
FML_UNREACHABLE();
}
std::shared_ptr<impeller::ShaderLibrary> GetShaderLibrary() const override {
FML_UNREACHABLE();
}
std::shared_ptr<impeller::SamplerLibrary> GetSamplerLibrary() const override {
FML_UNREACHABLE();
}
std::shared_ptr<impeller::PipelineLibrary> GetPipelineLibrary()
const override {
FML_UNREACHABLE();
}
std::shared_ptr<impeller::CommandBuffer> CreateCommandBuffer()
const override {
FML_UNREACHABLE();
}
std::shared_ptr<impeller::CommandQueue> GetCommandQueue() const override {
FML_UNREACHABLE();
}
void Shutdown() override { did_shutdown = true; }
bool did_shutdown = false;
};
class TestAndroidContext : public AndroidContext {
public:
TestAndroidContext(const std::shared_ptr<impeller::Context>& impeller_context,
AndroidRenderingAPI rendering_api)
: AndroidContext(rendering_api) {
SetImpellerContext(impeller_context);
}
};
TEST(AndroidContextGl, Create) {
GrMockOptions main_context_options;
sk_sp<GrDirectContext> main_context =
GrDirectContext::MakeMock(&main_context_options);
auto environment = fml::MakeRefCounted<AndroidEnvironmentGL>();
std::string thread_label =
::testing::UnitTest::GetInstance()->current_test_info()->name();
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
thread_label, ThreadHost::Type::kUi | ThreadHost::Type::kRaster |
ThreadHost::Type::kIo));
TaskRunners task_runners = MakeTaskRunners(thread_label, thread_host);
auto context =
std::make_unique<AndroidContextGLSkia>(environment, task_runners, 0);
context->SetMainSkiaContext(main_context);
EXPECT_NE(context.get(), nullptr);
context.reset();
EXPECT_TRUE(main_context->abandoned());
}
TEST(AndroidContextGl, CreateImpeller) {
auto impeller_context = std::make_shared<TestImpellerContext>();
auto android_context = std::make_unique<TestAndroidContext>(
impeller_context, AndroidRenderingAPI::kImpellerOpenGLES);
EXPECT_FALSE(impeller_context->did_shutdown);
android_context.reset();
EXPECT_TRUE(impeller_context->did_shutdown);
}
TEST(AndroidContextGl, CreateSingleThread) {
GrMockOptions main_context_options;
sk_sp<GrDirectContext> main_context =
GrDirectContext::MakeMock(&main_context_options);
auto environment = fml::MakeRefCounted<AndroidEnvironmentGL>();
std::string thread_label =
::testing::UnitTest::GetInstance()->current_test_info()->name();
fml::MessageLoop::EnsureInitializedForCurrentThread();
fml::RefPtr<fml::TaskRunner> platform_runner =
fml::MessageLoop::GetCurrent().GetTaskRunner();
TaskRunners task_runners =
TaskRunners(thread_label, platform_runner, platform_runner,
platform_runner, platform_runner);
auto context =
std::make_unique<AndroidContextGLSkia>(environment, task_runners, 0);
context->SetMainSkiaContext(main_context);
EXPECT_NE(context.get(), nullptr);
context.reset();
EXPECT_TRUE(main_context->abandoned());
}
TEST(AndroidSurfaceGL, CreateSnapshopSurfaceWhenOnscreenSurfaceIsNotNull) {
GrMockOptions main_context_options;
sk_sp<GrDirectContext> main_context =
GrDirectContext::MakeMock(&main_context_options);
auto environment = fml::MakeRefCounted<AndroidEnvironmentGL>();
std::string thread_label =
::testing::UnitTest::GetInstance()->current_test_info()->name();
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
thread_label, ThreadHost::Type::kUi | ThreadHost::Type::kRaster |
ThreadHost::Type::kIo));
TaskRunners task_runners = MakeTaskRunners(thread_label, thread_host);
auto android_context =
std::make_shared<AndroidContextGLSkia>(environment, task_runners, 0);
auto android_surface =
std::make_unique<AndroidSurfaceGLSkia>(android_context);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(
nullptr, /*is_fake_window=*/true);
android_surface->SetNativeWindow(window);
auto onscreen_surface = android_surface->GetOnscreenSurface();
EXPECT_NE(onscreen_surface, nullptr);
android_surface->CreateSnapshotSurface();
EXPECT_EQ(onscreen_surface, android_surface->GetOnscreenSurface());
}
TEST(AndroidSurfaceGL, CreateSnapshopSurfaceWhenOnscreenSurfaceIsNull) {
GrMockOptions main_context_options;
sk_sp<GrDirectContext> main_context =
GrDirectContext::MakeMock(&main_context_options);
auto environment = fml::MakeRefCounted<AndroidEnvironmentGL>();
std::string thread_label =
::testing::UnitTest::GetInstance()->current_test_info()->name();
auto mask =
ThreadHost::Type::kUi | ThreadHost::Type::kRaster | ThreadHost::Type::kIo;
flutter::ThreadHost::ThreadHostConfig host_config(mask);
ThreadHost thread_host(host_config);
TaskRunners task_runners = MakeTaskRunners(thread_label, thread_host);
auto android_context =
std::make_shared<AndroidContextGLSkia>(environment, task_runners, 0);
auto android_surface =
std::make_unique<AndroidSurfaceGLSkia>(android_context);
EXPECT_EQ(android_surface->GetOnscreenSurface(), nullptr);
android_surface->CreateSnapshotSurface();
EXPECT_NE(android_surface->GetOnscreenSurface(), nullptr);
}
// TODO(https://github.com/flutter/flutter/issues/104463): Flaky test.
TEST(AndroidContextGl, DISABLED_MSAAx4) {
GrMockOptions main_context_options;
sk_sp<GrDirectContext> main_context =
GrDirectContext::MakeMock(&main_context_options);
auto environment = fml::MakeRefCounted<AndroidEnvironmentGL>();
std::string thread_label =
::testing::UnitTest::GetInstance()->current_test_info()->name();
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
thread_label, ThreadHost::Type::kUi | ThreadHost::Type::kRaster |
ThreadHost::Type::kIo));
TaskRunners task_runners = MakeTaskRunners(thread_label, thread_host);
auto context =
std::make_unique<AndroidContextGLSkia>(environment, task_runners, 4);
context->SetMainSkiaContext(main_context);
EGLint sample_count;
eglGetConfigAttrib(environment->Display(), context->Config(), EGL_SAMPLES,
&sample_count);
EXPECT_EQ(sample_count, 4);
}
TEST(AndroidContextGl, EnsureMakeCurrentChecksCurrentContextStatus) {
GrMockOptions main_context_options;
sk_sp<GrDirectContext> main_context =
GrDirectContext::MakeMock(&main_context_options);
auto environment = fml::MakeRefCounted<AndroidEnvironmentGL>();
std::string thread_label =
::testing::UnitTest::GetInstance()->current_test_info()->name();
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
thread_label, ThreadHost::Type::kUi | ThreadHost::Type::kRaster |
ThreadHost::Type::kIo));
TaskRunners task_runners = MakeTaskRunners(thread_label, thread_host);
auto context =
std::make_unique<AndroidContextGLSkia>(environment, task_runners, 0);
auto pbuffer_surface = context->CreatePbufferSurface();
auto status = pbuffer_surface->MakeCurrent();
EXPECT_EQ(AndroidEGLSurfaceMakeCurrentStatus::kSuccessMadeCurrent, status);
// context already current, so status must reflect that.
status = pbuffer_surface->MakeCurrent();
EXPECT_EQ(AndroidEGLSurfaceMakeCurrentStatus::kSuccessAlreadyCurrent, status);
}
} // namespace android
} // namespace testing
} // namespace flutter
| engine/shell/platform/android/android_context_gl_unittests.cc/0 | {
"file_path": "engine/shell/platform/android/android_context_gl_unittests.cc",
"repo_id": "engine",
"token_count": 3222
} | 437 |
// 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_ANDROID_SURFACE_GL_IMPELLER_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_IMPELLER_H_
#include "flutter/fml/macros.h"
#include "flutter/impeller/renderer/context.h"
#include "flutter/shell/gpu/gpu_surface_gl_delegate.h"
#include "flutter/shell/platform/android/android_context_gl_impeller.h"
#include "flutter/shell/platform/android/surface/android_native_window.h"
#include "flutter/shell/platform/android/surface/android_surface.h"
namespace flutter {
class AndroidSurfaceGLImpeller final : public GPUSurfaceGLDelegate,
public AndroidSurface {
public:
explicit AndroidSurfaceGLImpeller(
const std::shared_ptr<AndroidContextGLImpeller>& android_context);
// |AndroidSurface|
~AndroidSurfaceGLImpeller() override;
// |AndroidSurface|
bool IsValid() const override;
// |AndroidSurface|
std::unique_ptr<Surface> CreateGPUSurface(
GrDirectContext* gr_context) override;
// |AndroidSurface|
void TeardownOnScreenContext() override;
// |AndroidSurface|
bool OnScreenSurfaceResize(const SkISize& size) override;
// |AndroidSurface|
bool ResourceContextMakeCurrent() override;
// |AndroidSurface|
bool ResourceContextClearCurrent() override;
// |AndroidSurface|
bool SetNativeWindow(fml::RefPtr<AndroidNativeWindow> window) override;
// |AndroidSurface|
std::unique_ptr<Surface> CreateSnapshotSurface() override;
// |AndroidSurface|
std::shared_ptr<impeller::Context> GetImpellerContext() override;
// |GPUSurfaceGLDelegate|
std::unique_ptr<GLContextResult> GLContextMakeCurrent() override;
// |GPUSurfaceGLDelegate|
bool GLContextClearCurrent() override;
// |GPUSurfaceGLDelegate|
SurfaceFrame::FramebufferInfo GLContextFramebufferInfo() const override;
// |GPUSurfaceGLDelegate|
void GLContextSetDamageRegion(const std::optional<SkIRect>& region) override;
// |GPUSurfaceGLDelegate|
bool GLContextPresent(const GLPresentInfo& present_info) override;
// |GPUSurfaceGLDelegate|
GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const override;
// |GPUSurfaceGLDelegate|
sk_sp<const GrGLInterface> GetGLInterface() const override;
private:
std::shared_ptr<AndroidContextGLImpeller> android_context_;
std::unique_ptr<impeller::egl::Surface> onscreen_surface_;
std::unique_ptr<impeller::egl::Surface> offscreen_surface_;
fml::RefPtr<AndroidNativeWindow> native_window_;
bool is_valid_ = false;
bool OnGLContextMakeCurrent();
bool RecreateOnscreenSurfaceAndMakeOnscreenContextCurrent();
FML_DISALLOW_COPY_AND_ASSIGN(AndroidSurfaceGLImpeller);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_IMPELLER_H_
| engine/shell/platform/android/android_surface_gl_impeller.h/0 | {
"file_path": "engine/shell/platform/android/android_surface_gl_impeller.h",
"repo_id": "engine",
"token_count": 1002
} | 438 |
// 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_EXTERNAL_VIEW_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_H_
#include <unordered_map>
#include "flutter/common/task_runners.h"
#include "flutter/flow/embedded_views.h"
#include "flutter/shell/platform/android/context/android_context.h"
#include "flutter/shell/platform/android/external_view_embedder/surface_pool.h"
#include "flutter/shell/platform/android/jni/platform_view_android_jni.h"
#include "flutter/shell/platform/android/surface/android_surface.h"
namespace flutter {
//------------------------------------------------------------------------------
/// Allows to embed Android views into a Flutter application.
///
/// This class calls Java methods via |PlatformViewAndroidJNI| to manage the
/// lifecycle of the Android view corresponding to |flutter::PlatformViewLayer|.
///
/// It also orchestrates overlay surfaces. These are Android views
/// that render above (by Z order) the Android view corresponding to
/// |flutter::PlatformViewLayer|.
///
class AndroidExternalViewEmbedder final : public ExternalViewEmbedder {
public:
AndroidExternalViewEmbedder(
const AndroidContext& android_context,
std::shared_ptr<PlatformViewAndroidJNI> jni_facade,
std::shared_ptr<AndroidSurfaceFactory> surface_factory,
const TaskRunners& task_runners);
// |ExternalViewEmbedder|
void PrerollCompositeEmbeddedView(
int64_t view_id,
std::unique_ptr<flutter::EmbeddedViewParams> params) override;
// |ExternalViewEmbedder|
DlCanvas* CompositeEmbeddedView(int64_t view_id) override;
// |ExternalViewEmbedder|
void SubmitFlutterView(
GrDirectContext* context,
const std::shared_ptr<impeller::AiksContext>& aiks_context,
std::unique_ptr<SurfaceFrame> frame) override;
// |ExternalViewEmbedder|
PostPrerollResult PostPrerollAction(
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger)
override;
// |ExternalViewEmbedder|
DlCanvas* GetRootCanvas() override;
// |ExternalViewEmbedder|
void BeginFrame(GrDirectContext* context,
const fml::RefPtr<fml::RasterThreadMerger>&
raster_thread_merger) override;
// |ExternalViewEmbedder|
void PrepareFlutterView(int64_t flutter_view_id,
SkISize frame_size,
double device_pixel_ratio) override;
// |ExternalViewEmbedder|
void CancelFrame() override;
// |ExternalViewEmbedder|
void EndFrame(bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>&
raster_thread_merger) override;
bool SupportsDynamicThreadMerging() override;
void Teardown() override;
// Gets the rect based on the device pixel ratio of a platform view displayed
// on the screen.
SkRect GetViewRect(int64_t view_id) const;
private:
// The number of frames the rasterizer task runner will continue
// to run on the platform thread after no platform view is rendered.
//
// Note: this is an arbitrary number that attempts to account for cases
// where the platform view might be momentarily off the screen.
static const int kDefaultMergedLeaseDuration = 10;
// Provides metadata to the Android surfaces.
const AndroidContext& android_context_;
// Allows to call methods in Java.
const std::shared_ptr<PlatformViewAndroidJNI> jni_facade_;
// Allows to create surfaces.
const std::shared_ptr<AndroidSurfaceFactory> surface_factory_;
// Holds surfaces. Allows to recycle surfaces or allocate new ones.
const std::unique_ptr<SurfacePool> surface_pool_;
// The task runners.
const TaskRunners task_runners_;
// The size of the root canvas.
SkISize frame_size_;
// The pixel ratio used to determinate the size of a platform view layer
// relative to the device layout system.
double device_pixel_ratio_;
// The order of composition. Each entry contains a unique id for the platform
// view.
std::vector<int64_t> composition_order_;
// The |EmbedderViewSlice| implementation keyed off the platform view id,
// which contains any subsequent operations until the next platform view or
// the end of the last leaf node in the layer tree.
std::unordered_map<int64_t, std::unique_ptr<EmbedderViewSlice>> slices_;
// The params for a platform view, which contains the size, position and
// mutation stack.
std::unordered_map<int64_t, EmbeddedViewParams> view_params_;
// The number of platform views in the previous frame.
int64_t previous_frame_view_count_;
// Destroys the surfaces created from the surface factory.
// This method schedules a task on the platform thread, and waits for
// the task until it completes.
void DestroySurfaces();
// Resets the state.
void Reset();
// Whether the layer tree in the current frame has platform layers.
bool FrameHasPlatformLayers();
// Creates a Surface when needed or recycles an existing one.
// Finally, draws the picture on the frame's canvas.
std::unique_ptr<SurfaceFrame> CreateSurfaceIfNeeded(GrDirectContext* context,
int64_t view_id,
EmbedderViewSlice* slice,
const SkRect& rect);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_H_
| engine/shell/platform/android/external_view_embedder/external_view_embedder.h/0 | {
"file_path": "engine/shell/platform/android/external_view_embedder/external_view_embedder.h",
"repo_id": "engine",
"token_count": 1929
} | 439 |
// 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_LRU_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_LRU_H_
#include <array>
#include <cstddef>
#include "display_list/image/dl_image.h"
namespace flutter {
// This value needs to be larger than the number of swapchain images
// that a typical image reader will produce to ensure that we effectively
// cache. If the value is too small, we will unnecessarily churn through
// images, while if it is too large we may retain images longer than
// necessary.
static constexpr size_t kImageReaderSwapchainSize = 6u;
using HardwareBufferKey = uint64_t;
class ImageLRU {
public:
ImageLRU() = default;
~ImageLRU() = default;
/// @brief Retrieve the image associated with the given [key], or nullptr.
sk_sp<flutter::DlImage> FindImage(std::optional<HardwareBufferKey> key);
/// @brief Add a new image to the cache with a key, returning the key of the
/// LRU entry that was removed.
///
/// The value may be `0`, in which case nothing was removed.
HardwareBufferKey AddImage(const sk_sp<flutter::DlImage>& image,
HardwareBufferKey key);
/// @brief Remove all entires from the image cache.
void Clear();
private:
/// @brief Marks [key] as the most recently used.
void UpdateKey(const sk_sp<flutter::DlImage>& image, HardwareBufferKey key);
struct Data {
HardwareBufferKey key = 0u;
sk_sp<flutter::DlImage> value;
};
std::array<Data, kImageReaderSwapchainSize> images_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_LRU_H_
| engine/shell/platform/android/image_lru.h/0 | {
"file_path": "engine/shell/platform/android/image_lru.h",
"repo_id": "engine",
"token_count": 584
} | 440 |
// 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 android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.DEFAULT_INITIAL_ROUTE;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.lifecycle.Lifecycle;
import io.flutter.FlutterInjector;
import io.flutter.Log;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.FlutterEngineGroup;
import io.flutter.embedding.engine.FlutterEngineGroupCache;
import io.flutter.embedding.engine.FlutterShellArgs;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener;
import io.flutter.plugin.platform.PlatformPlugin;
import java.util.Arrays;
import java.util.List;
/**
* Delegate that implements all Flutter logic that is the same between a {@link FlutterActivity} and
* a {@link FlutterFragment}.
*
* <p><strong>Why does this class exist?</strong>
*
* <p>One might ask why an {@code Activity} and {@code Fragment} delegate needs to exist. Given that
* a {@code Fragment} can be placed within an {@code Activity}, it would make more sense to use a
* {@link FlutterFragment} within a {@link FlutterActivity}.
*
* <p>The {@code Fragment} support library adds 100k of binary size to an app, and full-Flutter apps
* do not otherwise require that binary hit. Therefore, it was concluded that Flutter must provide a
* {@link FlutterActivity} based on the AOSP {@code Activity}, and an independent {@link
* FlutterFragment} for add-to-app developers.
*
* <p>If a time ever comes where the inclusion of {@code Fragment}s in a full-Flutter app is no
* longer deemed an issue, this class should be immediately decomposed between {@link
* FlutterActivity} and {@link FlutterFragment} and then eliminated.
*
* <p><strong>Caution when modifying this class</strong>
*
* <p>Any time that a "delegate" is created with the purpose of encapsulating the internal behaviors
* of another object, that delegate is highly susceptible to degeneration. It is easy to tack new
* responsibilities on to the delegate which would not otherwise be added to the original object. It
* is also easy to begin hanging listeners and callbacks on a delegate object that likewise would
* not be added to the original object. A delegate can quickly become a complex web of dependencies
* and optional references that are very difficult to track.
*
* <p>Maintainers of this class should take care to only place code in this delegate that would
* otherwise be placed in either {@link FlutterActivity} or {@link FlutterFragment}, and in exactly
* the same form. <strong>Do not use this class as a convenient shortcut for any other
* behavior.</strong>
*/
/* package */ class FlutterActivityAndFragmentDelegate implements ExclusiveAppComponent<Activity> {
private static final String TAG = "FlutterActivityAndFragmentDelegate";
private static final String FRAMEWORK_RESTORATION_BUNDLE_KEY = "framework";
private static final String PLUGINS_RESTORATION_BUNDLE_KEY = "plugins";
private static final int FLUTTER_SPLASH_VIEW_FALLBACK_ID = 486947586;
/** Factory to obtain a FlutterActivityAndFragmentDelegate instance. */
public interface DelegateFactory {
FlutterActivityAndFragmentDelegate createDelegate(FlutterActivityAndFragmentDelegate.Host host);
}
// The FlutterActivity or FlutterFragment that is delegating most of its calls
// to this FlutterActivityAndFragmentDelegate.
@NonNull private Host host;
@Nullable private FlutterEngine flutterEngine;
@VisibleForTesting @Nullable FlutterView flutterView;
@Nullable private PlatformPlugin platformPlugin;
@VisibleForTesting @Nullable OnPreDrawListener activePreDrawListener;
private boolean isFlutterEngineFromHost;
private boolean isFlutterUiDisplayed;
private boolean isFirstFrameRendered;
private boolean isAttached;
private Integer previousVisibility;
@Nullable private FlutterEngineGroup engineGroup;
@NonNull
private final FlutterUiDisplayListener flutterUiDisplayListener =
new FlutterUiDisplayListener() {
@Override
public void onFlutterUiDisplayed() {
host.onFlutterUiDisplayed();
isFlutterUiDisplayed = true;
isFirstFrameRendered = true;
}
@Override
public void onFlutterUiNoLongerDisplayed() {
host.onFlutterUiNoLongerDisplayed();
isFlutterUiDisplayed = false;
}
};
FlutterActivityAndFragmentDelegate(@NonNull Host host) {
this(host, null);
}
FlutterActivityAndFragmentDelegate(@NonNull Host host, @Nullable FlutterEngineGroup engineGroup) {
this.host = host;
this.isFirstFrameRendered = false;
this.engineGroup = engineGroup;
}
/**
* Disconnects this {@code FlutterActivityAndFragmentDelegate} from its host {@code Activity} or
* {@code Fragment}.
*
* <p>No further method invocations may occur on this {@code FlutterActivityAndFragmentDelegate}
* after invoking this method. If a method is invoked, an exception will occur.
*
* <p>This method only clears out references. It does not destroy its {@link
* io.flutter.embedding.engine.FlutterEngine}. The behavior that destroys a {@link
* io.flutter.embedding.engine.FlutterEngine} can be found in {@link #onDetach()}.
*/
void release() {
this.host = null;
this.flutterEngine = null;
this.flutterView = null;
this.platformPlugin = null;
}
/**
* Returns the {@link io.flutter.embedding.engine.FlutterEngine} that is owned by this delegate
* and its host {@code Activity} or {@code Fragment}.
*/
@Nullable
/* package */ FlutterEngine getFlutterEngine() {
return flutterEngine;
}
/**
* Returns true if the host {@code Activity}/{@code Fragment} provided a {@code FlutterEngine}, as
* opposed to this delegate creating a new one.
*/
/* package */ boolean isFlutterEngineFromHost() {
return isFlutterEngineFromHost;
}
/**
* Whether or not this {@code FlutterActivityAndFragmentDelegate} is attached to a {@code
* FlutterEngine}.
*/
/* package */ boolean isAttached() {
return isAttached;
}
/**
* Invoke this method from {@code Activity#onCreate(Bundle)} or {@code
* Fragment#onAttach(Context)}.
*
* <p>This method does the following:
*
* <p>
*
* <ol>
* <li>Initializes the Flutter system.
* <li>Obtains or creates a {@link io.flutter.embedding.engine.FlutterEngine}.
* <li>Creates and configures a {@link PlatformPlugin}.
* <li>Attaches the {@link io.flutter.embedding.engine.FlutterEngine} to the surrounding {@code
* Activity}, if desired.
* <li>Configures the {@link io.flutter.embedding.engine.FlutterEngine} via {@link
* Host#configureFlutterEngine(FlutterEngine)}.
* </ol>
*/
void onAttach(@NonNull Context context) {
ensureAlive();
// When "retain instance" is true, the FlutterEngine will survive configuration
// changes. Therefore, we create a new one only if one does not already exist.
if (flutterEngine == null) {
setUpFlutterEngine();
}
if (host.shouldAttachEngineToActivity()) {
// Notify any plugins that are currently attached to our FlutterEngine that they
// are now attached to an Activity.
//
// Passing this Fragment's Lifecycle should be sufficient because as long as this Fragment
// is attached to its Activity, the lifecycles should be in sync. Once this Fragment is
// detached from its Activity, that Activity will be detached from the FlutterEngine, too,
// which means there shouldn't be any possibility for the Fragment Lifecycle to get out of
// sync with the Activity. We use the Fragment's Lifecycle because it is possible that the
// attached Activity is not a LifecycleOwner.
Log.v(TAG, "Attaching FlutterEngine to the Activity that owns this delegate.");
flutterEngine.getActivityControlSurface().attachToActivity(this, host.getLifecycle());
}
// Regardless of whether or not a FlutterEngine already existed, the PlatformPlugin
// is bound to a specific Activity. Therefore, it needs to be created and configured
// every time this Fragment attaches to a new Activity.
// TODO(mattcarroll): the PlatformPlugin needs to be reimagined because it implicitly takes
// control of the entire window. This is unacceptable for non-fullscreen
// use-cases.
platformPlugin = host.providePlatformPlugin(host.getActivity(), flutterEngine);
host.configureFlutterEngine(flutterEngine);
isAttached = true;
}
@Override
public @NonNull Activity getAppComponent() {
final Activity activity = host.getActivity();
if (activity == null) {
throw new AssertionError(
"FlutterActivityAndFragmentDelegate's getAppComponent should only "
+ "be queried after onAttach, when the host's activity should always be non-null");
}
return activity;
}
private FlutterEngineGroup.Options addEntrypointOptions(FlutterEngineGroup.Options options) {
String appBundlePathOverride = host.getAppBundlePath();
if (appBundlePathOverride == null || appBundlePathOverride.isEmpty()) {
appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath();
}
DartExecutor.DartEntrypoint dartEntrypoint =
new DartExecutor.DartEntrypoint(
appBundlePathOverride, host.getDartEntrypointFunctionName());
String initialRoute = host.getInitialRoute();
if (initialRoute == null) {
initialRoute = maybeGetInitialRouteFromIntent(host.getActivity().getIntent());
if (initialRoute == null) {
initialRoute = DEFAULT_INITIAL_ROUTE;
}
}
return options
.setDartEntrypoint(dartEntrypoint)
.setInitialRoute(initialRoute)
.setDartEntrypointArgs(host.getDartEntrypointArgs());
}
/**
* Obtains a reference to a FlutterEngine to back this delegate and its {@code host}.
*
* <p>
*
* <p>First, the {@code host} is asked if it would like to use a cached {@link
* io.flutter.embedding.engine.FlutterEngine}, and if so, the cached {@link
* io.flutter.embedding.engine.FlutterEngine} is retrieved.
*
* <p>Second, the {@code host} is given an opportunity to provide a {@link
* io.flutter.embedding.engine.FlutterEngine} via {@link Host#provideFlutterEngine(Context)}.
*
* <p>Third, the {@code host} is asked if it would like to use a cached {@link
* io.flutter.embedding.engine.FlutterEngineGroup} to create a new {@link FlutterEngine} by {@link
* FlutterEngineGroup#createAndRunEngine}
*
* <p>If the {@code host} does not provide a {@link io.flutter.embedding.engine.FlutterEngine},
* then a new {@link FlutterEngine} is instantiated.
*/
@VisibleForTesting
/* package */ void setUpFlutterEngine() {
Log.v(TAG, "Setting up FlutterEngine.");
// First, check if the host wants to use a cached FlutterEngine.
String cachedEngineId = host.getCachedEngineId();
if (cachedEngineId != null) {
flutterEngine = FlutterEngineCache.getInstance().get(cachedEngineId);
isFlutterEngineFromHost = true;
if (flutterEngine == null) {
throw new IllegalStateException(
"The requested cached FlutterEngine did not exist in the FlutterEngineCache: '"
+ cachedEngineId
+ "'");
}
return;
}
// Second, defer to subclasses for a custom FlutterEngine.
flutterEngine = host.provideFlutterEngine(host.getContext());
if (flutterEngine != null) {
isFlutterEngineFromHost = true;
return;
}
// Third, check if the host wants to use a cached FlutterEngineGroup
// and create new FlutterEngine using FlutterEngineGroup#createAndRunEngine
String cachedEngineGroupId = host.getCachedEngineGroupId();
if (cachedEngineGroupId != null) {
FlutterEngineGroup flutterEngineGroup =
FlutterEngineGroupCache.getInstance().get(cachedEngineGroupId);
if (flutterEngineGroup == null) {
throw new IllegalStateException(
"The requested cached FlutterEngineGroup did not exist in the FlutterEngineGroupCache: '"
+ cachedEngineGroupId
+ "'");
}
flutterEngine =
flutterEngineGroup.createAndRunEngine(
addEntrypointOptions(new FlutterEngineGroup.Options(host.getContext())));
isFlutterEngineFromHost = false;
return;
}
// Our host did not provide a custom FlutterEngine. Create a FlutterEngine to back our
// FlutterView.
Log.v(
TAG,
"No preferred FlutterEngine was provided. Creating a new FlutterEngine for"
+ " this FlutterFragment.");
FlutterEngineGroup group =
engineGroup == null
? new FlutterEngineGroup(host.getContext(), host.getFlutterShellArgs().toArray())
: engineGroup;
flutterEngine =
group.createAndRunEngine(
addEntrypointOptions(
new FlutterEngineGroup.Options(host.getContext())
.setAutomaticallyRegisterPlugins(false)
.setWaitForRestorationData(host.shouldRestoreAndSaveState())));
isFlutterEngineFromHost = false;
}
/**
* Invoke this method from {@code Activity#onCreate(Bundle)} to create the content {@code View},
* or from {@code Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}.
*
* <p>{@code inflater} and {@code container} may be null when invoked from an {@code Activity}.
*
* <p>{@code shouldDelayFirstAndroidViewDraw} determines whether to set up an {@link
* android.view.ViewTreeObserver.OnPreDrawListener}, which will defer the current drawing pass
* till after the Flutter UI has been displayed. This results in more accurate timings reported
* with Android tools, such as "Displayed" timing printed with `am start`.
*
* <p>Note that it should only be set to true when {@code Host#getRenderMode()} is {@code
* RenderMode.surface}.
*
* <p>This method:
*
* <ol>
* <li>creates a new {@link FlutterView} in a {@code View} hierarchy
* <li>adds a {@link FlutterUiDisplayListener} to it
* <li>attaches a {@link io.flutter.embedding.engine.FlutterEngine} to the new {@link
* FlutterView}
* <li>returns the new {@code View} hierarchy
* </ol>
*/
@NonNull
View onCreateView(
LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState,
int flutterViewId,
boolean shouldDelayFirstAndroidViewDraw) {
Log.v(TAG, "Creating FlutterView.");
ensureAlive();
if (host.getRenderMode() == RenderMode.surface) {
FlutterSurfaceView flutterSurfaceView =
new FlutterSurfaceView(
host.getContext(), host.getTransparencyMode() == TransparencyMode.transparent);
// Allow our host to customize FlutterSurfaceView, if desired.
host.onFlutterSurfaceViewCreated(flutterSurfaceView);
// Create the FlutterView that owns the FlutterSurfaceView.
flutterView = new FlutterView(host.getContext(), flutterSurfaceView);
} else {
FlutterTextureView flutterTextureView = new FlutterTextureView(host.getContext());
flutterTextureView.setOpaque(host.getTransparencyMode() == TransparencyMode.opaque);
// Allow our host to customize FlutterSurfaceView, if desired.
host.onFlutterTextureViewCreated(flutterTextureView);
// Create the FlutterView that owns the FlutterTextureView.
flutterView = new FlutterView(host.getContext(), flutterTextureView);
}
// Add listener to be notified when Flutter renders its first frame.
flutterView.addOnFirstFrameRenderedListener(flutterUiDisplayListener);
if (host.attachToEngineAutomatically()) {
Log.v(TAG, "Attaching FlutterEngine to FlutterView.");
flutterView.attachToFlutterEngine(flutterEngine);
}
flutterView.setId(flutterViewId);
if (shouldDelayFirstAndroidViewDraw) {
delayFirstAndroidViewDraw(flutterView);
}
return flutterView;
}
void onRestoreInstanceState(@Nullable Bundle bundle) {
Log.v(
TAG,
"onRestoreInstanceState. Giving framework and plugins an opportunity to restore state.");
ensureAlive();
Bundle pluginState = null;
byte[] frameworkState = null;
if (bundle != null) {
pluginState = bundle.getBundle(PLUGINS_RESTORATION_BUNDLE_KEY);
frameworkState = bundle.getByteArray(FRAMEWORK_RESTORATION_BUNDLE_KEY);
}
if (host.shouldRestoreAndSaveState()) {
flutterEngine.getRestorationChannel().setRestorationData(frameworkState);
}
if (host.shouldAttachEngineToActivity()) {
flutterEngine.getActivityControlSurface().onRestoreInstanceState(pluginState);
}
}
/**
* Invoke this from {@code Activity#onStart()} or {@code Fragment#onStart()}.
*
* <p>This method:
*
* <p>
*
* <ol>
* <li>Begins executing Dart code, if it is not already executing.
* </ol>
*/
void onStart() {
Log.v(TAG, "onStart()");
ensureAlive();
doInitialFlutterViewRun();
// This is a workaround for a bug on some OnePlus phones. The visibility of the application
// window is still true after locking the screen on some OnePlus phones, and shows a black
// screen when unlocked. We can work around this by changing the visibility of FlutterView in
// onStart and onStop.
// See https://github.com/flutter/flutter/issues/93276
if (previousVisibility != null) {
flutterView.setVisibility(previousVisibility);
}
}
/**
* Starts running Dart within the FlutterView for the first time.
*
* <p>Reloading/restarting Dart within a given FlutterView is not supported. If this method is
* invoked while Dart is already executing then it does nothing.
*
* <p>{@code flutterEngine} must be non-null when invoking this method.
*/
private void doInitialFlutterViewRun() {
// Don't attempt to start a FlutterEngine if we're using a cached FlutterEngine.
if (host.getCachedEngineId() != null) {
return;
}
if (flutterEngine.getDartExecutor().isExecutingDart()) {
// No warning is logged because this situation will happen on every config
// change if the developer does not choose to retain the Fragment instance.
// So this is expected behavior in many cases.
return;
}
String initialRoute = host.getInitialRoute();
if (initialRoute == null) {
initialRoute = maybeGetInitialRouteFromIntent(host.getActivity().getIntent());
if (initialRoute == null) {
initialRoute = DEFAULT_INITIAL_ROUTE;
}
}
@Nullable String libraryUri = host.getDartEntrypointLibraryUri();
Log.v(
TAG,
"Executing Dart entrypoint: "
+ host.getDartEntrypointFunctionName()
+ ", library uri: "
+ libraryUri
== null
? "\"\""
: libraryUri + ", and sending initial route: " + initialRoute);
// The engine needs to receive the Flutter app's initial route before executing any
// Dart code to ensure that the initial route arrives in time to be applied.
flutterEngine.getNavigationChannel().setInitialRoute(initialRoute);
String appBundlePathOverride = host.getAppBundlePath();
if (appBundlePathOverride == null || appBundlePathOverride.isEmpty()) {
appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath();
}
// Configure the Dart entrypoint and execute it.
DartExecutor.DartEntrypoint entrypoint =
libraryUri == null
? new DartExecutor.DartEntrypoint(
appBundlePathOverride, host.getDartEntrypointFunctionName())
: new DartExecutor.DartEntrypoint(
appBundlePathOverride, libraryUri, host.getDartEntrypointFunctionName());
flutterEngine.getDartExecutor().executeDartEntrypoint(entrypoint, host.getDartEntrypointArgs());
}
private String maybeGetInitialRouteFromIntent(Intent intent) {
if (host.shouldHandleDeeplinking()) {
Uri data = intent.getData();
if (data != null) {
return data.toString();
}
}
return null;
}
/**
* Delays the first drawing of the {@code flutterView} until the Flutter first has been displayed.
*/
private void delayFirstAndroidViewDraw(FlutterView flutterView) {
if (host.getRenderMode() != RenderMode.surface) {
// Using a TextureView will cause a deadlock, where the underlying SurfaceTexture is never
// available since it will wait for drawing to be completed first. At the same time, the
// preDraw listener keeps returning false since the Flutter Engine waits for the
// SurfaceTexture to be available.
throw new IllegalArgumentException(
"Cannot delay the first Android view draw when the render mode is not set to"
+ " `RenderMode.surface`.");
}
if (activePreDrawListener != null) {
flutterView.getViewTreeObserver().removeOnPreDrawListener(activePreDrawListener);
}
activePreDrawListener =
new OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (isFlutterUiDisplayed && activePreDrawListener != null) {
flutterView.getViewTreeObserver().removeOnPreDrawListener(this);
activePreDrawListener = null;
}
return isFlutterUiDisplayed;
}
};
flutterView.getViewTreeObserver().addOnPreDrawListener(activePreDrawListener);
}
/**
* Invoke this from {@code Activity#onResume()} or {@code Fragment#onResume()}.
*
* <p>This method notifies the running Flutter app that it is "resumed" as per the Flutter app
* lifecycle.
*/
void onResume() {
Log.v(TAG, "onResume()");
ensureAlive();
if (host.shouldDispatchAppLifecycleState() && flutterEngine != null) {
flutterEngine.getLifecycleChannel().appIsResumed();
}
}
/**
* Invoke this from {@code Activity#onPostResume()}.
*
* <p>A {@code Fragment} host must have its containing {@code Activity} forward this call so that
* the {@code Fragment} can then invoke this method.
*
* <p>This method informs the {@link PlatformPlugin} that {@code onPostResume()} has run, which is
* used to update system UI overlays.
*/
// TODO(mattcarroll): determine why this can't be in onResume(). Comment reason, or move if
// possible.
void onPostResume() {
Log.v(TAG, "onPostResume()");
ensureAlive();
if (flutterEngine != null) {
updateSystemUiOverlays();
} else {
Log.w(TAG, "onPostResume() invoked before FlutterFragment was attached to an Activity.");
}
}
/**
* Refreshes Android's window system UI (AKA system chrome) to match Flutter's desired system
* chrome style.
*/
void updateSystemUiOverlays() {
if (platformPlugin != null) {
// TODO(mattcarroll): find a better way to handle the update of UI overlays than calling
// through to platformPlugin. We're implicitly entangling the Window, Activity,
// Fragment, and engine all with this one call.
platformPlugin.updateSystemUiOverlays();
}
}
/**
* Invoke this from {@code Activity#onPause()} or {@code Fragment#onPause()}.
*
* <p>This method notifies the running Flutter app that it is "inactive" as per the Flutter app
* lifecycle.
*/
void onPause() {
Log.v(TAG, "onPause()");
ensureAlive();
if (host.shouldDispatchAppLifecycleState() && flutterEngine != null) {
flutterEngine.getLifecycleChannel().appIsInactive();
}
}
/**
* Invoke this from {@code Activity#onStop()} or {@code Fragment#onStop()}.
*
* <p>This method:
*
* <p>
*
* <ol>
* <li>This method notifies the running Flutter app that it is "paused" as per the Flutter app
* lifecycle.
* <li>Detaches this delegate's {@link io.flutter.embedding.engine.FlutterEngine} from this
* delegate's {@link FlutterView}.
* </ol>
*/
void onStop() {
Log.v(TAG, "onStop()");
ensureAlive();
if (host.shouldDispatchAppLifecycleState() && flutterEngine != null) {
flutterEngine.getLifecycleChannel().appIsPaused();
}
// This is a workaround for a bug on some OnePlus phones. The visibility of the application
// window is still true after locking the screen on some OnePlus phones, and shows a black
// screen when unlocked. We can work around this by changing the visibility of FlutterView in
// onStart and onStop.
// See https://github.com/flutter/flutter/issues/93276
previousVisibility = flutterView.getVisibility();
flutterView.setVisibility(View.GONE);
}
/**
* Invoke this from {@code Activity#onDestroy()} or {@code Fragment#onDestroyView()}.
*
* <p>This method removes this delegate's {@link FlutterView}'s {@link FlutterUiDisplayListener}.
*/
void onDestroyView() {
Log.v(TAG, "onDestroyView()");
ensureAlive();
if (activePreDrawListener != null) {
flutterView.getViewTreeObserver().removeOnPreDrawListener(activePreDrawListener);
activePreDrawListener = null;
}
// flutterView can be null in instances where a delegate.onDestroyView is called without
// onCreateView being called. See https://github.com/flutter/engine/pull/41082 for more detail.
if (flutterView != null) {
flutterView.detachFromFlutterEngine();
flutterView.removeOnFirstFrameRenderedListener(flutterUiDisplayListener);
}
}
void onSaveInstanceState(@Nullable Bundle bundle) {
Log.v(TAG, "onSaveInstanceState. Giving framework and plugins an opportunity to save state.");
ensureAlive();
if (host.shouldRestoreAndSaveState()) {
bundle.putByteArray(
FRAMEWORK_RESTORATION_BUNDLE_KEY,
flutterEngine.getRestorationChannel().getRestorationData());
}
if (host.shouldAttachEngineToActivity()) {
final Bundle plugins = new Bundle();
flutterEngine.getActivityControlSurface().onSaveInstanceState(plugins);
bundle.putBundle(PLUGINS_RESTORATION_BUNDLE_KEY, plugins);
}
}
@Override
public void detachFromFlutterEngine() {
if (host.shouldDestroyEngineWithHost()) {
// The host owns the engine and should never have its engine taken by another exclusive
// activity.
throw new AssertionError(
"The internal FlutterEngine created by "
+ host
+ " has been attached to by another activity. To persist a FlutterEngine beyond the "
+ "ownership of this activity, explicitly create a FlutterEngine");
}
// Default, but customizable, behavior is for the host to call {@link #onDetach}
// deterministically as to not mix more events during the lifecycle of the next exclusive
// activity.
host.detachFromFlutterEngine();
}
/**
* Invoke this from {@code Activity#onDestroy()} or {@code Fragment#onDetach()}.
*
* <p>This method:
*
* <p>
*
* <ol>
* <li>Detaches this delegate's {@link io.flutter.embedding.engine.FlutterEngine} from its
* surrounding {@code Activity}, if it was previously attached.
* <li>Destroys this delegate's {@link PlatformPlugin}.
* <li>Destroys this delegate's {@link io.flutter.embedding.engine.FlutterEngine} if {@link
* Host#shouldDestroyEngineWithHost()} ()} returns true.
* </ol>
*/
void onDetach() {
if (!isAttached) {
// Already detached.
return;
}
Log.v(TAG, "onDetach()");
ensureAlive();
// Give the host an opportunity to cleanup any references that were created in
// configureFlutterEngine().
host.cleanUpFlutterEngine(flutterEngine);
if (host.shouldAttachEngineToActivity()) {
// Notify plugins that they are no longer attached to an Activity.
Log.v(TAG, "Detaching FlutterEngine from the Activity that owns this Fragment.");
if (host.getActivity().isChangingConfigurations()) {
flutterEngine.getActivityControlSurface().detachFromActivityForConfigChanges();
} else {
flutterEngine.getActivityControlSurface().detachFromActivity();
}
}
// Null out the platformPlugin to avoid a possible retain cycle between the plugin, this
// Fragment,
// and this Fragment's Activity.
if (platformPlugin != null) {
platformPlugin.destroy();
platformPlugin = null;
}
if (host.shouldDispatchAppLifecycleState() && flutterEngine != null) {
flutterEngine.getLifecycleChannel().appIsDetached();
}
// Destroy our FlutterEngine if we're not set to retain it.
if (host.shouldDestroyEngineWithHost()) {
flutterEngine.destroy();
if (host.getCachedEngineId() != null) {
FlutterEngineCache.getInstance().remove(host.getCachedEngineId());
}
flutterEngine = null;
}
isAttached = false;
}
/**
* Invoke this from {@link android.app.Activity#onBackPressed()}.
*
* <p>A {@code Fragment} host must have its containing {@code Activity} forward this call so that
* the {@code Fragment} can then invoke this method.
*
* <p>This method instructs Flutter's navigation system to "pop route".
*/
void onBackPressed() {
ensureAlive();
if (flutterEngine != null) {
Log.v(TAG, "Forwarding onBackPressed() to FlutterEngine.");
flutterEngine.getNavigationChannel().popRoute();
} else {
Log.w(TAG, "Invoked onBackPressed() before FlutterFragment was attached to an Activity.");
}
}
/**
* Invoke this from {@link android.app.Activity#onRequestPermissionsResult(int, String[], int[])}
* or {@code Fragment#onRequestPermissionsResult(int, String[], int[])}.
*
* <p>This method forwards to interested Flutter plugins.
*/
void onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
ensureAlive();
if (flutterEngine != null) {
Log.v(
TAG,
"Forwarding onRequestPermissionsResult() to FlutterEngine:\n"
+ "requestCode: "
+ requestCode
+ "\n"
+ "permissions: "
+ Arrays.toString(permissions)
+ "\n"
+ "grantResults: "
+ Arrays.toString(grantResults));
flutterEngine
.getActivityControlSurface()
.onRequestPermissionsResult(requestCode, permissions, grantResults);
} else {
Log.w(
TAG,
"onRequestPermissionResult() invoked before FlutterFragment was attached to an Activity.");
}
}
/**
* Invoke this from {@code Activity#onNewIntent(Intent)}.
*
* <p>A {@code Fragment} host must have its containing {@code Activity} forward this call so that
* the {@code Fragment} can then invoke this method.
*
* <p>This method forwards to interested Flutter plugins.
*/
void onNewIntent(@NonNull Intent intent) {
ensureAlive();
if (flutterEngine != null) {
Log.v(
TAG,
"Forwarding onNewIntent() to FlutterEngine and sending pushRouteInformation message.");
flutterEngine.getActivityControlSurface().onNewIntent(intent);
String initialRoute = maybeGetInitialRouteFromIntent(intent);
if (initialRoute != null && !initialRoute.isEmpty()) {
flutterEngine.getNavigationChannel().pushRouteInformation(initialRoute);
}
} else {
Log.w(TAG, "onNewIntent() invoked before FlutterFragment was attached to an Activity.");
}
}
/**
* Invoke this from {@code Activity#onActivityResult(int, int, Intent)} or {@code
* Fragment#onActivityResult(int, int, Intent)}.
*
* <p>This method forwards to interested Flutter plugins.
*/
void onActivityResult(int requestCode, int resultCode, Intent data) {
ensureAlive();
if (flutterEngine != null) {
Log.v(
TAG,
"Forwarding onActivityResult() to FlutterEngine:\n"
+ "requestCode: "
+ requestCode
+ "\n"
+ "resultCode: "
+ resultCode
+ "\n"
+ "data: "
+ data);
flutterEngine.getActivityControlSurface().onActivityResult(requestCode, resultCode, data);
} else {
Log.w(TAG, "onActivityResult() invoked before FlutterFragment was attached to an Activity.");
}
}
/**
* Invoke this from {@code Activity#onUserLeaveHint()}.
*
* <p>A {@code Fragment} host must have its containing {@code Activity} forward this call so that
* the {@code Fragment} can then invoke this method.
*
* <p>This method forwards to interested Flutter plugins.
*/
void onUserLeaveHint() {
ensureAlive();
if (flutterEngine != null) {
Log.v(TAG, "Forwarding onUserLeaveHint() to FlutterEngine.");
flutterEngine.getActivityControlSurface().onUserLeaveHint();
} else {
Log.w(TAG, "onUserLeaveHint() invoked before FlutterFragment was attached to an Activity.");
}
}
/**
* Invoke this from {@code Activity#onWindowFocusChanged()}.
*
* <p>A {@code Fragment} host must have its containing {@code Activity} forward this call so that
* the {@code Fragment} can then invoke this method.
*/
void onWindowFocusChanged(boolean hasFocus) {
ensureAlive();
Log.v(TAG, "Received onWindowFocusChanged: " + (hasFocus ? "true" : "false"));
if (host.shouldDispatchAppLifecycleState() && flutterEngine != null) {
// TODO(gspencergoog): Once we have support for multiple windows/views,
// this code will need to consult the list of windows/views to determine if
// any windows in the app are focused and call the appropriate function.
if (hasFocus) {
flutterEngine.getLifecycleChannel().aWindowIsFocused();
} else {
flutterEngine.getLifecycleChannel().noWindowsAreFocused();
}
}
}
/**
* Invoke this from {@link android.app.Activity#onTrimMemory(int)}.
*
* <p>A {@code Fragment} host must have its containing {@code Activity} forward this call so that
* the {@code Fragment} can then invoke this method.
*
* <p>This method sends a "memory pressure warning" message to Flutter over the "system channel".
*/
void onTrimMemory(int level) {
ensureAlive();
if (flutterEngine != null) {
// Use a trim level delivered while the application is running so the
// framework has a chance to react to the notification.
// Avoid being too aggressive before the first frame is rendered. If it is
// not at least running critical, we should avoid delaying the frame for
// an overly aggressive GC.
boolean trim = isFirstFrameRendered && level >= TRIM_MEMORY_RUNNING_LOW;
if (trim) {
flutterEngine.getDartExecutor().notifyLowMemoryWarning();
flutterEngine.getSystemChannel().sendMemoryPressureWarning();
}
flutterEngine.getRenderer().onTrimMemory(level);
}
}
/**
* Ensures that this delegate has not been {@link #release()}'ed.
*
* <p>An {@code IllegalStateException} is thrown if this delegate has been {@link #release()}'ed.
*/
private void ensureAlive() {
if (host == null) {
throw new IllegalStateException(
"Cannot execute method on a destroyed FlutterActivityAndFragmentDelegate.");
}
}
/**
* The {@link FlutterActivity} or {@link FlutterFragment} that owns this {@code
* FlutterActivityAndFragmentDelegate}.
*/
/* package */ interface Host
extends FlutterEngineProvider,
FlutterEngineConfigurator,
PlatformPlugin.PlatformPluginDelegate {
/**
* Returns the {@link Context} that backs the host {@link android.app.Activity} or {@code
* Fragment}.
*/
@NonNull
Context getContext();
/** Returns true if the delegate should retrieve the initial route from the {@link Intent}. */
@Nullable
boolean shouldHandleDeeplinking();
/**
* Returns the host {@link android.app.Activity} or the {@code Activity} that is currently
* attached to the host {@code Fragment}.
*/
@Nullable
Activity getActivity();
/**
* Returns the {@link Lifecycle} that backs the host {@link android.app.Activity} or {@code
* Fragment}.
*/
@NonNull
Lifecycle getLifecycle();
/** Returns the {@link FlutterShellArgs} that should be used when initializing Flutter. */
@NonNull
FlutterShellArgs getFlutterShellArgs();
/**
* Returns the ID of a statically cached {@link io.flutter.embedding.engine.FlutterEngine} to
* use within this delegate's host, or {@code null} if this delegate's host does not want to use
* a cached {@link FlutterEngine}.
*/
@Nullable
String getCachedEngineId();
@Nullable
String getCachedEngineGroupId();
/**
* Returns true if the {@link io.flutter.embedding.engine.FlutterEngine} used in this delegate
* should be destroyed when the host/delegate are destroyed.
*
* <p>The default value is {@code true} in cases where {@code FlutterFragment} created its own
* {@link io.flutter.embedding.engine.FlutterEngine}, and {@code false} in cases where a cached
* {@link io.flutter.embedding.engine.FlutterEngine} was provided.
*/
boolean shouldDestroyEngineWithHost();
/**
* Callback called when the {@link io.flutter.embedding.engine.FlutterEngine} has been attached
* to by another activity before this activity was destroyed.
*
* <p>The expected behavior is for this activity to synchronously stop using the {@link
* FlutterEngine} to avoid lifecycle crosstalk with the new activity.
*/
void detachFromFlutterEngine();
/**
* Returns the Dart entrypoint that should run when a new {@link
* io.flutter.embedding.engine.FlutterEngine} is created.
*/
@NonNull
String getDartEntrypointFunctionName();
/**
* Returns the URI of the Dart library which contains the entrypoint method (example
* "package:foo_package/main.dart"). If null, this will default to the same library as the
* `main()` function in the Dart program.
*/
@Nullable
String getDartEntrypointLibraryUri();
/** Returns arguments that passed as a list of string to Dart's entrypoint function. */
@Nullable
List<String> getDartEntrypointArgs();
/** Returns the path to the app bundle where the Dart code exists. */
@NonNull
String getAppBundlePath();
/** Returns the initial route that Flutter renders. */
@Nullable
String getInitialRoute();
/**
* Returns the {@link RenderMode} used by the {@link FlutterView} that displays the {@link
* FlutterEngine}'s content.
*/
@NonNull
RenderMode getRenderMode();
/**
* Returns the {@link TransparencyMode} used by the {@link FlutterView} that displays the {@link
* FlutterEngine}'s content.
*/
@NonNull
TransparencyMode getTransparencyMode();
/**
* Returns the {@link ExclusiveAppComponent<Activity>} that is associated with {@link
* io.flutter.embedding.engine.FlutterEngine}.
*
* <p>In the scenario where multiple {@link FlutterActivity} or {@link FlutterFragment} share
* the same {@link FlutterEngine}, to attach/re-attache a {@link FlutterActivity} or {@link
* FlutterFragment} to the shared {@link FlutterEngine}, we MUST manually invoke {@link
* ActivityControlSurface#attachToActivity(ExclusiveAppComponent, Lifecycle)}.
*
* <p>The {@link ExclusiveAppComponent} is exposed here so that subclasses of {@link
* FlutterActivity} or {@link FlutterFragment} can access it.
*/
ExclusiveAppComponent<Activity> getExclusiveAppComponent();
/**
* Returns the {@link io.flutter.embedding.engine.FlutterEngine} that should be rendered to a
* {@link FlutterView}.
*
* <p>If {@code null} is returned, a new {@link io.flutter.embedding.engine.FlutterEngine} will
* be created automatically.
*/
@Nullable
FlutterEngine provideFlutterEngine(@NonNull Context context);
/**
* Hook for the host to create/provide a {@link PlatformPlugin} if the associated Flutter
* experience should control system chrome.
*/
@Nullable
PlatformPlugin providePlatformPlugin(
@Nullable Activity activity, @NonNull FlutterEngine flutterEngine);
/**
* Hook for the host to configure the {@link io.flutter.embedding.engine.FlutterEngine} as
* desired.
*/
void configureFlutterEngine(@NonNull FlutterEngine flutterEngine);
/**
* Hook for the host to cleanup references that were established in {@link
* #configureFlutterEngine(FlutterEngine)} before the host is destroyed or detached.
*/
void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine);
/**
* Returns true if the {@link io.flutter.embedding.engine.FlutterEngine}'s plugin system should
* be connected to the host {@link android.app.Activity}, allowing plugins to interact with it.
*/
boolean shouldAttachEngineToActivity();
/**
* Invoked by this delegate when the {@link FlutterSurfaceView} that renders the Flutter UI is
* initially instantiated.
*
* <p>This method is only invoked if the {@link
* io.flutter.embedding.android.FlutterView.RenderMode} is set to {@link
* io.flutter.embedding.android.FlutterView.RenderMode#surface}. Otherwise, {@link
* #onFlutterTextureViewCreated(FlutterTextureView)} is invoked.
*
* <p>This method is invoked before the given {@link FlutterSurfaceView} is attached to the
* {@code View} hierarchy. Implementers should not attempt to climb the {@code View} hierarchy
* or make assumptions about relationships with other {@code View}s.
*/
void onFlutterSurfaceViewCreated(@NonNull FlutterSurfaceView flutterSurfaceView);
/**
* Invoked by this delegate when the {@link FlutterTextureView} that renders the Flutter UI is
* initially instantiated.
*
* <p>This method is only invoked if the {@link
* io.flutter.embedding.android.FlutterView.RenderMode} is set to {@link
* io.flutter.embedding.android.FlutterView.RenderMode#texture}. Otherwise, {@link
* #onFlutterSurfaceViewCreated(FlutterSurfaceView)} is invoked.
*
* <p>This method is invoked before the given {@link FlutterTextureView} is attached to the
* {@code View} hierarchy. Implementers should not attempt to climb the {@code View} hierarchy
* or make assumptions about relationships with other {@code View}s.
*/
void onFlutterTextureViewCreated(@NonNull FlutterTextureView flutterTextureView);
/** Invoked by this delegate when its {@link FlutterView} starts painting pixels. */
void onFlutterUiDisplayed();
/** Invoked by this delegate when its {@link FlutterView} stops painting pixels. */
void onFlutterUiNoLongerDisplayed();
/**
* Whether state restoration is enabled.
*
* <p>When this returns true, the instance state provided to {@code
* onRestoreInstanceState(Bundle)} will be forwarded to the framework via the {@code
* RestorationChannel} and during {@code onSaveInstanceState(Bundle)} the current framework
* instance state obtained from {@code RestorationChannel} will be stored in the provided
* bundle.
*
* <p>This defaults to true, unless a cached engine is used.
*/
boolean shouldRestoreAndSaveState();
/**
* Refreshes Android's window system UI (AKA system chrome) to match Flutter's desired system
* chrome style.
*
* <p>This is useful when using the splash screen API available in Android 12. {@code
* SplashScreenView#remove} resets the system UI colors to the values set prior to the execution
* of the Dart entrypoint. As a result, the values set from Dart are reverted by this API. To
* workaround this issue, call this method after removing the splash screen with {@code
* SplashScreenView#remove}.
*/
void updateSystemUiOverlays();
/**
* Give the host application a chance to take control of the app lifecycle events to avoid
* lifecycle crosstalk.
*
* <p>In the add-to-app scenario where multiple {@link FlutterActivity} shares the same {@link
* FlutterEngine}, the application lifecycle state will have crosstalk causing the page to
* freeze. For example, we open a new page called FlutterActivity#2 from the previous page
* called FlutterActivity#1. The flow of app lifecycle states received by dart is as follows:
*
* <p>inactive (from FlutterActivity#1) -> resumed (from FlutterActivity#2) -> paused (from
* FlutterActivity#1)
*
* <p>On the one hand, the {@code paused} state from FlutterActivity#1 will cause the
* FlutterActivity#2 page to be stuck; On the other hand, these states are not expected from the
* perspective of the entire application lifecycle. If the host application gets the control of
* sending {@link AppLifecycleState}, It will be possible to correctly match the {@link
* AppLifecycleState} with the application-level lifecycle.
*
* <p>Return {@code false} means the host application dispatches these app lifecycle events,
* while return {@code true} means the engine dispatches these events.
*/
boolean shouldDispatchAppLifecycleState();
/**
* Whether to automatically attach the {@link FlutterView} to the engine.
*
* <p>In the add-to-app scenario where multiple {@link FlutterView} share the same {@link
* FlutterEngine}, the host application desires to determine the timing of attaching the {@link
* FlutterView} to the engine, for example, during the {@code onResume} instead of the {@code
* onCreateView}.
*
* <p>Defaults to {@code true}.
*/
boolean attachToEngineAutomatically();
}
}
| engine/shell/platform/android/io/flutter/embedding/android/FlutterActivityAndFragmentDelegate.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/android/FlutterActivityAndFragmentDelegate.java",
"repo_id": "engine",
"token_count": 16180
} | 441 |
package io.flutter.embedding.android;
import android.util.LongSparseArray;
import android.view.MotionEvent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.PriorityQueue;
import java.util.concurrent.atomic.AtomicLong;
/** Tracks the motion events received by the FlutterView. */
public final class MotionEventTracker {
private static final String TAG = "MotionEventTracker";
/** Represents a unique identifier corresponding to a motion event. */
public static class MotionEventId {
private static final AtomicLong ID_COUNTER = new AtomicLong(0);
private final long id;
private MotionEventId(long id) {
this.id = id;
}
@NonNull
public static MotionEventId from(long id) {
return new MotionEventId(id);
}
@NonNull
public static MotionEventId createUnique() {
return MotionEventId.from(ID_COUNTER.incrementAndGet());
}
public long getId() {
return id;
}
}
private final LongSparseArray<MotionEvent> eventById;
private final PriorityQueue<Long> unusedEvents;
private static MotionEventTracker INSTANCE;
@NonNull
public static MotionEventTracker getInstance() {
if (INSTANCE == null) {
INSTANCE = new MotionEventTracker();
}
return INSTANCE;
}
private MotionEventTracker() {
eventById = new LongSparseArray<>();
unusedEvents = new PriorityQueue<>();
}
/** Tracks the event and returns a unique MotionEventId identifying the event. */
@NonNull
public MotionEventId track(@NonNull MotionEvent event) {
MotionEventId eventId = MotionEventId.createUnique();
// We copy event here because the original MotionEvent delivered to us
// will be automatically recycled (`MotionEvent.recycle`) by the RootView and we need
// access to it after the RootView code runs.
// The return value of `MotionEvent.obtain(event)` is still verifiable if the input
// event was verifiable. Other overloads of `MotionEvent.obtain` do not have this
// guarantee and should be avoided when possible.
MotionEvent eventCopy = MotionEvent.obtain(event);
eventById.put(eventId.id, eventCopy);
unusedEvents.add(eventId.id);
return eventId;
}
/**
* Returns the MotionEvent corresponding to the eventId while discarding all the motion events
* that occurred prior to the event represented by the eventId. Returns null if this event was
* popped or discarded.
*/
@Nullable
public MotionEvent pop(@NonNull MotionEventId eventId) {
// remove all the older events.
while (!unusedEvents.isEmpty() && unusedEvents.peek() < eventId.id) {
eventById.remove(unusedEvents.poll());
}
// remove the current event from the heap if it exists.
if (!unusedEvents.isEmpty() && unusedEvents.peek() == eventId.id) {
unusedEvents.poll();
}
MotionEvent event = eventById.get(eventId.id);
eventById.remove(eventId.id);
return event;
}
}
| engine/shell/platform/android/io/flutter/embedding/android/MotionEventTracker.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/android/MotionEventTracker.java",
"repo_id": "engine",
"token_count": 929
} | 442 |
// 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.deferredcomponents;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.embedding.engine.systemchannels.DeferredComponentChannel;
// TODO: add links to external documentation on how to use split aot features.
/**
* Basic interface that handles downloading and loading of deferred components.
*
* <p>Flutter deferred component support is still in early developer preview and should not be used
* in production apps yet.
*
* <p>The Flutter default implementation is PlayStoreDeferredComponentManager.
*
* <p>DeferredComponentManager handles the embedder/Android level tasks of downloading, installing,
* and loading Dart deferred libraries. A typical code-flow begins with a Dart call to loadLibrary()
* on deferred imported library. See https://dart.dev/guides/language/language-tour#deferred-loading
* This call retrieves a unique identifier called the loading unit id, which is assigned by
* gen_snapshot during compilation. The loading unit id is passed down through the engine and
* invokes installDeferredComponent. Once the component is downloaded, loadAssets and
* loadDartLibrary should be invoked. loadDartLibrary should find shared library .so files for the
* engine to open and pass the .so path to FlutterJNI.loadDartDeferredLibrary. loadAssets should
* typically ensure the new assets are available to the engine's asset manager by passing an updated
* Android AssetManager to the engine via FlutterJNI.updateAssetManager.
*
* <p>The loadAssets and loadDartLibrary methods are separated out because they may also be called
* manually via platform channel messages. A full installDeferredComponent implementation should
* call these two methods as needed.
*
* <p>A deferred component is uniquely identified by a component name as defined in
* bundle_config.yaml. Each component may contain one or more loading units, uniquely identified by
* the loading unit ID and assets.
*/
public interface DeferredComponentManager {
/**
* Sets the FlutterJNI to be used to communication with the Flutter native engine.
*
* <p>A FlutterJNI is required in order to properly execute loadAssets and loadDartLibrary.
*
* <p>Since this class may be instantiated for injection before the FlutterEngine and FlutterJNI
* is fully initialized, this method should be called to provide the FlutterJNI instance to use
* for use in loadDartLibrary and loadAssets.
*/
public abstract void setJNI(FlutterJNI flutterJNI);
/**
* Sets the DeferredComponentChannel system channel to handle the framework API to directly call
* methods in DeferredComponentManager.
*
* <p>A DeferredComponentChannel is required to handle assets-only deferred components and
* manually installed deferred components.
*
* <p>Since this class may be instantiated for injection before the FlutterEngine and System
* Channels are initialized, this method should be called to provide the DeferredComponentChannel.
* Similarly, the {@link DeferredComponentChannel.setDeferredComponentManager} method should also
* be called with this DeferredComponentManager instance to properly forward method invocations.
*
* <p>The {@link DeferredComponentChannel} passes manual invocations of {@link
* installDeferredComponent} and {@link getDeferredComponentInstallState} from the method channel
* to this DeferredComponentManager. Upon completion of the install process, successful
* installations should notify the DeferredComponentChannel by calling {@link
* DeferredComponentChannel.completeInstallSuccess} while errors and failures should call {@link
* DeferredComponentChannel.completeInstallError}.
*/
public abstract void setDeferredComponentChannel(DeferredComponentChannel channel);
/**
* Request that the deferred component be downloaded and installed.
*
* <p>This method begins the download and installation of the specified deferred component. For
* example, the Play Store dynamic delivery implementation uses SplitInstallManager to request the
* download of the component. Download is not complete when this method returns. The download
* process should be listened for and upon completion of download, listeners should invoke
* loadAssets first and then loadDartLibrary to complete the deferred component load process.
* Assets-only deferred components should also call {@link
* DeferredComponentChannel.completeInstallSuccess} or {@link
* DeferredComponentChannel.completeInstallError} to complete the method channel invocation's dart
* Future.
*
* <p>Both parameters are not always necessary to identify which component to install. Asset-only
* components do not have an associated loadingUnitId. Instead, an invalid ID like -1 may be
* passed to download only with componentName. On the other hand, it can be possible to resolve
* the componentName based on the loadingUnitId. This resolution is done if componentName is null.
* At least one of loadingUnitId or componentName must be valid or non-null.
*
* <p>Flutter will typically call this method in two ways. When invoked as part of a dart
* `loadLibrary()` call, a valid loadingUnitId is passed in while the componentName is null. In
* this case, this method is responsible for figuring out what component the loadingUnitId
* corresponds to.
*
* <p>When invoked manually as part of loading an assets-only component, loadingUnitId is -1
* (invalid) and componentName is supplied. Without a loadingUnitId, this method just downloads
* the component by name and attempts to load assets via loadAssets while loadDartLibrary is
* skipped, even if the deferred component includes valid dart libs. To load dart libs, call
* `loadLibrary()` using the first way described in the previous paragraph as the method channel
* invocation will not load dart shared libraries.
*
* <p>While the Future retuned by either `loadLibary` or the method channel invocation will
* indicate when the code and assets are ready to be used, informational querying of the install
* process' state can be done with {@link getDeferredComponentInstallState}, though the results of
* this query should not be used to decide if the deferred component is ready to use. Only the
* Future completion should be used to do this.
*
* @param loadingUnitId The unique identifier associated with a Dart deferred library. This id is
* assigned by the compiler and can be seen for reference in bundle_config.yaml. This ID is
* primarily used in loadDartLibrary to indicate to Dart which Dart library is being loaded.
* Loading unit ids range from 0 to the number existing loading units. Passing a negative
* loading unit id indicates that no Dart deferred library should be loaded after download
* completes. This is the case when the deferred component is an assets-only component. If a
* negative loadingUnitId is passed, then componentName must not be null. Passing a
* loadingUnitId larger than the highest valid loading unit's id will cause the Dart
* loadLibrary() to complete with a failure.
* @param componentName The deferred component name as defined in bundle_config.yaml. This may be
* null if the deferred component to be loaded is associated with a loading unit/deferred dart
* library. In this case, it is this method's responsibility to map the loadingUnitId to its
* corresponding componentName. When loading asset-only or other deferred components without
* an associated Dart deferred library, loading unit id should a negative value and
* componentName must be non-null.
*/
public abstract void installDeferredComponent(int loadingUnitId, String componentName);
/**
* Gets the current state of the installation session corresponding to the specified loadingUnitId
* and/or componentName.
*
* <p>Invocations of {@link installDeferredComponent} typically result in asynchronous downloading
* and other tasks. This method enables querying of the state of the installation. Querying the
* installation state is purely informational and does not impact the installation process. The
* results of this query should not be used to decide if the deferred component is ready to use.
* Upon completion of installation, the Future returned by the installation request will complete.
* Only after dart Future completion is it safe to use code and assets from the deferred
* component.
*
* <p>If no deferred component has been installed or requested to be installed by the provided
* loadingUnitId or componentName, then this method will return null.
*
* <p>Depending on the implementation, the returned String may vary. The Play store default
* implementation begins in the "requested" state before transitioning to the "downloading" and
* "installed" states.
*
* <p>Only successfully requested components have state. Modules that are invalid or have not been
* requested with {@link installDeferredComponent} will not have a state. Due to the asynchronous
* nature of the download process, components may not immediately have a valid state upon return
* of {@link installDeferredComponent}, though valid components will eventually obtain a state.
*
* <p>Both parameters are not always necessary to identify which component to install. Asset-only
* components do not have an associated loadingUnitId. Instead, an invalid ID like -1 may be
* passed to query only with componentName. On the other hand, it can be possible to resolve the
* componentName based on the loadingUnitId. This resolution is done if componentName is null. At
* least one of loadingUnitId or componentName must be valid or non-null.
*
* @param loadingUnitId The unique identifier associated with a Dart deferred library.
* @param componentName The deferred component name as defined in bundle_config.yaml.
*/
public abstract String getDeferredComponentInstallState(int loadingUnitId, String componentName);
/**
* Extract and load any assets and resources from the deferred component for use by Flutter.
*
* <p>This method should provide a refreshed AssetManager to FlutterJNI.updateAssetManager that
* can access the new assets. If no assets are included as part of the deferred component, then
* nothing needs to be done.
*
* <p>If using the Play Store deferred component delivery, refresh the context via: {@code
* context.createPackageContext(context.getPackageName(), 0);} This returns a new context, from
* which an updated asset manager may be obtained and passed to updateAssetManager in FlutterJNI.
* This process does not require loadingUnitId or componentName, however, the two parameters are
* still present for custom implementations that store assets outside of Android's native system.
*
* <p>Assets shoud be loaded before the Dart deferred library is loaded, as successful loading of
* the Dart loading unit indicates the deferred component is fully loaded. Implementations of
* installDeferredComponent should invoke this after successful download.
*
* @param loadingUnitId The unique identifier associated with a Dart deferred library.
* @param componentName The deferred component name as defined in bundle_config.yaml.
*/
public abstract void loadAssets(int loadingUnitId, String componentName);
/**
* Load the .so shared library file into the Dart VM.
*
* <p>When the download of a deferred component completes, this method should be called to find
* the path .so library file. The path(s) should then be passed to
* FlutterJNI.loadDartDeferredLibrary to be dlopen-ed and loaded into the Dart VM.
*
* <p>Specifically, APKs distributed by Android's app bundle format may vary by device and API
* number, so FlutterJNI's loadDartDeferredLibrary accepts a list of search paths with can include
* paths within APKs that have not been unpacked using the
* `path/to/apk.apk!path/inside/apk/lib.so` format. Each search path will be attempted in order
* until a shared library is found. This allows for the developer to avoid unpacking the apk zip.
*
* <p>Upon successful load of the Dart library, the Dart future from the originating loadLibary()
* call completes and developers are able to use symbols and assets from the deferred component.
*
* @param loadingUnitId The unique identifier associated with a Dart deferred library. This id is
* assigned by the compiler and can be seen for reference in bundle_config.yaml. This ID is
* primarily used in loadDartLibrary to indicate to Dart which Dart library is being loaded.
* Loading unit ids range from 0 to the number existing loading units. Negative loading unit
* ids are considered invalid and this method will result in a no-op.
* @param componentName The deferred component name as defined in bundle_config.yaml. If using
* Play Store deferred component delivery, this name corresponds to the root name on the
* installed APKs in which to search for the desired shared library .so file.
*/
public abstract void loadDartLibrary(int loadingUnitId, String componentName);
/**
* Request that the specified component be uninstalled.
*
* <p>Since uninstallation requires significant disk i/o, this method only signals the intent to
* uninstall. Actual uninstallation (eg, removal of assets and files) may occur at a later time.
* However, once uninstallation is requested, the deferred component should not be used anymore
* until {@link installDeferredComponent} is called again.
*
* <p>Uninstallation, once complete, removes downloaded files and will require redownloading to
* install again.
*
* <p>Both parameters are not always necessary to identify which component to uninstall.
* Asset-only components do not have an associated loadingUnitId. Instead, an invalid ID like -1
* may be passed to download only with componentName. On the other hand, it can be possible to
* resolve the componentName based on the loadingUnitId. This resolution is done if componentName
* is null. At least one of loadingUnitId or componentName must be valid or non-null.
*
* @return false if no deferred component was found matching the input, true if an uninstall was
* successfully requested.
* @param loadingUnitId The unique identifier associated with a Dart deferred library.
* @param componentName The deferred component name as defined in bundle_config.yaml.
*/
public abstract boolean uninstallDeferredComponent(int loadingUnitId, String componentName);
/**
* Cleans up and releases resources. This object is no longer usable after calling this method.
*/
public abstract void destroy();
}
| engine/shell/platform/android/io/flutter/embedding/engine/deferredcomponents/DeferredComponentManager.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/deferredcomponents/DeferredComponentManager.java",
"repo_id": "engine",
"token_count": 3776
} | 443 |
// 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.contentprovider;
import androidx.annotation.NonNull;
/**
* A {@link io.flutter.embedding.engine.plugins.FlutterPlugin} that wants to know when it is running
* within a {@link android.content.ContentProvider}.
*/
public interface ContentProviderAware {
/**
* Callback triggered when a {@code ContentProviderAware} {@link
* io.flutter.embedding.engine.plugins.FlutterPlugin} is associated with a {@link
* android.content.ContentProvider}.
*/
void onAttachedToContentProvider(@NonNull ContentProviderPluginBinding binding);
/**
* Callback triggered when a {@code ContentProviderAware} {@link
* io.flutter.embedding.engine.plugins.FlutterPlugin} is detached from a {@link
* android.content.ContentProvider}.
*/
void onDetachedFromContentProvider();
}
| engine/shell/platform/android/io/flutter/embedding/engine/plugins/contentprovider/ContentProviderAware.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/contentprovider/ContentProviderAware.java",
"repo_id": "engine",
"token_count": 291
} | 444 |
// 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 androidx.annotation.VisibleForTesting;
import io.flutter.FlutterInjector;
import io.flutter.Log;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.StandardMethodCodec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Method channel that handles manual installation requests and queries for installation state for
* deferred components.
*
* <p>This channel is able to handle multiple simultaneous installation requests
*/
public class DeferredComponentChannel {
private static final String TAG = "DeferredComponentChannel";
@NonNull private final MethodChannel channel;
@Nullable private DeferredComponentManager deferredComponentManager;
// Track the Result objects to be able to handle multiple install requests of
// the same components at a time. When installation enters a terminal state, either
// completeInstallSuccess or completeInstallError can be called.
@NonNull private Map<String, List<MethodChannel.Result>> componentNameToResults;
@NonNull @VisibleForTesting
final MethodChannel.MethodCallHandler parsingMethodHandler =
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
if (deferredComponentManager == null) {
// If no DeferredComponentManager has been injected, then this channel is a no-op.
return;
}
String method = call.method;
Map<String, Object> args = call.arguments();
Log.v(TAG, "Received '" + method + "' message.");
final int loadingUnitId = (int) args.get("loadingUnitId");
final String componentName = (String) args.get("componentName");
switch (method) {
case "installDeferredComponent":
deferredComponentManager.installDeferredComponent(loadingUnitId, componentName);
if (!componentNameToResults.containsKey(componentName)) {
componentNameToResults.put(componentName, new ArrayList<>());
}
componentNameToResults.get(componentName).add(result);
break;
case "getDeferredComponentInstallState":
result.success(
deferredComponentManager.getDeferredComponentInstallState(
loadingUnitId, componentName));
break;
case "uninstallDeferredComponent":
deferredComponentManager.uninstallDeferredComponent(loadingUnitId, componentName);
result.success(null);
break;
default:
result.notImplemented();
break;
}
}
};
/**
* Constructs a {@code DeferredComponentChannel} that connects Android to the Dart code running in
* {@code dartExecutor}.
*
* <p>The given {@code dartExecutor} is permitted to be idle or executing code.
*
* <p>See {@link DartExecutor}.
*/
public DeferredComponentChannel(@NonNull DartExecutor dartExecutor) {
this.channel =
new MethodChannel(dartExecutor, "flutter/deferredcomponent", StandardMethodCodec.INSTANCE);
channel.setMethodCallHandler(parsingMethodHandler);
deferredComponentManager = FlutterInjector.instance().deferredComponentManager();
componentNameToResults = new HashMap<>();
}
/**
* Sets the DeferredComponentManager to exectue method channel calls with.
*
* @param deferredComponentManager the DeferredComponentManager to use.
*/
@VisibleForTesting
public void setDeferredComponentManager(
@Nullable DeferredComponentManager deferredComponentManager) {
this.deferredComponentManager = deferredComponentManager;
}
/**
* Finishes the `installDeferredComponent` method channel call for the specified componentName
* with a success.
*
* @param componentName The name of the android deferred component install request to complete.
*/
public void completeInstallSuccess(String componentName) {
if (componentNameToResults.containsKey(componentName)) {
for (MethodChannel.Result result : componentNameToResults.get(componentName)) {
result.success(null);
}
componentNameToResults.get(componentName).clear();
}
return;
}
/**
* Finishes the `installDeferredComponent` method channel call for the specified componentName
* with an error/failure.
*
* @param componentName The name of the android deferred component install request to complete.
* @param errorMessage The error message to display to complete the future with.
*/
public void completeInstallError(String componentName, String errorMessage) {
if (componentNameToResults.containsKey(componentName)) {
for (MethodChannel.Result result : componentNameToResults.get(componentName)) {
result.error("DeferredComponent Install failure", errorMessage, null);
}
componentNameToResults.get(componentName).clear();
}
return;
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/DeferredComponentChannel.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/DeferredComponentChannel.java",
"repo_id": "engine",
"token_count": 1816
} | 445 |
// 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 androidx.annotation.UiThread;
import io.flutter.BuildConfig;
import io.flutter.Log;
import io.flutter.plugin.common.BinaryMessenger.BinaryMessageHandler;
import io.flutter.plugin.common.BinaryMessenger.BinaryReply;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* A named channel for communicating with the Flutter application using basic, asynchronous message
* passing.
*
* <p>Messages are encoded into binary before being sent, and binary messages received are decoded
* into Java objects. The {@link MessageCodec} used must be compatible with the one used by the
* Flutter application. This can be achieved by creating a <a
* href="https://api.flutter.dev/flutter/services/BasicMessageChannel-class.html">BasicMessageChannel</a>
* counterpart of this channel on the Dart side. The static Java type of messages sent and received
* is {@code Object}, but only values supported by the specified {@link MessageCodec} can be used.
*
* <p>The logical identity of the channel is given by its name. Identically named channels will
* interfere with each other's communication.
*/
public final class BasicMessageChannel<T> {
private static final String TAG = "BasicMessageChannel#";
public static final String CHANNEL_BUFFERS_CHANNEL = "dev.flutter/channel-buffers";
@NonNull private final BinaryMessenger messenger;
@NonNull private final String name;
@NonNull private final MessageCodec<T> codec;
@Nullable private final BinaryMessenger.TaskQueue taskQueue;
/**
* Creates a new channel associated with the specified {@link BinaryMessenger} and with the
* specified name and {@link MessageCodec}.
*
* @param messenger a {@link BinaryMessenger}.
* @param name a channel name String.
* @param codec a {@link MessageCodec}.
*/
public BasicMessageChannel(
@NonNull BinaryMessenger messenger, @NonNull String name, @NonNull MessageCodec<T> codec) {
this(messenger, name, codec, null);
}
/**
* Creates a new channel associated with the specified {@link BinaryMessenger} and with the
* specified name and {@link MessageCodec}.
*
* @param messenger a {@link BinaryMessenger}.
* @param name a channel name String.
* @param codec a {@link MessageCodec}.
* @param taskQueue a {@link BinaryMessenger.TaskQueue} that specifies what thread will execute
* the handler. Specifying null means execute on the platform thread. See also {@link
* BinaryMessenger#makeBackgroundTaskQueue()}.
*/
public BasicMessageChannel(
@NonNull BinaryMessenger messenger,
@NonNull String name,
@NonNull MessageCodec<T> codec,
BinaryMessenger.TaskQueue taskQueue) {
if (BuildConfig.DEBUG) {
if (messenger == null) {
Log.e(TAG, "Parameter messenger must not be null.");
}
if (name == null) {
Log.e(TAG, "Parameter name must not be null.");
}
if (codec == null) {
Log.e(TAG, "Parameter codec must not be null.");
}
}
this.messenger = messenger;
this.name = name;
this.codec = codec;
this.taskQueue = taskQueue;
}
/**
* Sends the specified message to the Flutter application on this channel.
*
* @param message the message, possibly null.
*/
public void send(@Nullable T message) {
send(message, null);
}
/**
* Sends the specified message to the Flutter application, optionally expecting a reply.
*
* <p>Any uncaught exception thrown by the reply callback will be caught and logged.
*
* @param message the message, possibly null.
* @param callback a {@link Reply} callback, possibly null.
*/
@UiThread
public void send(@Nullable T message, @Nullable final Reply<T> callback) {
messenger.send(
name,
codec.encodeMessage(message),
callback == null ? null : new IncomingReplyHandler(callback));
}
/**
* Registers a message handler on this channel for receiving messages sent from the Flutter
* application.
*
* <p>Overrides any existing handler registration for (the name of) this channel.
*
* <p>If no handler has been registered, any incoming message on this channel will be handled
* silently by sending a null reply.
*
* @param handler a {@link MessageHandler}, or null to deregister.
*/
@UiThread
public void setMessageHandler(@Nullable final MessageHandler<T> handler) {
// We call the 2 parameter variant specifically to avoid breaking changes in
// mock verify calls.
// See https://github.com/flutter/flutter/issues/92582.
if (taskQueue != null) {
messenger.setMessageHandler(
name, handler == null ? null : new IncomingMessageHandler(handler), taskQueue);
} else {
messenger.setMessageHandler(
name, handler == null ? null : new IncomingMessageHandler(handler));
}
}
/**
* Adjusts the number of messages that will get buffered when sending messages to channels that
* aren't fully set up yet. For example, the engine isn't running yet or the channel's message
* handler isn't set up on the Dart side yet.
*/
public void resizeChannelBuffer(int newSize) {
resizeChannelBuffer(messenger, name, newSize);
}
/**
* Toggles whether the channel should show warning messages when discarding messages due to
* overflow. When 'warns' is false the channel is expected to overflow and warning messages will
* not be shown.
*/
public void setWarnsOnChannelOverflow(boolean warns) {
setWarnsOnChannelOverflow(messenger, name, warns);
}
private static ByteBuffer packetFromEncodedMessage(ByteBuffer message) {
// Create a bytes array using the buffer content (messages.array() can not be used here).
message.flip();
final byte[] bytes = new byte[message.remaining()];
message.get(bytes);
// The current Android Java/JNI platform message implementation assumes
// that all buffers passed to native are direct buffers.
ByteBuffer packet = ByteBuffer.allocateDirect(bytes.length);
packet.put(bytes);
return packet;
}
/**
* Adjusts the number of messages that will get buffered when sending messages to channels that
* aren't fully set up yet. For example, the engine isn't running yet or the channel's message
* handler isn't set up on the Dart side yet.
*/
public static void resizeChannelBuffer(
@NonNull BinaryMessenger messenger, @NonNull String channel, int newSize) {
final StandardMethodCodec codec = StandardMethodCodec.INSTANCE;
Object[] arguments = {channel, newSize};
MethodCall methodCall = new MethodCall("resize", Arrays.asList(arguments));
ByteBuffer message = codec.encodeMethodCall(methodCall);
ByteBuffer packet = packetFromEncodedMessage(message);
messenger.send(BasicMessageChannel.CHANNEL_BUFFERS_CHANNEL, packet);
}
/**
* Toggles whether the channel should show warning messages when discarding messages due to
* overflow. When 'warns' is false the channel is expected to overflow and warning messages will
* not be shown.
*/
public static void setWarnsOnChannelOverflow(
@NonNull BinaryMessenger messenger, @NonNull String channel, boolean warns) {
final StandardMethodCodec codec = StandardMethodCodec.INSTANCE;
Object[] arguments = {channel, !warns};
MethodCall methodCall = new MethodCall("overflow", Arrays.asList(arguments));
ByteBuffer message = codec.encodeMethodCall(methodCall);
ByteBuffer packet = packetFromEncodedMessage(message);
messenger.send(BasicMessageChannel.CHANNEL_BUFFERS_CHANNEL, packet);
}
/** A handler of incoming messages. */
public interface MessageHandler<T> {
/**
* Handles the specified message received from Flutter.
*
* <p>Handler implementations must reply to all incoming messages, by submitting a single reply
* message to the given {@link Reply}. Failure to do so will result in lingering Flutter reply
* handlers. The reply may be submitted asynchronously and invoked on any thread.
*
* <p>Any uncaught exception thrown by this method, or the preceding message decoding, will be
* caught by the channel implementation and logged, and a null reply message will be sent back
* to Flutter.
*
* <p>Any uncaught exception thrown during encoding a reply message submitted to the {@link
* Reply} is treated similarly: the exception is logged, and a null reply is sent to Flutter.
*
* @param message the message, possibly null.
* @param reply a {@link Reply} for sending a single message reply back to Flutter.
*/
void onMessage(@Nullable T message, @NonNull Reply<T> reply);
}
/**
* Message reply callback. Used to submit a reply to an incoming message from Flutter. Also used
* in the dual capacity to handle a reply received from Flutter after sending a message.
*/
public interface Reply<T> {
/**
* Handles the specified message reply.
*
* @param reply the reply, possibly null.
*/
void reply(@Nullable T reply);
}
private final class IncomingReplyHandler implements BinaryReply {
private final Reply<T> callback;
private IncomingReplyHandler(@NonNull Reply<T> callback) {
this.callback = callback;
}
@Override
public void reply(@Nullable ByteBuffer reply) {
try {
callback.reply(codec.decodeMessage(reply));
} catch (RuntimeException e) {
Log.e(TAG + name, "Failed to handle message reply", e);
}
}
}
private final class IncomingMessageHandler implements BinaryMessageHandler {
private final MessageHandler<T> handler;
private IncomingMessageHandler(@NonNull MessageHandler<T> handler) {
this.handler = handler;
}
@Override
public void onMessage(@Nullable ByteBuffer message, @NonNull final BinaryReply callback) {
try {
handler.onMessage(
codec.decodeMessage(message),
new Reply<T>() {
@Override
public void reply(T reply) {
callback.reply(codec.encodeMessage(reply));
}
});
} catch (RuntimeException e) {
Log.e(TAG + name, "Failed to handle message", e);
callback.reply(null);
}
}
}
}
| engine/shell/platform/android/io/flutter/plugin/common/BasicMessageChannel.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/common/BasicMessageChannel.java",
"repo_id": "engine",
"token_count": 3305
} | 446 |
// 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.Nullable;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
/**
* A {@link MessageCodec} using UTF-8 encoded String messages.
*
* <p>This codec is guaranteed to be compatible with the corresponding <a
* href="https://api.flutter.dev/flutter/services/StringCodec-class.html">StringCodec</a> on the
* Dart side. These parts of the Flutter SDK are evolved synchronously.
*/
public final class StringCodec implements MessageCodec<String> {
private static final Charset UTF8 = Charset.forName("UTF8");
public static final StringCodec INSTANCE = new StringCodec();
private StringCodec() {}
@Override
@Nullable
public ByteBuffer encodeMessage(@Nullable String message) {
if (message == null) {
return null;
}
// TODO(mravn): Avoid the extra copy below.
final byte[] bytes = message.getBytes(UTF8);
final ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.length);
buffer.put(bytes);
return buffer;
}
@Override
@Nullable
public String decodeMessage(@Nullable ByteBuffer message) {
if (message == null) {
return null;
}
final byte[] bytes;
final int offset;
final int length = message.remaining();
if (message.hasArray()) {
bytes = message.array();
offset = message.arrayOffset();
} else {
// TODO(mravn): Avoid the extra copy below.
bytes = new byte[length];
message.get(bytes);
offset = 0;
}
return new String(bytes, offset, length, UTF8);
}
}
| engine/shell/platform/android/io/flutter/plugin/common/StringCodec.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/common/StringCodec.java",
"repo_id": "engine",
"token_count": 572
} | 447 |
// 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 androidx.annotation.NonNull;
/**
* Registry for platform view factories.
*
* <p>Plugins can register factories for specific view types.
*/
public interface PlatformViewRegistry {
/**
* Registers a factory for a platform view.
*
* @param viewTypeId unique identifier for the platform view's type.
* @param factory factory for creating platform views of the specified type.
* @return true if succeeded, false if a factory is already registered for viewTypeId.
*/
boolean registerViewFactory(@NonNull String viewTypeId, @NonNull PlatformViewFactory factory);
}
| engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistry.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistry.java",
"repo_id": "engine",
"token_count": 209
} | 448 |
// 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.util;
import androidx.annotation.Nullable;
/**
* Static convenience methods that help a method or constructor check whether it was invoked
* correctly (that is, whether its <i>preconditions</i> were met).
*/
public final class Preconditions {
private Preconditions() {}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures the truth of an expression involving the state of the calling instance.
*
* @param expression a boolean expression that must be checked to be true
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance.
*
* @param expression a boolean expression that must be checked to be true
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
}
| engine/shell/platform/android/io/flutter/util/Preconditions.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/util/Preconditions.java",
"repo_id": "engine",
"token_count": 526
} | 449 |
# 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/config.gni")
source_set("surface") {
sources = [
"android_surface.cc",
"android_surface.h",
"snapshot_surface_producer.cc",
"snapshot_surface_producer.h",
]
public_configs = [ "//flutter:config" ]
deps = [
":native_window",
"//flutter/flow",
"//flutter/fml",
"//flutter/shell/common",
"//flutter/shell/platform/android/context",
"//flutter/shell/platform/android/jni",
"//flutter/skia",
]
}
source_set("native_window") {
sources = [
"android_native_window.cc",
"android_native_window.h",
]
public_configs = [ "//flutter:config" ]
deps = [
"//flutter/fml",
"//flutter/skia",
]
}
source_set("surface_mock") {
testonly = true
sources = [
"android_surface_mock.cc",
"android_surface_mock.h",
]
public_configs = [ "//flutter:config" ]
deps = [
":surface",
"//flutter/flow",
"//flutter/shell/gpu:gpu_surface_gl",
"//flutter/third_party/googletest:gmock",
"//flutter/third_party/googletest:gtest",
]
if (shell_enable_vulkan) {
deps += [ "//flutter/vulkan" ]
}
}
| engine/shell/platform/android/surface/BUILD.gn/0 | {
"file_path": "engine/shell/platform/android/surface/BUILD.gn",
"repo_id": "engine",
"token_count": 532
} | 450 |
// 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;
import static org.junit.Assert.assertEquals;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class LogTest {
@Test
public void canGetStacktraceString() {
Exception exception = new Exception();
String str = Log.getStackTraceString(exception);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
exception.printStackTrace(printWriter);
String expectStr = stringWriter.toString();
assertEquals(str, expectStr);
}
}
| engine/shell/platform/android/test/io/flutter/LogTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/LogTest.java",
"repo_id": "engine",
"token_count": 286
} | 451 |
// 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.nullable;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.res.AssetManager;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.FlutterInjector;
import io.flutter.embedding.engine.dart.DartExecutor.DartEntrypoint;
import io.flutter.embedding.engine.loader.FlutterLoader;
import io.flutter.embedding.engine.systemchannels.NavigationChannel;
import io.flutter.plugin.platform.PlatformViewsController;
import io.flutter.plugins.GeneratedPluginRegistrant;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
// It's a component test because it tests the FlutterEngineGroup its components such as the
// FlutterEngine and the DartExecutor.
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
public class FlutterEngineGroupComponentTest {
private final Context ctx = ApplicationProvider.getApplicationContext();
@Mock FlutterJNI mockFlutterJNI;
@Mock FlutterLoader mockFlutterLoader;
FlutterEngineGroup engineGroupUnderTest;
FlutterEngine firstEngineUnderTest;
boolean jniAttached;
@Before
public void setUp() {
FlutterInjector.reset();
MockitoAnnotations.openMocks(this);
jniAttached = false;
when(mockFlutterJNI.isAttached()).thenAnswer(invocation -> jniAttached);
doAnswer(invocation -> jniAttached = true).when(mockFlutterJNI).attachToNative();
GeneratedPluginRegistrant.clearRegisteredEngines();
when(mockFlutterLoader.findAppBundlePath()).thenReturn("some/path/to/flutter_assets");
FlutterJNI.Factory jniFactory =
new FlutterJNI.Factory() {
@Override
public FlutterJNI provideFlutterJNI() {
// The default implementation is that `new FlutterJNI()` will report errors when
// creating the engine later,
// Change mockFlutterJNI to the default so that we can create the engine directly in
// later tests
return mockFlutterJNI;
}
};
FlutterInjector.setInstance(
new FlutterInjector.Builder()
.setFlutterLoader(mockFlutterLoader)
.setFlutterJNIFactory(jniFactory)
.build());
firstEngineUnderTest =
spy(
new FlutterEngine(
ctx,
mock(FlutterLoader.class),
mockFlutterJNI,
/*dartVmArgs=*/ new String[] {},
/*automaticallyRegisterPlugins=*/ false));
engineGroupUnderTest =
new FlutterEngineGroup(ctx) {
@Override
FlutterEngine createEngine(
Context context,
PlatformViewsController platformViewsController,
boolean automaticallyRegisterPlugins,
boolean waitForRestorationData) {
return firstEngineUnderTest;
}
};
}
@After
public void tearDown() {
GeneratedPluginRegistrant.clearRegisteredEngines();
engineGroupUnderTest = null;
firstEngineUnderTest = null;
}
@Test
public void listensToEngineDestruction() {
FlutterEngine firstEngine =
engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class));
assertEquals(1, engineGroupUnderTest.activeEngines.size());
firstEngine.destroy();
assertEquals(0, engineGroupUnderTest.activeEngines.size());
}
@Test
public void canRecreateEngines() {
FlutterEngine firstEngine =
engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class));
assertEquals(1, engineGroupUnderTest.activeEngines.size());
firstEngine.destroy();
assertEquals(0, engineGroupUnderTest.activeEngines.size());
FlutterEngine secondEngine =
engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class));
assertEquals(1, engineGroupUnderTest.activeEngines.size());
// They happen to be equal in our test since we mocked it to be so.
assertEquals(firstEngine, secondEngine);
}
@Test
public void canSpawnMoreEngines() {
FlutterEngine firstEngine =
engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class));
assertEquals(1, engineGroupUnderTest.activeEngines.size());
doReturn(mock(FlutterEngine.class))
.when(firstEngine)
.spawn(
any(Context.class),
any(DartEntrypoint.class),
nullable(String.class),
nullable(List.class),
any(PlatformViewsController.class),
any(Boolean.class),
any(Boolean.class));
FlutterEngine secondEngine =
engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class));
assertEquals(2, engineGroupUnderTest.activeEngines.size());
firstEngine.destroy();
assertEquals(1, engineGroupUnderTest.activeEngines.size());
// Now the second spawned engine is the only one left and it will be called to spawn the next
// engine in the chain.
when(secondEngine.spawn(
any(Context.class),
any(DartEntrypoint.class),
nullable(String.class),
nullable(List.class),
any(PlatformViewsController.class),
any(Boolean.class),
any(Boolean.class)))
.thenReturn(mock(FlutterEngine.class));
FlutterEngine thirdEngine =
engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class));
assertEquals(2, engineGroupUnderTest.activeEngines.size());
}
@Test
public void canCreateAndRunCustomEntrypoints() {
FlutterEngine firstEngine =
engineGroupUnderTest.createAndRunEngine(
ctx,
new DartEntrypoint(
FlutterInjector.instance().flutterLoader().findAppBundlePath(),
"other entrypoint"));
assertEquals(1, engineGroupUnderTest.activeEngines.size());
verify(mockFlutterJNI, times(1))
.runBundleAndSnapshotFromLibrary(
eq("some/path/to/flutter_assets"),
eq("other entrypoint"),
isNull(),
any(AssetManager.class),
nullable(List.class));
}
@Test
public void canCreateAndRunWithCustomInitialRoute() {
when(firstEngineUnderTest.getNavigationChannel()).thenReturn(mock(NavigationChannel.class));
FlutterEngine firstEngine =
engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class), "/foo");
assertEquals(1, engineGroupUnderTest.activeEngines.size());
verify(firstEngine.getNavigationChannel(), times(1)).setInitialRoute("/foo");
when(mockFlutterJNI.isAttached()).thenReturn(true);
jniAttached = false;
FlutterJNI secondMockFlutterJNI = mock(FlutterJNI.class);
when(secondMockFlutterJNI.isAttached()).thenAnswer(invocation -> jniAttached);
doAnswer(invocation -> jniAttached = true).when(secondMockFlutterJNI).attachToNative();
doReturn(secondMockFlutterJNI)
.when(mockFlutterJNI)
.spawn(
nullable(String.class),
nullable(String.class),
nullable(String.class),
nullable(List.class));
FlutterEngine secondEngine =
engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class), "/bar");
assertEquals(2, engineGroupUnderTest.activeEngines.size());
verify(mockFlutterJNI, times(1))
.spawn(nullable(String.class), nullable(String.class), eq("/bar"), nullable(List.class));
}
@Test
public void canCreateAndRunWithCustomEntrypointArgs() {
List<String> firstDartEntrypointArgs = new ArrayList<String>();
FlutterEngine firstEngine =
engineGroupUnderTest.createAndRunEngine(
new FlutterEngineGroup.Options(ctx)
.setDartEntrypoint(mock(DartEntrypoint.class))
.setDartEntrypointArgs(firstDartEntrypointArgs));
assertEquals(1, engineGroupUnderTest.activeEngines.size());
verify(mockFlutterJNI, times(1))
.runBundleAndSnapshotFromLibrary(
nullable(String.class),
nullable(String.class),
isNull(),
any(AssetManager.class),
eq(firstDartEntrypointArgs));
when(mockFlutterJNI.isAttached()).thenReturn(true);
jniAttached = false;
FlutterJNI secondMockFlutterJNI = mock(FlutterJNI.class);
when(secondMockFlutterJNI.isAttached()).thenAnswer(invocation -> jniAttached);
doAnswer(invocation -> jniAttached = true).when(secondMockFlutterJNI).attachToNative();
doReturn(secondMockFlutterJNI)
.when(mockFlutterJNI)
.spawn(
nullable(String.class),
nullable(String.class),
nullable(String.class),
nullable(List.class));
List<String> secondDartEntrypointArgs = new ArrayList<String>();
FlutterEngine secondEngine =
engineGroupUnderTest.createAndRunEngine(
new FlutterEngineGroup.Options(ctx)
.setDartEntrypoint(mock(DartEntrypoint.class))
.setDartEntrypointArgs(secondDartEntrypointArgs));
assertEquals(2, engineGroupUnderTest.activeEngines.size());
verify(mockFlutterJNI, times(1))
.spawn(
nullable(String.class),
nullable(String.class),
nullable(String.class),
eq(secondDartEntrypointArgs));
}
@Test
public void createEngineSupportMoreParams() {
// Create a new FlutterEngineGroup because the first engine created in engineGroupUnderTest was
// changed to firstEngineUnderTest in `setUp()`, so can't use it to validate params.
FlutterEngineGroup engineGroup = new FlutterEngineGroup(ctx);
PlatformViewsController controller = new PlatformViewsController();
boolean waitForRestorationData = true;
boolean automaticallyRegisterPlugins = true;
when(FlutterInjector.instance().flutterLoader().automaticallyRegisterPlugins())
.thenReturn(true);
assertTrue(FlutterInjector.instance().flutterLoader().automaticallyRegisterPlugins());
assertEquals(0, GeneratedPluginRegistrant.getRegisteredEngines().size());
FlutterEngine firstEngine =
engineGroup.createAndRunEngine(
new FlutterEngineGroup.Options(ctx)
.setDartEntrypoint(mock(DartEntrypoint.class))
.setPlatformViewsController(controller)
.setWaitForRestorationData(waitForRestorationData)
.setAutomaticallyRegisterPlugins(automaticallyRegisterPlugins));
assertEquals(1, GeneratedPluginRegistrant.getRegisteredEngines().size());
assertEquals(controller, firstEngine.getPlatformViewsController());
assertEquals(
waitForRestorationData, firstEngine.getRestorationChannel().waitForRestorationData);
}
@Test
public void spawnEngineSupportMoreParams() {
FlutterEngine firstEngine =
engineGroupUnderTest.createAndRunEngine(
new FlutterEngineGroup.Options(ctx).setDartEntrypoint(mock(DartEntrypoint.class)));
assertEquals(1, engineGroupUnderTest.activeEngines.size());
verify(mockFlutterJNI, times(1))
.runBundleAndSnapshotFromLibrary(
nullable(String.class),
nullable(String.class),
isNull(),
any(AssetManager.class),
nullable(List.class));
when(mockFlutterJNI.isAttached()).thenReturn(true);
jniAttached = false;
FlutterJNI secondMockFlutterJNI = mock(FlutterJNI.class);
when(secondMockFlutterJNI.isAttached()).thenAnswer(invocation -> jniAttached);
doAnswer(invocation -> jniAttached = true).when(secondMockFlutterJNI).attachToNative();
doReturn(secondMockFlutterJNI)
.when(mockFlutterJNI)
.spawn(
nullable(String.class),
nullable(String.class),
nullable(String.class),
nullable(List.class));
PlatformViewsController controller = new PlatformViewsController();
boolean waitForRestorationData = false;
boolean automaticallyRegisterPlugins = false;
when(FlutterInjector.instance().flutterLoader().automaticallyRegisterPlugins())
.thenReturn(true);
assertTrue(FlutterInjector.instance().flutterLoader().automaticallyRegisterPlugins());
assertEquals(0, GeneratedPluginRegistrant.getRegisteredEngines().size());
FlutterEngine secondEngine =
engineGroupUnderTest.createAndRunEngine(
new FlutterEngineGroup.Options(ctx)
.setDartEntrypoint(mock(DartEntrypoint.class))
.setWaitForRestorationData(waitForRestorationData)
.setPlatformViewsController(controller)
.setAutomaticallyRegisterPlugins(automaticallyRegisterPlugins));
assertEquals(
waitForRestorationData, secondEngine.getRestorationChannel().waitForRestorationData);
assertEquals(controller, secondEngine.getPlatformViewsController());
assertEquals(0, GeneratedPluginRegistrant.getRegisteredEngines().size());
}
}
| engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineGroupComponentTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineGroupComponentTest.java",
"repo_id": "engine",
"token_count": 5315
} | 452 |
package io.flutter.embedding.engine.systemchannels;
import static io.flutter.Build.API_LEVELS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import android.annotation.TargetApi;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.BasicMessageChannel;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@Config(
manifest = Config.NONE,
shadows = {})
@RunWith(RobolectricTestRunner.class)
@TargetApi(API_LEVELS.API_24)
public class AccessibilityChannelTest {
@Test
public void repliesWhenNoAccessibilityHandler() throws JSONException {
AccessibilityChannel accessibilityChannel =
new AccessibilityChannel(mock(DartExecutor.class), mock(FlutterJNI.class));
JSONObject arguments = new JSONObject();
arguments.put("type", "announce");
BasicMessageChannel.Reply reply = mock(BasicMessageChannel.Reply.class);
accessibilityChannel.parsingMessageHandler.onMessage(arguments, reply);
verify(reply).reply(null);
}
@Test
public void handleFocus() throws JSONException {
AccessibilityChannel accessibilityChannel =
new AccessibilityChannel(mock(DartExecutor.class), mock(FlutterJNI.class));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("type", "focus");
arguments.put("nodeId", 123);
AccessibilityChannel.AccessibilityMessageHandler handler =
mock(AccessibilityChannel.AccessibilityMessageHandler.class);
accessibilityChannel.setAccessibilityMessageHandler(handler);
BasicMessageChannel.Reply reply = mock(BasicMessageChannel.Reply.class);
accessibilityChannel.parsingMessageHandler.onMessage(arguments, reply);
verify(handler).onFocus(123);
}
}
| engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/AccessibilityChannelTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/AccessibilityChannelTest.java",
"repo_id": "engine",
"token_count": 625
} | 453 |
package io.flutter.plugin.editing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.view.View;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.embedding.android.KeyboardManager;
import io.flutter.embedding.engine.systemchannels.TextInputChannel;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
public class ListenableEditingStateTest {
private final Context ctx = ApplicationProvider.getApplicationContext();
@Mock KeyboardManager mockKeyboardManager;
private BaseInputConnection getTestInputConnection(View view, Editable mEditable) {
new View(ctx);
return new BaseInputConnection(view, true) {
@Override
public Editable getEditable() {
return mEditable;
}
};
}
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testConstructor() {
// When provided valid composing range, should not fail
new ListenableEditingState(
new TextInputChannel.TextEditState("hello", 1, 4, 1, 4), new View(ctx));
}
// -------- Start: Test BatchEditing -------
@Test
public void testBatchEditing() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
final Listener listener = new Listener();
final View testView = new View(ctx);
final BaseInputConnection inputConnection = getTestInputConnection(testView, editingState);
editingState.addEditingStateListener(listener);
editingState.replace(0, editingState.length(), "update");
assertTrue(listener.isCalled());
assertTrue(listener.textChanged);
assertFalse(listener.selectionChanged);
assertFalse(listener.composingRegionChanged);
assertEquals(-1, editingState.getSelectionStart());
assertEquals(-1, editingState.getSelectionEnd());
listener.reset();
// Batch edit depth = 1.
editingState.beginBatchEdit();
editingState.replace(0, editingState.length(), "update1");
assertFalse(listener.isCalled());
// Batch edit depth = 2.
editingState.beginBatchEdit();
editingState.replace(0, editingState.length(), "update2");
inputConnection.setComposingRegion(0, editingState.length());
assertFalse(listener.isCalled());
// Batch edit depth = 1.
editingState.endBatchEdit();
assertFalse(listener.isCalled());
// Batch edit depth = 2.
editingState.beginBatchEdit();
assertFalse(listener.isCalled());
inputConnection.setSelection(0, 0);
assertFalse(listener.isCalled());
// Batch edit depth = 1.
editingState.endBatchEdit();
assertFalse(listener.isCalled());
// Remove composing region.
inputConnection.finishComposingText();
// Batch edit depth = 0. Last endBatchEdit.
editingState.endBatchEdit();
// Now notify the listener.
assertTrue(listener.isCalled());
assertTrue(listener.textChanged);
assertFalse(listener.composingRegionChanged);
}
@Test
public void testBatchingEditing_callEndBeforeBegin() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
final Listener listener = new Listener();
editingState.addEditingStateListener(listener);
editingState.endBatchEdit();
assertFalse(listener.isCalled());
editingState.replace(0, editingState.length(), "text");
assertTrue(listener.isCalled());
assertTrue(listener.textChanged);
listener.reset();
// Does not disrupt the followup events.
editingState.beginBatchEdit();
editingState.replace(0, editingState.length(), "more text");
assertFalse(listener.isCalled());
editingState.endBatchEdit();
assertTrue(listener.isCalled());
}
@Test
public void testBatchingEditing_addListenerDuringBatchEdit() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
final Listener listener = new Listener();
editingState.beginBatchEdit();
editingState.addEditingStateListener(listener);
editingState.replace(0, editingState.length(), "update");
editingState.endBatchEdit();
assertTrue(listener.isCalled());
assertTrue(listener.textChanged);
assertTrue(listener.selectionChanged);
assertTrue(listener.composingRegionChanged);
listener.reset();
// Verifies the listener is officially added.
editingState.replace(0, editingState.length(), "more updates");
assertTrue(listener.isCalled());
assertTrue(listener.textChanged);
editingState.removeEditingStateListener(listener);
listener.reset();
// Now remove before endBatchEdit();
editingState.beginBatchEdit();
editingState.addEditingStateListener(listener);
editingState.replace(0, editingState.length(), "update");
editingState.removeEditingStateListener(listener);
editingState.endBatchEdit();
assertFalse(listener.isCalled());
}
@Test
public void testBatchingEditing_removeListenerDuringBatchEdit() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
final Listener listener = new Listener();
editingState.addEditingStateListener(listener);
editingState.beginBatchEdit();
editingState.replace(0, editingState.length(), "update");
editingState.removeEditingStateListener(listener);
editingState.endBatchEdit();
assertFalse(listener.isCalled());
}
@Test
public void testBatchingEditing_listenerCallsReplaceWhenBatchEditEnds() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
final Listener listener =
new Listener() {
@Override
public void didChangeEditingState(
boolean textChanged, boolean selectionChanged, boolean composingRegionChanged) {
super.didChangeEditingState(textChanged, selectionChanged, composingRegionChanged);
editingState.replace(
0, editingState.length(), "one does not simply replace the text in the listener");
}
};
editingState.addEditingStateListener(listener);
editingState.beginBatchEdit();
editingState.replace(0, editingState.length(), "update");
editingState.endBatchEdit();
assertTrue(listener.isCalled());
assertEquals(1, listener.timesCalled);
assertEquals("one does not simply replace the text in the listener", editingState.toString());
}
// -------- End: Test BatchEditing -------
@Test
public void testSetComposingRegion() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
editingState.replace(0, editingState.length(), "text");
// (-1, -1) clears the composing region.
editingState.setComposingRange(-1, -1);
assertEquals(-1, editingState.getComposingStart());
assertEquals(-1, editingState.getComposingEnd());
editingState.setComposingRange(-1, 5);
assertEquals(-1, editingState.getComposingStart());
assertEquals(-1, editingState.getComposingEnd());
editingState.setComposingRange(2, 3);
assertEquals(2, editingState.getComposingStart());
assertEquals(3, editingState.getComposingEnd());
// Empty range is invalid. Clears composing region.
editingState.setComposingRange(1, 1);
assertEquals(-1, editingState.getComposingStart());
assertEquals(-1, editingState.getComposingEnd());
// Covers everything.
editingState.setComposingRange(0, editingState.length());
assertEquals(0, editingState.getComposingStart());
assertEquals(editingState.length(), editingState.getComposingEnd());
}
@Test
public void testClearBatchDeltas() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
editingState.replace(0, editingState.length(), "text");
editingState.delete(0, 1);
editingState.insert(0, "This is t");
editingState.clearBatchDeltas();
assertEquals(0, editingState.extractBatchTextEditingDeltas().size());
}
@Test
public void testExtractBatchTextEditingDeltas() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
// Creating some deltas.
editingState.replace(0, editingState.length(), "test");
editingState.delete(0, 1);
editingState.insert(0, "This is a t");
ArrayList<TextEditingDelta> batchDeltas = editingState.extractBatchTextEditingDeltas();
assertEquals(3, batchDeltas.size());
}
// -------- Start: Test InputMethods actions -------
@Test
public void inputMethod_batchEditingBeginAndEnd() {
final ArrayList<String> batchMarkers = new ArrayList<>();
final ListenableEditingState editingState =
new ListenableEditingState(null, new View(ctx)) {
@Override
public final void beginBatchEdit() {
super.beginBatchEdit();
batchMarkers.add("begin");
}
@Override
public void endBatchEdit() {
super.endBatchEdit();
batchMarkers.add("end");
}
};
final Listener listener = new Listener();
final View testView = new View(ctx);
final InputConnectionAdaptor inputConnection =
new InputConnectionAdaptor(
testView,
0,
mock(TextInputChannel.class),
mockKeyboardManager,
editingState,
new EditorInfo());
// Make sure begin/endBatchEdit is called on the Editable when the input method calls
// InputConnection#begin/endBatchEdit.
inputConnection.beginBatchEdit();
assertEquals(1, batchMarkers.size());
assertEquals("begin", batchMarkers.get(0));
inputConnection.endBatchEdit();
assertEquals(2, batchMarkers.size());
assertEquals("end", batchMarkers.get(1));
}
@Test
public void inputMethod_testSetSelection() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
final Listener listener = new Listener();
final View testView = new View(ctx);
final InputConnectionAdaptor inputConnection =
new InputConnectionAdaptor(
testView,
0,
mock(TextInputChannel.class),
mockKeyboardManager,
editingState,
new EditorInfo());
editingState.replace(0, editingState.length(), "initial text");
editingState.addEditingStateListener(listener);
inputConnection.setSelection(0, 0);
assertTrue(listener.isCalled());
assertFalse(listener.textChanged);
assertTrue(listener.selectionChanged);
assertFalse(listener.composingRegionChanged);
listener.reset();
inputConnection.setSelection(5, 5);
assertTrue(listener.isCalled());
assertFalse(listener.textChanged);
assertTrue(listener.selectionChanged);
assertFalse(listener.composingRegionChanged);
}
@Test
public void inputMethod_testSetComposition() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
final Listener listener = new Listener();
final View testView = new View(ctx);
final InputConnectionAdaptor inputConnection =
new InputConnectionAdaptor(
testView,
0,
mock(TextInputChannel.class),
mockKeyboardManager,
editingState,
new EditorInfo());
editingState.replace(0, editingState.length(), "initial text");
editingState.addEditingStateListener(listener);
// setComposingRegion test.
inputConnection.setComposingRegion(1, 3);
assertTrue(listener.isCalled());
assertFalse(listener.textChanged);
assertFalse(listener.selectionChanged);
assertTrue(listener.composingRegionChanged);
Selection.setSelection(editingState, 0, 0);
listener.reset();
// setComposingText test: non-empty text, does not move cursor.
inputConnection.setComposingText("composing", -1);
assertTrue(listener.isCalled());
assertTrue(listener.textChanged);
assertFalse(listener.selectionChanged);
assertTrue(listener.composingRegionChanged);
listener.reset();
// setComposingText test: non-empty text, moves cursor.
inputConnection.setComposingText("composing2", 1);
assertTrue(listener.isCalled());
assertTrue(listener.textChanged);
assertTrue(listener.selectionChanged);
assertTrue(listener.composingRegionChanged);
listener.reset();
// setComposingText test: empty text.
inputConnection.setComposingText("", 1);
assertTrue(listener.isCalled());
assertTrue(listener.textChanged);
assertTrue(listener.selectionChanged);
assertTrue(listener.composingRegionChanged);
// finishComposingText test.
inputConnection.setComposingText("composing text", 1);
listener.reset();
inputConnection.finishComposingText();
assertTrue(listener.isCalled());
assertFalse(listener.textChanged);
assertFalse(listener.selectionChanged);
assertTrue(listener.composingRegionChanged);
}
@Test
public void inputMethod_testCommitText() {
final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx));
final Listener listener = new Listener();
final View testView = new View(ctx);
final InputConnectionAdaptor inputConnection =
new InputConnectionAdaptor(
testView,
0,
mock(TextInputChannel.class),
mockKeyboardManager,
editingState,
new EditorInfo());
editingState.replace(0, editingState.length(), "initial text");
editingState.addEditingStateListener(listener);
}
// -------- End: Test InputMethods actions -------
public static class Listener implements ListenableEditingState.EditingStateWatcher {
public boolean isCalled() {
return timesCalled > 0;
}
int timesCalled = 0;
boolean textChanged = false;
boolean selectionChanged = false;
boolean composingRegionChanged = false;
@Override
public void didChangeEditingState(
boolean textChanged, boolean selectionChanged, boolean composingRegionChanged) {
timesCalled++;
this.textChanged = textChanged;
this.selectionChanged = selectionChanged;
this.composingRegionChanged = composingRegionChanged;
}
public void reset() {
timesCalled = 0;
textChanged = false;
selectionChanged = false;
composingRegionChanged = false;
}
}
}
| engine/shell/platform/android/test/io/flutter/plugin/editing/ListenableEditingStateTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/plugin/editing/ListenableEditingStateTest.java",
"repo_id": "engine",
"token_count": 5125
} | 454 |
package io.flutter.plugins;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import io.flutter.embedding.engine.FlutterEngine;
import java.util.ArrayList;
import java.util.List;
/**
* A fake of the {@code GeneratedPluginRegistrant} normally built by the tool into Flutter apps.
*
* <p>Used to test engine logic which interacts with the generated class.
*/
@VisibleForTesting
public class GeneratedPluginRegistrant {
private static final List<FlutterEngine> registeredEngines = new ArrayList<>();
public static @Nullable RuntimeException pluginRegistrationException;
/**
* The one and only method currently generated by the tool.
*
* <p>Normally it registers all plugins in an app with the given {@code engine}. This fake tracks
* all registered engines instead.
*/
public static void registerWith(@NonNull FlutterEngine engine) {
if (pluginRegistrationException != null) {
throw pluginRegistrationException;
}
registeredEngines.add(engine);
}
/**
* Clears the mutable static state regrettably stored in this class.
*
* <p>{@link #registerWith} is a static call with no visible side effects. In order to verify when
* it's been called we also unfortunately need to store the state statically. This should be
* called before and after each test run accessing this class to make sure the state is clear both
* before and after the run.
*/
public static void clearRegisteredEngines() {
registeredEngines.clear();
}
/**
* Returns a list of all the engines registered so far.
*
* <p>CAUTION: This list is static and must be manually wiped in between test runs. See {@link
* #clearRegisteredEngines()}.
*/
@NonNull
public static List<FlutterEngine> getRegisteredEngines() {
return new ArrayList<>(registeredEngines);
}
}
| engine/shell/platform/android/test/io/flutter/plugins/GeneratedPluginRegistrant.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/plugins/GeneratedPluginRegistrant.java",
"repo_id": "engine",
"token_count": 540
} | 455 |
# 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/common/config.gni")
import("//flutter/testing/testing.gni")
config("desktop_library_implementation") {
defines = [ "FLUTTER_DESKTOP_LIBRARY" ]
}
_public_headers = [
"public/flutter_export.h",
"public/flutter_macros.h",
"public/flutter_messenger.h",
"public/flutter_plugin_registrar.h",
"public/flutter_texture_registrar.h",
]
# Any files that are built by clients (client_wrapper code, library headers for
# implementations using this shared code, etc.) include the public headers
# assuming they are in the include path. This configuration should be added to
# any such code that is also built by GN to make the includes work.
config("relative_flutter_library_headers") {
include_dirs = [ "public" ]
}
# The headers are a separate source set since the client wrapper is allowed
# to depend on the public headers, but none of the rest of the code.
source_set("common_cpp_library_headers") {
public = _public_headers
configs += [ ":desktop_library_implementation" ]
}
copy("publish_headers") {
sources = _public_headers
outputs = [ "$root_out_dir/{{source_file_part}}" ]
}
source_set("common_cpp_input") {
public = [
"text_editing_delta.h",
"text_input_model.h",
"text_range.h",
]
sources = [
"text_editing_delta.cc",
"text_input_model.cc",
]
configs += [ ":desktop_library_implementation" ]
public_configs = [ "//flutter:config" ]
deps = [ "//flutter/fml:fml" ]
}
source_set("common_cpp_enums") {
public = [
"app_lifecycle_state.h",
"platform_provided_menu.h",
]
public_configs = [
"//flutter:config",
"//flutter/common:flutter_config",
]
}
source_set("common_cpp_switches") {
public = [ "engine_switches.h" ]
sources = [ "engine_switches.cc" ]
public_configs = [
"//flutter:config",
"//flutter/common:flutter_config",
]
}
source_set("common_cpp_accessibility") {
public = [
"accessibility_bridge.h",
"alert_platform_node_delegate.h",
"flutter_platform_node_delegate.h",
]
sources = [
"accessibility_bridge.cc",
"alert_platform_node_delegate.cc",
"flutter_platform_node_delegate.cc",
]
public_configs =
[ "//flutter/third_party/accessibility:accessibility_config" ]
public_deps = [
"//flutter/fml:fml",
"//flutter/shell/platform/embedder:embedder_as_internal_library",
"//flutter/third_party/accessibility",
]
}
source_set("common_cpp") {
public = [
"incoming_message_dispatcher.h",
"json_message_codec.h",
"json_method_codec.h",
]
# TODO: Refactor flutter_glfw.cc to move the implementations corresponding
# to the _public_headers above into this target.
sources = [
"incoming_message_dispatcher.cc",
"json_message_codec.cc",
"json_method_codec.cc",
]
configs += [ ":desktop_library_implementation" ]
public_configs = [ "//flutter:config" ]
deps = [
":common_cpp_library_headers",
"//flutter/shell/platform/common/client_wrapper:client_wrapper",
"//flutter/shell/platform/embedder:embedder_as_internal_library",
]
public_deps = [
":common_cpp_core",
"//flutter/third_party/rapidjson",
]
}
# The portion of common_cpp that has no dependencies on the public/
# headers. This division should be revisited once the Linux GTK
# embedding is further along and it's clearer how much, if any, shared
# API surface there will be.
source_set("common_cpp_core") {
public = [
"geometry.h",
"path_utils.h",
]
sources = [ "path_utils.cc" ]
public_configs = [ "//flutter:config" ]
}
if (enable_unittests) {
test_fixtures("common_cpp_core_fixtures") {
fixtures = []
}
executable("common_cpp_core_unittests") {
testonly = true
sources = [ "path_utils_unittests.cc" ]
deps = [
":common_cpp_core",
":common_cpp_core_fixtures",
"$dart_src/runtime:libdart_jit",
"//flutter/testing",
]
public_configs = [ "//flutter:config" ]
}
test_fixtures("common_cpp_fixtures") {
fixtures = []
}
executable("common_cpp_unittests") {
testonly = true
sources = [
"engine_switches_unittests.cc",
"geometry_unittests.cc",
"incoming_message_dispatcher_unittests.cc",
"json_message_codec_unittests.cc",
"json_method_codec_unittests.cc",
"text_editing_delta_unittests.cc",
"text_input_model_unittests.cc",
"text_range_unittests.cc",
]
deps = [
":common_cpp",
":common_cpp_fixtures",
":common_cpp_input",
":common_cpp_switches",
"//flutter/fml:string_conversion",
"//flutter/shell/platform/common/client_wrapper:client_wrapper",
"//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs",
"//flutter/testing",
]
# The accessibility bridge only supports MacOS for now.
if (is_mac || is_win) {
sources += [
"accessibility_bridge_unittests.cc",
"flutter_platform_node_delegate_unittests.cc",
"test_accessibility_bridge.cc",
"test_accessibility_bridge.h",
]
deps += [ ":common_cpp_accessibility" ]
}
public_configs = [ "//flutter:config" ]
}
}
| engine/shell/platform/common/BUILD.gn/0 | {
"file_path": "engine/shell/platform/common/BUILD.gn",
"repo_id": "engine",
"token_count": 2071
} | 456 |
// 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/event_channel.h"
#include <memory>
#include <string>
#include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/event_stream_handler_functions.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h"
#include "gtest/gtest.h"
namespace flutter {
namespace {
class TestBinaryMessenger : public BinaryMessenger {
public:
void Send(const std::string& channel,
const uint8_t* message,
const size_t message_size,
BinaryReply reply) const override {}
void SetMessageHandler(const std::string& channel,
BinaryMessageHandler handler) override {
last_message_handler_channel_ = channel;
last_message_handler_ = handler;
}
std::string last_message_handler_channel() {
return last_message_handler_channel_;
}
const BinaryMessageHandler& last_message_handler() {
return last_message_handler_;
}
private:
std::string last_message_handler_channel_;
BinaryMessageHandler last_message_handler_;
};
} // namespace
// Tests that SetStreamHandler sets a handler that correctly interacts with
// the binary messenger.
TEST(EventChannelTest, Registration) {
TestBinaryMessenger messenger;
const std::string channel_name("some_channel");
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
EventChannel channel(&messenger, channel_name, &codec);
bool on_listen_called = false;
auto handler = std::make_unique<StreamHandlerFunctions<>>(
[&on_listen_called](const EncodableValue* arguments,
std::unique_ptr<EventSink<>>&& events)
-> std::unique_ptr<StreamHandlerError<>> {
on_listen_called = true;
return nullptr;
},
[](const EncodableValue* arguments)
-> std::unique_ptr<StreamHandlerError<>> { return nullptr; });
channel.SetStreamHandler(std::move(handler));
EXPECT_EQ(messenger.last_message_handler_channel(), channel_name);
EXPECT_NE(messenger.last_message_handler(), nullptr);
// Send test listen message.
MethodCall<> call("listen", nullptr);
auto message = codec.EncodeMethodCall(call);
messenger.last_message_handler()(
message->data(), message->size(),
[](const uint8_t* reply, const size_t reply_size) {});
// Check results.
EXPECT_EQ(on_listen_called, true);
}
// Tests that SetStreamHandler with a null handler unregisters the handler.
TEST(EventChannelTest, Unregistration) {
TestBinaryMessenger messenger;
const std::string channel_name("some_channel");
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
EventChannel channel(&messenger, channel_name, &codec);
auto handler = std::make_unique<StreamHandlerFunctions<>>(
[](const EncodableValue* arguments, std::unique_ptr<EventSink<>>&& events)
-> std::unique_ptr<StreamHandlerError<>> { return nullptr; },
[](const EncodableValue* arguments)
-> std::unique_ptr<StreamHandlerError<>> { return nullptr; });
channel.SetStreamHandler(std::move(handler));
EXPECT_EQ(messenger.last_message_handler_channel(), channel_name);
EXPECT_NE(messenger.last_message_handler(), nullptr);
channel.SetStreamHandler(nullptr);
EXPECT_EQ(messenger.last_message_handler_channel(), channel_name);
EXPECT_EQ(messenger.last_message_handler(), nullptr);
}
// Test that OnCancel callback sequence.
TEST(EventChannelTest, Cancel) {
TestBinaryMessenger messenger;
const std::string channel_name("some_channel");
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
EventChannel channel(&messenger, channel_name, &codec);
bool on_listen_called = false;
bool on_cancel_called = false;
auto handler = std::make_unique<StreamHandlerFunctions<>>(
[&on_listen_called](const EncodableValue* arguments,
std::unique_ptr<EventSink<>>&& events)
-> std::unique_ptr<StreamHandlerError<>> {
on_listen_called = true;
return nullptr;
},
[&on_cancel_called](const EncodableValue* arguments)
-> std::unique_ptr<StreamHandlerError<>> {
on_cancel_called = true;
return nullptr;
});
channel.SetStreamHandler(std::move(handler));
EXPECT_EQ(messenger.last_message_handler_channel(), channel_name);
EXPECT_NE(messenger.last_message_handler(), nullptr);
// Send test listen message.
MethodCall<> call_listen("listen", nullptr);
auto message = codec.EncodeMethodCall(call_listen);
messenger.last_message_handler()(
message->data(), message->size(),
[](const uint8_t* reply, const size_t reply_size) {});
EXPECT_EQ(on_listen_called, true);
// Send test cancel message.
MethodCall<> call_cancel("cancel", nullptr);
message = codec.EncodeMethodCall(call_cancel);
messenger.last_message_handler()(
message->data(), message->size(),
[](const uint8_t* reply, const size_t reply_size) {});
// Check results.
EXPECT_EQ(on_cancel_called, true);
}
// Tests that OnCancel in not called on registration.
TEST(EventChannelTest, ListenNotCancel) {
TestBinaryMessenger messenger;
const std::string channel_name("some_channel");
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
EventChannel channel(&messenger, channel_name, &codec);
bool on_listen_called = false;
bool on_cancel_called = false;
auto handler = std::make_unique<StreamHandlerFunctions<>>(
[&on_listen_called](const EncodableValue* arguments,
std::unique_ptr<EventSink<>>&& events)
-> std::unique_ptr<StreamHandlerError<>> {
on_listen_called = true;
return nullptr;
},
[&on_cancel_called](const EncodableValue* arguments)
-> std::unique_ptr<StreamHandlerError<>> {
on_cancel_called = true;
return nullptr;
});
channel.SetStreamHandler(std::move(handler));
EXPECT_EQ(messenger.last_message_handler_channel(), channel_name);
EXPECT_NE(messenger.last_message_handler(), nullptr);
// Send test listen message.
MethodCall<> call_listen("listen", nullptr);
auto message = codec.EncodeMethodCall(call_listen);
messenger.last_message_handler()(
message->data(), message->size(),
[](const uint8_t* reply, const size_t reply_size) {});
// Check results.
EXPECT_EQ(on_listen_called, true);
EXPECT_EQ(on_cancel_called, false);
}
// Pseudo test when user re-registers or call OnListen to the same channel.
// Confirm that OnCancel is called and OnListen is called again
// when user re-registers the same channel that has already started
// communication.
TEST(EventChannelTest, ReRegistration) {
TestBinaryMessenger messenger;
const std::string channel_name("some_channel");
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
EventChannel channel(&messenger, channel_name, &codec);
bool on_listen_called = false;
bool on_cancel_called = false;
auto handler = std::make_unique<StreamHandlerFunctions<>>(
[&on_listen_called](const EncodableValue* arguments,
std::unique_ptr<EventSink<>>&& events)
-> std::unique_ptr<StreamHandlerError<>> {
on_listen_called = true;
return nullptr;
},
[&on_cancel_called](const EncodableValue* arguments)
-> std::unique_ptr<StreamHandlerError<>> {
on_cancel_called = true;
return nullptr;
});
channel.SetStreamHandler(std::move(handler));
EXPECT_EQ(messenger.last_message_handler_channel(), channel_name);
EXPECT_NE(messenger.last_message_handler(), nullptr);
// Send test listen message.
MethodCall<> call("listen", nullptr);
auto message = codec.EncodeMethodCall(call);
messenger.last_message_handler()(
message->data(), message->size(),
[](const uint8_t* reply, const size_t reply_size) {});
EXPECT_EQ(on_listen_called, true);
// Send second test message to test StreamHandler's OnCancel
// method is called before OnListen method is called.
on_listen_called = false;
message = codec.EncodeMethodCall(call);
messenger.last_message_handler()(
message->data(), message->size(),
[](const uint8_t* reply, const size_t reply_size) {});
// Check results.
EXPECT_EQ(on_cancel_called, true);
EXPECT_EQ(on_listen_called, true);
}
// Test that the handler is called even if the event channel is destroyed.
TEST(EventChannelTest, HandlerOutlivesEventChannel) {
TestBinaryMessenger messenger;
const std::string channel_name("some_channel");
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
bool on_listen_called = false;
bool on_cancel_called = false;
{
EventChannel channel(&messenger, channel_name, &codec);
auto handler = std::make_unique<StreamHandlerFunctions<>>(
[&on_listen_called](const EncodableValue* arguments,
std::unique_ptr<EventSink<>>&& events)
-> std::unique_ptr<StreamHandlerError<>> {
on_listen_called = true;
return nullptr;
},
[&on_cancel_called](const EncodableValue* arguments)
-> std::unique_ptr<StreamHandlerError<>> {
on_cancel_called = true;
return nullptr;
});
channel.SetStreamHandler(std::move(handler));
}
// The event channel was destroyed but the handler should still be alive.
EXPECT_EQ(messenger.last_message_handler_channel(), channel_name);
EXPECT_NE(messenger.last_message_handler(), nullptr);
// Send test listen message.
MethodCall<> call_listen("listen", nullptr);
auto message = codec.EncodeMethodCall(call_listen);
messenger.last_message_handler()(
message->data(), message->size(),
[](const uint8_t* reply, const size_t reply_size) {});
EXPECT_EQ(on_listen_called, true);
// Send test cancel message.
MethodCall<> call_cancel("cancel", nullptr);
message = codec.EncodeMethodCall(call_cancel);
messenger.last_message_handler()(
message->data(), message->size(),
[](const uint8_t* reply, const size_t reply_size) {});
EXPECT_EQ(on_cancel_called, true);
}
TEST(EventChannelTest, StreamHandlerErrorPassByValue) {
std::unique_ptr<StreamHandlerError<>> error = nullptr;
{
std::string code = "Code";
std::string msg = "Message";
std::unique_ptr<EncodableValue> details =
std::make_unique<EncodableValue>("Details");
error =
std::make_unique<StreamHandlerError<>>(code, msg, std::move(details));
}
ASSERT_NE(error.get(), nullptr);
EXPECT_EQ(error->error_code, "Code");
EXPECT_EQ(error->error_message, "Message");
EXPECT_EQ(std::get<std::string>(*error->error_details), "Details");
}
TEST(EventChannelTest, StreamHandlerErrorNullptr) {
std::unique_ptr<StreamHandlerError<>> error =
std::make_unique<StreamHandlerError<>>("Code", "Message", nullptr);
ASSERT_NE(error.get(), nullptr);
EXPECT_FALSE(error->error_details);
}
} // namespace flutter
| engine/shell/platform/common/client_wrapper/event_channel_unittests.cc/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/event_channel_unittests.cc",
"repo_id": "engine",
"token_count": 4013
} | 457 |
// 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_PLUGIN_REGISTRAR_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_H_
#include <flutter_plugin_registrar.h>
#include <map>
#include <memory>
#include <set>
#include <string>
#include "binary_messenger.h"
#include "texture_registrar.h"
namespace flutter {
class Plugin;
// A object managing the registration of a plugin for various events.
//
// Currently this class has very limited functionality, but is expected to
// expand over time to more closely match the functionality of
// the Flutter mobile plugin APIs' plugin registrars.
class PluginRegistrar {
public:
// Creates a new PluginRegistrar. |core_registrar| and the messenger it
// provides must remain valid as long as this object exists.
explicit PluginRegistrar(FlutterDesktopPluginRegistrarRef core_registrar);
virtual ~PluginRegistrar();
// Prevent copying.
PluginRegistrar(PluginRegistrar const&) = delete;
PluginRegistrar& operator=(PluginRegistrar const&) = delete;
// Returns the messenger to use for creating channels to communicate with the
// Flutter engine.
//
// This pointer will remain valid for the lifetime of this instance.
BinaryMessenger* messenger() { return messenger_.get(); }
// Returns the texture registrar to use for the plugin to render a pixel
// buffer.
TextureRegistrar* texture_registrar() { return texture_registrar_.get(); }
// Takes ownership of |plugin|.
//
// Plugins are not required to call this method if they have other lifetime
// management, but this is a convenient place for plugins to be owned to
// ensure that they stay valid for any registered callbacks.
void AddPlugin(std::unique_ptr<Plugin> plugin);
protected:
FlutterDesktopPluginRegistrarRef registrar() const { return registrar_; }
// Destroys all owned plugins. Subclasses should call this at the beginning of
// their destructors to prevent the possibility of an owned plugin trying to
// access destroyed state during its own destruction.
void ClearPlugins();
private:
// Handle for interacting with the C API's registrar.
FlutterDesktopPluginRegistrarRef registrar_;
std::unique_ptr<BinaryMessenger> messenger_;
std::unique_ptr<TextureRegistrar> texture_registrar_;
// Plugins registered for ownership.
std::set<std::unique_ptr<Plugin>> plugins_;
};
// A plugin that can be registered for ownership by a PluginRegistrar.
class Plugin {
public:
virtual ~Plugin() = default;
};
// A singleton to own PluginRegistrars. This is intended for use in plugins,
// where there is no higher-level object to own a PluginRegistrar that can
// own plugin instances and ensure that they live as long as the engine they
// are registered with.
class PluginRegistrarManager {
public:
static PluginRegistrarManager* GetInstance();
// Prevent copying.
PluginRegistrarManager(PluginRegistrarManager const&) = delete;
PluginRegistrarManager& operator=(PluginRegistrarManager const&) = delete;
// Returns a plugin registrar wrapper of type T, which must be a kind of
// PluginRegistrar, creating it if necessary. The returned registrar will
// live as long as the underlying FlutterDesktopPluginRegistrarRef, so
// can be used to own plugin instances.
//
// Calling this multiple times for the same registrar_ref with different
// template types results in undefined behavior.
template <class T>
T* GetRegistrar(FlutterDesktopPluginRegistrarRef registrar_ref) {
auto insert_result =
registrars_.emplace(registrar_ref, std::make_unique<T>(registrar_ref));
auto& registrar_pair = *(insert_result.first);
FlutterDesktopPluginRegistrarSetDestructionHandler(registrar_pair.first,
OnRegistrarDestroyed);
return static_cast<T*>(registrar_pair.second.get());
}
// Destroys all registrar wrappers created by the manager.
//
// This is intended primarily for use in tests.
void Reset() { registrars_.clear(); }
private:
PluginRegistrarManager();
using WrapperMap = std::map<FlutterDesktopPluginRegistrarRef,
std::unique_ptr<PluginRegistrar>>;
static void OnRegistrarDestroyed(FlutterDesktopPluginRegistrarRef registrar);
WrapperMap* registrars() { return ®istrars_; }
WrapperMap registrars_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_H_
| engine/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h",
"repo_id": "engine",
"token_count": 1430
} | 458 |
// 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_TESTING_STUB_FLUTTER_API_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_API_H_
#include <memory>
#include "flutter/shell/platform/common/public/flutter_messenger.h"
#include "flutter/shell/platform/common/public/flutter_plugin_registrar.h"
namespace flutter {
namespace testing {
// Base class for a object that provides test implementations of the APIs in
// the headers in platform/common/public/.
// Linking this class into a test binary will provide dummy forwarding
// implementations of that C API, so that the wrapper can be tested separately
// from the actual library.
class StubFlutterApi {
public:
// Used by the callers to simulate a result from the engine when sending a
// message.
bool message_engine_result = true;
// Sets |stub| as the instance to which calls to the Flutter library C APIs
// will be forwarded.
static void SetTestStub(StubFlutterApi* stub);
// Returns the current stub, as last set by SetTestFlutterStub.
static StubFlutterApi* GetTestStub();
virtual ~StubFlutterApi() {}
// Called for FlutterDesktopPluginRegistrarSetDestructionHandler.
virtual void PluginRegistrarSetDestructionHandler(
FlutterDesktopOnPluginRegistrarDestroyed callback) {}
// Called for FlutterDesktopMessengerSend.
virtual bool MessengerSend(const char* channel,
const uint8_t* message,
const size_t message_size) {
return message_engine_result;
}
// Called for FlutterDesktopMessengerSendWithReply.
virtual bool MessengerSendWithReply(const char* channel,
const uint8_t* message,
const size_t message_size,
const FlutterDesktopBinaryReply reply,
void* user_data) {
return message_engine_result;
}
// Called for FlutterDesktopMessengerSendResponse.
virtual void MessengerSendResponse(
const FlutterDesktopMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length) {}
// Called for FlutterDesktopMessengerSetCallback.
virtual void MessengerSetCallback(const char* channel,
FlutterDesktopMessageCallback callback,
void* user_data) {}
// Called for FlutterDesktopTextureRegistrarRegisterExternalTexture.
virtual int64_t TextureRegistrarRegisterExternalTexture(
const FlutterDesktopTextureInfo* info) {
return -1;
}
// Called for FlutterDesktopTextureRegistrarUnregisterExternalTexture.
virtual void TextureRegistrarUnregisterExternalTexture(
int64_t texture_id,
void (*callback)(void* user_data),
void* user_data) {}
// Called for FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable.
virtual bool TextureRegistrarMarkTextureFrameAvailable(int64_t texture_id) {
return false;
}
};
// A test helper that owns a stub implementation, making it the test stub for
// the lifetime of the object, then restoring the previous value.
class ScopedStubFlutterApi {
public:
// Calls SetTestFlutterStub with |stub|.
explicit ScopedStubFlutterApi(std::unique_ptr<StubFlutterApi> stub);
// Restores the previous test stub.
~ScopedStubFlutterApi();
StubFlutterApi* stub() { return stub_.get(); }
private:
std::unique_ptr<StubFlutterApi> stub_;
// The previous stub.
StubFlutterApi* previous_stub_;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_API_H_
| engine/shell/platform/common/client_wrapper/testing/stub_flutter_api.h/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/testing/stub_flutter_api.h",
"repo_id": "engine",
"token_count": 1368
} | 459 |
// 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/json_message_codec.h"
#include <iostream>
#include <string>
#include "rapidjson/error/en.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
namespace flutter {
// static
const JsonMessageCodec& JsonMessageCodec::GetInstance() {
static JsonMessageCodec sInstance;
return sInstance;
}
std::unique_ptr<std::vector<uint8_t>> JsonMessageCodec::EncodeMessageInternal(
const rapidjson::Document& message) const {
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
// clang-tidy has trouble reasoning about some of the complicated array and
// pointer-arithmetic code in rapidjson.
// NOLINTNEXTLINE(clang-analyzer-core.*)
message.Accept(writer);
const char* buffer_start = buffer.GetString();
return std::make_unique<std::vector<uint8_t>>(
buffer_start, buffer_start + buffer.GetSize());
}
std::unique_ptr<rapidjson::Document> JsonMessageCodec::DecodeMessageInternal(
const uint8_t* binary_message,
const size_t message_size) const {
auto raw_message = reinterpret_cast<const char*>(binary_message);
auto json_message = std::make_unique<rapidjson::Document>();
rapidjson::ParseResult result =
json_message->Parse(raw_message, message_size);
if (result.IsError()) {
std::cerr << "Unable to parse JSON message:" << std::endl
<< rapidjson::GetParseError_En(result.Code()) << std::endl;
return nullptr;
}
return json_message;
}
} // namespace flutter
| engine/shell/platform/common/json_message_codec.cc/0 | {
"file_path": "engine/shell/platform/common/json_message_codec.cc",
"repo_id": "engine",
"token_count": 566
} | 460 |
// 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_TEST_ACCESSIBILITY_BRIDGE_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_TEST_ACCESSIBILITY_BRIDGE_H_
#include "accessibility_bridge.h"
namespace flutter {
class TestAccessibilityBridge : public AccessibilityBridge {
public:
TestAccessibilityBridge() = default;
void DispatchAccessibilityAction(AccessibilityNodeId target,
FlutterSemanticsAction action,
fml::MallocMapping data) override;
std::vector<ui::AXEventGenerator::Event> accessibility_events;
std::vector<FlutterSemanticsAction> performed_actions;
protected:
void OnAccessibilityEvent(
ui::AXEventGenerator::TargetedEvent targeted_event) override;
std::shared_ptr<FlutterPlatformNodeDelegate>
CreateFlutterPlatformNodeDelegate() override;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_TEST_ACCESSIBILITY_BRIDGE_H_
| engine/shell/platform/common/test_accessibility_bridge.h/0 | {
"file_path": "engine/shell/platform/common/test_accessibility_bridge.h",
"repo_id": "engine",
"token_count": 393
} | 461 |
// 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_COMMON_BUFFER_CONVERSIONS_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_BUFFER_CONVERSIONS_H_
#include <Foundation/Foundation.h>
#include <vector>
#include "flutter/fml/mapping.h"
namespace flutter {
fml::MallocMapping CopyNSDataToMapping(NSData* data);
NSData* ConvertMappingToNSData(fml::MallocMapping buffer);
std::unique_ptr<fml::Mapping> ConvertNSDataToMappingPtr(NSData* data);
NSData* CopyMappingPtrToNSData(std::unique_ptr<fml::Mapping> mapping);
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_BUFFER_CONVERSIONS_H_
| engine/shell/platform/darwin/common/buffer_conversions.h/0 | {
"file_path": "engine/shell/platform/darwin/common/buffer_conversions.h",
"repo_id": "engine",
"token_count": 279
} | 462 |
// 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_COMMON_FRAMEWORK_SOURCE_FLUTTERNSBUNDLEUTILS_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERNSBUNDLEUTILS_H_
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
extern const NSString* kDefaultAssetPath;
// Finds a bundle with the named `flutterFrameworkBundleID` within `searchURL`.
//
// Returns `nil` if the bundle cannot be found or if errors are encountered.
NSBundle* FLTFrameworkBundleInternal(NSString* flutterFrameworkBundleID, NSURL* searchURL);
// Finds a bundle with the named `flutterFrameworkBundleID`.
//
// `+[NSBundle bundleWithIdentifier:]` is slow, and can take in the order of
// tens of milliseconds in a minimal flutter app, and closer to 100 milliseconds
// in a medium sized Flutter app on an iPhone 13. It is likely that the slowness
// comes from having to traverse and load all bundles known to the process.
// Using `+[NSBundle allframeworks]` and filtering also suffers from the same
// problem.
//
// This implementation is an optimization to first limit the search space to
// `+[NSBundle privateFrameworksURL]` of the main bundle, which is usually where
// frameworks used by this file are placed. If the desired bundle cannot be
// found here, the implementation falls back to
// `+[NSBundle bundleWithIdentifier:]`.
NSBundle* FLTFrameworkBundleWithIdentifier(NSString* flutterFrameworkBundleID);
// Finds the bundle of the application.
//
// Returns [NSBundle mainBundle] if the current running process is the application.
NSBundle* FLTGetApplicationBundle();
// Gets the flutter assets path directory from `bundle`.
//
// Returns `kDefaultAssetPath` if unable to find asset path from info.plist in `bundle`.
NSString* FLTAssetPath(NSBundle* bundle);
// Finds the Flutter asset directory from `bundle`.
//
// The raw path can be set by the application via info.plist's `FLTAssetsPath` key.
// If the key is not set, `flutter_assets` is used as the raw path value.
//
// If no valid asset is found under the raw path, returns nil.
NSString* FLTAssetsPathFromBundle(NSBundle* bundle);
NS_ASSUME_NONNULL_END
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERNSBUNDLEUTILS_H_
| engine/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h/0 | {
"file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h",
"repo_id": "engine",
"token_count": 730
} | 463 |
// 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/graphics/FlutterDarwinContextMetalSkia.h"
#include "flutter/common/graphics/persistent_cache.h"
#include "flutter/fml/logging.h"
#include "flutter/shell/common/context_options.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
FLUTTER_ASSERT_ARC
@implementation FlutterDarwinContextMetalSkia
- (instancetype)initWithDefaultMTLDevice {
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
return [self initWithMTLDevice:device commandQueue:[device newCommandQueue]];
}
- (instancetype)initWithMTLDevice:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue {
self = [super init];
if (self != nil) {
_device = device;
if (!_device) {
FML_DLOG(ERROR) << "Could not acquire Metal device.";
return nil;
}
_commandQueue = commandQueue;
if (!_commandQueue) {
FML_DLOG(ERROR) << "Could not create Metal command queue.";
return nil;
}
[_commandQueue setLabel:@"Flutter Main Queue"];
CVReturn cvReturn = CVMetalTextureCacheCreate(kCFAllocatorDefault, // allocator
nil, // cache attributes (nil default)
_device, // metal device
nil, // texture attributes (nil default)
&_textureCache // [out] cache
);
if (cvReturn != kCVReturnSuccess) {
FML_DLOG(ERROR) << "Could not create Metal texture cache.";
return nil;
}
// The devices are in the same "sharegroup" because they share the same device and command
// queues for now. When the resource context gets its own transfer queue, this will have to be
// refactored.
_mainContext = [self createGrContext];
_resourceContext = [self createGrContext];
if (!_mainContext || !_resourceContext) {
FML_DLOG(ERROR) << "Could not create Skia Metal contexts.";
return nil;
}
FML_LOG(IMPORTANT) << "Using the Skia rendering backend (Metal).";
_resourceContext->setResourceCacheLimit(0u);
}
return self;
}
- (sk_sp<GrDirectContext>)createGrContext {
const auto contextOptions =
flutter::MakeDefaultContextOptions(flutter::ContextType::kRender, GrBackendApi::kMetal);
id<MTLDevice> device = _device;
id<MTLCommandQueue> commandQueue = _commandQueue;
return [FlutterDarwinContextMetalSkia createGrContext:device commandQueue:commandQueue];
}
+ (sk_sp<GrDirectContext>)createGrContext:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue {
const auto contextOptions =
flutter::MakeDefaultContextOptions(flutter::ContextType::kRender, GrBackendApi::kMetal);
// Skia expect arguments to `MakeMetal` transfer ownership of the reference in for release later
// when the GrDirectContext is collected.
return GrDirectContext::MakeMetal((__bridge_retained void*)device,
(__bridge_retained void*)commandQueue, contextOptions);
}
- (void)dealloc {
if (_textureCache) {
CFRelease(_textureCache);
}
}
- (FlutterDarwinExternalTextureMetal*)
createExternalTextureWithIdentifier:(int64_t)textureID
texture:(NSObject<FlutterTexture>*)texture {
return [[FlutterDarwinExternalTextureMetal alloc] initWithTextureCache:_textureCache
textureID:textureID
texture:texture
enableImpeller:NO];
}
@end
| engine/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm/0 | {
"file_path": "engine/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm",
"repo_id": "engine",
"token_count": 1613
} | 464 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyTrackingDomains</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyAccessedAPITypes</key>
<array>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>0A2A.1</string>
<string>C617.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>35F9.1</string>
</array>
</dict>
</array>
</dict>
</plist>
| engine/shell/platform/darwin/ios/framework/PrivacyInfo.xcprivacy/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/PrivacyInfo.xcprivacy",
"repo_id": "engine",
"token_count": 398
} | 465 |
// 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 <Foundation/Foundation.h>
#import <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
#include <_types/_uint64_t.h>
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.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/KeyCodeMap_Internal.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h"
using namespace flutter::testing::keycodes;
using namespace flutter::testing;
FLUTTER_ASSERT_ARC;
#define XCTAssertStrEqual(value, expected) \
XCTAssertTrue(strcmp(value, expected) == 0, \
@"String \"%s\" not equal to the expected value of \"%s\"", value, expected)
// A wrap to convert FlutterKeyEvent to a ObjC class.
@interface TestKeyEvent : NSObject
@property(nonatomic) FlutterKeyEvent* data;
@property(nonatomic) FlutterKeyEventCallback callback;
@property(nonatomic) void* _Nullable userData;
- (nonnull instancetype)initWithEvent:(const FlutterKeyEvent*)event
callback:(nullable FlutterKeyEventCallback)callback
userData:(void* _Nullable)userData;
- (BOOL)hasCallback;
- (void)respond:(BOOL)handled;
@end
@implementation TestKeyEvent
- (instancetype)initWithEvent:(const FlutterKeyEvent*)event
callback:(nullable FlutterKeyEventCallback)callback
userData:(void* _Nullable)userData {
self = [super init];
_data = new FlutterKeyEvent(*event);
if (event->character != nullptr) {
size_t len = strlen(event->character);
char* character = new char[len + 1];
strlcpy(character, event->character, len + 1);
_data->character = character;
}
_callback = callback;
_userData = userData;
return self;
}
- (BOOL)hasCallback {
return _callback != nil;
}
- (void)respond:(BOOL)handled {
NSAssert(
_callback != nil,
@"Improper call to `respond` that does not have a callback."); // Caller's responsibility
_callback(handled, _userData);
}
- (void)dealloc {
if (_data->character != nullptr) {
delete[] _data->character;
}
delete _data;
}
@end
namespace {
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeUndefined = (UIKeyboardHIDUsage)0x03;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeKeyA = (UIKeyboardHIDUsage)0x04;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodePeriod = (UIKeyboardHIDUsage)0x37;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeKeyW = (UIKeyboardHIDUsage)0x1a;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeShiftLeft = (UIKeyboardHIDUsage)0xe1;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeShiftRight = (UIKeyboardHIDUsage)0xe5;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeNumpad1 = (UIKeyboardHIDUsage)0x59;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeCapsLock = (UIKeyboardHIDUsage)0x39;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeF1 = (UIKeyboardHIDUsage)0x3a;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeCommandLeft = (UIKeyboardHIDUsage)0xe3;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeAltRight = (UIKeyboardHIDUsage)0xe6;
API_AVAILABLE(ios(13.4))
constexpr UIKeyboardHIDUsage kKeyCodeEject = (UIKeyboardHIDUsage)0xb8;
constexpr uint64_t kPhysicalKeyUndefined = 0x00070003;
constexpr uint64_t kLogicalKeyUndefined = 0x1300000003;
constexpr uint64_t kModifierFlagNone = 0x0;
typedef void (^ResponseCallback)(bool handled);
} // namespace
@interface FlutterEmbedderKeyResponderTest : XCTestCase
@end
@implementation FlutterEmbedderKeyResponderTest
- (void)setUp {
// All of these tests were designed to run on iOS 13.4 or later.
if (@available(iOS 13.4, *)) {
} else {
XCTSkip(@"Required API not present for test.");
}
}
- (void)tearDown {
}
// Test the most basic key events.
//
// Press, hold, and release key A on an US keyboard.
- (void)testBasicKeyEvent API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
__block BOOL last_handled = TRUE;
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
last_handled = FALSE;
[responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a")
callback:^(BOOL handled) {
last_handled = handled;
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->timestamp, 123000000.0f);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertStrEqual(event->character, "a");
XCTAssertEqual(event->synthesized, false);
XCTAssertEqual(last_handled, FALSE);
XCTAssert([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
XCTAssertEqual(last_handled, TRUE);
[events removeAllObjects];
last_handled = TRUE;
[responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f)
callback:^(BOOL handled) {
last_handled = handled;
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->timestamp, 123000000.0f);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
XCTAssertEqual(last_handled, TRUE);
XCTAssert([[events lastObject] hasCallback]);
[[events lastObject] respond:FALSE]; // Check if responding FALSE works
XCTAssertEqual(last_handled, FALSE);
[events removeAllObjects];
}
- (void)testIosKeyPlane API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
__block BOOL last_handled = TRUE;
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
last_handled = FALSE;
// Verify that the eject key (keycode 0xb8, which is not present in the keymap)
// should be translated to the right logical and physical keys.
[responder handlePress:keyDownEvent(kKeyCodeEject, kModifierFlagNone, 123.0f)
callback:^(BOOL handled) {
last_handled = handled;
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kKeyCodeEject | kIosPlane);
XCTAssertEqual(event->logical, kKeyCodeEject | kIosPlane);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
XCTAssertEqual(last_handled, FALSE);
XCTAssert([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
XCTAssertEqual(last_handled, TRUE);
[events removeAllObjects];
last_handled = TRUE;
[responder handlePress:keyUpEvent(kKeyCodeEject, kModifierFlagNone, 123.0f)
callback:^(BOOL handled) {
last_handled = handled;
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kKeyCodeEject | kIosPlane);
XCTAssertEqual(event->logical, kKeyCodeEject | kIosPlane);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
XCTAssertEqual(last_handled, TRUE);
XCTAssert([[events lastObject] hasCallback]);
[[events lastObject] respond:FALSE]; // Check if responding FALSE works
XCTAssertEqual(last_handled, FALSE);
[events removeAllObjects];
}
- (void)testOutOfOrderModifiers API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
// This tests that we synthesize the correct modifier keys when we release the
// modifier key that created the letter before we release the letter.
[responder handlePress:keyDownEvent(kKeyCodeAltRight, kModifierFlagAltAny, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalAltRight);
XCTAssertEqual(event->logical, kLogicalAltRight);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
// Test non-ASCII characters being produced.
[responder handlePress:keyDownEvent(kKeyCodeKeyW, kModifierFlagAltAny, 123.0f, "∑", "w")
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyW);
XCTAssertEqual(event->logical, kLogicalKeyW);
XCTAssertStrEqual(event->character, "∑");
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
// Releasing the modifier key before the letter should send the key up to the
// framework.
[responder handlePress:keyUpEvent(kKeyCodeAltRight, kModifierFlagAltAny, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalAltRight);
XCTAssertEqual(event->logical, kLogicalAltRight);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
// Yes, iOS sends a modifier flag for the Alt key being down on this event,
// even though the Alt (Option) key has already been released. This means that
// for the framework to be in the correct state, we must synthesize a key down
// event for the modifier key here, and another key up before the next key
// event.
[responder handlePress:keyUpEvent(kKeyCodeKeyW, kModifierFlagAltAny, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyW);
XCTAssertEqual(event->logical, kLogicalKeyW);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
// Here we should simulate a key up for the Alt key, since it is no longer
// shown as down in the modifier flags.
[responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "å", "a")
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertStrEqual(event->character, "å");
XCTAssertEqual(event->synthesized, false);
}
- (void)testIgnoreDuplicateDownEvent API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
__block BOOL last_handled = TRUE;
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
last_handled = FALSE;
[responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a")
callback:^(BOOL handled) {
last_handled = handled;
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertStrEqual(event->character, "a");
XCTAssertEqual(event->synthesized, false);
XCTAssertEqual(last_handled, FALSE);
[[events lastObject] respond:TRUE];
XCTAssertEqual(last_handled, TRUE);
[events removeAllObjects];
last_handled = FALSE;
[responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a")
callback:^(BOOL handled) {
last_handled = handled;
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->physical, 0ull);
XCTAssertEqual(event->logical, 0ull);
XCTAssertEqual(event->synthesized, false);
XCTAssertFalse([[events lastObject] hasCallback]);
XCTAssertEqual(last_handled, TRUE);
[events removeAllObjects];
last_handled = FALSE;
[responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f)
callback:^(BOOL handled) {
last_handled = handled;
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
XCTAssertEqual(last_handled, FALSE);
[[events lastObject] respond:TRUE];
XCTAssertEqual(last_handled, TRUE);
[events removeAllObjects];
}
- (void)testIgnoreAbruptUpEvent API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
__block BOOL last_handled = TRUE;
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
last_handled = FALSE;
[responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f)
callback:^(BOOL handled) {
last_handled = handled;
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->physical, 0ull);
XCTAssertEqual(event->logical, 0ull);
XCTAssertEqual(event->synthesized, false);
XCTAssertFalse([[events lastObject] hasCallback]);
XCTAssertEqual(last_handled, TRUE);
[events removeAllObjects];
}
// Press R-Shift, A, then release R-Shift then A, on a US keyboard.
//
// This is special because the characters for the A key will change in this
// process.
- (void)testToggleModifiersDuringKeyTap API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
[responder handlePress:keyDownEvent(kKeyCodeShiftRight, kModifierFlagShiftAny, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->timestamp, 123000000.0f);
XCTAssertEqual(event->physical, kPhysicalShiftRight);
XCTAssertEqual(event->logical, kLogicalShiftRight);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagShiftAny, 123.0f, "A", "A")
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertStrEqual(event->character, "A");
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder handlePress:keyUpEvent(kKeyCodeShiftRight, kModifierFlagNone, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalShiftRight);
XCTAssertEqual(event->logical, kLogicalShiftRight);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
}
// Special modifier flags.
//
// Some keys in modifierFlags are not to indicate modifier state, but to mark
// the key area that the key belongs to, such as numpad keys or function keys.
// Ensure these flags do not obstruct other keys.
- (void)testSpecialModiferFlags API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
FlutterKeyEvent* event;
__block BOOL last_handled = TRUE;
id keyEventCallback = ^(BOOL handled) {
last_handled = handled;
};
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
// Keydown: Numpad1, Fn (undefined), F1, KeyA, ShiftLeft
// Then KeyUp: Numpad1, Fn (undefined), F1, KeyA, ShiftLeft
// Numpad 1
// OS provides: char: "1", code: 0x59, modifiers: 0x200000
[responder handlePress:keyDownEvent(kKeyCodeNumpad1, kModifierFlagNumPadKey, 123.0, "1", "1")
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalNumpad1);
XCTAssertEqual(event->logical, kLogicalNumpad1);
XCTAssertStrEqual(event->character, "1");
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// Fn Key (sends HID undefined)
// OS provides: char: nil, keycode: 0x3, modifiers: 0x0
[responder handlePress:keyDownEvent(kKeyCodeUndefined, kModifierFlagNone, 123.0)
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyUndefined);
XCTAssertEqual(event->logical, kLogicalKeyUndefined);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// F1 Down
// OS provides: char: UIKeyInputF1, code: 0x3a, modifiers: 0x0
[responder handlePress:keyDownEvent(kKeyCodeF1, kModifierFlagNone, 123.0f, "\\^P", "\\^P")
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalF1);
XCTAssertEqual(event->logical, kLogicalF1);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// KeyA Down
// OS provides: char: "q", code: 0x4, modifiers: 0x0
[responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a")
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertStrEqual(event->character, "a");
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// ShiftLeft Down
// OS Provides: char: nil, code: 0xe1, modifiers: 0x20000
[responder handlePress:keyDownEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f)
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalShiftLeft);
XCTAssertEqual(event->logical, kLogicalShiftLeft);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
// Numpad 1 Up
// OS provides: char: "1", code: 0x59, modifiers: 0x200000
[responder handlePress:keyUpEvent(kKeyCodeNumpad1, kModifierFlagNumPadKey, 123.0f)
callback:keyEventCallback];
XCTAssertEqual([events count], 2u);
// Because the OS no longer provides the 0x20000 (kModifierFlagShiftAny), we
// have to simulate a keyup.
event = [events firstObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalShiftLeft);
XCTAssertEqual(event->logical, kLogicalShiftLeft);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, true);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalNumpad1);
XCTAssertEqual(event->logical, kLogicalNumpad1);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// F1 Up
// OS provides: char: UIKeyInputF1, code: 0x3a, modifiers: 0x0
[responder handlePress:keyUpEvent(kKeyCodeF1, kModifierFlagNone, 123.0f)
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalF1);
XCTAssertEqual(event->logical, kLogicalF1);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// Fn Key (sends HID undefined)
// OS provides: char: nil, code: 0x3, modifiers: 0x0
[responder handlePress:keyUpEvent(kKeyCodeUndefined, kModifierFlagNone, 123.0)
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyUndefined);
XCTAssertEqual(event->logical, kLogicalKeyUndefined);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// KeyA Up
// OS provides: char: "a", code: 0x4, modifiers: 0x0
[responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f)
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// ShiftLeft Up
// OS provides: char: nil, code: 0xe1, modifiers: 0x20000
[responder handlePress:keyUpEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f)
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->physical, 0ull);
XCTAssertEqual(event->logical, 0ull);
XCTAssertEqual(event->synthesized, false);
XCTAssertFalse([[events lastObject] hasCallback]);
XCTAssertEqual(last_handled, TRUE);
[events removeAllObjects];
}
- (void)testIdentifyLeftAndRightModifiers API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
[responder handlePress:keyDownEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalShiftLeft);
XCTAssertEqual(event->logical, kLogicalShiftLeft);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder handlePress:keyDownEvent(kKeyCodeShiftRight, kModifierFlagShiftAny, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalShiftRight);
XCTAssertEqual(event->logical, kLogicalShiftRight);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder handlePress:keyUpEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalShiftLeft);
XCTAssertEqual(event->logical, kLogicalShiftLeft);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder handlePress:keyUpEvent(kKeyCodeShiftRight, kModifierFlagShiftAny, 123.0f)
callback:^(BOOL handled){
}];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalShiftRight);
XCTAssertEqual(event->logical, kLogicalShiftRight);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
}
// Press the CapsLock key when CapsLock state is desynchronized
- (void)testSynchronizeCapsLockStateOnCapsLock API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
__block BOOL last_handled = TRUE;
id keyEventCallback = ^(BOOL handled) {
last_handled = handled;
};
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
last_handled = FALSE;
[responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagCapsLock, 123.0f, "A", "A")
callback:keyEventCallback];
XCTAssertEqual([events count], 3u);
event = events[0].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalCapsLock);
XCTAssertEqual(event->logical, kLogicalCapsLock);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, true);
XCTAssertFalse([events[0] hasCallback]);
event = events[1].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalCapsLock);
XCTAssertEqual(event->logical, kLogicalCapsLock);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, true);
XCTAssertFalse([events[1] hasCallback]);
event = events[2].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertStrEqual(event->character, "A");
XCTAssertEqual(event->synthesized, false);
XCTAssert([events[2] hasCallback]);
XCTAssertEqual(last_handled, FALSE);
[[events lastObject] respond:TRUE];
XCTAssertEqual(last_handled, TRUE);
[events removeAllObjects];
// Release the "A" key.
[responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagCapsLock, 123.0f)
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
// In: CapsLock down
// Out: CapsLock down
last_handled = FALSE;
[responder handlePress:keyDownEvent(kKeyCodeCapsLock, kModifierFlagCapsLock, 123.0f)
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events firstObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalCapsLock);
XCTAssertEqual(event->logical, kLogicalCapsLock);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
XCTAssert([[events firstObject] hasCallback]);
[events removeAllObjects];
// In: CapsLock up
// Out: CapsLock up
// This turns off the caps lock, triggering a synthesized up/down to tell the
// framework that.
last_handled = FALSE;
[responder handlePress:keyUpEvent(kKeyCodeCapsLock, kModifierFlagCapsLock, 123.0f)
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = [events firstObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalCapsLock);
XCTAssertEqual(event->logical, kLogicalCapsLock);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
XCTAssert([[events firstObject] hasCallback]);
[events removeAllObjects];
last_handled = FALSE;
[responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a")
callback:keyEventCallback];
// Just to make sure that we aren't simulating events now, since the state is
// consistent, and should be off.
XCTAssertEqual([events count], 1u);
event = [events lastObject].data;
XCTAssertNotEqual(event, nullptr);
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertStrEqual(event->character, "a");
XCTAssertEqual(event->synthesized, false);
XCTAssert([[events firstObject] hasCallback]);
}
// Press the CapsLock key when CapsLock state is desynchronized
- (void)testSynchronizeCapsLockStateOnNormalKey API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
__block BOOL last_handled = TRUE;
id keyEventCallback = ^(BOOL handled) {
last_handled = handled;
};
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event
callback:callback
userData:user_data]];
}];
last_handled = FALSE;
[responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagCapsLock, 123.0f, "A", "a")
callback:keyEventCallback];
XCTAssertEqual([events count], 3u);
event = events[0].data;
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalCapsLock);
XCTAssertEqual(event->logical, kLogicalCapsLock);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, true);
XCTAssertFalse([events[0] hasCallback]);
event = events[1].data;
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalCapsLock);
XCTAssertEqual(event->logical, kLogicalCapsLock);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, true);
XCTAssertFalse([events[1] hasCallback]);
event = events[2].data;
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalKeyA);
XCTAssertEqual(event->logical, kLogicalKeyA);
XCTAssertStrEqual(event->character, "A");
XCTAssertEqual(event->synthesized, false);
XCTAssert([events[2] hasCallback]);
XCTAssertEqual(last_handled, FALSE);
[[events lastObject] respond:TRUE];
XCTAssertEqual(last_handled, TRUE);
[events removeAllObjects];
}
// Press Cmd-. should correctly result in an Escape event.
- (void)testCommandPeriodKey API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
id keyEventCallback = ^(BOOL handled) {
};
FlutterKeyEvent* event;
FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback,
void* _Nullable user_data) {
[events addObject:[[TestKeyEvent alloc] initWithEvent:&event callback:nil userData:nil]];
callback(true, user_data);
}];
// MetaLeft down.
[responder handlePress:keyDownEvent(kKeyCodeCommandLeft, kModifierFlagMetaAny, 123.0f, "", "")
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = events[0].data;
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalMetaLeft);
XCTAssertEqual(event->logical, kLogicalMetaLeft);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
// Period down, which is logically Escape.
[responder handlePress:keyDownEvent(kKeyCodePeriod, kModifierFlagMetaAny, 123.0f,
"UIKeyInputEscape", "UIKeyInputEscape")
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = events[0].data;
XCTAssertEqual(event->type, kFlutterKeyEventTypeDown);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalPeriod);
XCTAssertEqual(event->logical, kLogicalEscape);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
// Period up, which unconventionally has characters.
[responder handlePress:keyUpEvent(kKeyCodePeriod, kModifierFlagMetaAny, 123.0f,
"UIKeyInputEscape", "UIKeyInputEscape")
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = events[0].data;
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalPeriod);
XCTAssertEqual(event->logical, kLogicalEscape);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
// MetaLeft up.
[responder handlePress:keyUpEvent(kKeyCodeCommandLeft, kModifierFlagMetaAny, 123.0f, "", "")
callback:keyEventCallback];
XCTAssertEqual([events count], 1u);
event = events[0].data;
XCTAssertEqual(event->type, kFlutterKeyEventTypeUp);
XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard);
XCTAssertEqual(event->physical, kPhysicalMetaLeft);
XCTAssertEqual(event->logical, kLogicalMetaLeft);
XCTAssertEqual(event->character, nullptr);
XCTAssertEqual(event->synthesized, false);
[events removeAllObjects];
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponderTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponderTest.mm",
"repo_id": "engine",
"token_count": 17276
} | 466 |
// 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 <Foundation/Foundation.h>
#import <OCMock/OCMock.h>
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#include <_types/_uint32_t.h>
#include "flutter/fml/platform/darwin/message_loop_darwin.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h"
FLUTTER_ASSERT_ARC;
namespace flutter {
class PointerDataPacket {};
} // namespace flutter
using namespace flutter::testing;
/// Sometimes we have to use a custom mock to avoid retain cycles in ocmock.
@interface FlutterEnginePartialMock : FlutterEngine
@property(nonatomic, strong) FlutterBasicMessageChannel* lifecycleChannel;
@property(nonatomic, weak) FlutterViewController* viewController;
@property(nonatomic, assign) BOOL didCallNotifyLowMemory;
@end
@interface FlutterEngine ()
- (BOOL)createShell:(NSString*)entrypoint
libraryURI:(NSString*)libraryURI
initialRoute:(NSString*)initialRoute;
- (void)dispatchPointerDataPacket:(std::unique_ptr<flutter::PointerDataPacket>)packet;
@end
@interface FlutterEngine (TestLowMemory)
- (void)notifyLowMemory;
@end
extern NSNotificationName const FlutterViewControllerWillDealloc;
/// A simple mock class for FlutterEngine.
///
/// OCMockClass 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.
@interface MockEngine : NSObject
@end
@interface FlutterKeyboardManagerUnittestsObjC : NSObject
- (bool)nextResponderShouldThrowOnPressesEnded;
- (bool)singlePrimaryResponder;
- (bool)doublePrimaryResponder;
- (bool)singleSecondaryResponder;
- (bool)emptyNextResponder;
@end
namespace {
typedef void (^KeyCallbackSetter)(FlutterUIPressProxy* press, FlutterAsyncKeyCallback callback)
API_AVAILABLE(ios(13.4));
typedef BOOL (^BoolGetter)();
} // namespace
@interface FlutterKeyboardManagerTest : XCTestCase
@property(nonatomic, strong) id mockEngine;
- (FlutterViewController*)mockOwnerWithPressesBeginOnlyNext API_AVAILABLE(ios(13.4));
@end
@implementation FlutterKeyboardManagerTest
- (void)setUp {
// All of these tests were designed to run on iOS 13.4 or later.
if (@available(iOS 13.4, *)) {
} else {
XCTSkip(@"Required API not present for test.");
}
[super setUp];
self.mockEngine = OCMClassMock([FlutterEngine class]);
}
- (void)tearDown {
// We stop mocking here to avoid retain cycles that stop
// FlutterViewControllers from deallocing.
[self.mockEngine stopMocking];
self.mockEngine = nil;
[super tearDown];
}
- (id)checkKeyDownEvent:(UIKeyboardHIDUsage)keyCode API_AVAILABLE(ios(13.4)) {
return [OCMArg checkWithBlock:^BOOL(id value) {
if (![value isKindOfClass:[FlutterUIPressProxy class]]) {
return NO;
}
FlutterUIPressProxy* press = value;
return press.key.keyCode == keyCode;
}];
}
- (id<FlutterKeyPrimaryResponder>)mockPrimaryResponder:(KeyCallbackSetter)callbackSetter
API_AVAILABLE(ios(13.4)) {
id<FlutterKeyPrimaryResponder> mock =
OCMStrictProtocolMock(@protocol(FlutterKeyPrimaryResponder));
OCMStub([mock handlePress:[OCMArg any] callback:[OCMArg any]])
.andDo((^(NSInvocation* invocation) {
FlutterUIPressProxy* press;
FlutterAsyncKeyCallback callback;
[invocation getArgument:&press atIndex:2];
[invocation getArgument:&callback atIndex:3];
CFRunLoopPerformBlock(CFRunLoopGetCurrent(),
fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode, ^() {
callbackSetter(press, callback);
});
}));
return mock;
}
- (id<FlutterKeySecondaryResponder>)mockSecondaryResponder:(BoolGetter)resultGetter
API_AVAILABLE(ios(13.4)) {
id<FlutterKeySecondaryResponder> mock =
OCMStrictProtocolMock(@protocol(FlutterKeySecondaryResponder));
OCMStub([mock handlePress:[OCMArg any]]).andDo((^(NSInvocation* invocation) {
BOOL result = resultGetter();
[invocation setReturnValue:&result];
}));
return mock;
}
- (FlutterViewController*)mockOwnerWithPressesBeginOnlyNext API_AVAILABLE(ios(13.4)) {
// The nextResponder is a strict mock and hasn't stubbed pressesEnded.
// An error will be thrown on pressesEnded.
UIResponder* nextResponder = OCMStrictClassMock([UIResponder class]);
OCMStub([nextResponder pressesBegan:[OCMArg any] withEvent:[OCMArg any]]).andDo(nil);
FlutterViewController* viewController =
[[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil];
FlutterViewController* owner = OCMPartialMock(viewController);
OCMStub([owner nextResponder]).andReturn(nextResponder);
return owner;
}
// Verify that the nextResponder returned from mockOwnerWithPressesBeginOnlyNext()
// throws exception when pressesEnded is called.
- (bool)testNextResponderShouldThrowOnPressesEnded API_AVAILABLE(ios(13.4)) {
FlutterViewController* owner = [self mockOwnerWithPressesBeginOnlyNext];
@try {
[owner.nextResponder pressesEnded:[NSSet init] withEvent:[[UIPressesEvent alloc] init]];
return false;
} @catch (...) {
return true;
}
}
- (void)testSinglePrimaryResponder API_AVAILABLE(ios(13.4)) {
FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init];
__block BOOL primaryResponse = FALSE;
__block int callbackCount = 0;
[manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press,
FlutterAsyncKeyCallback callback) {
callbackCount++;
callback(primaryResponse);
}]];
constexpr UIKeyboardHIDUsage keyId = (UIKeyboardHIDUsage)0x50;
// Case: The responder reports TRUE
__block bool completeHandled = true;
primaryResponse = TRUE;
[manager handlePress:keyDownEvent(keyId)
nextAction:^() {
completeHandled = false;
}];
XCTAssertEqual(callbackCount, 1);
XCTAssertTrue(completeHandled);
completeHandled = true;
callbackCount = 0;
// Case: The responder reports FALSE
primaryResponse = FALSE;
[manager handlePress:keyUpEvent(keyId)
nextAction:^() {
completeHandled = false;
}];
XCTAssertEqual(callbackCount, 1);
XCTAssertFalse(completeHandled);
}
- (void)testDoublePrimaryResponder API_AVAILABLE(ios(13.4)) {
FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init];
__block BOOL callback1Response = FALSE;
__block int callback1Count = 0;
[manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press,
FlutterAsyncKeyCallback callback) {
callback1Count++;
callback(callback1Response);
}]];
__block BOOL callback2Response = FALSE;
__block int callback2Count = 0;
[manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press,
FlutterAsyncKeyCallback callback) {
callback2Count++;
callback(callback2Response);
}]];
// Case: Both responders report TRUE.
__block bool somethingWasHandled = true;
constexpr UIKeyboardHIDUsage keyId = (UIKeyboardHIDUsage)0x50;
callback1Response = TRUE;
callback2Response = TRUE;
[manager handlePress:keyUpEvent(keyId)
nextAction:^() {
somethingWasHandled = false;
}];
XCTAssertEqual(callback1Count, 1);
XCTAssertEqual(callback2Count, 1);
XCTAssertTrue(somethingWasHandled);
somethingWasHandled = true;
callback1Count = 0;
callback2Count = 0;
// Case: One responder reports TRUE.
callback1Response = TRUE;
callback2Response = FALSE;
[manager handlePress:keyUpEvent(keyId)
nextAction:^() {
somethingWasHandled = false;
}];
XCTAssertEqual(callback1Count, 1);
XCTAssertEqual(callback2Count, 1);
XCTAssertTrue(somethingWasHandled);
somethingWasHandled = true;
callback1Count = 0;
callback2Count = 0;
// Case: Both responders report FALSE.
callback1Response = FALSE;
callback2Response = FALSE;
[manager handlePress:keyDownEvent(keyId)
nextAction:^() {
somethingWasHandled = false;
}];
XCTAssertEqual(callback1Count, 1);
XCTAssertEqual(callback2Count, 1);
XCTAssertFalse(somethingWasHandled);
}
- (void)testSingleSecondaryResponder API_AVAILABLE(ios(13.4)) {
FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init];
__block BOOL primaryResponse = FALSE;
__block int callbackCount = 0;
[manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press,
FlutterAsyncKeyCallback callback) {
callbackCount++;
callback(primaryResponse);
}]];
__block BOOL secondaryResponse;
[manager addSecondaryResponder:[self mockSecondaryResponder:^() {
return secondaryResponse;
}]];
// Case: Primary responder responds TRUE. The event shouldn't be handled by
// the secondary responder.
constexpr UIKeyboardHIDUsage keyId = (UIKeyboardHIDUsage)0x50;
secondaryResponse = FALSE;
primaryResponse = TRUE;
__block bool completeHandled = true;
[manager handlePress:keyUpEvent(keyId)
nextAction:^() {
completeHandled = false;
}];
XCTAssertEqual(callbackCount, 1);
XCTAssertTrue(completeHandled);
completeHandled = true;
callbackCount = 0;
// Case: Primary responder responds FALSE. The secondary responder returns
// TRUE.
secondaryResponse = TRUE;
primaryResponse = FALSE;
[manager handlePress:keyUpEvent(keyId)
nextAction:^() {
completeHandled = false;
}];
XCTAssertEqual(callbackCount, 1);
XCTAssertTrue(completeHandled);
completeHandled = true;
callbackCount = 0;
// Case: Primary responder responds FALSE. The secondary responder returns FALSE.
secondaryResponse = FALSE;
primaryResponse = FALSE;
[manager handlePress:keyDownEvent(keyId)
nextAction:^() {
completeHandled = false;
}];
XCTAssertEqual(callbackCount, 1);
XCTAssertFalse(completeHandled);
}
- (void)testEventsProcessedSequentially API_AVAILABLE(ios(13.4)) {
constexpr UIKeyboardHIDUsage keyId1 = (UIKeyboardHIDUsage)0x50;
constexpr UIKeyboardHIDUsage keyId2 = (UIKeyboardHIDUsage)0x51;
FlutterUIPressProxy* event1 = keyDownEvent(keyId1);
FlutterUIPressProxy* event2 = keyDownEvent(keyId2);
__block FlutterAsyncKeyCallback key1Callback;
__block FlutterAsyncKeyCallback key2Callback;
__block bool key1Handled = true;
__block bool key2Handled = true;
FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init];
[manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press,
FlutterAsyncKeyCallback callback) {
if (press == event1) {
key1Callback = callback;
} else if (press == event2) {
key2Callback = callback;
}
}]];
// Add both presses into the main CFRunLoop queue
CFRunLoopTimerRef timer0 = CFRunLoopTimerCreateWithHandler(
kCFAllocatorDefault, CFAbsoluteTimeGetCurrent(), 0, 0, 0, ^(CFRunLoopTimerRef timerRef) {
[manager handlePress:event1
nextAction:^() {
key1Handled = false;
}];
});
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer0, kCFRunLoopCommonModes);
CFRunLoopTimerRef timer1 = CFRunLoopTimerCreateWithHandler(
kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + 1, 0, 0, 0, ^(CFRunLoopTimerRef timerRef) {
// key1 should be completely finished by now
XCTAssertFalse(key1Handled);
[manager handlePress:event2
nextAction:^() {
key2Handled = false;
}];
// End the nested CFRunLoop
CFRunLoopStop(CFRunLoopGetCurrent());
});
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer1, kCFRunLoopCommonModes);
// Add the callbacks to the CFRunLoop with mode kMessageLoopCFRunLoopMode
// This allows them to interrupt the loop started within handlePress
CFRunLoopTimerRef timer2 = CFRunLoopTimerCreateWithHandler(
kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + 2, 0, 0, 0, ^(CFRunLoopTimerRef timerRef) {
// No processing should be done on key2 yet
XCTAssertTrue(key1Callback != nil);
XCTAssertTrue(key2Callback == nil);
key1Callback(false);
});
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer2,
fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode);
CFRunLoopTimerRef timer3 = CFRunLoopTimerCreateWithHandler(
kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + 3, 0, 0, 0, ^(CFRunLoopTimerRef timerRef) {
// Both keys should be processed by now
XCTAssertTrue(key1Callback != nil);
XCTAssertTrue(key2Callback != nil);
key2Callback(false);
});
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer3,
fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode);
// Start a nested CFRunLoop so we can wait for both presses to complete before exiting the test
CFRunLoopRun();
XCTAssertFalse(key2Handled);
XCTAssertFalse(key1Handled);
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm",
"repo_id": "engine",
"token_count": 5406
} | 467 |
// 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_SOURCE_FLUTTERRESTORATIONPLUGIN_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERRESTORATIONPLUGIN_H_
#import <UIKit/UIKit.h>
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h"
@interface FlutterRestorationPlugin : NSObject
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithChannel:(FlutterMethodChannel*)channel
restorationEnabled:(BOOL)waitForData NS_DESIGNATED_INITIALIZER;
@property(nonatomic, strong) NSData* restorationData;
- (void)markRestorationComplete;
- (void)reset;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERRESTORATIONPLUGIN_H_
| engine/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h",
"repo_id": "engine",
"token_count": 345
} | 468 |
// 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_SOURCE_FLUTTERUIPRESSPROXY_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUIPRESSPROXY_H_
#import <UIKit/UIKit.h>
#include <functional>
/**
* A event class that is a wrapper around a UIPress and a UIEvent to allow
* overidding for testing purposes, since UIKit doesn't allow creation of
* UIEvent or UIPress directly.
*/
API_AVAILABLE(ios(13.4))
@interface FlutterUIPressProxy : NSObject
- (instancetype)initWithPress:(UIPress*)press withEvent:(UIEvent*)event API_AVAILABLE(ios(13.4));
- (UIPressPhase)phase API_AVAILABLE(ios(13.4));
- (UIKey*)key API_AVAILABLE(ios(13.4));
- (UIEventType)type API_AVAILABLE(ios(13.4));
- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4));
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUIPRESSPROXY_H_
| engine/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h",
"repo_id": "engine",
"token_count": 393
} | 469 |
// 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_SOURCE_KEYCODEMAP_INTERNAL_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_
#import <UIKit/UIKit.h>
#include <map>
#include <set>
/**
* Maps iOS-specific key code values representing |PhysicalKeyboardKey|.
*
* MacOS doesn't provide a scan code, but a virtual keycode to represent a
* physical key.
*/
// NOLINTNEXTLINE(readability-identifier-naming)
extern const std::map<uint32_t, uint64_t> keyCodeToPhysicalKey;
/**
* A map from iOS 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|.
*/
// NOLINTNEXTLINE(readability-identifier-naming)
extern const std::map<uint32_t, uint64_t> keyCodeToLogicalKey;
/**
* Maps iOS specific string values of nonvisible keys to logical keys.
*
* TODO(dkwingsmt): Change this getter function to a global variable. I tried to
* do this but the unit test on CI threw errors saying "message sent to
* deallocated instance" on the NSDictionary.
*
* See:
* https://developer.apple.com/documentation/uikit/uikeycommand/input_strings_for_special_keys?language=objc
*/
extern NSDictionary<NSString*, NSNumber*>* specialKeyMapping;
// Several mask constants. See KeyCodeMap.g.mm for their descriptions.
extern const uint64_t kValueMask;
extern const uint64_t kUnicodePlane;
extern const uint64_t kIosPlane;
/**
* 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 |UIKey.modifierFlags| indicating whether a modifier key is pressed.
*/
typedef enum {
// These sided flags are not in any official Apple docs, they are derived from
// experiments.
kModifierFlagControlLeft = 0x1,
kModifierFlagShiftLeft = 0x2,
kModifierFlagShiftRight = 0x4,
kModifierFlagMetaLeft = 0x8,
kModifierFlagMetaRight = 0x10,
kModifierFlagAltLeft = 0x20,
kModifierFlagAltRight = 0x40,
kModifierFlagControlRight = 0x2000,
// These are equivalent to non-sided iOS values.
kModifierFlagCapsLock = UIKeyModifierAlphaShift, // 0x010000
kModifierFlagShiftAny = UIKeyModifierShift, // 0x020000
kModifierFlagControlAny = UIKeyModifierControl, // 0x040000
kModifierFlagAltAny = UIKeyModifierAlternate, // 0x080000
kModifierFlagMetaAny = UIKeyModifierCommand, // 0x100000
kModifierFlagNumPadKey = UIKeyModifierNumericPad // 0x200000
} ModifierFlag;
/**
* A mask of all the modifier flags that represent a modifier being pressed, but
* not whether it is the left or right modifier.
*/
constexpr uint32_t kModifierFlagAnyMask =
kModifierFlagShiftAny | kModifierFlagControlAny | kModifierFlagAltAny | kModifierFlagMetaAny;
/**
* A mask of the modifier flags that represent only left or right modifier
* keys, and not the generic "Any" mask.
*/
constexpr uint32_t kModifierFlagSidedMask = kModifierFlagControlLeft | kModifierFlagShiftLeft |
kModifierFlagShiftRight | kModifierFlagMetaLeft |
kModifierFlagMetaRight | kModifierFlagAltLeft |
kModifierFlagAltRight | kModifierFlagControlRight;
/**
* Map |UIKey.keyCode| to the matching sided modifier in UIEventModifierFlags.
*/
// NOLINTNEXTLINE(readability-identifier-naming)
extern const std::map<uint32_t, ModifierFlag> keyCodeToModifierFlag;
/**
* Map a bit of bitmask of sided modifiers in UIEventModifierFlags to their
* corresponding |UIKey.keyCode|.
*/
// NOLINTNEXTLINE(readability-identifier-naming)
extern const std::map<ModifierFlag, uint32_t> modifierFlagToKeyCode;
/**
* Maps a sided modifier key to the corresponding flag matching either side of
* that type of modifier.
*/
// NOLINTNEXTLINE(readability-identifier-naming)
extern const std::map<ModifierFlag, ModifierFlag> sidedModifierToAny;
/**
* Maps a non-sided modifier key to the corresponding flag matching the left key
* of that type of modifier.
*/
// NOLINTNEXTLINE(readability-identifier-naming)
extern const std::map<ModifierFlag, ModifierFlag> anyModifierToLeft;
/**
* A set of keycodes corresponding to function keys.
*/
// NOLINTNEXTLINE(readability-identifier-naming)
extern const std::set<uint32_t> functionKeyCodes;
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_
| engine/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h",
"repo_id": "engine",
"token_count": 1615
} | 470 |
// 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_SOURCE_CONNECTION_COLLECTION_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_CONNECTION_COLLECTION_H_
#include <cstdint>
#include <map>
#include <string>
namespace flutter {
/// Maintains a current integer assigned to a name (connections).
class ConnectionCollection {
public:
typedef int64_t Connection;
static const Connection kInvalidConnection = 0;
Connection AquireConnection(const std::string& name);
///\returns the name of the channel when cleanup is successful, otherwise
/// the empty string.
std::string CleanupConnection(Connection connection);
static bool IsValidConnection(Connection connection);
static Connection MakeErrorConnection(int errCode);
private:
std::map<std::string, Connection> connections_;
Connection counter_ = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_CONNECTION_COLLECTION_H_
| engine/shell/platform/darwin/ios/framework/Source/connection_collection.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/connection_collection.h",
"repo_id": "engine",
"token_count": 352
} | 471 |
// 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_SOFTWARE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_SOFTWARE_H_
#include "flutter/fml/macros.h"
#import "flutter/shell/platform/darwin/ios/ios_context.h"
namespace flutter {
class IOSContextSoftware final : public IOSContext {
public:
IOSContextSoftware();
// |IOSContext|
~IOSContextSoftware();
// |IOSContext|
sk_sp<GrDirectContext> CreateResourceContext() override;
// |IOSContext|
sk_sp<GrDirectContext> GetMainContext() const override;
// |IOSContext|
std::unique_ptr<GLContextResult> MakeCurrent() override;
// |IOSContext|
std::unique_ptr<Texture> CreateExternalTexture(
int64_t texture_id,
fml::scoped_nsobject<NSObject<FlutterTexture>> texture) override;
private:
FML_DISALLOW_COPY_AND_ASSIGN(IOSContextSoftware);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_SOFTWARE_H_
| engine/shell/platform/darwin/ios/ios_context_software.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/ios_context_software.h",
"repo_id": "engine",
"token_count": 400
} | 472 |
// 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 <XCTest/XCTest.h>
#import "flutter/shell/platform/darwin/ios/platform_message_handler_ios.h"
#import "flutter/common/task_runners.h"
#import "flutter/fml/message_loop.h"
#import "flutter/fml/thread.h"
#import "flutter/lib/ui/window/platform_message.h"
#import "flutter/lib/ui/window/platform_message_response.h"
#import "flutter/shell/common/thread_host.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
FLUTTER_ASSERT_ARC
namespace {
using namespace flutter;
fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) {
auto thread = std::make_unique<fml::Thread>(name);
auto runner = thread->GetTaskRunner();
return runner;
}
fml::RefPtr<fml::TaskRunner> GetCurrentTaskRunner() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
return fml::MessageLoop::GetCurrent().GetTaskRunner();
}
class MockPlatformMessageResponse : public PlatformMessageResponse {
public:
static fml::RefPtr<MockPlatformMessageResponse> Create() {
return fml::AdoptRef(new MockPlatformMessageResponse());
}
void Complete(std::unique_ptr<fml::Mapping> data) override { is_complete_ = true; }
void CompleteEmpty() override { is_complete_ = true; }
};
} // namespace
@interface PlatformMessageHandlerIosTest : XCTestCase
@end
@implementation PlatformMessageHandlerIosTest
- (void)testCreate {
TaskRunners task_runners("test", GetCurrentTaskRunner(), CreateNewThread("raster"),
CreateNewThread("ui"), CreateNewThread("io"));
auto handler = std::make_unique<PlatformMessageHandlerIos>(task_runners.GetPlatformTaskRunner());
XCTAssertTrue(handler);
}
- (void)testSetAndCallHandler {
ThreadHost thread_host("io.flutter.test." + std::string(self.name.UTF8String),
ThreadHost::Type::kRaster | ThreadHost::Type::kIo | ThreadHost::Type::kUi);
TaskRunners task_runners(
"test", GetCurrentTaskRunner(), thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(), thread_host.io_thread->GetTaskRunner());
auto handler = std::make_unique<PlatformMessageHandlerIos>(task_runners.GetPlatformTaskRunner());
std::string channel = "foo";
XCTestExpectation* didCallReply = [self expectationWithDescription:@"didCallReply"];
handler->SetMessageHandler(
channel,
^(NSData* _Nullable data, FlutterBinaryReply _Nonnull reply) {
reply(nil);
[didCallReply fulfill];
},
nil);
auto response = MockPlatformMessageResponse::Create();
task_runners.GetUITaskRunner()->PostTask([channel, response, &handler] {
auto platform_message = std::make_unique<flutter::PlatformMessage>(channel, response);
handler->HandlePlatformMessage(std::move(platform_message));
});
[self waitForExpectationsWithTimeout:1.0 handler:nil];
XCTAssertTrue(response->is_complete());
}
- (void)testSetClearAndCallHandler {
ThreadHost thread_host("io.flutter.test." + std::string(self.name.UTF8String),
ThreadHost::Type::kRaster | ThreadHost::Type::kIo | ThreadHost::Type::kUi);
TaskRunners task_runners(
"test", GetCurrentTaskRunner(), thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(), thread_host.io_thread->GetTaskRunner());
auto handler = std::make_unique<PlatformMessageHandlerIos>(task_runners.GetPlatformTaskRunner());
std::string channel = "foo";
XCTestExpectation* didCallMessage = [self expectationWithDescription:@"didCallMessage"];
handler->SetMessageHandler(
channel,
^(NSData* _Nullable data, FlutterBinaryReply _Nonnull reply) {
XCTFail(@"This shouldn't be called");
reply(nil);
},
nil);
handler->SetMessageHandler(channel, nil, nil);
auto response = MockPlatformMessageResponse::Create();
task_runners.GetUITaskRunner()->PostTask([channel, response, &handler, &didCallMessage] {
auto platform_message = std::make_unique<flutter::PlatformMessage>(channel, response);
handler->HandlePlatformMessage(std::move(platform_message));
[didCallMessage fulfill];
});
[self waitForExpectationsWithTimeout:1.0 handler:nil];
XCTAssertTrue(response->is_complete());
}
- (void)testSetAndCallHandlerTaskQueue {
ThreadHost thread_host("io.flutter.test." + std::string(self.name.UTF8String),
ThreadHost::Type::kRaster | ThreadHost::Type::kIo | ThreadHost::Type::kUi);
TaskRunners task_runners(
"test", GetCurrentTaskRunner(), thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(), thread_host.io_thread->GetTaskRunner());
auto handler = std::make_unique<PlatformMessageHandlerIos>(task_runners.GetPlatformTaskRunner());
std::string channel = "foo";
XCTestExpectation* didCallReply = [self expectationWithDescription:@"didCallReply"];
NSObject<FlutterTaskQueue>* taskQueue = PlatformMessageHandlerIos::MakeBackgroundTaskQueue();
handler->SetMessageHandler(
channel,
^(NSData* _Nullable data, FlutterBinaryReply _Nonnull reply) {
XCTAssertFalse([NSThread isMainThread]);
reply(nil);
[didCallReply fulfill];
},
taskQueue);
auto response = MockPlatformMessageResponse::Create();
task_runners.GetUITaskRunner()->PostTask([channel, response, &handler] {
auto platform_message = std::make_unique<flutter::PlatformMessage>(channel, response);
handler->HandlePlatformMessage(std::move(platform_message));
});
[self waitForExpectationsWithTimeout:1.0 handler:nil];
XCTAssertTrue(response->is_complete());
}
@end
| engine/shell/platform/darwin/ios/platform_message_handler_ios_test.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/platform_message_handler_ios_test.mm",
"repo_id": "engine",
"token_count": 1936
} | 473 |
// 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_ACCESSIBILITYBRIDGEMAC_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_ACCESSIBILITYBRIDGEMAC_H_
#import <Cocoa/Cocoa.h>
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/common/accessibility_bridge.h"
@class FlutterEngine;
@class FlutterViewController;
namespace flutter {
//------------------------------------------------------------------------------
/// The macOS implementation of AccessibilityBridge.
///
/// This interacts with macOS accessibility APIs, which includes routing
/// accessibility events fired from the framework to macOS, routing native
/// macOS accessibility events to the framework, and creating macOS-specific
/// FlutterPlatformNodeDelegate objects for each node in the semantics tree.
///
/// AccessibilityBridgeMac must be created as a shared_ptr, since some methods
/// acquires its weak_ptr.
class AccessibilityBridgeMac : public AccessibilityBridge {
public:
//---------------------------------------------------------------------------
/// @brief Creates an AccessibilityBridgeMacDelegate.
/// @param[in] flutter_engine The weak reference to the FlutterEngine.
/// @param[in] view_controller The weak reference to the FlutterViewController.
explicit AccessibilityBridgeMac(__weak FlutterEngine* flutter_engine,
__weak FlutterViewController* view_controller);
virtual ~AccessibilityBridgeMac() = default;
// |FlutterPlatformNodeDelegate::OwnerBridge|
void DispatchAccessibilityAction(AccessibilityNodeId target,
FlutterSemanticsAction action,
fml::MallocMapping data) override;
protected:
// |AccessibilityBridge|
void OnAccessibilityEvent(ui::AXEventGenerator::TargetedEvent targeted_event) override;
// |AccessibilityBridge|
std::shared_ptr<FlutterPlatformNodeDelegate> CreateFlutterPlatformNodeDelegate() override;
private:
/// A wrapper structure to wraps macOS native accessibility events.
struct NSAccessibilityEvent {
NSAccessibilityNotificationName name;
gfx::NativeViewAccessible target;
NSDictionary* user_info;
};
//---------------------------------------------------------------------------
/// @brief Posts the given event against the given node to the macOS
/// accessibility notification system.
/// @param[in] native_node The event target, must not be nil.
/// @param[in] mac_notification The event name, must not be nil.
virtual void DispatchMacOSNotification(gfx::NativeViewAccessible native_node,
NSAccessibilityNotificationName mac_notification);
//---------------------------------------------------------------------------
/// @brief Posts the given event against the given node with the
/// additional attributes to the macOS accessibility notification
/// system.
/// @param[in] native_node The event target, must not be nil.
/// @param[in] mac_notification The event name, must not be nil.
/// @param[in] user_info The additional attributes, must not be nil.
void DispatchMacOSNotificationWithUserInfo(gfx::NativeViewAccessible native_node,
NSAccessibilityNotificationName mac_notification,
NSDictionary* user_info);
//---------------------------------------------------------------------------
/// @brief Whether the given event is in current pending events.
/// @param[in] event_type The event to look up.
bool HasPendingEvent(ui::AXEventGenerator::Event event) const;
//---------------------------------------------------------------------------
/// @brief Converts the give ui::AXEventGenerator::Event into
/// macOS native accessibility event[s]
/// @param[in] event_type The original event type.
/// @param[in] ax_node The original event target.
std::vector<NSAccessibilityEvent> MacOSEventsFromAXEvent(ui::AXEventGenerator::Event event_type,
const ui::AXNode& ax_node) const;
__weak FlutterEngine* flutter_engine_;
__weak FlutterViewController* view_controller_;
FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridgeMac);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_ACCESSIBILITYBRIDGEMAC_H_
| engine/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h",
"repo_id": "engine",
"token_count": 1540
} | 474 |
// 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/common/framework/Headers/FlutterDartProject.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#include <vector>
#include "flutter/shell/platform/common/engine_switches.h"
static NSString* const kICUBundlePath = @"icudtl.dat";
static NSString* const kAppBundleIdentifier = @"io.flutter.flutter.app";
#pragma mark - Private interface declaration.
@interface FlutterDartProject ()
/**
Get the Flutter assets name path by pass the bundle. If bundle is nil, we use the main bundle as
default.
*/
+ (NSString*)flutterAssetsNameWithBundle:(NSBundle*)bundle;
@end
@implementation FlutterDartProject {
NSBundle* _dartBundle;
NSString* _assetsPath;
NSString* _ICUDataPath;
}
- (instancetype)init {
return [self initWithPrecompiledDartBundle:nil];
}
- (instancetype)initWithPrecompiledDartBundle:(NSBundle*)bundle {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_dartBundle = bundle ?: FLTFrameworkBundleWithIdentifier(kAppBundleIdentifier);
if (_dartBundle == nil) {
// The bundle isn't loaded and can't be found by bundle ID. Find it by path.
_dartBundle = [NSBundle bundleWithURL:[NSBundle.mainBundle.privateFrameworksURL
URLByAppendingPathComponent:@"App.framework"]];
}
if (!_dartBundle.isLoaded) {
[_dartBundle load];
}
_dartEntrypointArguments = [[NSProcessInfo processInfo] arguments];
// Remove the first element as it's the binary name
_dartEntrypointArguments = [_dartEntrypointArguments
subarrayWithRange:NSMakeRange(1, _dartEntrypointArguments.count - 1)];
return self;
}
- (instancetype)initWithAssetsPath:(NSString*)assets ICUDataPath:(NSString*)icuPath {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_assetsPath = assets;
_ICUDataPath = icuPath;
return self;
}
- (BOOL)enableImpeller {
NSNumber* enableImpeller =
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTEnableImpeller"];
if (enableImpeller != nil) {
return enableImpeller.boolValue;
}
return NO;
}
- (NSString*)assetsPath {
if (_assetsPath) {
return _assetsPath;
}
// If there's no App.framework, fall back to checking the main bundle for assets.
NSBundle* assetBundle = _dartBundle ?: [NSBundle mainBundle];
NSString* flutterAssetsName = [assetBundle objectForInfoDictionaryKey:@"FLTAssetsPath"];
if (flutterAssetsName == nil) {
flutterAssetsName = @"flutter_assets";
}
NSString* path = [assetBundle pathForResource:flutterAssetsName ofType:@""];
if (!path) {
NSLog(@"Failed to find path for \"%@\"", flutterAssetsName);
}
return path;
}
- (NSString*)ICUDataPath {
if (_ICUDataPath) {
return _ICUDataPath;
}
NSString* path = [[NSBundle bundleForClass:[self class]] pathForResource:kICUBundlePath
ofType:nil];
if (!path) {
NSLog(@"Failed to find path for \"%@\"", kICUBundlePath);
}
return path;
}
+ (NSString*)flutterAssetsNameWithBundle:(NSBundle*)bundle {
if (bundle == nil) {
bundle = FLTFrameworkBundleWithIdentifier(kAppBundleIdentifier);
}
if (bundle == nil) {
bundle = [NSBundle mainBundle];
}
NSString* flutterAssetsName = [bundle objectForInfoDictionaryKey:@"FLTAssetsPath"];
if (flutterAssetsName == nil) {
flutterAssetsName = @"Contents/Frameworks/App.framework/Resources/flutter_assets";
}
return flutterAssetsName;
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset {
return [self lookupKeyForAsset:asset fromBundle:nil];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset fromBundle:(nullable NSBundle*)bundle {
NSString* flutterAssetsName = [FlutterDartProject flutterAssetsNameWithBundle:bundle];
return [NSString stringWithFormat:@"%@/%@", flutterAssetsName, asset];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
return [self lookupKeyForAsset:asset fromPackage:package fromBundle:nil];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset
fromPackage:(NSString*)package
fromBundle:(nullable NSBundle*)bundle {
return [self lookupKeyForAsset:[NSString stringWithFormat:@"packages/%@/%@", package, asset]
fromBundle:bundle];
}
+ (NSString*)defaultBundleIdentifier {
return kAppBundleIdentifier;
}
@end
| engine/shell/platform/darwin/macos/framework/Source/FlutterDartProject.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterDartProject.mm",
"repo_id": "engine",
"token_count": 1728
} | 475 |
// 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_FLUTTERKEYPRIMARYRESPONDER_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYPRIMARYRESPONDER_H_
#import <Cocoa/Cocoa.h>
typedef void (^FlutterAsyncKeyCallback)(BOOL handled);
/**
* An interface for a responder that can process a key event and decides whether
* to handle an event asynchronously.
*
* To use this class, add it to a |FlutterKeyboardManager| with |addPrimaryResponder|.
*/
@protocol FlutterKeyPrimaryResponder
/**
* Process the event.
*
* The |callback| should be called with a value that indicates whether the
* responder has handled the given event. The |callback| must be called exactly
* once, and can be called before the return of this method, or after.
*/
@required
- (void)handleEvent:(nonnull NSEvent*)event callback:(nonnull FlutterAsyncKeyCallback)callback;
/**
* Synchronize the modifier flags if necessary. The new modifier flag would usually come from mouse
* event and may be out of sync with current keyboard state if the modifier flags have changed while
* window was not key.
*/
@required
- (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags
timestamp:(NSTimeInterval)timestamp;
/* A map from macOS key code to logical keyboard.
*
* The map is assigned on initialization, and updated when the user changes
* keyboard type or layout. The responder should prioritize this map when
* deriving logical keys.
*/
@required
@property(nonatomic, nullable, strong) NSMutableDictionary<NSNumber*, NSNumber*>* layoutMap;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYPRIMARYRESPONDER_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h",
"repo_id": "engine",
"token_count": 569
} | 476 |
// 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/testing/testing.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#include "flutter/shell/platform/common/accessibility_bridge.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
#include "flutter/third_party/accessibility/ax/ax_action_data.h"
namespace flutter::testing {
namespace {
// Returns a view controller configured for the text fixture resource configuration.
FlutterViewController* CreateTestViewController() {
NSString* fixtures = @(testing::GetFixturesPath());
FlutterDartProject* project = [[FlutterDartProject alloc]
initWithAssetsPath:fixtures
ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
return [[FlutterViewController alloc] initWithProject:project];
}
} // namespace
TEST(FlutterPlatformNodeDelegateMac, Basics) {
FlutterViewController* viewController = CreateTestViewController();
FlutterEngine* engine = viewController.engine;
engine.semanticsEnabled = YES;
auto bridge = viewController.accessibilityBridge.lock();
// Initialize ax node data.
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 = "accessibility";
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 root_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
// Verify the accessibility attribute matches.
NSAccessibilityElement* native_accessibility =
root_platform_node_delegate->GetNativeViewAccessible();
std::string value = [native_accessibility.accessibilityValue UTF8String];
EXPECT_TRUE(value == "accessibility");
EXPECT_EQ(native_accessibility.accessibilityRole, NSAccessibilityStaticTextRole);
EXPECT_EQ([native_accessibility.accessibilityChildren count], 0u);
[engine shutDownEngine];
}
TEST(FlutterPlatformNodeDelegateMac, SelectableTextHasCorrectSemantics) {
FlutterViewController* viewController = CreateTestViewController();
FlutterEngine* engine = viewController.engine;
engine.semanticsEnabled = YES;
auto bridge = viewController.accessibilityBridge.lock();
// Initialize ax node data.
FlutterSemanticsNode2 root;
root.id = 0;
root.flags =
static_cast<FlutterSemanticsFlag>(FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField |
FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly);
root.actions = static_cast<FlutterSemanticsAction>(0);
root.text_selection_base = 1;
root.text_selection_extent = 3;
root.label = "";
root.hint = "";
// Selectable text store its text in value
root.value = "selectable text";
root.increased_value = "";
root.decreased_value = "";
root.tooltip = "";
root.child_count = 0;
root.custom_accessibility_actions_count = 0;
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
auto root_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
// Verify the accessibility attribute matches.
NSAccessibilityElement* native_accessibility =
root_platform_node_delegate->GetNativeViewAccessible();
std::string value = [native_accessibility.accessibilityValue UTF8String];
EXPECT_EQ(value, "selectable text");
EXPECT_EQ(native_accessibility.accessibilityRole, NSAccessibilityStaticTextRole);
EXPECT_EQ([native_accessibility.accessibilityChildren count], 0u);
NSRange selection = native_accessibility.accessibilitySelectedTextRange;
EXPECT_EQ(selection.location, 1u);
EXPECT_EQ(selection.length, 2u);
std::string selected_text = [native_accessibility.accessibilitySelectedText UTF8String];
EXPECT_EQ(selected_text, "el");
}
TEST(FlutterPlatformNodeDelegateMac, SelectableTextWithoutSelectionReturnZeroRange) {
FlutterViewController* viewController = CreateTestViewController();
FlutterEngine* engine = viewController.engine;
engine.semanticsEnabled = YES;
auto bridge = viewController.accessibilityBridge.lock();
// Initialize ax node data.
FlutterSemanticsNode2 root;
root.id = 0;
root.flags =
static_cast<FlutterSemanticsFlag>(FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField |
FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly);
root.actions = static_cast<FlutterSemanticsAction>(0);
root.text_selection_base = -1;
root.text_selection_extent = -1;
root.label = "";
root.hint = "";
// Selectable text store its text in value
root.value = "selectable text";
root.increased_value = "";
root.decreased_value = "";
root.tooltip = "";
root.child_count = 0;
root.custom_accessibility_actions_count = 0;
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
auto root_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
// Verify the accessibility attribute matches.
NSAccessibilityElement* native_accessibility =
root_platform_node_delegate->GetNativeViewAccessible();
NSRange selection = native_accessibility.accessibilitySelectedTextRange;
EXPECT_TRUE(selection.location == NSNotFound);
EXPECT_EQ(selection.length, 0u);
}
// MOCK_ENGINE_PROC is leaky by design
// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape)
TEST(FlutterPlatformNodeDelegateMac, CanPerformAction) {
FlutterViewController* viewController = CreateTestViewController();
FlutterEngine* engine = viewController.engine;
// Attach the view to a NSWindow.
NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600)
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
window.contentView = viewController.view;
engine.semanticsEnabled = YES;
auto bridge = viewController.accessibilityBridge.lock();
// Initialize ax node data.
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_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock();
// Set up embedder API mock.
FlutterSemanticsAction called_action;
uint64_t called_id;
engine.embedderAPI.DispatchSemanticsAction = MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&called_id, &called_action](auto engine, uint64_t id, FlutterSemanticsAction action,
const uint8_t* data, size_t data_length) {
called_id = id;
called_action = action;
return kSuccess;
}));
// Performs an AXAction.
ui::AXActionData action_data;
action_data.action = ax::mojom::Action::kDoDefault;
root_platform_node_delegate->AccessibilityPerformAction(action_data);
EXPECT_EQ(called_action, FlutterSemanticsAction::kFlutterSemanticsActionTap);
EXPECT_EQ(called_id, 1u);
[engine setViewController:nil];
[engine shutDownEngine];
}
// NOLINTEND(clang-analyzer-core.StackAddressEscape)
TEST(FlutterPlatformNodeDelegateMac, TextFieldUsesFlutterTextField) {
FlutterViewController* viewController = CreateTestViewController();
FlutterEngine* engine = viewController.engine;
[viewController loadView];
// Unit test localization is unnecessary.
// NOLINTNEXTLINE(clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker)
viewController.textInputPlugin.string = @"textfield";
// Creates a NSWindow so that the native text field can become first responder.
NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600)
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
window.contentView = viewController.view;
engine.semanticsEnabled = YES;
auto bridge = viewController.accessibilityBridge.lock();
// Initialize ax node data.
FlutterSemanticsNode2 root;
root.id = 0;
root.flags = static_cast<FlutterSemanticsFlag>(0);
root.actions = static_cast<FlutterSemanticsAction>(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);
double rectSize = 50;
double transformFactor = 0.5;
FlutterSemanticsNode2 child1;
child1.id = 1;
child1.flags = FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField;
child1.actions = static_cast<FlutterSemanticsAction>(0);
child1.label = "";
child1.hint = "";
child1.value = "textfield";
child1.increased_value = "";
child1.decreased_value = "";
child1.tooltip = "";
child1.text_selection_base = -1;
child1.text_selection_extent = -1;
child1.child_count = 0;
child1.custom_accessibility_actions_count = 0;
child1.rect = {0, 0, rectSize, rectSize}; // LTRB
child1.transform = {transformFactor, 0, 0, 0, transformFactor, 0, 0, 0, 1};
bridge->AddFlutterSemanticsNodeUpdate(child1);
bridge->CommitUpdates();
auto child_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock();
// Verify the accessibility attribute matches.
id native_accessibility = child_platform_node_delegate->GetNativeViewAccessible();
EXPECT_EQ([native_accessibility isKindOfClass:[FlutterTextField class]], YES);
FlutterTextField* native_text_field = (FlutterTextField*)native_accessibility;
NSView* view = viewController.flutterView;
CGRect scaledBounds = [view convertRectToBacking:view.bounds];
CGSize scaledSize = scaledBounds.size;
double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width;
double expectedFrameSize = rectSize * transformFactor / pixelRatio;
EXPECT_EQ(NSEqualRects(native_text_field.frame, NSMakeRect(0, 600 - expectedFrameSize,
expectedFrameSize, expectedFrameSize)),
YES);
[native_text_field startEditing];
EXPECT_EQ([native_text_field.stringValue isEqualToString:@"textfield"], YES);
}
} // namespace flutter::testing
| engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMacTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMacTest.mm",
"repo_id": "engine",
"token_count": 4277
} | 477 |
// 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/FlutterViewController.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#import "flutter/testing/testing.h"
namespace flutter::testing {
namespace {
// Returns an engine configured for the text fixture resource configuration.
FlutterEngine* CreateTestEngine() {
NSString* fixtures = @(testing::GetFixturesPath());
FlutterDartProject* project = [[FlutterDartProject alloc]
initWithAssetsPath:fixtures
ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
return [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:true];
}
} // namespace
TEST(FlutterTextInputSemanticsObjectTest, DoesInitialize) {
FlutterEngine* engine = CreateTestEngine();
{
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
[viewController loadView];
// Create a NSWindow so that the native text field can become first responder.
NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600)
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
window.contentView = viewController.view;
engine.semanticsEnabled = YES;
auto bridge = viewController.accessibilityBridge.lock();
FlutterPlatformNodeDelegateMac delegate(bridge, viewController);
ui::AXTree tree;
ui::AXNode ax_node(&tree, nullptr, 0, 0);
ui::AXNodeData node_data;
node_data.SetValue("initial text");
ax_node.SetData(node_data);
delegate.Init(viewController.accessibilityBridge, &ax_node);
// Verify that a FlutterTextField is attached to the view.
FlutterTextPlatformNode text_platform_node(&delegate, viewController);
id native_accessibility = text_platform_node.GetNativeViewAccessible();
EXPECT_TRUE([native_accessibility isKindOfClass:[FlutterTextField class]]);
auto subviews = [viewController.view subviews];
EXPECT_EQ([subviews count], 2u);
EXPECT_TRUE([subviews[0] isKindOfClass:[FlutterTextField class]]);
FlutterTextField* nativeTextField = subviews[0];
EXPECT_EQ(text_platform_node.GetNativeViewAccessible(), nativeTextField);
}
[engine shutDownEngine];
engine = nil;
// Pump the event loop to make sure no stray nodes cause crashes after the
// engine has been destroyed.
// From issue: https://github.com/flutter/flutter/issues/115599
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
} // namespace flutter::testing
| engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObjectTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObjectTest.mm",
"repo_id": "engine",
"token_count": 1317
} | 478 |
// 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_FLUTTERVIEWCONTROLLERTESTUTILS_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLERTESTUTILS_H_
#import <Foundation/NSString.h>
#import <OCMock/OCMock.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#import "flutter/testing/testing.h"
namespace flutter::testing {
// Returns a mock FlutterViewController.
id CreateMockViewController();
} // namespace flutter::testing
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLERTESTUTILS_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h",
"repo_id": "engine",
"token_count": 316
} | 479 |
# 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("//build/toolchain/clang.gni")
import("//flutter/build/zip_bundle.gni")
import("//flutter/common/config.gni")
import("//flutter/impeller/tools/impeller.gni")
import("//flutter/shell/gpu/gpu.gni")
import("//flutter/shell/platform/embedder/embedder.gni")
import("//flutter/testing/testing.gni")
declare_args() {
embedder_enable_software = shell_enable_software
embedder_enable_vulkan = shell_enable_vulkan
embedder_enable_gl = shell_enable_gl
embedder_enable_metal = shell_enable_metal
}
shell_gpu_configuration("embedder_gpu_configuration") {
enable_software = embedder_enable_software
enable_vulkan = embedder_enable_vulkan
enable_gl = embedder_enable_gl
enable_metal = embedder_enable_metal
}
_framework_binary_subpath = "Versions/A/FlutterEmbedder"
config("embedder_header_config") {
include_dirs = [ "." ]
}
config("embedder_jit_snapshot_setup") {
_lib_snapshot_label = "//flutter/lib/snapshot:vm_isolate_snapshot.bin"
_lib_snapshot_gen_dir = get_label_info(_lib_snapshot_label, "target_gen_dir")
_isolate_snapshot_data = "${_lib_snapshot_gen_dir}/isolate_snapshot.bin"
_isolate_snapshot_instructions =
"${_lib_snapshot_gen_dir}/isolate_snapshot_instructions.bin"
_vm_snapshot_data = "${_lib_snapshot_gen_dir}/vm_isolate_snapshot.bin"
_vm_snapshot_instructions =
"${_lib_snapshot_gen_dir}/vm_snapshot_instructions.bin"
# For testing JIT snapshot setup.
defines = [
"TEST_ISOLATE_SNAPSHOT_DATA=\"${_isolate_snapshot_data}\"",
"TEST_ISOLATE_SNAPSHOT_INSTRUCTIONS=\"${_isolate_snapshot_instructions}\"",
"TEST_VM_SNAPSHOT_DATA=\"${_vm_snapshot_data}\"",
"TEST_VM_SNAPSHOT_INSTRUCTIONS=\"${_vm_snapshot_instructions}\"",
]
}
# Template for the embedder build. Used to allow building it multiple times with
# different flags.
template("embedder_source_set") {
forward_variables_from(invoker, "*")
source_set(target_name) {
sources = [
"embedder.cc",
"embedder_engine.cc",
"embedder_engine.h",
"embedder_external_texture_resolver.cc",
"embedder_external_texture_resolver.h",
"embedder_external_view.cc",
"embedder_external_view.h",
"embedder_external_view_embedder.cc",
"embedder_external_view_embedder.h",
"embedder_include.c",
"embedder_include2.c",
"embedder_layers.cc",
"embedder_layers.h",
"embedder_platform_message_response.cc",
"embedder_platform_message_response.h",
"embedder_render_target.cc",
"embedder_render_target.h",
"embedder_render_target_cache.cc",
"embedder_render_target_cache.h",
"embedder_render_target_skia.cc",
"embedder_render_target_skia.h",
"embedder_semantics_update.cc",
"embedder_semantics_update.h",
"embedder_struct_macros.h",
"embedder_surface.cc",
"embedder_surface.h",
"embedder_surface_software.cc",
"embedder_surface_software.h",
"embedder_task_runner.cc",
"embedder_task_runner.h",
"embedder_thread_host.cc",
"embedder_thread_host.h",
"pixel_formats.cc",
"pixel_formats.h",
"platform_view_embedder.cc",
"platform_view_embedder.h",
"vsync_waiter_embedder.cc",
"vsync_waiter_embedder.h",
]
public_deps = [ ":embedder_headers" ]
deps = [
":embedder_gpu_configuration",
"$dart_src/runtime/bin:dart_io_api",
"$dart_src/runtime/bin:elf_loader",
"//flutter/assets",
"//flutter/common",
"//flutter/common/graphics",
"//flutter/flow",
"//flutter/fml",
"//flutter/lib/ui",
"//flutter/runtime:libdart",
"//flutter/shell/common",
"//flutter/skia",
"//flutter/third_party/tonic",
]
if (embedder_enable_gl) {
sources += [
"embedder_external_texture_gl.cc",
"embedder_external_texture_gl.h",
"embedder_surface_gl.cc",
"embedder_surface_gl.h",
]
if (impeller_supports_rendering) {
sources += [
"embedder_surface_gl_impeller.cc",
"embedder_surface_gl_impeller.h",
]
deps += [ "//flutter/impeller/renderer/backend/gles" ]
}
}
if (impeller_supports_rendering) {
sources += [
"embedder_render_target_impeller.cc",
"embedder_render_target_impeller.h",
]
deps += [
"//flutter/impeller",
"//flutter/impeller/renderer",
]
}
if (embedder_enable_metal) {
sources += [
"embedder_external_texture_metal.h",
"embedder_external_texture_metal.mm",
"embedder_surface_metal.h",
"embedder_surface_metal.mm",
]
if (impeller_supports_rendering) {
sources += [
"embedder_surface_metal_impeller.h",
"embedder_surface_metal_impeller.mm",
]
deps += [ "//flutter/impeller/renderer/backend/metal" ]
}
cflags_objc = flutter_cflags_objc
cflags_objcc = flutter_cflags_objcc
deps += [ "//flutter/shell/platform/darwin/graphics" ]
}
if (embedder_enable_vulkan) {
sources += [
"embedder_surface_vulkan.cc",
"embedder_surface_vulkan.h",
]
deps += [
"//flutter/flutter_vma:flutter_skia_vma",
"//flutter/vulkan/procs",
]
}
# Depend on 'icudtl.dat.S' to avoid dynamic lookups of engine library symbols.
if (is_android) {
deps += [ "//flutter/shell/platform/android:icudtl_asm" ]
sources += [ "$root_build_dir/gen/flutter/shell/platform/android/flutter/third_party/icu/flutter/icudtl.dat.S" ]
}
public_configs += [
":embedder_gpu_configuration_config",
":embedder_header_config",
"//flutter:config",
"//flutter/impeller:impeller_public_config",
]
}
}
embedder_source_set("embedder") {
public_configs = []
}
embedder_source_set("embedder_as_internal_library") {
public_configs = [ ":embedder_internal_library_config" ]
}
source_set("embedder_headers") {
public = [ "embedder.h" ]
public_configs = [ "//flutter:config" ]
}
source_set("embedder_test_utils") {
public = [
"test_utils/key_codes.g.h",
"test_utils/proc_table_replacement.h",
]
deps = [ ":embedder_headers" ]
public_configs = [ "//flutter:config" ]
}
# For using the embedder API as internal implementation detail of an
# embedding.
config("embedder_internal_library_config") {
defines = [
# Use prefixed symbols to avoid collisions with higher level API.
"FLUTTER_API_SYMBOL_PREFIX=Embedder",
# Don't export the embedder.h API surface.
"FLUTTER_NO_EXPORT",
]
}
test_fixtures("fixtures") {
dart_main = "fixtures/main.dart"
fixtures = [
"fixtures/arc_end_caps.png",
"fixtures/compositor.png",
"fixtures/compositor_root_surface_xformation.png",
"fixtures/compositor_software.png",
"fixtures/compositor_with_platform_layer_on_bottom.png",
"fixtures/compositor_with_root_layer_only.png",
"fixtures/compositor_platform_layer_with_no_overlay.png",
"fixtures/dpr_noxform.png",
"fixtures/dpr_xform.png",
"fixtures/gradient.png",
"fixtures/impeller_gl_test.png",
"fixtures/vk_dpr_noxform.png",
"fixtures/vk_gradient.png",
"fixtures/gradient_metal.png",
"fixtures/external_texture_metal.png",
"fixtures/gradient_xform.png",
"fixtures/scene_without_custom_compositor.png",
"fixtures/scene_without_custom_compositor_with_xform.png",
"fixtures/snapshot_large_scene.png",
"fixtures/verifyb143464703.png",
"fixtures/verifyb143464703_soft_noxform.png",
]
}
if (enable_unittests) {
source_set("embedder_unittests_library") {
testonly = true
configs += [
":embedder_gpu_configuration_config",
"//flutter:export_dynamic_symbols",
]
include_dirs = [ "." ]
sources = [
"platform_view_embedder_unittests.cc",
"tests/embedder_config_builder.cc",
"tests/embedder_config_builder.h",
"tests/embedder_frozen.h",
"tests/embedder_test.cc",
"tests/embedder_test.h",
"tests/embedder_test_backingstore_producer.cc",
"tests/embedder_test_backingstore_producer.h",
"tests/embedder_test_compositor.cc",
"tests/embedder_test_compositor.h",
"tests/embedder_test_compositor_software.cc",
"tests/embedder_test_compositor_software.h",
"tests/embedder_test_context.cc",
"tests/embedder_test_context.h",
"tests/embedder_test_context_software.cc",
"tests/embedder_test_context_software.h",
"tests/embedder_unittests_util.cc",
]
public_deps = [
":embedder",
":embedder_gpu_configuration",
":fixtures",
"$dart_src/runtime/bin:elf_loader",
"//flutter/flow",
"//flutter/lib/snapshot",
"//flutter/lib/ui",
"//flutter/runtime",
"//flutter/skia",
"//flutter/testing",
"//flutter/testing:dart",
"//flutter/testing:skia",
"//flutter/third_party/tonic",
]
if (test_enable_gl) {
sources += [
"tests/embedder_test_compositor_gl.cc",
"tests/embedder_test_compositor_gl.h",
"tests/embedder_test_context_gl.cc",
"tests/embedder_test_context_gl.h",
]
public_deps += [
"//flutter/testing:opengl",
"//flutter/third_party/vulkan-deps/vulkan-headers/src:vulkan_headers",
]
}
if (test_enable_metal) {
sources += [
"tests/embedder_test_compositor_metal.cc",
"tests/embedder_test_compositor_metal.h",
"tests/embedder_test_context_metal.cc",
"tests/embedder_test_context_metal.h",
]
public_deps += [ "//flutter/testing:metal" ]
}
if (test_enable_vulkan) {
sources += [
"tests/embedder_test_compositor_vulkan.cc",
"tests/embedder_test_compositor_vulkan.h",
"tests/embedder_test_context_vulkan.cc",
"tests/embedder_test_context_vulkan.h",
]
public_deps += [
"//flutter/testing:vulkan",
"//flutter/vulkan",
"//flutter/vulkan/procs",
]
}
}
executable("embedder_unittests") {
testonly = true
configs += [
":embedder_jit_snapshot_setup",
":embedder_gpu_configuration_config",
"//flutter:export_dynamic_symbols",
]
include_dirs = [ "." ]
sources = [
"tests/embedder_frozen_unittests.cc",
"tests/embedder_unittests.cc",
]
deps = [ ":embedder_unittests_library" ]
if (test_enable_gl) {
sources += [ "tests/embedder_gl_unittests.cc" ]
}
if (test_enable_metal) {
sources += [ "tests/embedder_metal_unittests.mm" ]
}
if (test_enable_vulkan) {
sources += [ "tests/embedder_vk_unittests.cc" ]
}
}
executable("embedder_a11y_unittests") {
testonly = true
configs += [
":embedder_gpu_configuration_config",
"//flutter:export_dynamic_symbols",
]
include_dirs = [ "." ]
sources = [ "tests/embedder_a11y_unittests.cc" ]
deps = [ ":embedder_unittests_library" ]
}
# Tests that build in FLUTTER_ENGINE_NO_PROTOTYPES mode.
executable("embedder_proctable_unittests") {
testonly = true
configs += [
":embedder_gpu_configuration_config",
"//flutter:export_dynamic_symbols",
]
sources = [ "tests/embedder_unittests_proctable.cc" ]
defines = [ "FLUTTER_ENGINE_NO_PROTOTYPES" ]
if (is_win) {
libs = [ "psapi.lib" ]
}
deps = [
":embedder",
":embedder_gpu_configuration",
":fixtures",
"//flutter/lib/snapshot",
"//flutter/testing",
#"//flutter/testing:dart",
#"//flutter/testing:skia",
#"//flutter/third_party/tonic",
#"$dart_src/runtime/bin:elf_loader",
#"//flutter/skia",
]
}
}
shared_library("flutter_engine_library") {
visibility = [ ":*" ]
output_name = "flutter_engine"
ldflags = []
if (is_mac && !embedder_for_target) {
ldflags += [ "-Wl,-install_name,@rpath/FlutterEmbedder.framework/$_framework_binary_subpath" ]
}
if (is_linux) {
ldflags += [ "-Wl,--version-script=" + rebase_path("embedder_exports.lst") ]
}
deps = [ ":embedder" ]
public_configs = [ "//flutter:config" ]
}
copy("copy_headers") {
visibility = [ ":*" ]
sources = [ "embedder.h" ]
outputs = [ "$root_out_dir/flutter_embedder.h" ]
}
if (is_mac && !embedder_for_target) {
_flutter_embedder_framework_dir = "$root_out_dir/FlutterEmbedder.framework"
copy("copy_framework_headers") {
visibility = [ ":*" ]
sources = [ "embedder.h" ]
outputs = [
"$_flutter_embedder_framework_dir/Versions/A/Headers/FlutterEmbedder.h",
]
}
copy("copy_icu") {
visibility = [ ":*" ]
sources = [ "//flutter/third_party/icu/flutter/icudtl.dat" ]
outputs =
[ "$_flutter_embedder_framework_dir/Versions/A/Resources/icudtl.dat" ]
}
action("copy_info_plist") {
script = "//flutter/build/copy_info_plist.py"
visibility = [ ":*" ]
sources = [ "assets/EmbedderInfo.plist" ]
outputs =
[ "$_flutter_embedder_framework_dir/Versions/A/Resources/Info.plist" ]
args = [
"--source",
rebase_path(sources[0]),
"--destination",
rebase_path(outputs[0]),
]
}
copy("copy_module_map") {
visibility = [ ":*" ]
sources = [ "assets/embedder.modulemap" ]
outputs = [
"$_flutter_embedder_framework_dir/Versions/A/Modules/module.modulemap",
]
}
copy("copy_dylib") {
visibility = [ ":*" ]
sources = [ "$root_out_dir/libflutter_engine.dylib" ]
outputs = [ "$_flutter_embedder_framework_dir/$_framework_binary_subpath" ]
deps = [ ":flutter_engine_library" ]
}
action("generate_symlinks") {
visibility = [ ":*" ]
script = "//build/config/mac/package_framework.py"
outputs = [
"$root_build_dir/FlutterEmbedder.stamp",
_flutter_embedder_framework_dir,
"$_flutter_embedder_framework_dir/Resources",
"$_flutter_embedder_framework_dir/Headers",
"$_flutter_embedder_framework_dir/Modules",
]
args = [
"--framework",
"FlutterEmbedder.framework",
"--version",
"A",
"--contents",
"FlutterEmbedder",
"Resources",
"Headers",
"Modules",
"--stamp",
"FlutterEmbedder.stamp",
]
deps = [
":copy_dylib",
":copy_framework_headers",
":copy_icu",
":copy_info_plist",
":copy_module_map",
]
}
group("flutter_embedder_framework") {
visibility = [ ":*" ]
deps = [ ":generate_symlinks" ]
}
}
group("flutter_engine") {
deps = []
build_embedder_api =
current_toolchain == host_toolchain || embedder_for_target
if (build_embedder_api) {
# All platforms require the embedder dylib and headers.
deps += [
":copy_headers",
":flutter_engine_library",
]
# For the Mac, the dylib is packaged in a framework with the appropriate headers.
if (is_mac && !embedder_for_target) {
deps += [ ":flutter_embedder_framework" ]
}
}
}
if (is_mac) {
zip_bundle("flutter_embedder_framework_archive") {
deps = [ ":generate_symlinks" ]
output = "$full_platform_name/FlutterEmbedder.framework.zip"
files = [
{
source = "$root_out_dir/FlutterEmbedder.framework"
destination = "FlutterEmbedder.framework"
},
{
source = "$root_out_dir/FlutterEmbedder.framework/Resources"
destination = "FlutterEmbedder.framework/Resources"
},
{
source = "$root_out_dir/FlutterEmbedder.framework/Headers"
destination = "FlutterEmbedder.framework/Headers"
},
{
source = "$root_out_dir/FlutterEmbedder.framework/Modules"
destination = "FlutterEmbedder.framework/Modules"
},
]
}
}
if (host_os == "linux" || host_os == "win") {
zip_bundle("embedder-archive") {
output =
"$full_target_platform_name/$full_target_platform_name-embedder.zip"
deps = [
"//flutter/shell/platform/embedder:copy_headers",
"//flutter/shell/platform/embedder:flutter_engine_library",
]
files = [
{
source = "$root_out_dir/flutter_embedder.h"
destination = "flutter_embedder.h"
},
]
if (host_os == "linux") {
files += [
{
source = "$root_out_dir/libflutter_engine.so"
destination = "libflutter_engine.so"
},
]
}
if (host_os == "win") {
files += [
{
source = "$root_out_dir/flutter_engine.dll"
destination = "flutter_engine.dll"
},
{
source = "$root_out_dir/flutter_engine.dll.lib"
destination = "flutter_engine.dll.lib"
},
]
}
}
}
| engine/shell/platform/embedder/BUILD.gn/0 | {
"file_path": "engine/shell/platform/embedder/BUILD.gn",
"repo_id": "engine",
"token_count": 7606
} | 480 |
// 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_VIEW_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_VIEW_H_
#include <optional>
#include <unordered_map>
#include <unordered_set>
#include "flutter/flow/embedded_views.h"
#include "flutter/fml/hash_combine.h"
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/embedder/embedder_render_target.h"
namespace flutter {
class EmbedderExternalView {
public:
using PlatformViewID = int64_t;
struct ViewIdentifier {
std::optional<PlatformViewID> platform_view_id;
ViewIdentifier() {}
explicit ViewIdentifier(PlatformViewID view_id)
: platform_view_id(view_id) {}
struct Hash {
constexpr std::size_t operator()(const ViewIdentifier& desc) const {
if (!desc.platform_view_id.has_value()) {
return fml::HashCombine();
}
return fml::HashCombine(desc.platform_view_id.value());
}
};
struct Equal {
constexpr bool operator()(const ViewIdentifier& lhs,
const ViewIdentifier& rhs) const {
return lhs.platform_view_id == rhs.platform_view_id;
}
};
};
struct RenderTargetDescriptor {
SkISize surface_size;
explicit RenderTargetDescriptor(const SkISize& p_surface_size)
: surface_size(p_surface_size) {}
struct Hash {
constexpr std::size_t operator()(
const RenderTargetDescriptor& desc) const {
return fml::HashCombine(desc.surface_size.width(),
desc.surface_size.height());
}
};
struct Equal {
bool operator()(const RenderTargetDescriptor& lhs,
const RenderTargetDescriptor& rhs) const {
return lhs.surface_size == rhs.surface_size;
}
};
};
using ViewIdentifierSet = std::unordered_set<ViewIdentifier,
ViewIdentifier::Hash,
ViewIdentifier::Equal>;
using PendingViews = std::unordered_map<ViewIdentifier,
std::unique_ptr<EmbedderExternalView>,
ViewIdentifier::Hash,
ViewIdentifier::Equal>;
EmbedderExternalView(const SkISize& frame_size,
const SkMatrix& surface_transformation);
EmbedderExternalView(const SkISize& frame_size,
const SkMatrix& surface_transformation,
ViewIdentifier view_identifier,
std::unique_ptr<EmbeddedViewParams> params);
~EmbedderExternalView();
bool IsRootView() const;
bool HasPlatformView() const;
bool HasEngineRenderedContents();
ViewIdentifier GetViewIdentifier() const;
const EmbeddedViewParams* GetEmbeddedViewParams() const;
RenderTargetDescriptor CreateRenderTargetDescriptor() const;
DlCanvas* GetCanvas();
SkISize GetRenderSurfaceSize() const;
bool Render(const EmbedderRenderTarget& render_target,
bool clear_surface = true);
const DlRegion& GetDlRegion() const;
private:
// End the recording of the slice.
// Noop if the slice's recording has already ended.
void TryEndRecording() const;
const SkISize render_surface_size_;
const SkMatrix surface_transformation_;
ViewIdentifier view_identifier_;
std::unique_ptr<EmbeddedViewParams> embedded_view_params_;
std::unique_ptr<DisplayListEmbedderViewSlice> slice_;
std::optional<bool> has_engine_rendered_contents_;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderExternalView);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_VIEW_H_
| engine/shell/platform/embedder/embedder_external_view.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_external_view.h",
"repo_id": "engine",
"token_count": 1636
} | 481 |
// 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_SKIA_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_SKIA_H_
#include "flutter/shell/platform/embedder/embedder_render_target.h"
namespace flutter {
class EmbedderRenderTargetSkia final : public EmbedderRenderTarget {
public:
EmbedderRenderTargetSkia(FlutterBackingStore backing_store,
sk_sp<SkSurface> render_surface,
fml::closure on_release);
// |EmbedderRenderTarget|
~EmbedderRenderTargetSkia() override;
// |EmbedderRenderTarget|
sk_sp<SkSurface> GetSkiaSurface() const override;
// |EmbedderRenderTarget|
impeller::RenderTarget* GetImpellerRenderTarget() const override;
// |EmbedderRenderTarget|
std::shared_ptr<impeller::AiksContext> GetAiksContext() const override;
// |EmbedderRenderTarget|
SkISize GetRenderTargetSize() const override;
private:
sk_sp<SkSurface> render_surface_;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderRenderTargetSkia);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_SKIA_H_
| engine/shell/platform/embedder/embedder_render_target_skia.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_render_target_skia.h",
"repo_id": "engine",
"token_count": 493
} | 482 |
// 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/embedder_surface_vulkan.h"
#include <utility>
#include "flutter/flutter_vma/flutter_skia_vma.h"
#include "flutter/shell/common/shell_io_manager.h"
#include "flutter/shell/gpu/gpu_surface_vulkan.h"
#include "flutter/shell/gpu/gpu_surface_vulkan_delegate.h"
#include "flutter/vulkan/vulkan_skia_proc_table.h"
#include "include/gpu/GrDirectContext.h"
#include "include/gpu/vk/GrVkBackendContext.h"
#include "include/gpu/vk/GrVkExtensions.h"
#include "third_party/skia/include/gpu/ganesh/vk/GrVkDirectContext.h"
namespace flutter {
EmbedderSurfaceVulkan::EmbedderSurfaceVulkan(
uint32_t version,
VkInstance instance,
size_t instance_extension_count,
const char** instance_extensions,
size_t device_extension_count,
const char** device_extensions,
VkPhysicalDevice physical_device,
VkDevice device,
uint32_t queue_family_index,
VkQueue queue,
const VulkanDispatchTable& vulkan_dispatch_table,
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder)
: vk_(fml::MakeRefCounted<vulkan::VulkanProcTable>(
vulkan_dispatch_table.get_instance_proc_address)),
device_(*vk_,
vulkan::VulkanHandle<VkPhysicalDevice>{physical_device},
vulkan::VulkanHandle<VkDevice>{device},
queue_family_index,
vulkan::VulkanHandle<VkQueue>{queue}),
vulkan_dispatch_table_(vulkan_dispatch_table),
external_view_embedder_(std::move(external_view_embedder)) {
// Make sure all required members of the dispatch table are checked.
if (!vulkan_dispatch_table_.get_instance_proc_address ||
!vulkan_dispatch_table_.get_next_image ||
!vulkan_dispatch_table_.present_image) {
return;
}
bool success = vk_->SetupInstanceProcAddresses(
vulkan::VulkanHandle<VkInstance>{instance});
if (!success) {
FML_LOG(ERROR) << "Could not setup instance proc addresses.";
return;
}
success =
vk_->SetupDeviceProcAddresses(vulkan::VulkanHandle<VkDevice>{device});
if (!success) {
FML_LOG(ERROR) << "Could not setup device proc addresses.";
return;
}
if (!vk_->IsValid()) {
FML_LOG(ERROR) << "VulkanProcTable invalid.";
return;
}
main_context_ = CreateGrContext(instance, version, instance_extension_count,
instance_extensions, device_extension_count,
device_extensions, ContextType::kRender);
// TODO(96954): Add a second (optional) queue+family index to the Embedder API
// to allow embedders to specify a dedicated transfer queue for
// use by the resource context. Queue families with graphics
// capability can always be used for memory transferring, but it
// would be advantageous to use a dedicated transter queue here.
resource_context_ = CreateGrContext(
instance, version, instance_extension_count, instance_extensions,
device_extension_count, device_extensions, ContextType::kResource);
valid_ = main_context_ && resource_context_;
}
EmbedderSurfaceVulkan::~EmbedderSurfaceVulkan() {
if (main_context_) {
main_context_->releaseResourcesAndAbandonContext();
}
if (resource_context_) {
resource_context_->releaseResourcesAndAbandonContext();
}
}
// |GPUSurfaceVulkanDelegate|
const vulkan::VulkanProcTable& EmbedderSurfaceVulkan::vk() {
return *vk_;
}
// |GPUSurfaceVulkanDelegate|
FlutterVulkanImage EmbedderSurfaceVulkan::AcquireImage(const SkISize& size) {
return vulkan_dispatch_table_.get_next_image(size);
}
// |GPUSurfaceVulkanDelegate|
bool EmbedderSurfaceVulkan::PresentImage(VkImage image, VkFormat format) {
return vulkan_dispatch_table_.present_image(image, format);
}
// |EmbedderSurface|
bool EmbedderSurfaceVulkan::IsValid() const {
return valid_;
}
// |EmbedderSurface|
std::unique_ptr<Surface> EmbedderSurfaceVulkan::CreateGPUSurface() {
const bool render_to_surface = !external_view_embedder_;
return std::make_unique<GPUSurfaceVulkan>(this, main_context_,
render_to_surface);
}
// |EmbedderSurface|
sk_sp<GrDirectContext> EmbedderSurfaceVulkan::CreateResourceContext() const {
return resource_context_;
}
sk_sp<GrDirectContext> EmbedderSurfaceVulkan::CreateGrContext(
VkInstance instance,
uint32_t version,
size_t instance_extension_count,
const char** instance_extensions,
size_t device_extension_count,
const char** device_extensions,
ContextType context_type) const {
uint32_t skia_features = 0;
if (!device_.GetPhysicalDeviceFeaturesSkia(&skia_features)) {
FML_LOG(ERROR) << "Failed to get physical device features.";
return nullptr;
}
auto get_proc = CreateSkiaGetProc(vk_);
if (get_proc == nullptr) {
FML_LOG(ERROR) << "Failed to create Vulkan getProc for Skia.";
return nullptr;
}
GrVkExtensions extensions;
GrVkBackendContext backend_context = {};
backend_context.fInstance = instance;
backend_context.fPhysicalDevice = device_.GetPhysicalDeviceHandle();
backend_context.fDevice = device_.GetHandle();
backend_context.fQueue = device_.GetQueueHandle();
backend_context.fGraphicsQueueIndex = device_.GetGraphicsQueueIndex();
backend_context.fMinAPIVersion = version;
backend_context.fMaxAPIVersion = version;
backend_context.fFeatures = skia_features;
backend_context.fVkExtensions = &extensions;
backend_context.fGetProc = get_proc;
backend_context.fOwnsInstanceAndDevice = false;
uint32_t vulkan_api_version = version;
sk_sp<skgpu::VulkanMemoryAllocator> allocator =
flutter::FlutterSkiaVulkanMemoryAllocator::Make(
vulkan_api_version, instance, device_.GetPhysicalDeviceHandle(),
device_.GetHandle(), vk_, true);
backend_context.fMemoryAllocator = allocator;
extensions.init(backend_context.fGetProc, backend_context.fInstance,
backend_context.fPhysicalDevice, instance_extension_count,
instance_extensions, device_extension_count,
device_extensions);
GrContextOptions options =
MakeDefaultContextOptions(context_type, GrBackendApi::kVulkan);
options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo;
return GrDirectContexts::MakeVulkan(backend_context, options);
}
} // namespace flutter
| engine/shell/platform/embedder/embedder_surface_vulkan.cc/0 | {
"file_path": "engine/shell/platform/embedder/embedder_surface_vulkan.cc",
"repo_id": "engine",
"token_count": 2439
} | 483 |
// 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_PLATFORM_VIEW_EMBEDDER_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_PLATFORM_VIEW_EMBEDDER_H_
#include <functional>
#include "flow/embedded_views.h"
#include "flutter/fml/macros.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/embedder_surface.h"
#include "flutter/shell/platform/embedder/embedder_surface_software.h"
#include "flutter/shell/platform/embedder/vsync_waiter_embedder.h"
#ifdef SHELL_ENABLE_GL
#include "flutter/shell/platform/embedder/embedder_surface_gl.h"
#include "flutter/shell/platform/embedder/embedder_surface_gl_impeller.h"
#endif
#ifdef SHELL_ENABLE_METAL
#include "flutter/shell/platform/embedder/embedder_surface_metal.h"
#endif
#ifdef SHELL_ENABLE_VULKAN
#include "flutter/shell/platform/embedder/embedder_surface_vulkan.h"
#endif
namespace flutter {
class PlatformViewEmbedder final : public PlatformView {
public:
using UpdateSemanticsCallback =
std::function<void(flutter::SemanticsNodeUpdates update,
flutter::CustomAccessibilityActionUpdates actions)>;
using PlatformMessageResponseCallback =
std::function<void(std::unique_ptr<PlatformMessage>)>;
using ComputePlatformResolvedLocaleCallback =
std::function<std::unique_ptr<std::vector<std::string>>(
const std::vector<std::string>& supported_locale_data)>;
using OnPreEngineRestartCallback = std::function<void()>;
using ChanneUpdateCallback = std::function<void(const std::string&, bool)>;
struct PlatformDispatchTable {
UpdateSemanticsCallback update_semantics_callback; // optional
PlatformMessageResponseCallback
platform_message_response_callback; // optional
VsyncWaiterEmbedder::VsyncCallback vsync_callback; // optional
ComputePlatformResolvedLocaleCallback
compute_platform_resolved_locale_callback;
OnPreEngineRestartCallback on_pre_engine_restart_callback; // optional
ChanneUpdateCallback on_channel_update; // optional
};
// Create a platform view that sets up a software rasterizer.
PlatformViewEmbedder(
PlatformView::Delegate& delegate,
const flutter::TaskRunners& task_runners,
const EmbedderSurfaceSoftware::SoftwareDispatchTable&
software_dispatch_table,
PlatformDispatchTable platform_dispatch_table,
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder);
#ifdef SHELL_ENABLE_GL
// Creates a platform view that sets up an OpenGL rasterizer.
PlatformViewEmbedder(
PlatformView::Delegate& delegate,
const flutter::TaskRunners& task_runners,
std::unique_ptr<EmbedderSurface> embedder_surface,
PlatformDispatchTable platform_dispatch_table,
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder);
#endif
#ifdef SHELL_ENABLE_METAL
// Creates a platform view that sets up an metal rasterizer.
PlatformViewEmbedder(
PlatformView::Delegate& delegate,
const flutter::TaskRunners& task_runners,
std::unique_ptr<EmbedderSurface> embedder_surface,
PlatformDispatchTable platform_dispatch_table,
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder);
#endif
#ifdef SHELL_ENABLE_VULKAN
// Creates a platform view that sets up an Vulkan rasterizer.
PlatformViewEmbedder(
PlatformView::Delegate& delegate,
const flutter::TaskRunners& task_runners,
std::unique_ptr<EmbedderSurfaceVulkan> embedder_surface,
PlatformDispatchTable platform_dispatch_table,
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder);
#endif
~PlatformViewEmbedder() override;
// |PlatformView|
void UpdateSemantics(
flutter::SemanticsNodeUpdates update,
flutter::CustomAccessibilityActionUpdates actions) override;
// |PlatformView|
void HandlePlatformMessage(std::unique_ptr<PlatformMessage> message) override;
// |PlatformView|
std::shared_ptr<PlatformMessageHandler> GetPlatformMessageHandler()
const override;
private:
class EmbedderPlatformMessageHandler;
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder_;
std::unique_ptr<EmbedderSurface> embedder_surface_;
std::shared_ptr<EmbedderPlatformMessageHandler> platform_message_handler_;
PlatformDispatchTable platform_dispatch_table_;
// |PlatformView|
std::unique_ptr<Surface> CreateRenderingSurface() override;
// |PlatformView|
std::shared_ptr<ExternalViewEmbedder> CreateExternalViewEmbedder() override;
// |PlatformView|
std::shared_ptr<impeller::Context> GetImpellerContext() const override;
// |PlatformView|
sk_sp<GrDirectContext> CreateResourceContext() const override;
// |PlatformView|
std::unique_ptr<VsyncWaiter> CreateVSyncWaiter() override;
// |PlatformView|
void OnPreEngineRestart() const override;
// |PlatformView|
std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocales(
const std::vector<std::string>& supported_locale_data) override;
// |PlatformView|
void SendChannelUpdate(const std::string& name, bool listening) override;
FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewEmbedder);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_PLATFORM_VIEW_EMBEDDER_H_
| engine/shell/platform/embedder/platform_view_embedder.h/0 | {
"file_path": "engine/shell/platform/embedder/platform_view_embedder.h",
"repo_id": "engine",
"token_count": 1885
} | 484 |
// 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_compositor.h"
#include <utility>
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/embedder/tests/embedder_assertions.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace flutter {
namespace testing {
EmbedderTestCompositor::EmbedderTestCompositor(SkISize surface_size,
sk_sp<GrDirectContext> context)
: surface_size_(surface_size), context_(std::move(context)) {
FML_CHECK(!surface_size_.isEmpty()) << "Surface size must not be empty";
}
EmbedderTestCompositor::~EmbedderTestCompositor() = default;
static void InvokeAllCallbacks(const std::vector<fml::closure>& callbacks) {
for (const auto& callback : callbacks) {
if (callback) {
callback();
}
}
}
bool EmbedderTestCompositor::CreateBackingStore(
const FlutterBackingStoreConfig* config,
FlutterBackingStore* backing_store_out) {
bool success = backingstore_producer_->Create(config, backing_store_out);
if (success) {
backing_stores_created_++;
InvokeAllCallbacks(on_create_render_target_callbacks_);
}
return success;
}
bool EmbedderTestCompositor::CollectBackingStore(
const FlutterBackingStore* backing_store) {
// We have already set the destruction callback for the various backing
// stores. Our user_data is just the canvas from that backing store and does
// not need to be explicitly collected. Embedders might have some other state
// they want to collect though.
backing_stores_collected_++;
InvokeAllCallbacks(on_collect_render_target_callbacks_);
return true;
}
void EmbedderTestCompositor::SetBackingStoreProducer(
std::unique_ptr<EmbedderTestBackingStoreProducer> backingstore_producer) {
backingstore_producer_ = std::move(backingstore_producer);
}
sk_sp<SkImage> EmbedderTestCompositor::GetLastComposition() {
return last_composition_;
}
bool EmbedderTestCompositor::Present(FlutterViewId view_id,
const FlutterLayer** layers,
size_t layers_count) {
if (!UpdateOffscrenComposition(layers, layers_count)) {
FML_LOG(ERROR)
<< "Could not update the off-screen composition in the test compositor";
return false;
}
// If the test has asked to access the layers and renderers being presented.
// Access the same and present it to the test for its test assertions.
if (present_callback_) {
auto callback = present_callback_;
if (present_callback_is_one_shot_) {
present_callback_ = nullptr;
}
callback(view_id, layers, layers_count);
}
InvokeAllCallbacks(on_present_callbacks_);
return true;
}
void EmbedderTestCompositor::SetNextPresentCallback(
const PresentCallback& next_present_callback) {
SetPresentCallback(next_present_callback, true);
}
void EmbedderTestCompositor::SetPresentCallback(
const PresentCallback& present_callback,
bool one_shot) {
FML_CHECK(!present_callback_);
present_callback_ = present_callback;
present_callback_is_one_shot_ = one_shot;
}
void EmbedderTestCompositor::SetNextSceneCallback(
const NextSceneCallback& next_scene_callback) {
FML_CHECK(!next_scene_callback_);
next_scene_callback_ = next_scene_callback;
}
void EmbedderTestCompositor::SetPlatformViewRendererCallback(
const PlatformViewRendererCallback& callback) {
platform_view_renderer_callback_ = callback;
}
size_t EmbedderTestCompositor::GetPendingBackingStoresCount() const {
FML_CHECK(backing_stores_created_ >= backing_stores_collected_);
return backing_stores_created_ - backing_stores_collected_;
}
size_t EmbedderTestCompositor::GetBackingStoresCreatedCount() const {
return backing_stores_created_;
}
size_t EmbedderTestCompositor::GetBackingStoresCollectedCount() const {
return backing_stores_collected_;
}
void EmbedderTestCompositor::AddOnCreateRenderTargetCallback(
const fml::closure& callback) {
on_create_render_target_callbacks_.push_back(callback);
}
void EmbedderTestCompositor::AddOnCollectRenderTargetCallback(
const fml::closure& callback) {
on_collect_render_target_callbacks_.push_back(callback);
}
void EmbedderTestCompositor::AddOnPresentCallback(
const fml::closure& callback) {
on_present_callbacks_.push_back(callback);
}
sk_sp<GrDirectContext> EmbedderTestCompositor::GetGrContext() {
return context_;
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/embedder/tests/embedder_test_compositor.cc/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_test_compositor.cc",
"repo_id": "engine",
"token_count": 1595
} | 485 |
// 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_software.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/shell/platform/embedder/tests/embedder_test_compositor_software.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 {
EmbedderTestContextSoftware::EmbedderTestContextSoftware(
std::string assets_path)
: EmbedderTestContext(std::move(assets_path)) {}
EmbedderTestContextSoftware::~EmbedderTestContextSoftware() = default;
bool EmbedderTestContextSoftware::Present(const sk_sp<SkImage>& image) {
software_surface_present_count_++;
FireRootSurfacePresentCallbackIfPresent([image] { return image; });
return true;
}
size_t EmbedderTestContextSoftware::GetSurfacePresentCount() const {
return software_surface_present_count_;
}
EmbedderTestContextType EmbedderTestContextSoftware::GetContextType() const {
return EmbedderTestContextType::kSoftwareContext;
}
void EmbedderTestContextSoftware::SetupSurface(SkISize surface_size) {
surface_size_ = surface_size;
}
void EmbedderTestContextSoftware::SetupCompositor() {
FML_CHECK(!compositor_) << "Already set up a compositor in this context.";
compositor_ = std::make_unique<EmbedderTestCompositorSoftware>(surface_size_);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/embedder/tests/embedder_test_context_software.cc/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_test_context_software.cc",
"repo_id": "engine",
"token_count": 560
} | 486 |
// 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_PKG_ZIRCON_SDK_EXT_HANDLE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_H_
#include <zircon/syscalls.h>
#include <optional>
#include <vector>
#include "flutter/fml/memory/ref_counted.h"
#include "handle_waiter.h"
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_wrappable.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
namespace zircon {
namespace dart {
/**
* Handle is the native peer of a Dart object (Handle in dart:zircon)
* that holds an zx_handle_t. It tracks active waiters on handle too.
*/
class Handle : public fml::RefCountedThreadSafe<Handle>,
public tonic::DartWrappable {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_REF_COUNTED_THREAD_SAFE(Handle);
FML_FRIEND_MAKE_REF_COUNTED(Handle);
public:
~Handle();
static void RegisterNatives(tonic::DartLibraryNatives* natives);
static fml::RefPtr<Handle> Create(zx_handle_t handle);
static fml::RefPtr<Handle> Create(zx::handle handle) {
return Create(handle.release());
}
static fml::RefPtr<Handle> Unwrap(Dart_Handle handle) {
return fml::RefPtr<Handle>(
tonic::DartConverter<zircon::dart::Handle*>::FromDart(handle));
}
static Dart_Handle CreateInvalid();
zx_handle_t ReleaseHandle();
bool is_valid() const { return handle_ != ZX_HANDLE_INVALID; }
zx_handle_t handle() const { return handle_; }
zx_koid_t koid() const {
if (!cached_koid_.has_value()) {
zx_info_handle_basic_t info;
zx_status_t status = zx_object_get_info(
handle_, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr);
cached_koid_ = std::optional<zx_koid_t>(
status == ZX_OK ? info.koid : ZX_KOID_INVALID);
}
return cached_koid_.value();
}
zx_status_t Close();
fml::RefPtr<HandleWaiter> AsyncWait(zx_signals_t signals,
Dart_Handle callback);
void ReleaseWaiter(HandleWaiter* waiter);
Dart_Handle Duplicate(uint32_t rights);
Dart_Handle Replace(uint32_t rights);
private:
explicit Handle(zx_handle_t handle);
void RetainDartWrappableReference() const override { AddRef(); }
void ReleaseDartWrappableReference() const override { Release(); }
zx_handle_t handle_;
std::vector<HandleWaiter*> waiters_;
// Cache koid. To guarantee proper cache invalidation, only one `Handle`
// should own the `zx_handle_t` at a time and use of syscalls that invalidate
// the handle should use `ReleaseHandle()`.
mutable std::optional<zx_koid_t> cached_koid_;
};
} // namespace dart
} // namespace zircon
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_H_
| engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.h/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.h",
"repo_id": "engine",
"token_count": 1151
} | 487 |
// 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 "dart_component_controller.h"
#include <fcntl.h>
#include <lib/async-loop/loop.h>
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fd.h>
#include <lib/fdio/namespace.h>
#include <lib/fidl/cpp/string.h>
#include <lib/sys/cpp/service_directory.h>
#include <lib/vfs/cpp/composed_service_dir.h>
#include <lib/vfs/cpp/remote_dir.h>
#include <lib/zx/clock.h>
#include <lib/zx/thread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <zircon/status.h>
#include <regex>
#include <utility>
#include "dart_api.h"
#include "flutter/fml/logging.h"
#include "runtime/dart/utils/files.h"
#include "runtime/dart/utils/handle_exception.h"
#include "runtime/dart/utils/tempfs.h"
#include "third_party/dart/runtime/include/dart_tools_api.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_message_handler.h"
#include "third_party/tonic/dart_microtask_queue.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/logging/dart_error.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "builtin_libraries.h"
using tonic::ToDart;
namespace dart_runner {
namespace {
constexpr char kTmpPath[] = "/tmp";
constexpr zx::duration kIdleWaitDuration = zx::sec(2);
constexpr zx::duration kIdleNotifyDuration = zx::msec(500);
constexpr zx::duration kIdleSlack = zx::sec(1);
void AfterTask(async_loop_t*, void*) {
tonic::DartMicrotaskQueue* queue =
tonic::DartMicrotaskQueue::GetForCurrentThread();
// Verify that the queue exists, as this method could have been called back as
// part of the exit routine, after the destruction of the microtask queue.
if (queue) {
queue->RunMicrotasks();
}
}
constexpr async_loop_config_t kLoopConfig = {
.default_accessors =
{
.getter = async_get_default_dispatcher,
.setter = async_set_default_dispatcher,
},
.make_default_for_current_thread = true,
.epilogue = &AfterTask,
};
// Find the last path of the component.
// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cmx -> hello_dart.cmx
std::string GetLabelFromUrl(const std::string& url) {
for (size_t i = url.length() - 1; i > 0; i--) {
if (url[i] == '/') {
return url.substr(i + 1, url.length() - 1);
}
}
return url;
}
// Find the name of the component.
// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cm -> hello_dart
std::string GetComponentNameFromUrl(const std::string& url) {
const std::string label = GetLabelFromUrl(url);
for (size_t i = 0; i < label.length(); ++i) {
if (label[i] == '.') {
return label.substr(0, i);
}
}
return label;
}
} // namespace
DartComponentController::DartComponentController(
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller)
: loop_(new async::Loop(&kLoopConfig)),
label_(GetLabelFromUrl(start_info.resolved_url())),
url_(start_info.resolved_url()),
runner_incoming_services_(std::move(runner_incoming_services)),
dart_outgoing_dir_(new vfs::PseudoDir()),
start_info_(std::move(start_info)),
binding_(this, std::move(controller)) {
binding_.set_error_handler([this](zx_status_t status) { Kill(); });
// TODO(fxb/84537): This data path is configured based how we build Flutter
// applications in tree currently, but the way we build the Flutter
// application may change. We should avoid assuming the data path and let the
// CML file specify this data path instead.
const std::string component_name = GetComponentNameFromUrl(url_);
data_path_ = "pkg/data/" + component_name;
zx_status_t idle_timer_status =
zx::timer::create(ZX_TIMER_SLACK_LATE, ZX_CLOCK_MONOTONIC, &idle_timer_);
if (idle_timer_status != ZX_OK) {
FML_LOG(INFO) << "Idle timer creation failed: "
<< zx_status_get_string(idle_timer_status);
} else {
idle_wait_.set_object(idle_timer_.get());
idle_wait_.set_trigger(ZX_TIMER_SIGNALED);
idle_wait_.Begin(async_get_default_dispatcher());
}
// Close the runtime_dir channel if we don't intend to serve it. Otherwise any
// access to the runtime_dir will hang forever.
start_info_.clear_runtime_dir();
}
DartComponentController::~DartComponentController() {
if (namespace_) {
fdio_ns_destroy(namespace_);
namespace_ = nullptr;
}
close(stdout_fd_);
close(stderr_fd_);
}
bool DartComponentController::SetUp() {
// Name the thread after the url of the component being launched.
zx::thread::self()->set_property(ZX_PROP_NAME, label_.c_str(), label_.size());
Dart_SetThreadName(label_.c_str());
if (!CreateAndBindNamespace()) {
return false;
}
if (SetUpFromAppSnapshot()) {
FML_LOG(INFO) << url_ << " is running from an app snapshot";
} else if (SetUpFromKernel()) {
FML_LOG(INFO) << url_ << " is running from kernel";
} else {
FML_LOG(ERROR) << "Failed to set up component controller for " << url_;
return false;
}
return true;
}
bool DartComponentController::CreateAndBindNamespace() {
if (!start_info_.has_ns()) {
FML_LOG(ERROR) << "Component start info does not have a namespace.";
return false;
}
const zx_status_t ns_create_status = fdio_ns_create(&namespace_);
if (ns_create_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to create namespace: "
<< zx_status_get_string(ns_create_status);
}
dart_utils::BindTemp(namespace_);
// Bind each directory in start_info's namespace to the controller's namespace
// instance.
for (auto& ns_entry : *start_info_.mutable_ns()) {
// TODO(akbiggs): Under what circumstances does a namespace entry not have a
// path or directory? Should we log an error for these?
if (!ns_entry.has_path() || !ns_entry.has_directory()) {
continue;
}
if (ns_entry.path() == kTmpPath) {
// /tmp is covered by a locally served virtual filesystem.
continue;
}
// We move ownership of the directory & path since RAII is used to keep
// the handle open.
fidl::InterfaceHandle<::fuchsia::io::Directory> dir =
std::move(*ns_entry.mutable_directory());
const std::string path = std::move(*ns_entry.mutable_path());
const zx_status_t ns_bind_status =
fdio_ns_bind(namespace_, path.c_str(), dir.TakeChannel().release());
if (ns_bind_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to bind " << path << " to namespace: "
<< zx_status_get_string(ns_bind_status);
return false;
}
}
dart_outgoing_dir_request_ = dart_outgoing_dir_ptr_.NewRequest();
fuchsia::io::DirectoryHandle dart_public_dir;
// TODO(anmittal): when fixing enumeration using new c++ vfs, make sure that
// flutter_public_dir is only accessed once we receive OnOpen Event.
// That will prevent FL-175 for public directory
fdio_service_connect_at(dart_outgoing_dir_ptr_.channel().get(), "svc",
dart_public_dir.NewRequest().TakeChannel().release());
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
auto composed_service_dir = std::make_unique<vfs::ComposedServiceDir>();
composed_service_dir->set_fallback(std::move(dart_public_dir));
#pragma clang diagnostic pop
// Clone and check if client is servicing the directory.
dart_outgoing_dir_ptr_->Clone(
fuchsia::io::OpenFlags::DESCRIBE |
fuchsia::io::OpenFlags::CLONE_SAME_RIGHTS,
dart_outgoing_dir_ptr_to_check_on_open_.NewRequest());
// Collect our standard set of directories.
std::vector<std::string> other_dirs = {"debug", "ctrl"};
dart_outgoing_dir_ptr_to_check_on_open_.events().OnOpen =
[this, other_dirs](zx_status_t status, auto unused) {
dart_outgoing_dir_ptr_to_check_on_open_.Unbind();
if (status != ZX_OK) {
FML_LOG(ERROR) << "could not bind out directory for dart component("
<< label_ << "): " << zx_status_get_string(status);
return;
}
// add other directories as RemoteDirs.
for (auto& dir_str : other_dirs) {
fuchsia::io::DirectoryHandle dir;
auto request = dir.NewRequest().TakeChannel();
auto status = fdio_open_at(
dart_outgoing_dir_ptr_.channel().get(), dir_str.c_str(),
static_cast<uint32_t>(fuchsia::io::OpenFlags::DIRECTORY |
fuchsia::io::OpenFlags::RIGHT_READABLE),
request.release());
if (status == ZX_OK) {
dart_outgoing_dir_->AddEntry(
dir_str.c_str(),
std::make_unique<vfs::RemoteDir>(dir.TakeChannel()));
} else {
FML_LOG(ERROR) << "could not add out directory entry(" << dir_str
<< ") for flutter component(" << label_
<< "): " << zx_status_get_string(status);
}
}
};
dart_outgoing_dir_ptr_to_check_on_open_.set_error_handler(
[this](zx_status_t status) {
dart_outgoing_dir_ptr_to_check_on_open_.Unbind();
});
// Expose the "Echo" service here on behalf of the running dart program, so
// that integration tests can make use of it.
//
// The flutter/engine repository doesn't support connecting to FIDL from Dart,
// so for the tests sake we connect to the FIDL from C++ here and proxy the
// Echo to dart using native hooks.
composed_service_dir->AddService(
dart::test::Echo::Name_,
std::make_unique<vfs::Service>([this](zx::channel channel,
async_dispatcher_t* dispatcher) {
echo_binding_.AddBinding(
this, fidl::InterfaceRequest<dart::test::Echo>(std::move(channel)));
}));
dart_outgoing_dir_->AddEntry("svc", std::move(composed_service_dir));
if (start_info_.has_outgoing_dir()) {
dart_outgoing_dir_->Serve(
fuchsia::io::OpenFlags::RIGHT_READABLE |
fuchsia::io::OpenFlags::RIGHT_WRITABLE |
fuchsia::io::OpenFlags::DIRECTORY,
start_info_.mutable_outgoing_dir()->TakeChannel());
}
return true;
}
bool DartComponentController::SetUpFromKernel() {
dart_utils::MappedResource manifest;
if (!dart_utils::MappedResource::LoadFromNamespace(
namespace_, data_path_ + "/app.dilplist", manifest)) {
return false;
}
if (!dart_utils::MappedResource::LoadFromNamespace(
nullptr, "/pkg/data/isolate_core_snapshot_data.bin",
isolate_snapshot_data_)) {
return false;
}
std::string str(reinterpret_cast<const char*>(manifest.address()),
manifest.size());
Dart_Handle library = Dart_Null();
for (size_t start = 0; start < manifest.size();) {
size_t end = str.find("\n", start);
if (end == std::string::npos) {
FML_LOG(ERROR) << "Malformed manifest";
Dart_ExitScope();
return false;
}
std::string path = data_path_ + "/" + str.substr(start, end - start);
start = end + 1;
dart_utils::MappedResource kernel;
if (!dart_utils::MappedResource::LoadFromNamespace(namespace_, path,
kernel)) {
FML_LOG(ERROR) << "Cannot load kernel from namespace: " << path;
Dart_ExitScope();
return false;
}
kernel_peices_.emplace_back(std::move(kernel));
}
if (!CreateIsolate(isolate_snapshot_data_.address(),
/*isolate_snapshot_instructions=*/nullptr)) {
return false;
}
Dart_EnterScope();
for (const auto& kernel : kernel_peices_) {
library = Dart_LoadLibraryFromKernel(kernel.address(), kernel.size());
if (Dart_IsError(library)) {
FML_LOG(ERROR) << "Cannot load library from kernel: "
<< Dart_GetError(library);
Dart_ExitScope();
return false;
}
}
Dart_SetRootLibrary(library);
Dart_Handle result = Dart_FinalizeLoading(false);
if (Dart_IsError(result)) {
FML_LOG(ERROR) << "Failed to FinalizeLoading: " << Dart_GetError(result);
Dart_ExitScope();
return false;
}
return true;
}
bool DartComponentController::SetUpFromAppSnapshot() {
#if !defined(AOT_RUNTIME)
return false;
#else
// Load the ELF snapshot as available, and fall back to a blobs snapshot
// otherwise.
const uint8_t *isolate_data, *isolate_instructions;
if (elf_snapshot_.Load(namespace_, data_path_ + "/app_aot_snapshot.so")) {
isolate_data = elf_snapshot_.IsolateData();
isolate_instructions = elf_snapshot_.IsolateInstrs();
if (isolate_data == nullptr || isolate_instructions == nullptr) {
return false;
}
} else {
if (!dart_utils::MappedResource::LoadFromNamespace(
namespace_, data_path_ + "/isolate_snapshot_data.bin",
isolate_snapshot_data_)) {
return false;
}
isolate_data = isolate_snapshot_data_.address();
isolate_instructions = nullptr;
}
return CreateIsolate(isolate_data, isolate_instructions);
#endif // defined(AOT_RUNTIME)
}
bool DartComponentController::CreateIsolate(
const uint8_t* isolate_snapshot_data,
const uint8_t* isolate_snapshot_instructions) {
// Create the isolate from the snapshot.
char* error = nullptr;
// TODO(dart_runner): Pass if we start using tonic's loader.
intptr_t namespace_fd = -1;
// Freed in IsolateShutdownCallback.
auto state = new std::shared_ptr<tonic::DartState>(new tonic::DartState(
namespace_fd, [this](Dart_Handle result) { MessageEpilogue(result); }));
Dart_IsolateFlags isolate_flags;
Dart_IsolateFlagsInitialize(&isolate_flags);
isolate_flags.null_safety = true;
isolate_ = Dart_CreateIsolateGroup(
url_.c_str(), label_.c_str(), isolate_snapshot_data,
isolate_snapshot_instructions, &isolate_flags, state, state, &error);
if (!isolate_) {
FML_LOG(ERROR) << "Dart_CreateIsolateGroup failed: " << error;
return false;
}
state->get()->SetIsolate(isolate_);
tonic::DartMessageHandler::TaskDispatcher dispatcher =
[loop = loop_.get()](auto callback) {
async::PostTask(loop->dispatcher(), std::move(callback));
};
state->get()->message_handler().Initialize(dispatcher);
state->get()->SetReturnCodeCallback(
[this](uint32_t return_code) { return_code_ = return_code; });
return true;
}
void DartComponentController::Run() {
async::PostTask(loop_->dispatcher(), [loop = loop_.get(), app = this] {
if (!app->RunDartMain()) {
loop->Quit();
}
});
loop_->Run();
if (binding_.is_bound()) {
// From the documentation for ComponentController, ZX_OK should be sent when
// the ComponentController receives a termination request. However, if the
// component exited with a non-zero return code, we indicate this by sending
// an INTERNAL epitaph instead.
//
// TODO(fxb/86666): Communicate return code from the ComponentController
// once v2 has support.
if (return_code_ == 0) {
binding_.Close(ZX_OK);
} else {
FML_LOG(ERROR) << "Component exited with non-zero return code: "
<< return_code_;
binding_.Close(zx_status_t(fuchsia::component::Error::INTERNAL));
}
}
}
bool DartComponentController::RunDartMain() {
FML_CHECK(namespace_ != nullptr);
Dart_EnterScope();
tonic::DartMicrotaskQueue::StartForCurrentThread();
// TODO(fxb/88384): Create a file descriptor for each component that is
// launched and listen for anything that is written to the component. When
// something is written to the component, forward that message along to the
// Fuchsia logger and decorate it with the tag that it came from the
// component.
stdout_fd_ = fileno(stdout);
stderr_fd_ = fileno(stderr);
InitBuiltinLibrariesForIsolate(url_, namespace_, stdout_fd_, stderr_fd_,
dart_outgoing_dir_request_.TakeChannel(),
false /* service_isolate */);
Dart_ExitScope();
Dart_ExitIsolate();
char* error = Dart_IsolateMakeRunnable(isolate_);
if (error != nullptr) {
Dart_EnterIsolate(isolate_);
Dart_ShutdownIsolate();
FML_LOG(ERROR) << "Unable to make isolate runnable: " << error;
free(error);
return false;
}
Dart_EnterIsolate(isolate_);
Dart_EnterScope();
// TODO(fxb/88383): Support argument passing.
Dart_Handle corelib = Dart_LookupLibrary(ToDart("dart:core"));
Dart_Handle string_type =
Dart_GetNonNullableType(corelib, ToDart("String"), 0, NULL);
Dart_Handle dart_arguments =
Dart_NewListOfTypeFilled(string_type, Dart_EmptyString(), 0);
if (Dart_IsError(dart_arguments)) {
FML_LOG(ERROR) << "Failed to allocate Dart arguments list: "
<< Dart_GetError(dart_arguments);
Dart_ExitScope();
return false;
}
Dart_Handle user_main = Dart_GetField(Dart_RootLibrary(), ToDart("main"));
if (Dart_IsError(user_main)) {
FML_LOG(ERROR) << "Failed to locate user_main in the root library: "
<< Dart_GetError(user_main);
Dart_ExitScope();
return false;
}
Dart_Handle fuchsia_lib = Dart_LookupLibrary(tonic::ToDart("dart:fuchsia"));
if (Dart_IsError(fuchsia_lib)) {
FML_LOG(ERROR) << "Failed to locate dart:fuchsia: "
<< Dart_GetError(fuchsia_lib);
Dart_ExitScope();
return false;
}
Dart_Handle main_result = tonic::DartInvokeField(
fuchsia_lib, "_runUserMainForDartRunner", {user_main, dart_arguments});
if (Dart_IsError(main_result)) {
auto dart_state = tonic::DartState::Current();
if (!dart_state->has_set_return_code()) {
// The program hasn't set a return code meaning this exit is unexpected.
FML_LOG(ERROR) << Dart_GetError(main_result);
return_code_ = tonic::GetErrorExitCode(main_result);
dart_utils::HandleIfException(runner_incoming_services_, url_,
main_result);
}
Dart_ExitScope();
return false;
}
Dart_ExitScope();
return true;
}
void DartComponentController::EchoString(fidl::StringPtr value,
EchoStringCallback callback) {
Dart_EnterScope();
Dart_Handle builtin_lib = Dart_LookupLibrary(ToDart("dart:fuchsia.builtin"));
FML_CHECK(!tonic::CheckAndHandleError(builtin_lib));
Dart_Handle receive_echo_string = ToDart("_receiveEchoString");
Dart_Handle string_to_echo =
value.has_value() ? tonic::ToDart(*value) : Dart_Null();
Dart_Handle result =
Dart_Invoke(builtin_lib, receive_echo_string, 1, &string_to_echo);
FML_CHECK(!tonic::CheckAndHandleError(result));
fidl::StringPtr echo_string;
if (!Dart_IsNull(result)) {
echo_string = tonic::StdStringFromDart(result);
}
callback(std::move(echo_string));
Dart_ExitScope();
}
void DartComponentController::Kill() {
if (Dart_CurrentIsolate()) {
tonic::DartMicrotaskQueue* queue =
tonic::DartMicrotaskQueue::GetForCurrentThread();
if (queue) {
queue->Destroy();
}
loop_->Quit();
// TODO(rosswang): The docs warn of threading issues if doing this again,
// but without this, attempting to shut down the isolate finalizes app
// contexts that can't tell a shutdown is in progress and so fatal.
Dart_SetMessageNotifyCallback(nullptr);
Dart_ShutdownIsolate();
}
}
void DartComponentController::Stop() {
Kill();
}
void DartComponentController::MessageEpilogue(Dart_Handle result) {
auto dart_state = tonic::DartState::Current();
// If the Dart program has set a return code, then it is intending to shut
// down by way of a fatal error, and so there is no need to override
// return_code_.
if (dart_state->has_set_return_code()) {
Dart_ShutdownIsolate();
return;
}
dart_utils::HandleIfException(runner_incoming_services_, url_, result);
// Otherwise, see if there was any other error.
return_code_ = tonic::GetErrorExitCode(result);
if (return_code_ != 0) {
Dart_ShutdownIsolate();
return;
}
idle_start_ = zx::clock::get_monotonic();
zx_status_t status =
idle_timer_.set(idle_start_ + kIdleWaitDuration, kIdleSlack);
if (status != ZX_OK) {
FML_LOG(INFO) << "Idle timer set failed: " << zx_status_get_string(status);
}
}
void DartComponentController::OnIdleTimer(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal* signal) {
if ((status != ZX_OK) || !(signal->observed & ZX_TIMER_SIGNALED) ||
!Dart_CurrentIsolate()) {
// Timer closed or isolate shutdown.
return;
}
zx::time deadline = idle_start_ + kIdleWaitDuration;
zx::time now = zx::clock::get_monotonic();
if (now >= deadline) {
// No Dart message has been processed for kIdleWaitDuration: assume we'll
// stay idle for kIdleNotifyDuration.
Dart_NotifyIdle((now + kIdleNotifyDuration).get());
idle_start_ = zx::time(0);
idle_timer_.cancel(); // De-assert signal.
} else {
// Early wakeup or message pushed idle time forward: reschedule.
zx_status_t status = idle_timer_.set(deadline, kIdleSlack);
if (status != ZX_OK) {
FML_LOG(INFO) << "Idle timer set failed: "
<< zx_status_get_string(status);
}
}
wait->Begin(dispatcher); // ignore errors
}
} // namespace dart_runner
| engine/shell/platform/fuchsia/dart_runner/dart_component_controller.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/dart_component_controller.cc",
"repo_id": "engine",
"token_count": 8589
} | 488 |
{
"comment:0": "NOTE: THIS FILE IS GENERATED. DO NOT EDIT.",
"comment:1": "Instead modify 'flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.yaml' and follow the instructions therein.",
"dart_runner": {
"include": [
{
"path": "../../../../../../third_party/dart/sdk/lib/libraries.json",
"target": "vm_common"
}
],
"libraries": {
"fuchsia.builtin": {
"uri": "../embedder/builtin.dart"
},
"zircon": {
"uri": "../../dart-pkg/zircon/lib/zircon.dart"
},
"zircon_ffi": {
"uri": "../../dart-pkg/zircon_ffi/lib/zircon_ffi.dart"
},
"fuchsia": {
"uri": "../../dart-pkg/fuchsia/lib/fuchsia.dart"
}
}
}
} | engine/shell/platform/fuchsia/dart_runner/kernel/libraries.json/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/kernel/libraries.json",
"repo_id": "engine",
"token_count": 375
} | 489 |
// 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: [
"sys/testing/gtest_runner.shard.cml",
"sys/component/realm_builder_absolute.shard.cml",
// This test needs both the vulkan facet and the hermetic-tier-2 facet,
// so we are forced to make it a system test.
"sys/testing/system-test.shard.cml",
],
program: {
binary: "bin/app",
},
offer: [
{
// Offer capabilities needed by components in this test realm.
// Keep it minimal, describe only what's actually needed.
protocol: [
"fuchsia.inspect.InspectSink",
"fuchsia.logger.LogSink",
"fuchsia.sysmem.Allocator",
"fuchsia.tracing.provider.Registry",
"fuchsia.vulkan.loader.Loader",
"fuchsia.posix.socket.Provider",
"fuchsia.intl.PropertyProvider",
],
from: "parent",
to: "#realm_builder",
},
{
directory: "pkg",
subdir: "config",
as: "config-data",
from: "framework",
to: "#realm_builder",
},
],
// TODO(https://fxbug.dev/114584): Figure out how to bring these in as deps (if possible oot).
facets: {
"fuchsia.test": {
"deprecated-allowed-packages": [
"dart_aot_echo_server",
"test_manager",
"oot_dart_aot_runner"
],
},
},
}
| engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/meta/dart-aot-runner-integration-test.cml/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/meta/dart-aot-runner-integration-test.cml",
"repo_id": "engine",
"token_count": 835
} | 490 |
Flutter Application Runner
==========================
Implements the `fuchsia::component::runner::ComponentRunner` FIDL interface to
launch and run multiple Flutter applications within the same process in Fuchsia.
| engine/shell/platform/fuchsia/flutter/README.md/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/README.md",
"repo_id": "engine",
"token_count": 49
} | 491 |
// 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 "file_in_namespace_buffer.h"
#include <fuchsia/io/cpp/fidl.h>
#include <lib/fdio/directory.h>
#include <zircon/status.h>
#include "flutter/fml/trace_event.h"
#include "runtime/dart/utils/files.h"
#include "runtime/dart/utils/handle_exception.h"
#include "runtime/dart/utils/mapped_resource.h"
#include "runtime/dart/utils/tempfs.h"
#include "runtime/dart/utils/vmo.h"
namespace flutter_runner {
FileInNamespaceBuffer::FileInNamespaceBuffer(int namespace_fd,
const char* path,
bool executable)
: address_(nullptr), size_(0) {
fuchsia::mem::Buffer buffer;
if (!dart_utils::VmoFromFilenameAt(namespace_fd, path, executable, &buffer) ||
buffer.size == 0) {
return;
}
uint32_t flags = ZX_VM_PERM_READ;
if (executable) {
flags |= ZX_VM_PERM_EXECUTE;
}
uintptr_t addr;
const zx_status_t status =
zx::vmar::root_self()->map(flags, 0, buffer.vmo, 0, buffer.size, &addr);
if (status != ZX_OK) {
FML_LOG(FATAL) << "Failed to map " << path << ": "
<< zx_status_get_string(status);
}
address_ = reinterpret_cast<void*>(addr);
size_ = buffer.size;
}
FileInNamespaceBuffer::~FileInNamespaceBuffer() {
if (address_ != nullptr) {
zx::vmar::root_self()->unmap(reinterpret_cast<uintptr_t>(address_), size_);
address_ = nullptr;
size_ = 0;
}
}
const uint8_t* FileInNamespaceBuffer::GetMapping() const {
return reinterpret_cast<const uint8_t*>(address_);
}
size_t FileInNamespaceBuffer::GetSize() const {
return size_;
}
bool FileInNamespaceBuffer::IsDontNeedSafe() const {
return true;
}
std::unique_ptr<fml::Mapping> LoadFile(int namespace_fd,
const char* path,
bool executable) {
FML_TRACE_EVENT("flutter", "LoadFile", "path", path);
return std::make_unique<FileInNamespaceBuffer>(namespace_fd, path,
executable);
}
std::unique_ptr<fml::FileMapping> MakeFileMapping(const char* path,
bool executable) {
auto flags = fuchsia::io::OpenFlags::RIGHT_READABLE;
if (executable) {
flags |= fuchsia::io::OpenFlags::RIGHT_EXECUTABLE;
}
// The returned file descriptor is compatible with standard posix operations
// such as close, mmap, etc. We only need to treat open/open_at specially.
int fd;
const zx_status_t status =
fdio_open_fd(path, static_cast<uint32_t>(flags), &fd);
if (status != ZX_OK) {
return nullptr;
}
using Protection = fml::FileMapping::Protection;
std::initializer_list<Protection> protection_execute = {Protection::kRead,
Protection::kExecute};
std::initializer_list<Protection> protection_read = {Protection::kRead};
auto mapping = std::make_unique<fml::FileMapping>(
fml::UniqueFD{fd}, executable ? protection_execute : protection_read);
if (!mapping->IsValid()) {
return nullptr;
}
return mapping;
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/file_in_namespace_buffer.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/file_in_namespace_buffer.cc",
"repo_id": "engine",
"token_count": 1427
} | 492 |
# 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: ../../../tools/analysis_options.yaml
analyzer:
errors:
avoid_catches_without_on_clauses: ignore
cascade_invocations: ignore
only_throw_errors: ignore # adds noise to error messages
prefer_foreach: ignore # for-in is preferable to closurization
prefer_single_quotes: ignore
| engine/shell/platform/fuchsia/flutter/kernel/analysis_options.yaml/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/kernel/analysis_options.yaml",
"repo_id": "engine",
"token_count": 142
} | 493 |
// 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_PLATFORM_VIEW_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_PLATFORM_VIEW_H_
#include <fuchsia/ui/composition/cpp/fidl.h>
#include <fuchsia/ui/input/cpp/fidl.h>
#include <fuchsia/ui/input3/cpp/fidl.h>
#include <fuchsia/ui/pointer/cpp/fidl.h>
#include <fuchsia/ui/test/input/cpp/fidl.h>
#include <lib/fidl/cpp/binding.h>
#include <lib/fit/function.h>
#include <lib/sys/cpp/service_directory.h>
#include <array>
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/shell/platform/fuchsia/flutter/external_view_embedder.h"
#include "flow/embedded_views.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/time/time_delta.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/platform/fuchsia/flutter/keyboard.h"
#include "flutter/shell/platform/fuchsia/flutter/vsync_waiter.h"
#include "focus_delegate.h"
#include "pointer_delegate.h"
#include "pointer_injector_delegate.h"
#include "text_delegate.h"
namespace flutter_runner {
using OnEnableWireframeCallback = fit::function<void(bool)>;
using ViewCallback = std::function<void()>;
using OnUpdateViewCallback = fit::function<void(int64_t, SkRect, bool, bool)>;
using OnCreateSurfaceCallback =
fit::function<std::unique_ptr<flutter::Surface>()>;
using OnSemanticsNodeUpdateCallback =
fit::function<void(flutter::SemanticsNodeUpdates, float)>;
using OnRequestAnnounceCallback = fit::function<void(std::string)>;
using OnCreateViewCallback =
fit::function<void(int64_t, ViewCallback, ViewCreatedCallback, bool, bool)>;
using OnDestroyViewCallback = fit::function<void(int64_t, ViewIdCallback)>;
// we use an std::function here because the fit::funtion causes problems with
// std:bind since HandleFuchsiaShaderWarmupChannelPlatformMessage takes one of
// these as its first argument.
using OnShaderWarmupCallback =
std::function<void(const std::vector<std::string>&,
std::function<void(uint32_t)>,
uint64_t,
uint64_t)>;
// PlatformView is the per-engine component residing on the platform thread that
// is responsible for all platform specific integrations -- particularly
// integration with the platform's accessibility, input, and windowing features.
//
// PlatformView communicates with the Dart code via "platform messages" handled
// in HandlePlatformMessage. This communication is bidirectional. Platform
// messages are notably responsible for communication related to input and
// external views / windowing.
class PlatformView : public flutter::PlatformView {
public:
PlatformView(
flutter::PlatformView::Delegate& delegate,
flutter::TaskRunners task_runners,
fuchsia::ui::views::ViewRef view_ref,
std::shared_ptr<flutter::ExternalViewEmbedder> external_view_embedder,
fuchsia::ui::input::ImeServiceHandle ime_service,
fuchsia::ui::input3::KeyboardHandle keyboard,
fuchsia::ui::pointer::TouchSourceHandle touch_source,
fuchsia::ui::pointer::MouseSourceHandle mouse_source,
fuchsia::ui::views::FocuserHandle focuser,
fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused,
fuchsia::ui::composition::ParentViewportWatcherHandle
parent_viewport_watcher,
fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry,
OnEnableWireframeCallback wireframe_enabled_callback,
OnCreateViewCallback on_create_view_callback,
OnUpdateViewCallback on_update_view_callback,
OnDestroyViewCallback on_destroy_view_callback,
OnCreateSurfaceCallback on_create_surface_callback,
OnSemanticsNodeUpdateCallback on_semantics_node_update_callback,
OnRequestAnnounceCallback on_request_announce_callback,
OnShaderWarmupCallback on_shader_warmup_callback,
AwaitVsyncCallback await_vsync_callback,
AwaitVsyncForSecondaryCallbackCallback
await_vsync_for_secondary_callback_callback,
std::shared_ptr<sys::ServiceDirectory> dart_application_svc);
~PlatformView() override;
void OnGetLayout(fuchsia::ui::composition::LayoutInfo info);
void OnParentViewportStatus(
fuchsia::ui::composition::ParentViewportStatus status);
void OnChildViewStatus(uint64_t content_id,
fuchsia::ui::composition::ChildViewStatus status);
void OnChildViewViewRef(uint64_t content_id,
uint64_t view_id,
fuchsia::ui::views::ViewRef view_ref);
// |flutter::PlatformView|
void SetSemanticsEnabled(bool enabled) override;
// |flutter::PlatformView|
std::shared_ptr<flutter::ExternalViewEmbedder> CreateExternalViewEmbedder()
override;
private:
void RegisterPlatformMessageHandlers();
bool OnHandlePointerEvent(const fuchsia::ui::input::PointerEvent& pointer);
bool OnHandleFocusEvent(const fuchsia::ui::input::FocusEvent& focus);
// |flutter::PlatformView|
std::unique_ptr<flutter::VsyncWaiter> CreateVSyncWaiter() override;
// |flutter::PlatformView|
std::unique_ptr<flutter::Surface> CreateRenderingSurface() override;
// |flutter::PlatformView|
void HandlePlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message) override;
// |flutter::PlatformView|
void UpdateSemantics(
flutter::SemanticsNodeUpdates update,
flutter::CustomAccessibilityActionUpdates actions) override;
// Channel handler for kAccessibilityChannel. This is currently not
// being used, but it is necessary to handle accessibility messages
// that are sent by Flutter when semantics is enabled.
bool HandleAccessibilityChannelPlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message);
// Channel handler for kFlutterPlatformChannel
bool HandleFlutterPlatformChannelPlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message);
// Channel handler for kPlatformViewsChannel.
bool HandleFlutterPlatformViewsChannelPlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message);
// Channel handler for kFuchsiaShaderWarmupChannel.
static bool HandleFuchsiaShaderWarmupChannelPlatformMessage(
OnShaderWarmupCallback on_shader_warmup_callback,
std::unique_ptr<flutter::PlatformMessage> message);
// Channel handler for kFuchsiaInputTestChannel.
bool HandleFuchsiaInputTestChannelPlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message);
// Channel handler for kFuchsiaChildViewChannel.
bool HandleFuchsiaChildViewChannelPlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message);
void OnCreateView(ViewCallback on_view_created,
int64_t view_id_raw,
bool hit_testable,
bool focusable);
void OnDisposeView(int64_t view_id_raw);
// Sends a 'View.viewConnected' platform message over 'flutter/platform_views'
// channel when a view gets created.
void OnChildViewConnected(uint64_t content_id);
// Sends a 'View.viewDisconnected' platform message over
// 'flutter/platform_views' channel when a view gets destroyed or the child
// view watcher channel of a view closes.
void OnChildViewDisconnected(uint64_t content_id);
// Utility function for coordinate massaging.
std::array<float, 2> ClampToViewSpace(const float x, const float y) const;
// Logical size and origin, and logical->physical ratio. These are optional
// to provide an "unset" state during program startup, before Scenic has sent
// any metrics-related events to provide initial values for these.
//
// The engine internally uses a default size of (0.f 0.f) with a default 1.f
// ratio, so there is no need to emit events until Scenic has actually sent a
// valid size and ratio.
std::optional<std::array<float, 2>> view_logical_size_;
std::optional<std::array<float, 2>> view_logical_origin_;
std::optional<float> view_pixel_ratio_;
std::shared_ptr<flutter::ExternalViewEmbedder> external_view_embedder_;
std::shared_ptr<FocusDelegate> focus_delegate_;
std::shared_ptr<PointerDelegate> pointer_delegate_;
std::unique_ptr<PointerInjectorDelegate> pointer_injector_delegate_;
// Text delegate is responsible for handling keyboard input and text editing.
std::unique_ptr<TextDelegate> text_delegate_;
std::set<int> down_pointers_;
std::map<std::string /* channel */,
std::function<bool /* response_handled */ (
std::unique_ptr<
flutter::PlatformMessage> /* message */)> /* handler */>
platform_message_handlers_;
// These are the channels that aren't registered and have been notified as
// such. Notifying via logs multiple times results in log-spam. See:
// https://github.com/flutter/flutter/issues/55966
std::set<std::string /* channel */> unregistered_channels_;
OnEnableWireframeCallback wireframe_enabled_callback_;
OnUpdateViewCallback on_update_view_callback_;
OnCreateSurfaceCallback on_create_surface_callback_;
OnSemanticsNodeUpdateCallback on_semantics_node_update_callback_;
OnRequestAnnounceCallback on_request_announce_callback_;
OnCreateViewCallback on_create_view_callback_;
OnDestroyViewCallback on_destroy_view_callback_;
OnShaderWarmupCallback on_shader_warmup_callback_;
AwaitVsyncCallback await_vsync_callback_;
AwaitVsyncForSecondaryCallbackCallback
await_vsync_for_secondary_callback_callback_;
// Proxies for input tests.
fuchsia::ui::test::input::TouchInputListenerPtr touch_input_listener_;
fuchsia::ui::test::input::KeyboardInputListenerPtr keyboard_input_listener_;
fuchsia::ui::test::input::MouseInputListenerPtr mouse_input_listener_;
// Component's service directory.
std::shared_ptr<sys::ServiceDirectory> dart_application_svc_;
// child_view_ids_ maintains a persistent mapping from Flatland ContentId's to
// flutter view ids, which are really zx_handle_t of ViewCreationToken.
struct ChildViewInfo {
ChildViewInfo(zx_handle_t token,
fuchsia::ui::composition::ChildViewWatcherPtr watcher)
: view_id(token), child_view_watcher(std::move(watcher)) {}
zx_handle_t view_id;
fuchsia::ui::composition::ChildViewWatcherPtr child_view_watcher;
};
std::unordered_map<uint64_t /*fuchsia::ui::composition::ContentId*/,
ChildViewInfo>
child_view_info_;
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher_;
fuchsia::ui::composition::ParentViewportStatus parent_viewport_status_;
fml::WeakPtrFactory<PlatformView> weak_factory_; // Must be the last member.
FML_DISALLOW_COPY_AND_ASSIGN(PlatformView);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_PLATFORM_VIEW_H_
| engine/shell/platform/fuchsia/flutter/platform_view.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/platform_view.h",
"repo_id": "engine",
"token_count": 3780
} | 494 |
// 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 "software_surface.h"
#include <lib/async/default.h>
#include <zircon/rights.h>
#include <zircon/status.h>
#include <zircon/types.h>
#include <cmath>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "fuchsia/sysmem/cpp/fidl.h"
#include "include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "../runtime/dart/utils/inlines.h"
namespace flutter_runner {
namespace {
constexpr SkColorType kSkiaColorType = kRGBA_8888_SkColorType;
uint32_t BytesPerRow(const fuchsia::sysmem::SingleBufferSettings& settings,
uint32_t bytes_per_pixel,
uint32_t image_width) {
const uint32_t bytes_per_row_divisor =
settings.image_format_constraints.bytes_per_row_divisor;
const uint32_t min_bytes_per_row =
settings.image_format_constraints.min_bytes_per_row;
const uint32_t unrounded_bytes_per_row =
std::max(image_width * bytes_per_pixel, min_bytes_per_row);
const uint32_t roundup_bytes =
unrounded_bytes_per_row % bytes_per_row_divisor;
return unrounded_bytes_per_row + roundup_bytes;
}
} // namespace
SoftwareSurface::SoftwareSurface(
fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
const SkISize& size)
: wait_for_surface_read_finished_(this) {
FML_CHECK(flatland_allocator.is_bound());
if (!SetupSkiaSurface(sysmem_allocator, flatland_allocator, size)) {
FML_LOG(ERROR) << "Could not create render surface.";
return;
}
if (!CreateFences()) {
FML_LOG(ERROR) << "Could not create signal fences.";
return;
}
wait_for_surface_read_finished_.set_object(release_event_.get());
wait_for_surface_read_finished_.set_trigger(ZX_EVENT_SIGNALED);
Reset();
valid_ = true;
}
SoftwareSurface::~SoftwareSurface() {
release_image_callback_();
wait_for_surface_read_finished_.Cancel();
wait_for_surface_read_finished_.set_object(ZX_HANDLE_INVALID);
}
bool SoftwareSurface::IsValid() const {
return valid_;
}
SkISize SoftwareSurface::GetSize() const {
if (!valid_) {
return SkISize::Make(0, 0);
}
return SkISize::Make(sk_surface_->width(), sk_surface_->height());
}
bool SoftwareSurface::CreateFences() {
if (zx::event::create(0, &acquire_event_) != ZX_OK) {
FML_LOG(ERROR) << "Failed to create acquire event.";
return false;
}
if (zx::event::create(0, &release_event_) != ZX_OK) {
FML_LOG(ERROR) << "Failed to create release event.";
return false;
}
return true;
}
bool SoftwareSurface::SetupSkiaSurface(
fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
const SkISize& size) {
if (size.isEmpty()) {
FML_LOG(ERROR) << "Failed to allocate surface, size is empty.";
return false;
}
// Allocate a "local" sysmem token to represent flutter's handle to the
// sysmem buffer.
fuchsia::sysmem::BufferCollectionTokenSyncPtr local_token;
zx_status_t allocate_status =
sysmem_allocator->AllocateSharedCollection(local_token.NewRequest());
if (allocate_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to allocate collection: "
<< zx_status_get_string(allocate_status);
return false;
}
// Create a single Duplicate of the token and Sync it; the single duplicate
// token represents scenic's handle to the sysmem buffer.
std::vector<fuchsia::sysmem::BufferCollectionTokenHandle> duplicate_tokens;
zx_status_t duplicate_status = local_token->DuplicateSync(
std::vector<zx_rights_t>{ZX_RIGHT_SAME_RIGHTS}, &duplicate_tokens);
if (duplicate_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to duplicate collection token: "
<< zx_status_get_string(duplicate_status);
return false;
}
if (duplicate_tokens.size() != 1u) {
FML_LOG(ERROR) << "Failed to duplicate collection token: Incorrect number "
"of tokens returned.";
return false;
}
auto scenic_token = std::move(duplicate_tokens[0]);
// Register the sysmem token with flatland.
//
// This binds the sysmem token to a composition token, which is used later
// to associate the rendering surface with a specific flatland Image.
fuchsia::ui::composition::BufferCollectionExportToken export_token;
zx_status_t token_create_status =
zx::eventpair::create(0, &export_token.value, &import_token_.value);
if (token_create_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to create flatland export token: "
<< zx_status_get_string(token_create_status);
return false;
}
fuchsia::ui::composition::RegisterBufferCollectionArgs args;
args.set_export_token(std::move(export_token));
args.set_buffer_collection_token(std::move(scenic_token));
args.set_usage(
fuchsia::ui::composition::RegisterBufferCollectionUsage::DEFAULT);
flatland_allocator->RegisterBufferCollection(
std::move(args),
[](fuchsia::ui::composition::Allocator_RegisterBufferCollection_Result
result) {
if (result.is_err()) {
FML_LOG(ERROR)
<< "RegisterBufferCollection call to Scenic Allocator failed.";
}
});
// Acquire flutter's local handle to the sysmem buffer.
fuchsia::sysmem::BufferCollectionSyncPtr buffer_collection;
zx_status_t bind_status = sysmem_allocator->BindSharedCollection(
std::move(local_token), buffer_collection.NewRequest());
if (bind_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to bind collection token: "
<< zx_status_get_string(bind_status);
return false;
}
// Set flutter's constraints on the sysmem buffer. Software rendering only
// requires CPU access to the surface and a basic R8G8B8A8 pixel format.
fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.min_buffer_count = 1;
constraints.usage.cpu =
fuchsia::sysmem::cpuUsageWrite | fuchsia::sysmem::cpuUsageWriteOften;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints.physically_contiguous_required = false;
constraints.buffer_memory_constraints.secure_required = false;
constraints.buffer_memory_constraints.ram_domain_supported = true;
constraints.buffer_memory_constraints.cpu_domain_supported = true;
constraints.buffer_memory_constraints.inaccessible_domain_supported = false;
constraints.image_format_constraints_count = 1;
fuchsia::sysmem::ImageFormatConstraints& image_constraints =
constraints.image_format_constraints[0];
image_constraints = fuchsia::sysmem::ImageFormatConstraints();
image_constraints.min_coded_width = static_cast<uint32_t>(size.fWidth);
image_constraints.min_coded_height = static_cast<uint32_t>(size.fHeight);
image_constraints.min_bytes_per_row = static_cast<uint32_t>(size.fWidth) * 4;
image_constraints.pixel_format.type =
fuchsia::sysmem::PixelFormatType::R8G8B8A8;
image_constraints.color_spaces_count = 1;
image_constraints.color_space[0].type = fuchsia::sysmem::ColorSpaceType::SRGB;
image_constraints.pixel_format.has_format_modifier = true;
image_constraints.pixel_format.format_modifier.value =
fuchsia::sysmem::FORMAT_MODIFIER_LINEAR;
zx_status_t set_constraints_status =
buffer_collection->SetConstraints(true, constraints);
if (set_constraints_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to set constraints: "
<< zx_status_get_string(set_constraints_status);
return false;
}
// Wait for sysmem to allocate, now that constraints are set.
fuchsia::sysmem::BufferCollectionInfo_2 buffer_collection_info;
zx_status_t allocation_status = ZX_OK;
zx_status_t wait_for_allocated_status =
buffer_collection->WaitForBuffersAllocated(&allocation_status,
&buffer_collection_info);
if (allocation_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to allocate: "
<< zx_status_get_string(allocation_status);
return false;
}
if (wait_for_allocated_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to wait for allocate: "
<< zx_status_get_string(wait_for_allocated_status);
return false;
}
// Cache the allocated surface VMO and metadata.
FML_CHECK(buffer_collection_info.settings.buffer_settings.size_bytes != 0);
FML_CHECK(buffer_collection_info.buffers[0].vmo != ZX_HANDLE_INVALID);
surface_vmo_ = std::move(buffer_collection_info.buffers[0].vmo);
surface_size_bytes_ =
buffer_collection_info.settings.buffer_settings.size_bytes;
if (buffer_collection_info.settings.buffer_settings.coherency_domain ==
fuchsia::sysmem::CoherencyDomain::RAM) {
// RAM coherency domain requires a cache clean when writes are finished.
needs_cache_clean_ = true;
}
// Map the allocated buffer to the CPU.
uint8_t* vmo_base = nullptr;
zx_status_t buffer_map_status = zx::vmar::root_self()->map(
ZX_VM_PERM_WRITE | ZX_VM_PERM_READ, 0, surface_vmo_, 0,
surface_size_bytes_, reinterpret_cast<uintptr_t*>(&vmo_base));
if (buffer_map_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to map buffer memory: "
<< zx_status_get_string(buffer_map_status);
return false;
}
// Now that the buffer is CPU-readable, it's safe to discard flutter's
// connection to sysmem.
zx_status_t close_status = buffer_collection->Close();
if (close_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to close buffer: "
<< zx_status_get_string(close_status);
return false;
}
// Wrap the buffer in a software-rendered Skia surface.
const uint64_t vmo_offset =
buffer_collection_info.buffers[0].vmo_usable_start;
const size_t vmo_stride =
BytesPerRow(buffer_collection_info.settings, 4u, size.width());
SkSurfaceProps sk_surface_props(0, kUnknown_SkPixelGeometry);
sk_surface_ = SkSurfaces::WrapPixels(
SkImageInfo::Make(size, kSkiaColorType, kPremul_SkAlphaType,
SkColorSpace::MakeSRGB()),
vmo_base + vmo_offset, vmo_stride, &sk_surface_props);
if (!sk_surface_ || sk_surface_->getCanvas() == nullptr) {
FML_LOG(ERROR) << "SkSurfaces::WrapPixels failed.";
return false;
}
return true;
}
void SoftwareSurface::SetImageId(uint32_t image_id) {
FML_CHECK(image_id_ == 0);
image_id_ = image_id;
}
uint32_t SoftwareSurface::GetImageId() {
return image_id_;
}
sk_sp<SkSurface> SoftwareSurface::GetSkiaSurface() const {
return valid_ ? sk_surface_ : nullptr;
}
fuchsia::ui::composition::BufferCollectionImportToken
SoftwareSurface::GetBufferCollectionImportToken() {
fuchsia::ui::composition::BufferCollectionImportToken import_dup;
import_token_.value.duplicate(ZX_RIGHT_SAME_RIGHTS, &import_dup.value);
return import_dup;
}
zx::event SoftwareSurface::GetAcquireFence() {
zx::event fence;
acquire_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence);
return fence;
}
zx::event SoftwareSurface::GetReleaseFence() {
zx::event fence;
release_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence);
return fence;
}
void SoftwareSurface::SetReleaseImageCallback(
ReleaseImageCallback release_image_callback) {
release_image_callback_ = release_image_callback;
}
size_t SoftwareSurface::AdvanceAndGetAge() {
return ++age_;
}
bool SoftwareSurface::FlushSessionAcquireAndReleaseEvents() {
age_ = 0;
return true;
}
void SoftwareSurface::SignalWritesFinished(
const std::function<void(void)>& on_surface_read_finished) {
FML_CHECK(on_surface_read_finished);
if (!valid_) {
on_surface_read_finished();
return;
}
FML_CHECK(surface_read_finished_callback_ == nullptr)
<< "Attempted to signal a write on the surface when the "
"previous write has not yet been acknowledged by the "
"compositor.";
surface_read_finished_callback_ = on_surface_read_finished;
// Sysmem *may* require the cache to be cleared after writes to the surface
// are complete.
if (needs_cache_clean_) {
surface_vmo_.op_range(ZX_VMO_OP_CACHE_CLEAN, 0, surface_size_bytes_,
/*buffer*/ nullptr,
/*buffer_size*/ 0);
}
// Inform scenic that flutter is finished writing to the surface.
zx_status_t signal_status = acquire_event_.signal(0u, ZX_EVENT_SIGNALED);
if (signal_status != ZX_OK) {
FML_LOG(ERROR) << "Failed to signal acquire event; "
<< zx_status_get_string(signal_status);
}
}
void SoftwareSurface::Reset() {
if (acquire_event_.signal(ZX_EVENT_SIGNALED, 0u) != ZX_OK ||
release_event_.signal(ZX_EVENT_SIGNALED, 0u) != ZX_OK) {
valid_ = false;
FML_LOG(ERROR) << "Could not reset fences. The surface is no longer valid.";
}
wait_for_surface_read_finished_.Begin(async_get_default_dispatcher());
// It is safe for the caller to collect the surface in the callback.
auto callback = surface_read_finished_callback_;
surface_read_finished_callback_ = nullptr;
if (callback) {
callback();
}
}
void SoftwareSurface::OnSurfaceReadFinished(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal_t* signal) {
if (status != ZX_OK) {
return;
}
FML_DCHECK(signal->observed & ZX_EVENT_SIGNALED);
Reset();
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/software_surface.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/software_surface.cc",
"repo_id": "engine",
"token_count": 5324
} | 495 |
// 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_TESTS_FAKES_PLATFORM_MESSAGE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_PLATFORM_MESSAGE_H_
#include <gtest/gtest.h>
#include <optional>
#include "flutter/lib/ui/window/platform_message.h"
#include "third_party/rapidjson/include/rapidjson/document.h"
using PlatformMessageResponse = flutter::PlatformMessageResponse;
using PlatformMessage = flutter::PlatformMessage;
namespace flutter_runner::testing {
class FakePlatformMessageResponse : public PlatformMessageResponse {
public:
static fml::RefPtr<FakePlatformMessageResponse> Create() {
return fml::AdoptRef(new FakePlatformMessageResponse());
}
void ExpectCompleted(std::string expected) {
EXPECT_TRUE(is_complete_);
if (is_complete_) {
EXPECT_EQ(expected, response_);
}
}
bool IsCompleted() { return is_complete_; }
std::unique_ptr<PlatformMessage> WithMessage(std::string channel,
std::string message) {
return std::make_unique<PlatformMessage>(
channel,
fml::MallocMapping::Copy(message.c_str(),
message.c_str() + message.size()),
fml::RefPtr<FakePlatformMessageResponse>(this));
}
void Complete(std::unique_ptr<fml::Mapping> data) override {
response_ =
std::string(data->GetMapping(), data->GetMapping() + data->GetSize());
FinalizeComplete();
};
void CompleteEmpty() override { FinalizeComplete(); };
private:
// Private constructors.
FakePlatformMessageResponse() {}
void FinalizeComplete() {
EXPECT_FALSE(std::exchange(is_complete_, true))
<< "Platform message responses can only be completed once!";
}
std::string response_;
};
} // namespace flutter_runner::testing
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_PLATFORM_MESSAGE_H_
| engine/shell/platform/fuchsia/flutter/tests/fakes/platform_message.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/platform_message.h",
"repo_id": "engine",
"token_count": 765
} | 496 |
// 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: [
"sys/testing/gtest_runner.shard.cml",
"sys/component/realm_builder_absolute.shard.cml",
// This test needs both the vulkan facet and the hermetic-tier-2 facet,
// so we are forced to make it a system test.
"sys/testing/system-test.shard.cml",
],
program: {
binary: "bin/app",
},
use: [
{
protocol: [
"fuchsia.ui.test.input.KeyboardInputListener",
]
}
],
offer: [
{
protocol: [
"fuchsia.inspect.InspectSink",
"fuchsia.kernel.RootJobForInspect",
"fuchsia.kernel.Stats",
"fuchsia.logger.LogSink",
"fuchsia.scheduler.ProfileProvider",
"fuchsia.sysmem.Allocator",
"fuchsia.tracing.provider.Registry",
"fuchsia.ui.input.ImeService",
"fuchsia.vulkan.loader.Loader",
"fuchsia.ui.test.input.KeyboardInputListener",
"fuchsia.ui.input3.Keyboard",
"fuchsia.intl.PropertyProvider",
"fuchsia.posix.socket.Provider",
"fuchsia.ui.pointerinjector.Registry",
"fuchsia.fonts.Provider",
"fuchsia.feedback.CrashReportingProductRegister",
"fuchsia.settings.Keyboard",
"fuchsia.accessibility.semantics.SemanticsManager",
],
from: "parent",
to: "#realm_builder",
},
{
directory: "pkg",
subdir: "config",
as: "config-data",
from: "framework",
to: "#realm_builder",
},
// See common.shard.cml.
{
directory: "tzdata-icu",
from: "framework",
to: "#realm_builder",
},
],
// TODO(https://fxbug.dev/114584): Figure out how to bring these in as deps (if possible oot).
facets: {
"fuchsia.test": {
"deprecated-allowed-packages": [
"cursor",
"flatland-scene-manager-test-ui-stack",
"test-ui-stack",
"oot_flutter_aot_runner",
"oot_flutter_jit_runner",
"oot_flutter_jit_product_runner",
"oot_flutter_aot_product_runner",
"test_manager",
"text-input-view",
],
},
},
}
| engine/shell/platform/fuchsia/flutter/tests/integration/text-input/meta/text-input-test.cml/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/text-input/meta/text-input-test.cml",
"repo_id": "engine",
"token_count": 1420
} | 497 |
# Timezone data for testing
This directory contains the fixed timezone data version 2019a for testing. It
is used in the runner tests to show that loading these files from a specified
location results in the TZ data version "2019a" becoming available to the
binaries.
| engine/shell/platform/fuchsia/flutter/tests/tzdata/README.md/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/tzdata/README.md",
"repo_id": "engine",
"token_count": 62
} | 498 |
// 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.
// On Fuchsia, in lieu of the ELF dynamic symbol table consumed through dladdr,
// the Dart VM profiler consumes symbols produced by this tool, which have the
// format
//
// struct {
// uint32_t num_entries;
// struct {
// uint32_t offset;
// uint32_t size;
// uint32_t string_table_offset;
// } entries[num_entries];
// const char* string_table;
// }
//
// Entries are sorted by offset. String table entries are NUL-terminated.
//
// See also //third_party/dart/runtime/vm/native_symbol_fuchsia.cc
import "dart:convert";
import "dart:io";
import "dart:typed_data";
import "package:args/args.dart";
import "package:path/path.dart" as path;
Future<void> main(List<String> args) async {
final parser = new ArgParser();
parser.addOption("nm", help: "Path to `nm` tool");
parser.addOption("binary",
help: "Path to the ELF file to extract symbols from");
parser.addOption("output", help: "Path to output symbol table");
final usage = """
Usage: dart_profiler_symbols.dart [options]
Options:
${parser.usage};
""";
String? buildIdDir;
String? buildIdScript;
String? nm;
String? binary;
String? output;
try {
final options = parser.parse(args);
nm = options["nm"];
if (nm == null) {
throw "Must specify --nm";
}
if (!FileSystemEntity.isFileSync(nm)) {
throw "Cannot find $nm";
}
binary = options["binary"];
if (binary == null) {
throw "Must specify --binary";
}
if (!FileSystemEntity.isFileSync(binary)) {
throw "Cannot find $binary";
}
output = options["output"];
if (output == null) {
throw "Must specify --output";
}
} catch (e) {
print("ERROR: $e\n");
print(usage);
exitCode = 1;
return;
}
await run(buildIdDir, buildIdScript, nm, binary, output);
}
class Symbol {
int offset;
int size;
String name;
Symbol({required this.offset, required this.size, required this.name});
}
Future<void> run(String? buildIdDir, String? buildIdScript, String nm,
String binary, String output) async {
final unstrippedFile = binary;
final args = ["--demangle", "--numeric-sort", "--print-size", unstrippedFile];
final result = await Process.run(nm, args);
if (result.exitCode != 0) {
print(result.stdout);
print(result.stderr);
throw "Command failed: $nm $args";
}
var symbols = [];
var regex = new RegExp("([0-9A-Za-z]+) ([0-9A-Za-z]+) (t|T|w|W) (.*)");
for (final line in result.stdout.split("\n")) {
var match = regex.firstMatch(line);
if (match == null) {
continue; // Ignore non-text symbols.
}
// Note that capture groups start at 1.
final symbol = new Symbol(offset: int.parse(match[1]!, radix: 16),
size: int.parse(match[2]!, radix: 16),
name: match[4]!.split("(")[0]);
if (symbol.name.startsWith("\$")) {
continue; // Ignore compiler/assembler temps.
}
symbols.add(symbol);
}
if (symbols.isEmpty) {
throw "$unstrippedFile has no symbols";
}
var nameTable = new BytesBuilder();
var binarySearchTable = new Uint32List(symbols.length * 3 + 1);
var binarySearchTableIndex = 0;
binarySearchTable[binarySearchTableIndex++] = symbols.length;
// Symbols are sorted by offset because of --numeric-sort.
for (var symbol in symbols) {
var nameOffset = nameTable.length;
nameTable.add(utf8.encode(symbol.name));
nameTable.addByte(0);
binarySearchTable[binarySearchTableIndex++] = symbol.offset;
binarySearchTable[binarySearchTableIndex++] = symbol.size;
binarySearchTable[binarySearchTableIndex++] = nameOffset;
}
var file = new File(output);
await file.parent.create(recursive: true);
var sink = file.openWrite();
sink.add(binarySearchTable.buffer.asUint8List());
sink.add(nameTable.takeBytes());
await sink.close();
}
| engine/shell/platform/fuchsia/runtime/dart/profiler_symbols/dart_profiler_symbols.dart/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/profiler_symbols/dart_profiler_symbols.dart",
"repo_id": "engine",
"token_count": 1497
} | 499 |