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.
part of ui;
enum FontStyle {
normal,
italic,
}
enum PlaceholderAlignment {
baseline,
aboveBaseline,
belowBaseline,
top,
bottom,
middle,
}
class FontWeight {
const FontWeight._(this.index, this.value);
final int index;
final int value;
static const FontWeight w100 = FontWeight._(0, 100);
static const FontWeight w200 = FontWeight._(1, 200);
static const FontWeight w300 = FontWeight._(2, 300);
static const FontWeight w400 = FontWeight._(3, 400);
static const FontWeight w500 = FontWeight._(4, 500);
static const FontWeight w600 = FontWeight._(5, 600);
static const FontWeight w700 = FontWeight._(6, 700);
static const FontWeight w800 = FontWeight._(7, 800);
static const FontWeight w900 = FontWeight._(8, 900);
static const FontWeight normal = w400;
static const FontWeight bold = w700;
static const List<FontWeight> values = <FontWeight>[
w100,
w200,
w300,
w400,
w500,
w600,
w700,
w800,
w900
];
static FontWeight? lerp(FontWeight? a, FontWeight? b, double t) {
if (a == null && b == null) {
return null;
}
return values[engine.clampInt(
lerpDouble(a?.index ?? normal.index, b?.index ?? normal.index, t)!
.round(),
0,
8,
)];
}
@override
String toString() {
return const <int, String>{
0: 'FontWeight.w100',
1: 'FontWeight.w200',
2: 'FontWeight.w300',
3: 'FontWeight.w400',
4: 'FontWeight.w500',
5: 'FontWeight.w600',
6: 'FontWeight.w700',
7: 'FontWeight.w800',
8: 'FontWeight.w900',
}[index]!;
}
}
class FontFeature {
const FontFeature(this.feature, [this.value = 1])
: assert(feature.length == 4,
'Feature tag must be exactly four characters long.'),
assert(value >= 0, 'Feature value must be zero or a positive integer.');
const FontFeature.enable(String feature) : this(feature, 1);
const FontFeature.disable(String feature) : this(feature, 0);
const FontFeature.alternative(this.value) : feature = 'aalt';
const FontFeature.alternativeFractions()
: feature = 'afrc',
value = 1;
const FontFeature.contextualAlternates()
: feature = 'calt',
value = 1;
const FontFeature.caseSensitiveForms()
: feature = 'case',
value = 1;
factory FontFeature.characterVariant(int value) {
assert(value >= 1);
assert(value <= 20);
return FontFeature('cv${value.toString().padLeft(2, "0")}');
}
const FontFeature.denominator()
: feature = 'dnom',
value = 1;
const FontFeature.fractions()
: feature = 'frac',
value = 1;
const FontFeature.historicalForms()
: feature = 'hist',
value = 1;
const FontFeature.historicalLigatures()
: feature = 'hlig',
value = 1;
const FontFeature.liningFigures()
: feature = 'lnum',
value = 1;
const FontFeature.localeAware({bool enable = true})
: feature = 'locl',
value = enable ? 1 : 0;
const FontFeature.notationalForms([this.value = 1])
: feature = 'nalt',
assert(value >= 0);
const FontFeature.numerators()
: feature = 'numr',
value = 1;
const FontFeature.oldstyleFigures()
: feature = 'onum',
value = 1;
const FontFeature.ordinalForms()
: feature = 'ordn',
value = 1;
const FontFeature.proportionalFigures()
: feature = 'pnum',
value = 1;
const FontFeature.randomize()
: feature = 'rand',
value = 1;
const FontFeature.stylisticAlternates()
: feature = 'salt',
value = 1;
const FontFeature.scientificInferiors()
: feature = 'sinf',
value = 1;
factory FontFeature.stylisticSet(int value) {
assert(value >= 1);
assert(value <= 20);
return FontFeature('ss${value.toString().padLeft(2, "0")}');
}
const FontFeature.subscripts()
: feature = 'subs',
value = 1;
const FontFeature.superscripts()
: feature = 'sups',
value = 1;
const FontFeature.swash([this.value = 1])
: feature = 'swsh',
assert(value >= 0);
const FontFeature.tabularFigures()
: feature = 'tnum',
value = 1;
const FontFeature.slashedZero()
: feature = 'zero',
value = 1;
final String feature;
final int value;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is FontFeature &&
other.feature == feature &&
other.value == value;
}
@override
int get hashCode => Object.hash(feature, value);
@override
String toString() => "FontFeature('$feature', $value)";
}
class FontVariation {
const FontVariation(
this.axis,
this.value,
) : assert(axis.length == 4, 'Axis tag must be exactly four characters long.'),
assert(value >= -32768.0 && value < 32768.0, 'Value must be representable as a signed 16.16 fixed-point number, i.e. it must be in this range: -32768.0 ≤ value < 32768.0');
const FontVariation.italic(this.value) : assert(value >= 0.0), assert(value <= 1.0), axis = 'ital';
const FontVariation.opticalSize(this.value) : assert(value > 0.0), axis = 'opsz';
const FontVariation.slant(this.value) : assert(value > -90.0), assert(value < 90.0), axis = 'slnt';
const FontVariation.width(this.value) : assert(value >= 0.0), axis = 'wdth';
const FontVariation.weight(this.value) : assert(value >= 1), assert(value <= 1000), axis = 'wght';
final String axis;
final double value;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is FontVariation
&& other.axis == axis
&& other.value == value;
}
@override
int get hashCode => Object.hash(axis, value);
static FontVariation? lerp(FontVariation? a, FontVariation? b, double t) {
if (a?.axis != b?.axis || (a == null && b == null)) {
return t < 0.5 ? a : b;
}
return FontVariation(
a!.axis,
clampDouble(lerpDouble(a.value, b!.value, t)!, -32768.0, 32768.0 - 1.0/65536.0),
);
}
@override
String toString() => "FontVariation('$axis', $value)";
}
final class GlyphInfo {
GlyphInfo(this.graphemeClusterLayoutBounds, this.graphemeClusterCodeUnitRange, this.writingDirection);
final Rect graphemeClusterLayoutBounds;
final TextRange graphemeClusterCodeUnitRange;
final TextDirection writingDirection;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is GlyphInfo
&& graphemeClusterLayoutBounds == other.graphemeClusterLayoutBounds
&& graphemeClusterCodeUnitRange == other.graphemeClusterCodeUnitRange
&& writingDirection == other.writingDirection;
}
@override
int get hashCode => Object.hash(graphemeClusterLayoutBounds, graphemeClusterCodeUnitRange, writingDirection);
@override
String toString() => 'Glyph($graphemeClusterLayoutBounds, textRange: $graphemeClusterCodeUnitRange, direction: $writingDirection)';
}
// The order of this enum must match the order of the values in RenderStyleConstants.h's ETextAlign.
enum TextAlign {
left,
right,
center,
justify,
start,
end,
}
enum TextBaseline {
alphabetic,
ideographic,
}
class TextDecoration {
const TextDecoration._(this._mask);
factory TextDecoration.combine(List<TextDecoration> decorations) {
int mask = 0;
for (final TextDecoration decoration in decorations) {
mask |= decoration._mask;
}
return TextDecoration._(mask);
}
final int _mask;
int get maskValue => _mask;
bool contains(TextDecoration other) {
return (_mask | other._mask) == _mask;
}
static const TextDecoration none = TextDecoration._(0x0);
static const TextDecoration underline = TextDecoration._(0x1);
static const TextDecoration overline = TextDecoration._(0x2);
static const TextDecoration lineThrough = TextDecoration._(0x4);
@override
bool operator ==(Object other) {
return other is TextDecoration && other._mask == _mask;
}
@override
int get hashCode => _mask.hashCode;
@override
String toString() {
if (_mask == 0) {
return 'TextDecoration.none';
}
final List<String> values = <String>[];
if (_mask & underline._mask != 0) {
values.add('underline');
}
if (_mask & overline._mask != 0) {
values.add('overline');
}
if (_mask & lineThrough._mask != 0) {
values.add('lineThrough');
}
if (values.length == 1) {
return 'TextDecoration.${values[0]}';
}
return 'TextDecoration.combine([${values.join(", ")}])';
}
}
enum TextDecorationStyle { solid, double, dotted, dashed, wavy }
enum TextLeadingDistribution {
proportional,
even,
}
class TextHeightBehavior {
const TextHeightBehavior({
this.applyHeightToFirstAscent = true,
this.applyHeightToLastDescent = true,
this.leadingDistribution = TextLeadingDistribution.proportional,
});
final bool applyHeightToFirstAscent;
final bool applyHeightToLastDescent;
final TextLeadingDistribution leadingDistribution;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is TextHeightBehavior &&
other.applyHeightToFirstAscent == applyHeightToFirstAscent &&
other.applyHeightToLastDescent == applyHeightToLastDescent &&
other.leadingDistribution == leadingDistribution;
}
@override
int get hashCode {
return Object.hash(
applyHeightToFirstAscent,
applyHeightToLastDescent,
);
}
@override
String toString() {
return 'TextHeightBehavior('
'applyHeightToFirstAscent: $applyHeightToFirstAscent, '
'applyHeightToLastDescent: $applyHeightToLastDescent, '
'leadingDistribution: $leadingDistribution'
')';
}
}
abstract class TextStyle {
factory TextStyle({
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,
}) => engine.renderer.createTextStyle(
color: color,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
decorationThickness: decorationThickness,
fontWeight: fontWeight,
fontStyle: fontStyle,
textBaseline: textBaseline,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSize: fontSize,
letterSpacing: letterSpacing,
wordSpacing: wordSpacing,
height: height,
leadingDistribution: leadingDistribution,
locale: locale,
background: background,
foreground: foreground,
shadows: shadows,
fontFeatures: fontFeatures,
fontVariations: fontVariations,
);
}
abstract class ParagraphStyle {
// See: https://github.com/flutter/flutter/issues/9819
factory ParagraphStyle({
TextAlign? textAlign,
TextDirection? textDirection,
int? maxLines,
String? fontFamily,
double? fontSize,
double? height,
TextHeightBehavior? textHeightBehavior,
FontWeight? fontWeight,
FontStyle? fontStyle,
StrutStyle? strutStyle,
String? ellipsis,
Locale? locale,
}) => engine.renderer.createParagraphStyle(
textAlign: textAlign,
textDirection: textDirection,
maxLines: maxLines,
fontFamily: fontFamily,
fontSize: fontSize,
height: height,
textHeightBehavior: textHeightBehavior,
fontWeight: fontWeight,
fontStyle: fontStyle,
strutStyle: strutStyle,
ellipsis: ellipsis,
locale: locale,
);
}
abstract class StrutStyle {
/// Creates a new StrutStyle object.
///
/// * `fontFamily`: The name of the font to use when painting the text (e.g.,
/// Roboto).
///
/// * `fontFamilyFallback`: An ordered list of font family names that will be searched for when
/// the font in `fontFamily` cannot be found.
///
/// * `fontSize`: The size of glyphs (in logical pixels) to use when painting
/// the text.
///
/// * `lineHeight`: The minimum height of the line boxes, as a multiple of the
/// font size. The lines of the paragraph will be at least
/// `(lineHeight + leading) * fontSize` tall when fontSize
/// is not null. When fontSize is null, there is no minimum line height. Tall
/// glyphs due to baseline alignment or large [TextStyle.fontSize] may cause
/// the actual line height after layout to be taller than specified here.
/// [fontSize] must be provided for this property to take effect.
///
/// * `leading`: The minimum amount of leading between lines as a multiple of
/// the font size. [fontSize] must be provided for this property to take effect.
///
/// * `fontWeight`: The typeface thickness to use when painting the text
/// (e.g., bold).
///
/// * `fontStyle`: The typeface variant to use when drawing the letters (e.g.,
/// italics).
///
/// * `forceStrutHeight`: When true, the paragraph will force all lines to be exactly
/// `(lineHeight + leading) * fontSize` tall from baseline to baseline.
/// [TextStyle] is no longer able to influence the line height, and any tall
/// glyphs may overlap with lines above. If a [fontFamily] is specified, the
/// total ascent of the first line will be the min of the `Ascent + half-leading`
/// of the [fontFamily] and `(lineHeight + leading) * fontSize`. Otherwise, it
/// will be determined by the Ascent + half-leading of the first text.
factory StrutStyle({
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? height,
TextLeadingDistribution? leadingDistribution,
double? leading,
FontWeight? fontWeight,
FontStyle? fontStyle,
bool? forceStrutHeight,
}) => engine.renderer.createStrutStyle(
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSize: fontSize,
height: height,
leadingDistribution: leadingDistribution,
leading: leading,
fontWeight: fontWeight,
fontStyle: fontStyle,
forceStrutHeight: forceStrutHeight,
);
}
// The order of this enum must match the order of the values in TextDirection.h's TextDirection.
enum TextDirection {
rtl,
ltr,
}
class TextBox {
const TextBox.fromLTRBD(
this.left,
this.top,
this.right,
this.bottom,
this.direction,
);
final double left;
final double top;
final double right;
final double bottom;
final TextDirection direction;
Rect toRect() => Rect.fromLTRB(left, top, right, bottom);
double get start {
return (direction == TextDirection.ltr) ? left : right;
}
double get end {
return (direction == TextDirection.ltr) ? right : left;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is TextBox &&
other.left == left &&
other.top == top &&
other.right == right &&
other.bottom == bottom &&
other.direction == direction;
}
@override
int get hashCode => Object.hash(left, top, right, bottom, direction);
@override
String toString() {
return 'TextBox.fromLTRBD(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)}, $direction)';
}
}
enum TextAffinity {
upstream,
downstream,
}
class TextPosition {
const TextPosition({
required this.offset,
this.affinity = TextAffinity.downstream,
});
final int offset;
final TextAffinity affinity;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is TextPosition &&
other.offset == offset &&
other.affinity == affinity;
}
@override
int get hashCode => Object.hash(offset, affinity);
@override
String toString() {
return '$runtimeType(offset: $offset, affinity: $affinity)';
}
}
class TextRange {
const TextRange({
required this.start,
required this.end,
}) : assert(start >= -1),
assert(end >= -1);
const TextRange.collapsed(int offset)
: assert(offset >= -1),
start = offset,
end = offset;
static const TextRange empty = TextRange(start: -1, end: -1);
final int start;
final int end;
bool get isValid => start >= 0 && end >= 0;
bool get isCollapsed => start == end;
bool get isNormalized => end >= start;
String textBefore(String text) {
assert(isNormalized);
return text.substring(0, start);
}
String textAfter(String text) {
assert(isNormalized);
return text.substring(end);
}
String textInside(String text) {
assert(isNormalized);
return text.substring(start, end);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is TextRange && other.start == start && other.end == end;
}
@override
int get hashCode => Object.hash(
start.hashCode,
end.hashCode,
);
@override
String toString() => 'TextRange(start: $start, end: $end)';
}
class ParagraphConstraints {
const ParagraphConstraints({
required this.width,
});
final double width;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is ParagraphConstraints && other.width == width;
}
@override
int get hashCode => width.hashCode;
@override
String toString() => '$runtimeType(width: $width)';
}
enum BoxHeightStyle {
tight,
max,
includeLineSpacingMiddle,
includeLineSpacingTop,
includeLineSpacingBottom,
strut,
}
enum BoxWidthStyle {
// Provide tight bounding boxes that fit widths to the runs of each line
// independently.
tight,
max,
}
abstract class LineMetrics {
factory LineMetrics({
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,
}) => engine.renderer.createLineMetrics(
hardBreak: hardBreak,
ascent: ascent,
descent: descent,
unscaledAscent: unscaledAscent,
height: height,
width: width,
left: left,
baseline: baseline,
lineNumber: lineNumber,
);
bool get hardBreak;
double get ascent;
double get descent;
double get unscaledAscent;
double get height;
double get width;
double get left;
double get baseline;
int get lineNumber;
}
abstract class Paragraph {
double get width;
double get height;
double get longestLine;
double get minIntrinsicWidth;
double get maxIntrinsicWidth;
double get alphabeticBaseline;
double get ideographicBaseline;
bool get didExceedMaxLines;
void layout(ParagraphConstraints constraints);
List<TextBox> getBoxesForRange(int start, int end,
{BoxHeightStyle boxHeightStyle = BoxHeightStyle.tight,
BoxWidthStyle boxWidthStyle = BoxWidthStyle.tight});
TextPosition getPositionForOffset(Offset offset);
GlyphInfo? getGlyphInfoAt(int codeUnitOffset);
GlyphInfo? getClosestGlyphInfoForOffset(Offset offset);
TextRange getWordBoundary(TextPosition position);
TextRange getLineBoundary(TextPosition position);
List<TextBox> getBoxesForPlaceholders();
List<LineMetrics> computeLineMetrics();
LineMetrics? getLineMetricsAt(int lineNumber);
int get numberOfLines;
int? getLineNumberAt(int codeUnitOffset);
void dispose();
bool get debugDisposed;
}
abstract class ParagraphBuilder {
factory ParagraphBuilder(ParagraphStyle style) =>
engine.renderer.createParagraphBuilder(style);
void pushStyle(TextStyle style);
void pop();
void addText(String text);
Paragraph build();
int get placeholderCount;
List<double> get placeholderScales;
void addPlaceholder(
double width,
double height,
PlaceholderAlignment alignment, {
double scale = 1.0,
double? baselineOffset,
TextBaseline? baseline,
});
}
Future<void> loadFontFromList(Uint8List list, {String? fontFamily}) async {
await engine.renderer.fontCollection.loadFontFromList(list, fontFamily: fontFamily);
engine.sendFontChangeMessage();
}
| engine/lib/web_ui/lib/text.dart/0 | {
"file_path": "engine/lib/web_ui/lib/text.dart",
"repo_id": "engine",
"token_count": 7469
} | 269 |
# Copyright 2019 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/wasm.gni")
wasm_lib("skwasm") {
public_configs = [ "//flutter:config" ]
sources = [
"canvas.cpp",
"contour_measure.cpp",
"data.cpp",
"export.h",
"filters.cpp",
"fonts.cpp",
"helpers.h",
"image.cpp",
"paint.cpp",
"path.cpp",
"picture.cpp",
"shaders.cpp",
"skwasm_support.h",
"string.cpp",
"surface.cpp",
"text/line_metrics.cpp",
"text/paragraph.cpp",
"text/paragraph_builder.cpp",
"text/paragraph_style.cpp",
"text/strut_style.cpp",
"text/text_style.cpp",
"vertices.cpp",
"wrappers.h",
]
cflags = [
"-mreference-types",
"-pthread",
]
ldflags = [
"-std=c++20",
"-lGL",
"-sUSE_WEBGL2=1",
"-sMAX_WEBGL_VERSION=2",
"-sOFFSCREENCANVAS_SUPPORT",
"-sPTHREAD_POOL_SIZE=1",
"-sALLOW_MEMORY_GROWTH",
"-sALLOW_TABLE_GROWTH",
"-lexports.js",
"-sEXPORTED_FUNCTIONS=[stackAlloc]",
"-sEXPORTED_RUNTIME_METHODS=[addFunction,wasmExports]",
"-Wno-pthreads-mem-growth",
"--js-library",
rebase_path("library_skwasm_support.js"),
]
inputs = [ rebase_path("library_skwasm_support.js") ]
if (is_debug) {
ldflags += [
"-sDEMANGLE_SUPPORT=1",
"-sASSERTIONS=1",
"-sGL_ASSERTIONS=1",
]
} else {
ldflags += [ "--closure=1" ]
}
deps = [
"//flutter/skia",
"//flutter/skia/modules/skparagraph",
]
}
| engine/lib/web_ui/skwasm/BUILD.gn/0 | {
"file_path": "engine/lib/web_ui/skwasm/BUILD.gn",
"repo_id": "engine",
"token_count": 748
} | 270 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "surface.h"
#include <algorithm>
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h"
#include "third_party/skia/include/gpu/ganesh/gl/GrGLDirectContext.h"
using namespace Skwasm;
Surface::Surface() {
assert(emscripten_is_main_browser_thread());
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(
&_thread, &attr,
[](void* context) -> void* {
static_cast<Surface*>(context)->_runWorker();
return nullptr;
},
this);
// Listen to messages from the worker
skwasm_registerMessageListener(_thread);
// Synchronize the time origin for the worker thread
skwasm_syncTimeOriginForThread(_thread);
}
// Main thread only
void Surface::dispose() {
assert(emscripten_is_main_browser_thread());
emscripten_dispatch_to_thread(_thread, EM_FUNC_SIG_VI,
reinterpret_cast<void*>(fDispose), nullptr,
this);
}
// Main thread only
uint32_t Surface::renderPictures(SkPicture** pictures, int count) {
assert(emscripten_is_main_browser_thread());
uint32_t callbackId = ++_currentCallbackId;
std::unique_ptr<sk_sp<SkPicture>[]> picturePointers =
std::make_unique<sk_sp<SkPicture>[]>(count);
for (int i = 0; i < count; i++) {
picturePointers[i] = sk_ref_sp(pictures[i]);
}
// Releasing picturePointers here and will recreate the unique_ptr on the
// other thread See surface_renderPicturesOnWorker
skwasm_dispatchRenderPictures(_thread, this, picturePointers.release(), count,
callbackId);
return callbackId;
}
// Main thread only
uint32_t Surface::rasterizeImage(SkImage* image, ImageByteFormat format) {
assert(emscripten_is_main_browser_thread());
uint32_t callbackId = ++_currentCallbackId;
image->ref();
emscripten_dispatch_to_thread(_thread, EM_FUNC_SIG_VIIII,
reinterpret_cast<void*>(fRasterizeImage),
nullptr, this, image, format, callbackId);
return callbackId;
}
std::unique_ptr<TextureSourceWrapper> Surface::createTextureSourceWrapper(
SkwasmObject textureSource) {
return std::unique_ptr<TextureSourceWrapper>(
new TextureSourceWrapper(_thread, textureSource));
}
// Main thread only
void Surface::setCallbackHandler(CallbackHandler* callbackHandler) {
assert(emscripten_is_main_browser_thread());
_callbackHandler = callbackHandler;
}
// Worker thread only
void Surface::_runWorker() {
_init();
emscripten_exit_with_live_runtime();
}
// Worker thread only
void Surface::_init() {
// Listen to messages from the main thread
skwasm_registerMessageListener(0);
_glContext = skwasm_createOffscreenCanvas(256, 256);
if (!_glContext) {
printf("Failed to create context!\n");
return;
}
makeCurrent(_glContext);
emscripten_webgl_enable_extension(_glContext, "WEBGL_debug_renderer_info");
_grContext = GrDirectContexts::MakeGL(GrGLMakeNativeInterface());
// WebGL should already be clearing the color and stencil buffers, but do it
// again here to ensure Skia receives them in the expected state.
emscripten_glBindFramebuffer(GL_FRAMEBUFFER, 0);
emscripten_glClearColor(0, 0, 0, 0);
emscripten_glClearStencil(0);
emscripten_glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
_grContext->resetContext(kRenderTarget_GrGLBackendState |
kMisc_GrGLBackendState);
// The on-screen canvas is FBO 0. Wrap it in a Skia render target so Skia
// can render to it.
_fbInfo.fFBOID = 0;
_fbInfo.fFormat = GL_RGBA8_OES;
emscripten_glGetIntegerv(GL_SAMPLES, &_sampleCount);
emscripten_glGetIntegerv(GL_STENCIL_BITS, &_stencil);
}
// Worker thread only
void Surface::_dispose() {
delete this;
}
// Worker thread only
void Surface::_resizeCanvasToFit(int width, int height) {
if (!_surface || width > _canvasWidth || height > _canvasHeight) {
_canvasWidth = std::max(width, _canvasWidth);
_canvasHeight = std::max(height, _canvasHeight);
_recreateSurface();
}
}
// Worker thread only
void Surface::_recreateSurface() {
makeCurrent(_glContext);
skwasm_resizeCanvas(_glContext, _canvasWidth, _canvasHeight);
auto target = GrBackendRenderTargets::MakeGL(_canvasWidth, _canvasHeight,
_sampleCount, _stencil, _fbInfo);
_surface = SkSurfaces::WrapBackendRenderTarget(
_grContext.get(), target, kBottomLeft_GrSurfaceOrigin,
kRGBA_8888_SkColorType, SkColorSpace::MakeSRGB(), nullptr);
}
// Worker thread only
void Surface::renderPicturesOnWorker(sk_sp<SkPicture>* pictures,
int pictureCount,
uint32_t callbackId,
double rasterStart) {
// This is populated by the `captureImageBitmap` call the first time it is
// passed in.
SkwasmObject imagePromiseArray = __builtin_wasm_ref_null_extern();
for (int i = 0; i < pictureCount; i++) {
sk_sp<SkPicture> picture = pictures[i];
SkRect pictureRect = picture->cullRect();
SkIRect roundedOutRect;
pictureRect.roundOut(&roundedOutRect);
_resizeCanvasToFit(roundedOutRect.width(), roundedOutRect.height());
SkMatrix matrix =
SkMatrix::Translate(-roundedOutRect.fLeft, -roundedOutRect.fTop);
makeCurrent(_glContext);
auto canvas = _surface->getCanvas();
canvas->drawColor(SK_ColorTRANSPARENT, SkBlendMode::kSrc);
canvas->drawPicture(picture, &matrix, nullptr);
_grContext->flush(_surface.get());
imagePromiseArray =
skwasm_captureImageBitmap(_glContext, roundedOutRect.width(),
roundedOutRect.height(), imagePromiseArray);
}
skwasm_resolveAndPostImages(this, imagePromiseArray, rasterStart, callbackId);
}
void Surface::_rasterizeImage(SkImage* image,
ImageByteFormat format,
uint32_t callbackId) {
// We handle PNG encoding with browser APIs so that we can omit libpng from
// skia to save binary size.
assert(format != ImageByteFormat::png);
sk_sp<SkData> data;
SkAlphaType alphaType = format == ImageByteFormat::rawStraightRgba
? SkAlphaType::kUnpremul_SkAlphaType
: SkAlphaType::kPremul_SkAlphaType;
SkImageInfo info = SkImageInfo::Make(image->width(), image->height(),
SkColorType::kRGBA_8888_SkColorType,
alphaType, SkColorSpace::MakeSRGB());
size_t bytesPerRow = 4 * image->width();
size_t byteSize = info.computeByteSize(bytesPerRow);
data = SkData::MakeUninitialized(byteSize);
uint8_t* pixels = reinterpret_cast<uint8_t*>(data->writable_data());
bool success = image->readPixels(_grContext.get(), image->imageInfo(), pixels,
bytesPerRow, 0, 0);
if (!success) {
printf("Failed to read pixels from image!\n");
data = nullptr;
}
emscripten_async_run_in_main_runtime_thread(
EM_FUNC_SIG_VIII, fOnRasterizeComplete, this, data.release(), callbackId);
}
void Surface::_onRasterizeComplete(SkData* data, uint32_t callbackId) {
_callbackHandler(callbackId, data, __builtin_wasm_ref_null_extern());
}
// Main thread only
void Surface::onRenderComplete(uint32_t callbackId, SkwasmObject imageBitmap) {
assert(emscripten_is_main_browser_thread());
_callbackHandler(callbackId, nullptr, imageBitmap);
}
void Surface::fDispose(Surface* surface) {
surface->_dispose();
}
void Surface::fOnRasterizeComplete(Surface* surface,
SkData* imageData,
uint32_t callbackId) {
surface->_onRasterizeComplete(imageData, callbackId);
}
void Surface::fRasterizeImage(Surface* surface,
SkImage* image,
ImageByteFormat format,
uint32_t callbackId) {
surface->_rasterizeImage(image, format, callbackId);
image->unref();
}
SKWASM_EXPORT Surface* surface_create() {
return new Surface();
}
SKWASM_EXPORT unsigned long surface_getThreadId(Surface* surface) {
return surface->getThreadId();
}
SKWASM_EXPORT void surface_setCallbackHandler(
Surface* surface,
Surface::CallbackHandler* callbackHandler) {
surface->setCallbackHandler(callbackHandler);
}
SKWASM_EXPORT void surface_destroy(Surface* surface) {
surface->dispose();
}
SKWASM_EXPORT uint32_t surface_renderPictures(Surface* surface,
SkPicture** pictures,
int count) {
return surface->renderPictures(pictures, count);
}
SKWASM_EXPORT void surface_renderPicturesOnWorker(Surface* surface,
sk_sp<SkPicture>* pictures,
int pictureCount,
uint32_t callbackId,
double rasterStart) {
// This will release the pictures when they leave scope.
std::unique_ptr<sk_sp<SkPicture>> picturesPointer =
std::unique_ptr<sk_sp<SkPicture>>(pictures);
surface->renderPicturesOnWorker(pictures, pictureCount, callbackId,
rasterStart);
}
SKWASM_EXPORT uint32_t surface_rasterizeImage(Surface* surface,
SkImage* image,
ImageByteFormat format) {
return surface->rasterizeImage(image, format);
}
// This is used by the skwasm JS support code to call back into C++ when the
// we finish creating the image bitmap, which is an asynchronous operation.
SKWASM_EXPORT void surface_onRenderComplete(Surface* surface,
uint32_t callbackId,
SkwasmObject imageBitmap) {
return surface->onRenderComplete(callbackId, imageBitmap);
}
| engine/lib/web_ui/skwasm/surface.cpp/0 | {
"file_path": "engine/lib/web_ui/skwasm/surface.cpp",
"repo_id": "engine",
"token_count": 4370
} | 271 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
import '../common/rendering.dart';
import '../common/test_initialization.dart';
export '../common/rendering.dart' show renderScene;
const MethodCodec codec = StandardMethodCodec();
/// Common test setup for all CanvasKit unit-tests.
void setUpCanvasKitTest({bool withImplicitView = false}) {
setUpUnitTests(
withImplicitView: withImplicitView,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
setUp(() => renderer.fontCollection.fontFallbackManager!.downloadQueue
.fallbackFontUrlPrefixOverride = 'assets/fallback_fonts/');
tearDown(() => renderer.fontCollection.fontFallbackManager!.downloadQueue
.fallbackFontUrlPrefixOverride = null);
}
/// Convenience getter for the implicit view.
ui.FlutterView get implicitView =>
EnginePlatformDispatcher.instance.implicitView!;
/// Utility function for CanvasKit tests to draw pictures without
/// the [CkPictureRecorder] boilerplate.
CkPicture paintPicture(
ui.Rect cullRect, void Function(CkCanvas canvas) painter) {
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(cullRect);
painter(canvas);
return recorder.endRecording();
}
Future<void> matchSceneGolden(
String goldenFile,
ui.Scene scene, {
required ui.Rect region,
}) async {
await renderScene(scene);
await matchGoldenFile(goldenFile, region: region);
}
/// Checks that a [picture] matches the [goldenFile].
///
/// The picture is drawn onto the UI at [ui.Offset.zero] with no additional
/// layers.
Future<void> matchPictureGolden(String goldenFile, CkPicture picture,
{required ui.Rect region}) async {
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, picture);
await renderScene(sb.build());
await matchGoldenFile(goldenFile, region: region);
}
Future<bool> matchImage(ui.Image left, ui.Image right) async {
if (left.width != right.width || left.height != right.height) {
return false;
}
int getPixel(ByteData data, int x, int y) =>
data.getUint32((x + y * left.width) * 4);
final ByteData leftData = (await left.toByteData())!;
final ByteData rightData = (await right.toByteData())!;
for (int y = 0; y < left.height; y++) {
for (int x = 0; x < left.width; x++) {
if (getPixel(leftData, x, y) != getPixel(rightData, x, y)) {
return false;
}
}
}
return true;
}
/// 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>();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/platform_views',
codec.encodeMethodCall(MethodCall(
'create',
<String, dynamic>{
'id': id,
'viewType': viewType,
},
)),
(dynamic _) => completer.complete(),
);
return completer.future;
}
/// Disposes of the platform view with the given [id].
Future<void> disposePlatformView(int id) {
final Completer<void> completer = Completer<void>();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/platform_views',
codec.encodeMethodCall(MethodCall('dispose', id)),
(dynamic _) => completer.complete(),
);
return completer.future;
}
/// Creates a pre-laid out one-line paragraph of text.
///
/// Useful in tests that need a simple label to annotate goldens.
CkParagraph makeSimpleText(
String text, {
String? fontFamily,
double? fontSize,
ui.FontStyle? fontStyle,
ui.FontWeight? fontWeight,
ui.Color? color,
}) {
final CkParagraphBuilder builder = CkParagraphBuilder(CkParagraphStyle(
fontFamily: fontFamily ?? 'Roboto',
fontSize: fontSize ?? 14,
fontStyle: fontStyle ?? ui.FontStyle.normal,
fontWeight: fontWeight ?? ui.FontWeight.normal,
));
builder.pushStyle(CkTextStyle(
color: color ?? const ui.Color(0xFF000000),
));
builder.addText(text);
builder.pop();
final CkParagraph paragraph = builder.build();
paragraph.layout(const ui.ParagraphConstraints(width: 10000));
return paragraph;
}
| engine/lib/web_ui/test/canvaskit/common.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/common.dart",
"repo_id": "engine",
"token_count": 1524
} | 272 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:js_interop';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'common.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
setUpCanvasKitTest();
late _MockNativeMemoryFinalizationRegistry mockFinalizationRegistry;
setUp(() {
TestSkDeletableMock.deleteCount = 0;
nativeMemoryFinalizationRegistry = mockFinalizationRegistry = _MockNativeMemoryFinalizationRegistry();
});
tearDown(() {
nativeMemoryFinalizationRegistry = NativeMemoryFinalizationRegistry();
});
group(UniqueRef, () {
test('create-dispose-collect cycle', () {
expect(mockFinalizationRegistry.registeredPairs, hasLength(0));
final Object owner = Object();
final TestSkDeletable nativeObject = TestSkDeletable();
final UniqueRef<TestSkDeletable> ref = UniqueRef<TestSkDeletable>(owner, nativeObject, 'TestSkDeletable');
expect(ref.isDisposed, isFalse);
expect(ref.nativeObject, same(nativeObject));
expect(TestSkDeletableMock.deleteCount, 0);
expect(mockFinalizationRegistry.registeredPairs, hasLength(1));
expect(mockFinalizationRegistry.registeredPairs.single.owner, same(owner));
expect(mockFinalizationRegistry.registeredPairs.single.ref, same(ref));
ref.dispose();
expect(TestSkDeletableMock.deleteCount, 1);
expect(ref.isDisposed, isTrue);
expect(
reason: 'Cannot access object that was disposed',
() => ref.nativeObject, throwsA(isA<AssertionError>()),
);
expect(
reason: 'Cannot dispose object more than once',
() => ref.dispose(), throwsA(isA<AssertionError>()),
);
expect(TestSkDeletableMock.deleteCount, 1);
// Simulate a GC
mockFinalizationRegistry.registeredPairs.single.ref.collect();
expect(
reason: 'Manually disposed object should not be deleted again by GC.',
TestSkDeletableMock.deleteCount, 1,
);
});
test('create-collect cycle', () {
expect(mockFinalizationRegistry.registeredPairs, hasLength(0));
final Object owner = Object();
final TestSkDeletable nativeObject = TestSkDeletable();
final UniqueRef<TestSkDeletable> ref = UniqueRef<TestSkDeletable>(owner, nativeObject, 'TestSkDeletable');
expect(ref.isDisposed, isFalse);
expect(ref.nativeObject, same(nativeObject));
expect(TestSkDeletableMock.deleteCount, 0);
expect(mockFinalizationRegistry.registeredPairs, hasLength(1));
ref.collect();
expect(TestSkDeletableMock.deleteCount, 1);
// There's nothing else to test for any practical gain. UniqueRef.collect
// is called when GC decided that the owner is no longer reachable. So
// there must not be anything else calling into this object for anything
// useful.
});
test('dispose instrumentation', () {
Instrumentation.enabled = true;
Instrumentation.instance.debugCounters.clear();
final Object owner = Object();
final TestSkDeletable nativeObject = TestSkDeletable();
expect(Instrumentation.instance.debugCounters, <String, int>{});
final UniqueRef<TestSkDeletable> ref = UniqueRef<TestSkDeletable>(owner, nativeObject, 'TestSkDeletable');
expect(Instrumentation.instance.debugCounters, <String, int>{
'TestSkDeletable Created': 1,
});
ref.dispose();
expect(Instrumentation.instance.debugCounters, <String, int>{
'TestSkDeletable Created': 1,
'TestSkDeletable Deleted': 1,
});
});
test('collect instrumentation', () {
Instrumentation.enabled = true;
Instrumentation.instance.debugCounters.clear();
final Object owner = Object();
final TestSkDeletable nativeObject = TestSkDeletable();
expect(Instrumentation.instance.debugCounters, <String, int>{});
final UniqueRef<TestSkDeletable> ref = UniqueRef<TestSkDeletable>(owner, nativeObject, 'TestSkDeletable');
expect(Instrumentation.instance.debugCounters, <String, int>{
'TestSkDeletable Created': 1,
});
ref.collect();
expect(Instrumentation.instance.debugCounters, <String, int>{
'TestSkDeletable Created': 1,
'TestSkDeletable Leaked': 1,
'TestSkDeletable Deleted': 1,
});
});
});
group(CountedRef, () {
test('single owner', () {
expect(mockFinalizationRegistry.registeredPairs, hasLength(0));
final TestSkDeletable nativeObject = TestSkDeletable();
final TestCountedRefOwner owner = TestCountedRefOwner(nativeObject);
expect(owner.ref.debugReferrers, hasLength(1));
expect(owner.ref.debugReferrers.single, owner);
expect(owner.ref.refCount, 1);
expect(owner.ref.nativeObject, nativeObject);
expect(TestSkDeletableMock.deleteCount, 0);
expect(mockFinalizationRegistry.registeredPairs, hasLength(1));
owner.dispose();
expect(owner.ref.debugReferrers, isEmpty);
expect(owner.ref.refCount, 0);
expect(
reason: 'Cannot access object that was disposed',
() => owner.ref.nativeObject, throwsA(isA<AssertionError>()),
);
expect(TestSkDeletableMock.deleteCount, 1);
expect(
reason: 'Cannot dispose object more than once',
() => owner.dispose(), throwsA(isA<AssertionError>()),
);
});
test('multiple owners', () {
expect(mockFinalizationRegistry.registeredPairs, hasLength(0));
final TestSkDeletable nativeObject = TestSkDeletable();
final TestCountedRefOwner owner1 = TestCountedRefOwner(nativeObject);
expect(owner1.ref.debugReferrers, hasLength(1));
expect(owner1.ref.debugReferrers.single, owner1);
expect(owner1.ref.refCount, 1);
expect(owner1.ref.nativeObject, nativeObject);
expect(TestSkDeletableMock.deleteCount, 0);
expect(mockFinalizationRegistry.registeredPairs, hasLength(1));
final TestCountedRefOwner owner2 = owner1.clone();
expect(owner2.ref, same(owner1.ref));
expect(owner2.ref.debugReferrers, hasLength(2));
expect(owner2.ref.debugReferrers.first, owner1);
expect(owner2.ref.debugReferrers.last, owner2);
expect(owner2.ref.refCount, 2);
expect(owner2.ref.nativeObject, nativeObject);
expect(TestSkDeletableMock.deleteCount, 0);
expect(
reason: 'Second owner does not add more native object owners. '
'The underlying shared UniqueRef is the only one.',
mockFinalizationRegistry.registeredPairs, hasLength(1),
);
owner1.dispose();
expect(owner2.ref.debugReferrers, hasLength(1));
expect(owner2.ref.debugReferrers.single, owner2);
expect(owner2.ref.refCount, 1);
expect(owner2.ref.nativeObject, nativeObject);
expect(TestSkDeletableMock.deleteCount, 0);
expect(
reason: 'The same owner cannot dispose its CountedRef more than once, even when CountedRef is still alive.',
() => owner1.dispose(), throwsA(isA<AssertionError>()),
);
owner2.dispose();
expect(owner2.ref.debugReferrers, isEmpty);
expect(owner2.ref.refCount, 0);
expect(
reason: 'Cannot access object that was disposed',
() => owner2.ref.nativeObject, throwsA(isA<AssertionError>()),
);
expect(TestSkDeletableMock.deleteCount, 1);
expect(
reason: 'The same owner cannot dispose its CountedRef more than once.',
() => owner2.dispose(), throwsA(isA<AssertionError>()),
);
// Simulate a GC
mockFinalizationRegistry.registeredPairs.single.ref.collect();
expect(
reason: 'Manually disposed object should not be deleted again by GC.',
TestSkDeletableMock.deleteCount, 1,
);
});
});
}
class TestSkDeletableMock {
static int deleteCount = 0;
bool isDeleted() => _isDeleted;
bool _isDeleted = false;
void delete() {
expect(_isDeleted, isFalse,
reason:
'CanvasKit does not allow deleting the same object more than once.');
_isDeleted = true;
deleteCount++;
}
JsConstructor get constructor => TestJsConstructor(name: 'TestSkDeletable');
}
@JS()
@anonymous
@staticInterop
class TestSkDeletable implements SkDeletable {
factory TestSkDeletable() {
final TestSkDeletableMock mock = TestSkDeletableMock();
return TestSkDeletable._(
isDeleted: () { return mock.isDeleted(); }.toJS,
delete: () { return mock.delete(); }.toJS,
constructor: mock.constructor);
}
external factory TestSkDeletable._({
JSFunction isDeleted,
JSFunction delete,
JsConstructor constructor});
}
@JS()
@anonymous
@staticInterop
class TestJsConstructor implements JsConstructor {
external factory TestJsConstructor({String name});
}
class TestCountedRefOwner implements StackTraceDebugger {
TestCountedRefOwner(TestSkDeletable nativeObject) {
assert(() {
_debugStackTrace = StackTrace.current;
return true;
}());
ref = CountedRef<TestCountedRefOwner, TestSkDeletable>(
nativeObject, this, 'TestCountedRefOwner');
}
TestCountedRefOwner.cloneOf(this.ref) {
assert(() {
_debugStackTrace = StackTrace.current;
return true;
}());
ref.ref(this);
}
@override
StackTrace get debugStackTrace => _debugStackTrace;
late StackTrace _debugStackTrace;
late final CountedRef<TestCountedRefOwner, TestSkDeletable> ref;
void dispose() {
ref.unref(this);
}
TestCountedRefOwner clone() => TestCountedRefOwner.cloneOf(ref);
}
class _MockNativeMemoryFinalizationRegistry implements NativeMemoryFinalizationRegistry {
final List<_MockPair> registeredPairs = <_MockPair>[];
@override
void register(Object owner, UniqueRef<Object> ref) {
registeredPairs.add(_MockPair(owner, ref));
}
}
class _MockPair {
_MockPair(this.owner, this.ref);
Object owner;
UniqueRef<Object> ref;
}
| engine/lib/web_ui/test/canvaskit/native_memory_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/native_memory_test.dart",
"repo_id": "engine",
"token_count": 3801
} | 273 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'common.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
setUpCanvasKitTest();
group('$fragmentUsingIntlSegmenter', () {
test('fragments text into words', () {
final Uint32List breaks = fragmentUsingIntlSegmenter(
'Hello world 你好世界',
IntlSegmenterGranularity.word,
);
expect(
breaks,
orderedEquals(<int>[0, 5, 6, 11, 12, 14, 16]),
);
});
test('fragments multi-line text into words', () {
final Uint32List breaks = fragmentUsingIntlSegmenter(
'Lorem ipsum\ndolor 你好世界 sit\namet',
IntlSegmenterGranularity.word,
);
expect(
breaks,
orderedEquals(<int>[
0, 5, 6, 11, 12, // "Lorem ipsum\n"
17, 18, 20, 22, 23, 26, 27, // "dolor 你好世界 sit\n"
31, // "amet"
]),
);
});
test('fragments text into grapheme clusters', () {
// The smiley emoji has a length of 2.
// The family emoji has a length of 11.
final Uint32List breaks = fragmentUsingIntlSegmenter(
'Lorem🙂ipsum👨👩👧👦',
IntlSegmenterGranularity.grapheme,
);
expect(
breaks,
orderedEquals(<int>[
0, 1, 2, 3, 4, 5, 7, // "Lorem🙂"
8, 9, 10, 11, 12, 23, // "ipsum👨👩👧👦"
]),
);
});
test('fragments multi-line text into grapheme clusters', () {
// The smiley emojis have a length of 2 each.
// The family emoji has a length of 11.
final Uint32List breaks = fragmentUsingIntlSegmenter(
'Lorem🙂\nipsum👨👩👧👦dolor\n😄',
IntlSegmenterGranularity.grapheme,
);
expect(
breaks,
orderedEquals(<int>[
0, 1, 2, 3, 4, 5, 7, 8, // "Lorem🙂\n"
9, 10, 11, 12, 13, 24, // "ipsum👨👩👧👦"
25, 26, 27, 28, 29, 30, 32, // "dolor😄\n"
]),
);
});
}, skip: !browserSupportsCanvaskitChromium);
group('$fragmentUsingV8LineBreaker', () {
const int kSoft = 0;
const int kHard = 1;
test('fragments text into soft and hard line breaks', () {
final Uint32List breaks = fragmentUsingV8LineBreaker(
'Lorem-ipsum 你好🙂\nDolor sit',
);
expect(
breaks,
orderedEquals(<int>[
0, kSoft,
6, kSoft, // "Lorem-"
12, kSoft, // "ipsum "
13, kSoft, // "你"
14, kSoft, // "好"
17, kHard, // "🙂\n"
23, kSoft, // "Dolor "
26, kSoft, // "sit"
]),
);
});
}, skip: !browserSupportsCanvaskitChromium);
group('segmentText', () {
setUp(() {
segmentationCache.clear();
});
tearDown(() {
segmentationCache.clear();
});
test('segments correctly', () {
const String text = 'Lorem-ipsum 你好🙂\nDolor sit';
final SegmentationResult segmentation = segmentText(text);
expect(
segmentation.words,
fragmentUsingIntlSegmenter(text, IntlSegmenterGranularity.word),
);
expect(
segmentation.graphemes,
fragmentUsingIntlSegmenter(text, IntlSegmenterGranularity.grapheme),
);
expect(
segmentation.breaks,
fragmentUsingV8LineBreaker(text),
);
});
test('caches segmentation results in LRU fashion', () {
const String text1 = 'hello';
segmentText(text1);
expect(segmentationCache.small.debugItemQueue, hasLength(1));
expect(segmentationCache.small[text1], isNotNull);
const String text2 = 'world';
segmentText(text2);
expect(segmentationCache.small.debugItemQueue, hasLength(2));
expect(segmentationCache.small[text2], isNotNull);
// "world" was segmented last, so it should be first, as in most recently used.
expect(segmentationCache.small.debugItemQueue.first.key, 'world');
expect(segmentationCache.small.debugItemQueue.last.key, 'hello');
});
test('puts segmentation results in the appropriate cache', () {
final String smallText = 'a' * (kSmallParagraphCacheSpec.maxTextLength - 1);
segmentText(smallText);
expect(segmentationCache.small.debugItemQueue, hasLength(1));
expect(segmentationCache.medium.debugItemQueue, hasLength(0));
expect(segmentationCache.large.debugItemQueue, hasLength(0));
expect(segmentationCache.small[smallText], isNotNull);
segmentationCache.clear();
final String mediumText = 'a' * (kMediumParagraphCacheSpec.maxTextLength - 1);
segmentText(mediumText);
expect(segmentationCache.small.debugItemQueue, hasLength(0));
expect(segmentationCache.medium.debugItemQueue, hasLength(1));
expect(segmentationCache.large.debugItemQueue, hasLength(0));
expect(segmentationCache.medium[mediumText], isNotNull);
segmentationCache.clear();
final String largeText = 'a' * (kLargeParagraphCacheSpec.maxTextLength - 1);
segmentText(largeText);
expect(segmentationCache.small.debugItemQueue, hasLength(0));
expect(segmentationCache.medium.debugItemQueue, hasLength(0));
expect(segmentationCache.large.debugItemQueue, hasLength(1));
expect(segmentationCache.large[largeText], isNotNull);
segmentationCache.clear();
// Should not cache extremely large texts.
final String tooLargeText = 'a' * (kLargeParagraphCacheSpec.maxTextLength + 1);
segmentText(tooLargeText);
expect(segmentationCache.small.debugItemQueue, hasLength(0));
expect(segmentationCache.medium.debugItemQueue, hasLength(0));
expect(segmentationCache.large.debugItemQueue, hasLength(0));
segmentationCache.clear();
});
test('has a limit on the number of entries', () {
testCacheCapacity(segmentationCache.small, kSmallParagraphCacheSpec);
testCacheCapacity(segmentationCache.medium, kMediumParagraphCacheSpec);
testCacheCapacity(segmentationCache.large, kLargeParagraphCacheSpec);
}, timeout: const Timeout.factor(4));
}, skip: !browserSupportsCanvaskitChromium);
}
void testCacheCapacity(
LruCache<String, SegmentationResult> cache,
SegmentationCacheSpec spec,
) {
// 1. Fill the cache.
for (int i = 0; i < spec.cacheSize; i++) {
final String text = _randomString(spec.maxTextLength);
segmentText(text);
// The segmented text should have been added to the cache.
// TODO(mdebbar): This may fail if the random string generator generates
// the same string twice.
expect(cache.debugItemQueue, hasLength(i + 1));
}
// 2. Make sure the cache is full.
expect(cache.length, spec.cacheSize);
// 3. Add more items to the cache.
for (int i = 0; i < 10; i++) {
final String text = _randomString(spec.maxTextLength);
segmentText(text);
// The cache size should remain the same.
expect(cache.debugItemQueue, hasLength(spec.cacheSize));
}
// 4. Clear the cache.
cache.clear();
}
int _seed = 0;
String _randomString(int length) {
const String allChars = ' 1234567890'
'abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
final String text = '*' * length;
return text.replaceAllMapped(
'*',
// Passing a seed so the results are reproducible.
(_) => allChars[Random(_seed++).nextInt(allChars.length)],
);
}
| engine/lib/web_ui/test/canvaskit/text_fragmenter_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/text_fragmenter_test.dart",
"repo_id": "engine",
"token_count": 3202
} | 274 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine/browser_detection.dart';
import 'package:ui/src/engine/dom.dart';
import 'package:ui/src/engine/text_editing/composition_aware_mixin.dart';
import 'package:ui/src/engine/text_editing/text_editing.dart';
import '../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
class _MockWithCompositionAwareMixin with CompositionAwareMixin {
// These variables should be equal to their counterparts in CompositionAwareMixin.
// Separate so the counterparts in CompositionAwareMixin can be private.
static const String _kCompositionUpdate = 'compositionupdate';
static const String _kCompositionStart = 'compositionstart';
static const String _kCompositionEnd = 'compositionend';
}
DomHTMLInputElement get _inputElement {
return defaultTextEditingRoot.querySelectorAll('input').first as DomHTMLInputElement;
}
GloballyPositionedTextEditingStrategy _enableEditingStrategy({
required bool deltaModel,
void Function(EditingState?, TextEditingDeltaState?)? onChange,
}) {
final HybridTextEditing owner = HybridTextEditing();
owner.configuration = InputConfiguration(enableDeltaModel: deltaModel);
final GloballyPositionedTextEditingStrategy editingStrategy =
GloballyPositionedTextEditingStrategy(owner);
owner.debugTextEditingStrategyOverride = editingStrategy;
editingStrategy.enable(owner.configuration!, onChange: onChange ?? (_, __) {}, onAction: (_) {});
return editingStrategy;
}
Future<void> testMain() async {
await bootstrapAndRunApp(withImplicitView: true);
const String fakeComposingText = 'ImComposingText';
group('$CompositionAwareMixin', () {
late TextEditingStrategy editingStrategy;
setUp(() {
editingStrategy = _enableEditingStrategy(deltaModel: false);
});
tearDown(() {
editingStrategy.disable();
});
group('composition end', () {
test('should reset composing text on handle composition end', () {
final _MockWithCompositionAwareMixin mockWithCompositionAwareMixin =
_MockWithCompositionAwareMixin();
mockWithCompositionAwareMixin.composingText = fakeComposingText;
mockWithCompositionAwareMixin.addCompositionEventHandlers(_inputElement);
_inputElement.dispatchEvent(createDomEvent('Event', _MockWithCompositionAwareMixin._kCompositionEnd));
expect(mockWithCompositionAwareMixin.composingText, null);
});
});
group('composition start', () {
test('should reset composing text on handle composition start', () {
final _MockWithCompositionAwareMixin mockWithCompositionAwareMixin =
_MockWithCompositionAwareMixin();
mockWithCompositionAwareMixin.composingText = fakeComposingText;
mockWithCompositionAwareMixin.addCompositionEventHandlers(_inputElement);
_inputElement.dispatchEvent(createDomEvent('Event', _MockWithCompositionAwareMixin._kCompositionStart));
expect(mockWithCompositionAwareMixin.composingText, null);
});
});
group('composition update', () {
test('should set composing text to event composing text', () {
const String fakeEventText = 'IAmComposingThis';
final _MockWithCompositionAwareMixin mockWithCompositionAwareMixin =
_MockWithCompositionAwareMixin();
mockWithCompositionAwareMixin.composingText = fakeComposingText;
mockWithCompositionAwareMixin.addCompositionEventHandlers(_inputElement);
_inputElement.dispatchEvent(createDomCompositionEvent(
_MockWithCompositionAwareMixin._kCompositionUpdate,
<Object?, Object?>{ 'data': fakeEventText }
));
expect(mockWithCompositionAwareMixin.composingText, fakeEventText);
});
});
group('determine composition state', () {
test('should return editing state if extentOffset is null', () {
final EditingState editingState = EditingState(text: 'Test');
final _MockWithCompositionAwareMixin mockWithCompositionAwareMixin =
_MockWithCompositionAwareMixin();
mockWithCompositionAwareMixin.composingText = 'Test';
expect(
mockWithCompositionAwareMixin.determineCompositionState(editingState),
editingState,
);
});
test('should return editing state if composingText is null', () {
final EditingState editingState = EditingState(
text: 'Test',
baseOffset: 0,
extentOffset: 4,
);
final _MockWithCompositionAwareMixin mockWithCompositionAwareMixin =
_MockWithCompositionAwareMixin();
expect(
mockWithCompositionAwareMixin.determineCompositionState(editingState),
editingState,
);
});
test('should return editing state if text is null', () {
final EditingState editingState = EditingState(
baseOffset: 0,
extentOffset: 0,
);
final _MockWithCompositionAwareMixin mockWithCompositionAwareMixin =
_MockWithCompositionAwareMixin();
mockWithCompositionAwareMixin.composingText = 'Test';
expect(
mockWithCompositionAwareMixin.determineCompositionState(editingState),
editingState,
);
});
test(
'should return editing state if extentOffset is smaller than composingText length',
() {
const String composingText = 'composeMe';
final EditingState editingState = EditingState(
text: 'Test',
baseOffset: 0,
extentOffset: 4,
);
final _MockWithCompositionAwareMixin mockWithCompositionAwareMixin =
_MockWithCompositionAwareMixin();
mockWithCompositionAwareMixin.composingText = composingText;
expect(
mockWithCompositionAwareMixin.determineCompositionState(editingState),
editingState,
);
});
test('should return new composition state - compositing middle of text',
() {
const int baseOffset = 7;
const String composingText = 'Test';
final EditingState editingState = EditingState(
text: 'Testing',
baseOffset: baseOffset,
extentOffset: baseOffset,
);
final _MockWithCompositionAwareMixin mockWithCompositionAwareMixin =
_MockWithCompositionAwareMixin();
mockWithCompositionAwareMixin.composingText = composingText;
const int expectedComposingBase = baseOffset - composingText.length;
expect(
mockWithCompositionAwareMixin.determineCompositionState(editingState),
editingState.copyWith(
composingBaseOffset: expectedComposingBase,
composingExtentOffset: expectedComposingBase + composingText.length,
),
);
});
test(
'should return new composition state - compositing from beginning of text',
() {
const String composingText = '今日は';
final EditingState editingState = EditingState(
text: '今日は',
baseOffset: 0,
extentOffset: 3,
);
final _MockWithCompositionAwareMixin mockWithCompositionAwareMixin =
_MockWithCompositionAwareMixin();
mockWithCompositionAwareMixin.composingText = composingText;
const int expectedComposingBase = 0;
expect(
mockWithCompositionAwareMixin
.determineCompositionState(editingState),
editingState.copyWith(
composingBaseOffset: expectedComposingBase,
composingExtentOffset:
expectedComposingBase + composingText.length));
});
});
});
group('composing range', () {
late GloballyPositionedTextEditingStrategy editingStrategy;
setUp(() {
editingStrategy = _enableEditingStrategy(deltaModel: false);
});
tearDown(() {
editingStrategy.disable();
});
test('should be [0, compostionStrLength] on new composition', () {
const String composingText = 'hi';
_inputElement.dispatchEvent(createDomCompositionEvent(
_MockWithCompositionAwareMixin._kCompositionUpdate,
<Object?, Object?>{'data': composingText}));
// Set the selection text.
_inputElement.value = composingText;
_inputElement.dispatchEvent(createDomEvent('Event', 'input'));
expect(
editingStrategy.lastEditingState,
isA<EditingState>()
.having((EditingState editingState) => editingState.composingBaseOffset,
'composingBaseOffset', 0)
.having((EditingState editingState) => editingState.composingExtentOffset,
'composingExtentOffset', composingText.length));
});
test(
'should be [beforeComposingText - composingText, compostionStrLength] on composition in the middle of text',
() {
const String composingText = 'hi';
const String beforeComposingText = 'beforeComposingText';
const String afterComposingText = 'afterComposingText';
// Type in the text box, then move cursor to the middle.
_inputElement.value = '$beforeComposingText$afterComposingText';
_inputElement.setSelectionRange(beforeComposingText.length, beforeComposingText.length);
_inputElement.dispatchEvent(createDomCompositionEvent(
_MockWithCompositionAwareMixin._kCompositionUpdate,
<Object?, Object?>{ 'data': composingText }
));
// Flush editing state (since we did not compositionend).
_inputElement.dispatchEvent(createDomEvent('Event', 'input'));
expect(
editingStrategy.lastEditingState,
isA<EditingState>()
.having((EditingState editingState) => editingState.composingBaseOffset,
'composingBaseOffset', beforeComposingText.length - composingText.length)
.having((EditingState editingState) => editingState.composingExtentOffset,
'composingExtentOffset', beforeComposingText.length));
});
});
group('Text Editing Delta Model', () {
late GloballyPositionedTextEditingStrategy editingStrategy;
final StreamController<TextEditingDeltaState?> deltaStream =
StreamController<TextEditingDeltaState?>.broadcast();
setUp(() {
editingStrategy = _enableEditingStrategy(
deltaModel: true,
onChange: (_, TextEditingDeltaState? deltaState) => deltaStream.add(deltaState)
);
});
tearDown(() {
editingStrategy.disable();
});
test('should have newly entered composing characters', () async {
const String newComposingText = 'n';
editingStrategy.setEditingState(EditingState(text: newComposingText, baseOffset: 1, extentOffset: 1));
final Future<dynamic> containExpect = expectLater(
deltaStream.stream.first,
completion(isA<TextEditingDeltaState>()
.having((TextEditingDeltaState deltaState) => deltaState.composingOffset, 'composingOffset', 0)
.having((TextEditingDeltaState deltaState) => deltaState.composingExtent, 'composingExtent', newComposingText.length)
));
_inputElement.dispatchEvent(createDomCompositionEvent(
_MockWithCompositionAwareMixin._kCompositionUpdate,
<Object?, Object?>{ 'data': newComposingText }));
await containExpect;
});
test('should emit changed composition', () async {
const String newComposingCharsInOrder = 'hiCompose';
for (int currCharIndex = 0; currCharIndex < newComposingCharsInOrder.length; currCharIndex++) {
final String currComposingSubstr = newComposingCharsInOrder.substring(0, currCharIndex + 1);
editingStrategy.setEditingState(
EditingState(text: currComposingSubstr, baseOffset: currCharIndex + 1, extentOffset: currCharIndex + 1)
);
final Future<dynamic> containExpect = expectLater(
deltaStream.stream.first,
completion(isA<TextEditingDeltaState>()
.having((TextEditingDeltaState deltaState) => deltaState.composingOffset, 'composingOffset', 0)
.having((TextEditingDeltaState deltaState) => deltaState.composingExtent, 'composingExtent', currCharIndex + 1)
));
_inputElement.dispatchEvent(createDomCompositionEvent(
_MockWithCompositionAwareMixin._kCompositionUpdate,
<Object?, Object?>{ 'data': currComposingSubstr }));
await containExpect;
}
},
// TODO(antholeole): This test fails on Firefox because of how it orders events;
// it's likely that this will be fixed by https://github.com/flutter/flutter/issues/105243.
// Until the refactor gets merged, this test should run on all other browsers to prevent
// regressions in the meantime.
skip: browserEngine == BrowserEngine.firefox);
});
}
| engine/lib/web_ui/test/engine/composition_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/composition_test.dart",
"repo_id": "engine",
"token_count": 4967
} | 275 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/ui.dart';
import '../common/matchers.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
// These tests should be kept in sync with the VM tests in
// testing/dart/lerp_test.dart.
void testMain() {
test('lerpDouble should return null if and only if both inputs are null', () {
expect(lerpDouble(null, null, 1.0), isNull);
expect(lerpDouble(5.0, null, 0.25), isNotNull);
expect(lerpDouble(null, 5.0, 0.25), isNotNull);
expect(lerpDouble(5, null, 0.25), isNotNull);
expect(lerpDouble(null, 5, 0.25), isNotNull);
});
test('lerpDouble should treat a null input as 0 if the other input is non-null', () {
expect(lerpDouble(null, 10.0, 0.25), within(from: 2.5));
expect(lerpDouble(10.0, null, 0.25), within(from: 7.5));
expect(lerpDouble(null, 10, 0.25), within(from: 2.5));
expect(lerpDouble(10, null, 0.25), within(from: 7.5));
});
test('lerpDouble should handle interpolation values < 0.0', () {
expect(lerpDouble(0.0, 10.0, -5.0), within(from: -50.0));
expect(lerpDouble(10.0, 0.0, -5.0), within(from: 60.0));
expect(lerpDouble(0, 10, -5), within(from: -50.0));
expect(lerpDouble(10, 0, -5), within(from: 60.0));
});
test('lerpDouble should return the start value at 0.0', () {
expect(lerpDouble(2.0, 10.0, 0.0), 2.0);
expect(lerpDouble(10.0, 2.0, 0.0), 10.0);
expect(lerpDouble(2, 10, 0), 2);
expect(lerpDouble(10, 2, 0), 10);
});
test('lerpDouble should interpolate between two values', () {
expect(lerpDouble(0.0, 10.0, 0.25), within(from: 2.5));
expect(lerpDouble(10.0, 0.0, 0.25), within(from: 7.5));
expect(lerpDouble(0, 10, 0.25), within(from: 2.5));
expect(lerpDouble(10, 0, 0.25), within(from: 7.5));
// Exact answer: 20.0 - 1.0e-29
expect(lerpDouble(10.0, 1.0e30, 1.0e-29), within(from: 20.0));
// Exact answer: 5.0 + 5.0e29
expect(lerpDouble(10.0, 1.0e30, 0.5), within(from: 5.0e29));
});
test('lerpDouble should return the end value at 1.0', () {
expect(lerpDouble(2.0, 10.0, 1.0), 10.0);
expect(lerpDouble(10.0, 2.0, 1.0), 2.0);
expect(lerpDouble(0, 10, 5), 50);
expect(lerpDouble(10, 0, 5), -40);
expect(lerpDouble(1.0e30, 10.0, 1.0), 10.0);
expect(lerpDouble(10.0, 1.0e30, 0.0), 10.0);
});
test('lerpDouble should handle interpolation values > 1.0', () {
expect(lerpDouble(0.0, 10.0, 5.0), within(from: 50.0));
expect(lerpDouble(10.0, 0.0, 5.0), within(from: -40.0));
expect(lerpDouble(0, 10, 5), within(from: 50.0));
expect(lerpDouble(10, 0, 5), within(from: -40.0));
});
test('lerpDouble should return input value in all cases if begin/end are equal', () {
expect(lerpDouble(10.0, 10.0, 5.0), 10.0);
expect(lerpDouble(10.0, 10.0, double.nan), 10.0);
expect(lerpDouble(10.0, 10.0, double.infinity), 10.0);
expect(lerpDouble(10.0, 10.0, -double.infinity), 10.0);
expect(lerpDouble(10, 10, 5.0), 10.0);
expect(lerpDouble(10, 10, double.nan), 10.0);
expect(lerpDouble(10, 10, double.infinity), 10.0);
expect(lerpDouble(10, 10, -double.infinity), 10.0);
expect(lerpDouble(double.nan, double.nan, 5.0), isNaN);
expect(lerpDouble(double.nan, double.nan, double.nan), isNaN);
expect(lerpDouble(double.nan, double.nan, double.infinity), isNaN);
expect(lerpDouble(double.nan, double.nan, -double.infinity), isNaN);
expect(lerpDouble(double.infinity, double.infinity, 5.0), double.infinity);
expect(lerpDouble(double.infinity, double.infinity, double.nan), double.infinity);
expect(lerpDouble(double.infinity, double.infinity, double.infinity), double.infinity);
expect(lerpDouble(double.infinity, double.infinity, -double.infinity), double.infinity);
expect(lerpDouble(-double.infinity, -double.infinity, 5.0), -double.infinity);
expect(lerpDouble(-double.infinity, -double.infinity, double.nan), -double.infinity);
expect(lerpDouble(-double.infinity, -double.infinity, double.infinity), -double.infinity);
expect(lerpDouble(-double.infinity, -double.infinity, -double.infinity), -double.infinity);
});
test('lerpDouble should throw AssertionError if interpolation value is NaN and a != b', () {
expectAssertion(() => lerpDouble(0.0, 10.0, double.nan));
});
test('lerpDouble should throw AssertionError if interpolation value is +/- infinity and a != b', () {
expectAssertion(() => lerpDouble(0.0, 10.0, double.infinity));
expectAssertion(() => lerpDouble(0.0, 10.0, -double.infinity));
});
test('lerpDouble should throw AssertionError if either start or end are NaN', () {
expectAssertion(() => lerpDouble(double.nan, 10.0, 5.0));
expectAssertion(() => lerpDouble(0.0, double.nan, 5.0));
});
test('lerpDouble should throw AssertionError if either start or end are +/- infinity', () {
expectAssertion(() => lerpDouble(double.infinity, 10.0, 5.0));
expectAssertion(() => lerpDouble(-double.infinity, 10.0, 5.0));
expectAssertion(() => lerpDouble(0.0, double.infinity, 5.0));
expectAssertion(() => lerpDouble(0.0, -double.infinity, 5.0));
});
}
typedef DoubleFunction = double? Function();
/// Asserts that `callback` throws an [AssertionError].
///
/// Verifies that the specified callback throws an [AssertionError] when
/// running in with assertions enabled. When asserts are not enabled, such as
/// when running using a release-mode VM with default settings, this acts as a
/// no-op.
void expectAssertion(DoubleFunction callback) {
bool assertsEnabled = false;
assert(() {
assertsEnabled = true;
return true;
}());
if (assertsEnabled) {
bool threw = false;
try {
callback();
} catch (e) {
expect(e is AssertionError, isTrue);
threw = true;
}
expect(threw, isTrue);
}
}
| engine/lib/web_ui/test/engine/lerp_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/lerp_test.dart",
"repo_id": "engine",
"token_count": 2387
} | 276 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:quiver/testing/async.dart';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('RawKeyboard', () {
/// Used to save and restore [PlatformDispatcher.onPlatformMessage] after each test.
ui.PlatformMessageCallback? savedCallback;
setUp(() {
savedCallback = ui.PlatformDispatcher.instance.onPlatformMessage;
});
tearDown(() {
ui.PlatformDispatcher.instance.onPlatformMessage = savedCallback;
});
test('initializes and disposes', () {
expect(RawKeyboard.instance, isNull);
RawKeyboard.initialize();
expect(RawKeyboard.instance, isA<RawKeyboard>());
RawKeyboard.instance!.dispose();
expect(RawKeyboard.instance, isNull);
});
test('dispatches keyup to flutter/keyevent channel', () {
RawKeyboard.initialize();
String? channelReceived;
Map<String, dynamic>? dataReceived;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
channelReceived = channel;
dataReceived = const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>?;
};
DomKeyboardEvent event;
// Dispatch a keydown event first so that KeyboardBinding will recognize the keyup event.
// and will not set preventDefault on it.
event = dispatchKeyboardEvent('keydown', key: 'SomeKey', code: 'SomeCode', keyCode: 1);
event = dispatchKeyboardEvent('keyup', key: 'SomeKey', code: 'SomeCode', keyCode: 1);
expect(event.defaultPrevented, isFalse);
expect(channelReceived, 'flutter/keyevent');
expect(dataReceived, <String, dynamic>{
'type': 'keyup',
'keymap': 'web',
'code': 'SomeCode',
'location': 0,
'key': 'SomeKey',
'metaState': 0x0,
'keyCode': 1,
});
RawKeyboard.instance!.dispose();
});
test('dispatches keydown to flutter/keyevent channel', () {
RawKeyboard.initialize();
String? channelReceived;
Map<String, dynamic>? dataReceived;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
channelReceived = channel;
dataReceived = const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>?;
};
DomKeyboardEvent event;
event =
dispatchKeyboardEvent('keydown', key: 'SomeKey', code: 'SomeCode', keyCode: 1);
expect(channelReceived, 'flutter/keyevent');
expect(dataReceived, <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'SomeCode',
'key': 'SomeKey',
'location': 0,
'metaState': 0x0,
'keyCode': 1,
});
expect(event.defaultPrevented, isFalse);
RawKeyboard.instance!.dispose();
});
test('dispatches correct meta state', () {
RawKeyboard.initialize();
Map<String, dynamic>? dataReceived;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
dataReceived = const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>?;
};
DomKeyboardEvent event;
event = dispatchKeyboardEvent(
'keydown',
key: 'SomeKey',
code: 'SomeCode',
isControlPressed: true,
);
expect(event.defaultPrevented, isFalse);
expect(dataReceived, <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'SomeCode',
'key': 'SomeKey',
'location': 0,
// ctrl
'metaState': 0x4,
'keyCode': 0,
});
event = dispatchKeyboardEvent(
'keydown',
key: 'SomeKey',
code: 'SomeCode',
isShiftPressed: true,
isAltPressed: true,
isMetaPressed: true,
);
expect(event.defaultPrevented, isFalse);
expect(dataReceived, <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'SomeCode',
'key': 'SomeKey',
'location': 0,
// shift alt meta
'metaState': 0x1 | 0x2 | 0x8,
'keyCode': 0,
});
RawKeyboard.instance!.dispose();
});
// Regression test for https://github.com/flutter/flutter/issues/125672.
test('updates meta state for Meta key and wrong DOM event metaKey value (Linux)', () {
RawKeyboard.initialize();
Map<String, dynamic>? dataReceived;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
dataReceived = const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>?;
};
// Purposely send an incoherent DOM event where Meta key is pressed but event.metaKey is not set to true.
final DomKeyboardEvent event = dispatchKeyboardEvent(
'keydown',
key: 'Meta',
code: 'MetaLeft',
);
expect(event.defaultPrevented, isFalse);
expect(dataReceived, <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'MetaLeft',
'key': 'Meta',
'location': 0,
'metaState': 0x8,
'keyCode': 0,
});
RawKeyboard.instance!.dispose();
}, skip: operatingSystem != OperatingSystem.linux);
// Regression test for https://github.com/flutter/flutter/issues/141186.
test('updates meta state for Meta key seen as "Process" key', () {
RawKeyboard.initialize();
Map<String, dynamic>? dataReceived;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
dataReceived = const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>?;
};
// Purposely send a DOM event where Meta key is pressed but event.metaKey is not set to true.
// This can happen when the Meta key is seen as the 'Process' key.
final DomKeyboardEvent event = dispatchKeyboardEvent(
'keydown',
key: 'Process',
code: 'MetaLeft',
location: 1,
keyCode: 229,
);
expect(event.defaultPrevented, isFalse);
expect(dataReceived, <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'MetaLeft',
'key': 'Process',
'location': 1,
'metaState': 0x8,
'keyCode': 229,
});
RawKeyboard.instance!.dispose();
});
test('dispatches repeat events', () {
RawKeyboard.initialize();
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
DomKeyboardEvent event;
event = dispatchKeyboardEvent(
'keydown',
key: 'SomeKey',
code: 'SomeCode',
repeat: true,
);
expect(event.defaultPrevented, isFalse);
event = dispatchKeyboardEvent(
'keydown',
key: 'SomeKey',
code: 'SomeCode',
repeat: true,
);
expect(event.defaultPrevented, isFalse);
event = dispatchKeyboardEvent(
'keydown',
key: 'SomeKey',
code: 'SomeCode',
repeat: true,
);
expect(event.defaultPrevented, isFalse);
final Map<String, dynamic> expectedMessage = <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'SomeCode',
'key': 'SomeKey',
'location': 0,
'metaState': 0,
'keyCode': 0,
};
expect(messages, <Map<String, dynamic>>[
expectedMessage,
expectedMessage,
expectedMessage,
]);
RawKeyboard.instance!.dispose();
});
test('stops dispatching events after dispose', () {
RawKeyboard.initialize();
int count = 0;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
count += 1;
};
dispatchKeyboardEvent('keydown');
expect(count, 1);
dispatchKeyboardEvent('keyup');
expect(count, 2);
RawKeyboard.instance!.dispose();
expect(RawKeyboard.instance, isNull);
// No more event dispatching.
dispatchKeyboardEvent('keydown');
expect(count, 2);
dispatchKeyboardEvent('keyup');
expect(count, 2);
});
test('prevents default when key is handled by the framework', () {
RawKeyboard.initialize();
int count = 0;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
count += 1;
final ByteData response = const JSONMessageCodec().encodeMessage(<String, dynamic>{'handled': true})!;
callback!(response);
};
final DomKeyboardEvent event = dispatchKeyboardEvent(
'keydown',
key: 'Tab',
code: 'Tab',
);
expect(event.defaultPrevented, isTrue);
expect(count, 1);
RawKeyboard.instance!.dispose();
});
test("Doesn't prevent default when key is not handled by the framework", () {
RawKeyboard.initialize();
int count = 0;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
count += 1;
final ByteData response = const JSONMessageCodec().encodeMessage(<String, dynamic>{'handled': false})!;
callback!(response);
};
final DomKeyboardEvent event = dispatchKeyboardEvent(
'keydown',
key: 'Tab',
code: 'Tab',
);
expect(event.defaultPrevented, isFalse);
expect(count, 1);
RawKeyboard.instance!.dispose();
});
test('keyboard events should be triggered on text fields', () {
RawKeyboard.initialize();
int count = 0;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
count += 1;
};
useTextEditingElement((DomElement element) {
final DomKeyboardEvent event = dispatchKeyboardEvent(
'keydown',
key: 'SomeKey',
code: 'SomeCode',
target: element,
);
expect(event.defaultPrevented, isFalse);
expect(count, 1);
});
RawKeyboard.instance!.dispose();
});
test(
'the "Tab" key should never be ignored when it is not a part of IME composition',
() {
RawKeyboard.initialize();
int count = 0;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
count += 1;
final ByteData response = const JSONMessageCodec().encodeMessage(<String, dynamic>{'handled': true})!;
callback!(response);
};
useTextEditingElement((DomElement element) {
final DomKeyboardEvent event = dispatchKeyboardEvent(
'keydown',
key: 'Tab',
code: 'Tab',
target: element,
);
expect(event.defaultPrevented, isTrue);
expect(count, 1);
});
RawKeyboard.instance!.dispose();
});
test('Ignores event when Tab key is hit during IME composition', () {
RawKeyboard.initialize();
int count = 0;
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
count += 1;
final ByteData response = const JSONMessageCodec()
.encodeMessage(<String, dynamic>{'handled': true})!;
callback!(response);
};
useTextEditingElement((DomElement element) {
dispatchKeyboardEvent('keydown',
key: 'Tab', code: 'Tab', target: element, isComposing: true);
expect(count, 0); // no message sent to framework
});
RawKeyboard.instance!.dispose();
});
testFakeAsync(
'On macOS, synthesize keyup when shortcut is handled by the system',
(FakeAsync async) {
// This can happen when the user clicks `cmd+alt+i` to open devtools. Here
// is the sequence we receive from the browser in such case:
//
// keydown(cmd) -> keydown(alt) -> keydown(i) -> keyup(alt) -> keyup(cmd)
//
// There's no `keyup(i)`. The web engine is expected to synthesize a
// `keyup(i)` event.
RawKeyboard.initialize(onMacOs: true);
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
dispatchKeyboardEvent(
'keydown',
key: 'Meta',
code: 'MetaLeft',
location: 1,
isMetaPressed: true,
);
dispatchKeyboardEvent(
'keydown',
key: 'Alt',
code: 'AltLeft',
location: 1,
isMetaPressed: true,
isAltPressed: true,
);
dispatchKeyboardEvent(
'keydown',
key: 'i',
code: 'KeyI',
isMetaPressed: true,
isAltPressed: true,
);
async.elapse(const Duration(milliseconds: 10));
dispatchKeyboardEvent(
'keyup',
key: 'Meta',
code: 'MetaLeft',
location: 1,
isAltPressed: true,
);
dispatchKeyboardEvent(
'keyup',
key: 'Alt',
code: 'AltLeft',
location: 1,
);
// Notice no `keyup` for "i".
expect(messages, <Map<String, dynamic>>[
<String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'key': 'Meta',
'code': 'MetaLeft',
'location': 1,
// meta
'metaState': 0x8,
'keyCode': 0,
},
<String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'key': 'Alt',
'code': 'AltLeft',
'location': 1,
// alt meta
'metaState': 0x2 | 0x8,
'keyCode': 0,
},
<String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'key': 'i',
'code': 'KeyI',
'location': 0,
// alt meta
'metaState': 0x2 | 0x8,
'keyCode': 0,
},
<String, dynamic>{
'type': 'keyup',
'keymap': 'web',
'key': 'Meta',
'code': 'MetaLeft',
'location': 1,
// alt
'metaState': 0x2,
'keyCode': 0,
},
<String, dynamic>{
'type': 'keyup',
'keymap': 'web',
'key': 'Alt',
'code': 'AltLeft',
'location': 1,
'metaState': 0x0,
'keyCode': 0,
},
]);
messages.clear();
// Still too eary to synthesize a keyup event.
async.elapse(const Duration(milliseconds: 50));
expect(messages, isEmpty);
async.elapse(const Duration(seconds: 3));
expect(messages, <Map<String, dynamic>>[
<String, dynamic>{
'type': 'keyup',
'keymap': 'web',
'key': 'i',
'code': 'KeyI',
'location': 0,
'metaState': 0x0,
'keyCode': 0,
}
]);
RawKeyboard.instance!.dispose();
},
);
testFakeAsync(
'On macOS, do not synthesize keyup when we receive repeat events',
(FakeAsync async) {
RawKeyboard.initialize(onMacOs: true);
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
dispatchKeyboardEvent(
'keydown',
key: 'Meta',
code: 'MetaLeft',
location: 1,
isMetaPressed: true,
);
dispatchKeyboardEvent(
'keydown',
key: 'Alt',
code: 'AltLeft',
location: 1,
isMetaPressed: true,
isAltPressed: true,
);
dispatchKeyboardEvent(
'keydown',
key: 'i',
code: 'KeyI',
isMetaPressed: true,
isAltPressed: true,
);
async.elapse(const Duration(milliseconds: 10));
dispatchKeyboardEvent(
'keyup',
key: 'Meta',
code: 'MetaLeft',
location: 1,
isAltPressed: true,
);
dispatchKeyboardEvent(
'keyup',
key: 'Alt',
code: 'AltLeft',
location: 1,
);
// Notice no `keyup` for "i".
messages.clear();
// Spend more than 2 seconds sending repeat events and make sure no
// keyup was synthesized.
for (int i = 0; i < 20; i++) {
async.elapse(const Duration(milliseconds: 100));
dispatchKeyboardEvent(
'keydown',
key: 'i',
code: 'KeyI',
repeat: true,
);
}
// There should be no synthesized keyup.
expect(messages, hasLength(20));
for (int i = 0; i < 20; i++) {
expect(messages[i], <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'key': 'i',
'code': 'KeyI',
'location': 0,
'metaState': 0x0,
'keyCode': 0,
});
}
messages.clear();
RawKeyboard.instance!.dispose();
},
);
testFakeAsync(
'On macOS, do not synthesize keyup when keys are not affected by meta modifiers',
(FakeAsync async) {
RawKeyboard.initialize();
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
dispatchKeyboardEvent(
'keydown',
key: 'i',
code: 'KeyI',
);
dispatchKeyboardEvent(
'keydown',
key: 'o',
code: 'KeyO',
);
messages.clear();
// Wait for a long-enough period of time and no events
// should be synthesized
async.elapse(const Duration(seconds: 3));
expect(messages, hasLength(0));
RawKeyboard.instance!.dispose();
},
);
testFakeAsync('On macOS, do not synthesize keyup for meta keys', (FakeAsync async) {
RawKeyboard.initialize(onMacOs: true);
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
dispatchKeyboardEvent(
'keydown',
key: 'Meta',
code: 'MetaLeft',
location: 1,
isMetaPressed: true,
);
dispatchKeyboardEvent(
'keydown',
key: 'Alt',
code: 'AltLeft',
location: 1,
isMetaPressed: true,
isAltPressed: true,
);
dispatchKeyboardEvent(
'keydown',
key: 'i',
code: 'KeyI',
isMetaPressed: true,
isAltPressed: true,
);
async.elapse(const Duration(milliseconds: 10));
dispatchKeyboardEvent(
'keyup',
key: 'Meta',
code: 'MetaLeft',
location: 1,
isAltPressed: true,
);
// Notice no `keyup` for "AltLeft" and "i".
messages.clear();
// There has been no repeat events for "AltLeft" nor "i". Only "i" should
// synthesize a keyup event.
async.elapse(const Duration(seconds: 3));
expect(messages, <Map<String, dynamic>>[
<String, dynamic>{
'type': 'keyup',
'keymap': 'web',
'key': 'i',
'code': 'KeyI',
'location': 0,
// alt
'metaState': 0x2,
'keyCode': 0,
}
]);
RawKeyboard.instance!.dispose();
});
testFakeAsync(
'On non-macOS, do not synthesize keyup for shortcuts',
(FakeAsync async) {
RawKeyboard.initialize(); // onMacOs: false
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
dispatchKeyboardEvent(
'keydown',
key: 'Meta',
code: 'MetaLeft',
location: 1,
isMetaPressed: true,
);
dispatchKeyboardEvent(
'keydown',
key: 'Alt',
code: 'AltLeft',
location: 1,
isMetaPressed: true,
isAltPressed: true,
);
dispatchKeyboardEvent(
'keydown',
key: 'i',
code: 'KeyI',
isMetaPressed: true,
isAltPressed: true,
);
async.elapse(const Duration(milliseconds: 10));
dispatchKeyboardEvent(
'keyup',
key: 'Meta',
code: 'MetaLeft',
location: 1,
isAltPressed: true,
);
dispatchKeyboardEvent(
'keyup',
key: 'Alt',
code: 'AltLeft',
location: 1,
);
// Notice no `keyup` for "i".
expect(messages, hasLength(5));
messages.clear();
// Never synthesize keyup events.
async.elapse(const Duration(seconds: 3));
expect(messages, isEmpty);
RawKeyboard.instance!.dispose();
},
);
});
}
typedef ElementCallback = void Function(DomElement element);
void useTextEditingElement(ElementCallback callback) {
final DomHTMLInputElement input = createDomHTMLInputElement();
input.classList.add(HybridTextEditing.textEditingClass);
try {
domDocument.body!.append(input);
callback(input);
} finally {
input.remove();
}
}
DomKeyboardEvent dispatchKeyboardEvent(
String type, {
DomEventTarget? target,
String? key,
String? code,
int location = 0,
bool repeat = false,
bool isShiftPressed = false,
bool isAltPressed = false,
bool isControlPressed = false,
bool isMetaPressed = false,
bool isComposing = false,
int keyCode = 0,
}) {
target ??= domWindow;
final DomKeyboardEvent event = createDomKeyboardEvent(type, <String, Object> {
if (key != null) 'key': key,
if (code != null) 'code': code,
'location': location,
'repeat': repeat,
'shiftKey': isShiftPressed,
'altKey': isAltPressed,
'ctrlKey': isControlPressed,
'metaKey': isMetaPressed,
'isComposing': isComposing,
'keyCode': keyCode,
'bubbles': true,
'cancelable': true,
});
target.dispatchEvent(event);
return event;
}
typedef FakeAsyncTest = void Function(FakeAsync);
void testFakeAsync(String description, FakeAsyncTest fn) {
test(description, () {
FakeAsync().run(fn);
});
}
| engine/lib/web_ui/test/engine/raw_keyboard_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/raw_keyboard_test.dart",
"repo_id": "engine",
"token_count": 11103
} | 277 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
// Some tests here cannot run in JS mode because of limited numerics. This
// should be fixed by dart2wasm.
const bool _kSupportsDartNumerics = !identical(0, 0.0);
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('Write and read buffer round-trip', () {
test('of single byte', () {
final WriteBuffer write = WriteBuffer();
write.putUint8(201);
final ByteData written = write.done();
expect(written.lengthInBytes, equals(1));
final ReadBuffer read = ReadBuffer(written);
expect(read.getUint8(), equals(201));
});
test('of 32-bit integer', () {
final WriteBuffer write = WriteBuffer();
write.putInt32(-9);
final ByteData written = write.done();
expect(written.lengthInBytes, equals(4));
final ReadBuffer read = ReadBuffer(written);
expect(read.getInt32(), equals(-9));
});
test('of 64-bit integer', () {
final WriteBuffer write = WriteBuffer();
write.putInt64(-9000000000000);
final ByteData written = write.done();
expect(written.lengthInBytes, equals(8));
final ReadBuffer read = ReadBuffer(written);
expect(read.getInt64(), equals(-9000000000000));
}, skip: !_kSupportsDartNumerics);
test('of double', () {
final WriteBuffer write = WriteBuffer();
write.putFloat64(3.14);
final ByteData written = write.done();
expect(written.lengthInBytes, equals(8));
final ReadBuffer read = ReadBuffer(written);
expect(read.getFloat64(), equals(3.14));
});
test('of 32-bit int list when unaligned', () {
final Int32List integers = Int32List.fromList(<int>[-99, 2, 99]);
final WriteBuffer write = WriteBuffer();
write.putUint8(9);
write.putInt32List(integers);
final ByteData written = write.done();
expect(written.lengthInBytes, equals(16));
final ReadBuffer read = ReadBuffer(written);
read.getUint8();
expect(read.getInt32List(3), equals(integers));
});
test('of 64-bit int list when unaligned', () {
final Int64List integers = Int64List.fromList(<int>[-99, 2, 99]);
final WriteBuffer write = WriteBuffer();
write.putUint8(9);
write.putInt64List(integers);
final ByteData written = write.done();
expect(written.lengthInBytes, equals(32));
final ReadBuffer read = ReadBuffer(written);
read.getUint8();
expect(read.getInt64List(3), equals(integers));
}, skip: !_kSupportsDartNumerics);
test('of double list when unaligned', () {
final Float64List doubles =
Float64List.fromList(<double>[3.14, double.nan]);
final WriteBuffer write = WriteBuffer();
write.putUint8(9);
write.putFloat64List(doubles);
final ByteData written = write.done();
expect(written.lengthInBytes, equals(24));
final ReadBuffer read = ReadBuffer(written);
read.getUint8();
final Float64List readDoubles = read.getFloat64List(2);
expect(readDoubles[0], equals(3.14));
expect(readDoubles[1], isNaN);
});
});
}
| engine/lib/web_ui/test/engine/services/serialization_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/services/serialization_test.dart",
"repo_id": "engine",
"token_count": 1272
} | 278 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
void main() {
internalBootstrapBrowserTest(() => doTests);
}
void doTests() {
final DomEventTarget eventTarget = createDomElement('div');
group('dprChanged Stream', () {
late DisplayDprStream dprStream;
setUp(() async {
dprStream = DisplayDprStream(EngineFlutterDisplay.instance,
overrides: DebugDisplayDprStreamOverrides(
getMediaQuery: (_) => eventTarget,
));
});
test('funnels display DPR on every mediaQuery "change" event.', () async {
final Future<List<double>> dprs = dprStream.dprChanged
.take(3)
.timeout(const Duration(seconds: 1))
.toList();
// Simulate the events
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(6.9);
eventTarget.dispatchEvent(createDomEvent('Event', 'change'));
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(4.2);
eventTarget.dispatchEvent(createDomEvent('Event', 'change'));
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(0.71);
eventTarget.dispatchEvent(createDomEvent('Event', 'change'));
expect(await dprs, <double>[6.9, 4.2, 0.71]);
});
});
}
| engine/lib/web_ui/test/engine/view_embedder/display_dpr_stream_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/view_embedder/display_dpr_stream_test.dart",
"repo_id": "engine",
"token_count": 541
} | 279 |
// 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' hide TextStyle;
import 'package:web_engine_tester/golden_tester.dart';
import '../common/test_initialization.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);
final SurfacePaint testPaint = SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFFFF00FF);
setUpUnitTests();
// Regression test for https://github.com/flutter/flutter/issues/51514
test("Canvas is reused and z-index doesn't leak across paints", () async {
final EngineCanvas engineCanvas = BitmapCanvas(screenRect,
RenderStrategy());
const Rect region = Rect.fromLTWH(0, 0, 500, 500);
// Draw first frame into engine canvas.
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTWH(1, 2, 300, 400));
final Path path = Path()
..moveTo(3, 0)
..lineTo(100, 97);
rc.drawPath(path, testPaint);
rc.endRecording();
rc.apply(engineCanvas, screenRect);
engineCanvas.endOfPaint();
DomElement sceneElement = createDomElement('flt-scene');
if (isIosSafari) {
// Shrink to fit on the iPhone screen.
sceneElement.style.position = 'absolute';
sceneElement.style.transformOrigin = '0 0 0';
sceneElement.style.transform = 'scale(0.3)';
}
sceneElement.append(engineCanvas.rootElement);
domDocument.body!.append(sceneElement);
final DomCanvasElement canvas = domDocument.querySelector('canvas')! as DomCanvasElement;
// ! Since canvas is first element, it should have zIndex = -1 for correct
// paint order.
expect(canvas.style.zIndex , '-1');
// Add id to canvas element to test for reuse.
const String kTestId = 'test-id-5698';
canvas.id = kTestId;
sceneElement.remove();
// Clear so resources are marked for reuse.
engineCanvas.clear();
// Now paint a second scene to same [BitmapCanvas] but paint an image
// before the path to move canvas element into second position.
final RecordingCanvas rc2 =
RecordingCanvas(const Rect.fromLTWH(1, 2, 300, 400));
final Path path2 = Path()
..moveTo(3, 0)
..quadraticBezierTo(100, 0, 100, 100);
rc2.drawImage(_createRealTestImage(), Offset.zero, SurfacePaint());
rc2.drawPath(path2, testPaint);
rc2.endRecording();
rc2.apply(engineCanvas, screenRect);
sceneElement = createDomElement('flt-scene');
if (isIosSafari) {
// Shrink to fit on the iPhone screen.
sceneElement.style.position = 'absolute';
sceneElement.style.transformOrigin = '0 0 0';
sceneElement.style.transform = 'scale(0.3)';
}
sceneElement.append(engineCanvas.rootElement);
domDocument.body!.append(sceneElement);
final DomCanvasElement canvas2 = domDocument.querySelector('canvas')! as DomCanvasElement;
// ZIndex should have been cleared since we have image element preceding
// canvas.
expect(canvas.style.zIndex != '-1', isTrue);
expect(canvas2.id, kTestId);
await matchGoldenFile('bitmap_canvas_reuse_zindex.png', region: region);
});
}
const String _base64Encoded20x20TestImage = 'iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAC4jAAAuIwF4pT92AAAA'
'B3RJTUUH5AMFFBksg4i3gQAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAAj'
'SURBVDjLY2TAC/7jlWVioACMah4ZmhnxpyHG0QAb1UyZZgBjWAIm/clP0AAAAABJRU5ErkJggg==';
HtmlImage _createRealTestImage() {
return HtmlImage(
createDomHTMLImageElement()
..src = 'data:text/plain;base64,$_base64Encoded20x20TestImage',
20,
20,
);
}
| engine/lib/web_ui/test/html/canvas_reuse_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/canvas_reuse_golden_test.dart",
"repo_id": "engine",
"token_count": 1511
} | 280 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import 'package:web_engine_tester/golden_tester.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
const Rect region = Rect.fromLTWH(0, 0, 300, 300);
late BitmapCanvas canvas;
late BitmapCanvas domCanvas;
setUp(() {
canvas = BitmapCanvas(region, RenderStrategy());
// setting isInsideSvgFilterTree true forces use of DOM canvas
domCanvas = BitmapCanvas(region, RenderStrategy()..isInsideSvgFilterTree = true);
});
tearDown(() {
canvas.rootElement.remove();
domCanvas.rootElement.remove();
});
test('draws lines with varying strokeWidth', () async {
paintLines(canvas);
domDocument.body!.append(canvas.rootElement);
await matchGoldenFile('canvas_lines_thickness.png', region: region);
});
test('draws lines with varying strokeWidth with dom canvas', () async {
paintLines(domCanvas);
domDocument.body!.append(domCanvas.rootElement);
await matchGoldenFile('canvas_lines_thickness_dom_canvas.png', region: region);
});
test('draws lines with negative Offset values with dom canvas', () async {
// test rendering lines correctly with negative offset when using DOM
final SurfacePaintData paintWithStyle = SurfacePaintData()
..color = 0xFFE91E63 // Colors.pink
..style = PaintingStyle.stroke
..strokeWidth = 16
..strokeCap = StrokeCap.round;
// canvas.drawLine ignores paint.style (defaults to fill) according to api docs.
// expect lines are rendered the same regardless of the set paint.style
final SurfacePaintData paintWithoutStyle = SurfacePaintData()
..color = 0xFF4CAF50 // Colors.green
..strokeWidth = 16
..strokeCap = StrokeCap.round;
// test vertical, horizontal, and diagonal lines
final List<Offset> points = <Offset>[
const Offset(-25, 50), const Offset(45, 50),
const Offset(100, -25), const Offset(100, 200),
const Offset(-150, -145), const Offset(100, 200),
];
final List<Offset> shiftedPoints = points.map((Offset point) => point.translate(20, 20)).toList();
paintLinesFromPoints(domCanvas, paintWithStyle, points);
paintLinesFromPoints(domCanvas, paintWithoutStyle, shiftedPoints);
domDocument.body!.append(domCanvas.rootElement);
await matchGoldenFile('canvas_lines_with_negative_offset.png', region: region);
});
test('drawLines method respects strokeCap with dom canvas', () async {
final SurfacePaintData paintStrokeCapRound = SurfacePaintData()
..color = 0xFFE91E63 // Colors.pink
..strokeWidth = 16
..strokeCap = StrokeCap.round;
final SurfacePaintData paintStrokeCapSquare = SurfacePaintData()
..color = 0xFF4CAF50 // Colors.green
..strokeWidth = 16
..strokeCap = StrokeCap.square;
final SurfacePaintData paintStrokeCapButt = SurfacePaintData()
..color = 0xFFFF9800 // Colors.orange
..strokeWidth = 16
..strokeCap = StrokeCap.butt;
// test vertical, horizontal, and diagonal lines
final List<Offset> points = <Offset>[
const Offset(5, 50), const Offset(45, 50),
const Offset(100, 5), const Offset(100, 200),
const Offset(5, 10), const Offset(100, 200),
];
final List<Offset> shiftedPoints = points.map((Offset point) => point.translate(50, 50)).toList();
final List<Offset> twiceShiftedPoints = shiftedPoints.map((Offset point) => point.translate(50, 50)).toList();
paintLinesFromPoints(domCanvas, paintStrokeCapRound, points);
paintLinesFromPoints(domCanvas, paintStrokeCapSquare, shiftedPoints);
paintLinesFromPoints(domCanvas, paintStrokeCapButt, twiceShiftedPoints);
domDocument.body!.append(domCanvas.rootElement);
await matchGoldenFile('canvas_lines_with_strokeCap.png', region: region);
});
}
void paintLines(BitmapCanvas canvas) {
final SurfacePaintData nullPaint = SurfacePaintData()
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
final SurfacePaintData paint1 = SurfacePaintData()
..color = 0xFF9E9E9E // Colors.grey
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
final SurfacePaintData paint2 = SurfacePaintData()
..color = 0x7fff0000
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
final SurfacePaintData paint3 = SurfacePaintData()
..color = 0xFF4CAF50 //Colors.green
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
// Draw markers around 100x100 box
canvas.drawLine(const Offset(50, 40), const Offset(148, 40), nullPaint);
canvas.drawLine(const Offset(50, 50), const Offset(52, 50), paint1);
canvas.drawLine(const Offset(150, 50), const Offset(148, 50), paint1);
canvas.drawLine(const Offset(50, 150), const Offset(52, 150), paint1);
canvas.drawLine(const Offset(150, 150), const Offset(148, 150), paint1);
// Draw diagonal
canvas.drawLine(const Offset(50, 50), const Offset(150, 150), paint2);
// Draw horizontal
paint3.strokeWidth = 1.0;
paint3.color = 0xFFFF0000;
canvas.drawLine(const Offset(50, 55), const Offset(150, 55), paint3);
paint3.strokeWidth = 2.0;
paint3.color = 0xFF2196F3; // Colors.blue;
canvas.drawLine(const Offset(50, 60), const Offset(150, 60), paint3);
paint3.strokeWidth = 4.0;
paint3.color = 0xFFFF9800; // Colors.orange;
canvas.drawLine(const Offset(50, 70), const Offset(150, 70), paint3);
}
void paintLinesFromPoints(BitmapCanvas canvas, SurfacePaintData paint, List<Offset> points) {
// points list contains pairs of Offset points, so for loop step is 2
for (int i = 0; i < points.length - 1; i += 2) {
canvas.drawLine(points[i], points[i + 1], paint);
}
}
| engine/lib/web_ui/test/html/drawing/canvas_lines_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/drawing/canvas_lines_golden_test.dart",
"repo_id": "engine",
"token_count": 2037
} | 281 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
import 'helper.dart';
/// Class that controls some details of how screenshotting is made.
class EngineGoldenTester {
EngineGoldenTester(this.viewportSize);
/// The size of the browser window used in this golden test.
final ui.Size viewportSize;
static Future<EngineGoldenTester> initialize(
{ui.Size viewportSize = const ui.Size(2400, 1800)}) async {
assert(() {
if (viewportSize.width.ceil() != viewportSize.width ||
viewportSize.height.ceil() != viewportSize.height) {
throw Exception(
'Gold only supports integer screen sizes, but found: $viewportSize');
}
return true;
}());
return EngineGoldenTester(viewportSize);
}
ui.Rect get viewportRegion =>
ui.Rect.fromLTWH(0, 0, viewportSize.width, viewportSize.height);
Future<void> diffScreenshot(
String fileName, {
ui.Rect? region,
}) async {
await matchGoldenFile(
'$fileName.png',
region: region ?? viewportRegion,
);
}
/// Prepares the DOM and inserts all the necessary nodes, then invokes Gold's
/// screenshot diffing.
///
/// It also cleans up the DOM after itself.
Future<void> diffCanvasScreenshot(
EngineCanvas canvas,
String fileName, {
ui.Rect? region,
}) async {
// Wrap in <flt-scene> so that our CSS selectors kick in.
final DomElement sceneElement = createDomElement('flt-scene');
if (isIosSafari) {
// Shrink to fit on the iPhone screen.
sceneElement.style.position = 'absolute';
sceneElement.style.transformOrigin = '0 0 0';
sceneElement.style.transform = 'scale(0.3)';
}
try {
sceneElement.append(canvas.rootElement);
domDocument.body!.append(sceneElement);
String screenshotName = '${fileName}_${canvas.runtimeType}';
if (canvas is BitmapCanvas) {
screenshotName += '+canvas_measurement';
}
await diffScreenshot(
screenshotName,
region: region,
);
} finally {
// The page is reused across tests, so remove the element after taking the
// screenshot.
sceneElement.remove();
}
}
}
/// Runs the given test [body] with each type of canvas.
void testEachCanvas(String description, CanvasTest body) {
const ui.Rect bounds = ui.Rect.fromLTWH(0, 0, 600, 800);
test('$description (bitmap + canvas measurement)', () async {
return body(BitmapCanvas(bounds, RenderStrategy()));
});
test('$description (dom)', () {
return body(DomCanvas(domDocument.createElement('flt-picture')));
});
}
final ui.TextStyle _defaultTextStyle = ui.TextStyle(
color: const ui.Color(0xFF000000),
fontFamily: 'Roboto',
fontSize: 14,
);
CanvasParagraph paragraph(
String text, {
ui.ParagraphStyle? paragraphStyle,
ui.TextStyle? textStyle,
double maxWidth = double.infinity,
}) {
final ui.ParagraphBuilder builder =
ui.ParagraphBuilder(paragraphStyle ?? ui.ParagraphStyle());
builder.pushStyle(textStyle ?? _defaultTextStyle);
builder.addText(text);
builder.pop();
final CanvasParagraph paragraph = builder.build() as CanvasParagraph;
paragraph.layout(ui.ParagraphConstraints(width: maxWidth));
return paragraph;
}
| engine/lib/web_ui/test/html/paragraph/text_goldens.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/paragraph/text_goldens.dart",
"repo_id": "engine",
"token_count": 1259
} | 282 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
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 {
setUpUnitTests(
setUpTestViewDimensions: false,
);
Future<void> testGradient(String fileName, Shader shader,
{Rect paintRect = const Rect.fromLTRB(50, 50, 300, 300),
Rect shaderRect = const Rect.fromLTRB(50, 50, 300, 300),
Rect region = const Rect.fromLTWH(0, 0, 500, 500)}) async {
final RecordingCanvas rc = RecordingCanvas(region);
final SurfacePaint paint = SurfacePaint()..shader = shader;
final Path path = Path();
path.addRect(paintRect);
rc.drawPath(path, paint);
await canvasScreenshot(rc, fileName, region: region);
}
test('Should draw centered radial gradient.', () async {
const Rect shaderRect = Rect.fromLTRB(50, 50, 300, 300);
await testGradient(
'radial_gradient_centered',
Gradient.radial(
Offset((shaderRect.left + shaderRect.right) / 2,
(shaderRect.top + shaderRect.bottom) / 2),
shaderRect.width / 2,
<Color>[
const Color.fromARGB(255, 0, 0, 0),
const Color.fromARGB(255, 0, 0, 255)
]));
});
test('Should draw right bottom centered radial gradient.', () async {
const Rect shaderRect = Rect.fromLTRB(50, 50, 300, 300);
await testGradient(
'radial_gradient_right_bottom',
Gradient.radial(
Offset(shaderRect.right, shaderRect.bottom),
shaderRect.width / 2,
<Color>[
const Color.fromARGB(255, 0, 0, 0),
const Color.fromARGB(255, 0, 0, 255)
],
),
);
});
test('Should draw with radial gradient with TileMode.clamp.', () async {
const Rect shaderRect = Rect.fromLTRB(50, 50, 100, 100);
await testGradient(
'radial_gradient_tilemode_clamp',
Gradient.radial(
Offset((shaderRect.left + shaderRect.right) / 2,
(shaderRect.top + shaderRect.bottom) / 2),
shaderRect.width / 2,
<Color>[
const Color.fromARGB(255, 0, 0, 0),
const Color.fromARGB(255, 0, 0, 255)
],
<double>[0.0, 1.0],
),
shaderRect: shaderRect,
);
});
const List<Color> colors = <Color>[
Color(0xFF000000),
Color(0xFFFF3C38),
Color(0xFFFF8C42),
Color(0xFFFFF275),
Color(0xFF6699CC),
Color(0xFF656D78),];
const List<double> colorStops = <double>[0.0, 0.05, 0.4, 0.6, 0.9, 1.0];
test('Should draw with radial gradient with TileMode.repeated.', () async {
const Rect shaderRect = Rect.fromLTRB(50, 50, 100, 100);
await testGradient(
'radial_gradient_tilemode_repeated',
Gradient.radial(
Offset((shaderRect.left + shaderRect.right) / 2,
(shaderRect.top + shaderRect.bottom) / 2),
shaderRect.width / 2,
colors,
colorStops,
TileMode.repeated),
shaderRect: shaderRect,
region: const Rect.fromLTWH(0, 0, 600, 800));
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
test('Should draw with radial gradient with TileMode.mirrored.', () async {
const Rect shaderRect = Rect.fromLTRB(50, 50, 100, 100);
await testGradient(
'radial_gradient_tilemode_mirror',
Gradient.radial(
Offset((shaderRect.left + shaderRect.right) / 2,
(shaderRect.top + shaderRect.bottom) / 2),
shaderRect.width / 2,
colors,
colorStops,
TileMode.mirror),
shaderRect: shaderRect,
region: const Rect.fromLTWH(0, 0, 600, 800));
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
}
| engine/lib/web_ui/test/html/shaders/radial_gradient_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/shaders/radial_gradient_golden_test.dart",
"repo_id": "engine",
"token_count": 1791
} | 283 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('$WordBreaker', () {
test('Does not go beyond the ends of a string', () {
expect(WordBreaker.prevBreakIndex('foo', -1), 0);
expect(WordBreaker.prevBreakIndex('foo', 0), 0);
expect(WordBreaker.prevBreakIndex('foo', 'foo'.length + 1), 'foo'.length);
expect(WordBreaker.nextBreakIndex('foo', -1), 0);
expect(WordBreaker.nextBreakIndex('foo', 'foo'.length), 'foo'.length);
expect(WordBreaker.nextBreakIndex('foo', 'foo'.length + 1), 'foo'.length);
});
test('Words and spaces', () {
expectWords('foo bar', <String>['foo', ' ', 'bar']);
expectWords('foo bar', <String>['foo', ' ', 'bar']);
});
test('Single-letter words', () {
expectWords('foo a bar', <String>['foo', ' ', 'a', ' ', 'bar']);
expectWords('a b c', <String>['a', ' ', 'b', ' ', 'c']);
expectWords(' a b ', <String>[' ', 'a', ' ', 'b', ' ']);
});
test('Multiple consecutive spaces', () {
// Different types of whitespace:
final String oghamSpace = String.fromCharCode(0x1680);
final String punctuationSpace = String.fromCharCode(0x2008);
final String mathSpace = String.fromCharCode(0x205F);
final String ideographicSpace = String.fromCharCode(0x3000);
expectWords(
'foo$oghamSpace ${punctuationSpace}bar',
<String>['foo', '$oghamSpace $punctuationSpace', 'bar'],
);
expectWords(
'$mathSpace$ideographicSpace${oghamSpace}foo',
<String>['$mathSpace$ideographicSpace$oghamSpace', 'foo'],
);
expectWords(
'foo$punctuationSpace$mathSpace ',
<String>['foo', '$punctuationSpace$mathSpace '],
);
expectWords(
'$oghamSpace $punctuationSpace$mathSpace$ideographicSpace',
<String>['$oghamSpace $punctuationSpace$mathSpace$ideographicSpace'],
);
});
test('Punctuation', () {
expectWords('foo,bar.baz', <String>['foo', ',', 'bar.baz']);
expectWords('foo_bar', <String>['foo_bar']);
expectWords('foo-bar', <String>['foo', '-', 'bar']);
});
test('Numeric', () {
expectWords('12ab ab12', <String>['12ab', ' ', 'ab12']);
expectWords('ab12,34cd', <String>['ab12,34cd']);
expectWords('123,456_789.0', <String>['123,456_789.0']);
});
test('Quotes', () {
expectWords("Mike's bike", <String>["Mike's", ' ', 'bike']);
expectWords("Students' grades", <String>['Students', "'", ' ', 'grades']);
expectWords(
'Joe said: "I\'m here"',
<String>['Joe', ' ', 'said', ':', ' ', '"', "I'm", ' ', 'here', '"'],
);
});
// Hebrew letters have the same rules as other letters, except
// when they are around quotes. So we need to test those rules separately.
test('Hebrew with quotes', () {
// A few hebrew letters:
const String h1 = 'א';
const String h2 = 'ל';
const String h3 = 'ט';
// Test the single quote behavior that should be the same as other letters.
expectWords("$h1$h2'$h3", <String>["$h1$h2'$h3"]);
// Single quote following a hebrew shouldn't break.
expectWords("$h1$h2'", <String>["$h1$h2'"]);
expectWords("$h1$h2' $h3", <String>["$h1$h2'", ' ', h3]);
// Double quotes around hebrew words should break.
expectWords('"$h1$h3"', <String>['"', '$h1$h3', '"']);
// Double quotes within hebrew words shouldn't break.
expectWords('$h3"$h2', <String>['$h3"$h2']);
});
test('Newline, CR and LF', () {
final String newline = String.fromCharCode(0x000B);
// The only sequence of new lines that isn't a word boundary is CR×LF.
expectWords('foo\r\nbar', <String>['foo', '\r\n', 'bar']);
// All other sequences are considered word boundaries.
expectWords('foo\n\nbar', <String>['foo', '\n', '\n', 'bar']);
expectWords('foo\r\rbar', <String>['foo', '\r', '\r', 'bar']);
expectWords(
'foo$newline${newline}bar', <String>['foo', newline, newline, 'bar']);
expectWords('foo\n\rbar', <String>['foo', '\n', '\r', 'bar']);
expectWords('foo$newline\rbar', <String>['foo', newline, '\r', 'bar']);
expectWords('foo\r${newline}bar', <String>['foo', '\r', newline, 'bar']);
expectWords('foo$newline\nbar', <String>['foo', newline, '\n', 'bar']);
expectWords('foo\n${newline}bar', <String>['foo', '\n', newline, 'bar']);
});
test('katakana', () {
// Katakana letters should stick together but not with other letters.
expectWords('ナヌ', <String>['ナヌ']);
expectWords('ナabcヌ', <String>['ナ', 'abc', 'ヌ']);
// Katakana sometimes behaves the same as other letters.
expectWords('ナ,ヌ_イ', <String>['ナ', ',', 'ヌ_イ']);
// Katakana sometimes behaves differently from other letters.
expectWords('ナ.ヌ', <String>['ナ', '.', 'ヌ']);
expectWords("ナ'ヌ", <String>['ナ', "'", 'ヌ']);
expectWords('ナ12ヌ', <String>['ナ', '12', 'ヌ']);
});
});
}
void expectWords(String text, List<String> expectedWords) {
int strIndex = 0;
// Forward word break lookup.
for (final String word in expectedWords) {
final int nextBreak = WordBreaker.nextBreakIndex(text, strIndex);
expect(
nextBreak, strIndex + word.length,
reason: 'Forward word break lookup: expecting to move to the end of "$word" in "$text".'
);
strIndex += word.length;
}
// Backward word break lookup.
strIndex = text.length;
for (final String word in expectedWords.reversed) {
final int prevBreak = WordBreaker.prevBreakIndex(text, strIndex);
expect(
prevBreak, strIndex - word.length,
reason: 'Backward word break lookup: expecting to move to the start of "$word" in "$text".'
);
strIndex -= word.length;
}
}
| engine/lib/web_ui/test/html/text/word_breaker_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/text/word_breaker_test.dart",
"repo_id": "engine",
"token_count": 2454
} | 284 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/ui.dart' as ui;
import '../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(setUpTestViewDimensions: false);
// Previously the logic that set the effective font family would forget the
// original value and would print incorrect value in toString.
test('TextStyle remembers original fontFamily value', () {
final ui.TextStyle style1 = ui.TextStyle();
expect(style1.toString(), contains('fontFamily: unspecified'));
final ui.TextStyle style2 = ui.TextStyle(
fontFamily: 'Hello',
);
expect(style2.toString(), contains('fontFamily: Hello'));
});
test('ParagraphStyle remembers original fontFamily value', () {
final ui.ParagraphStyle style1 = ui.ParagraphStyle();
expect(style1.toString(), contains('fontFamily: unspecified'));
final ui.ParagraphStyle style2 = ui.ParagraphStyle(
fontFamily: 'Hello',
);
expect(style2.toString(), contains('fontFamily: Hello'));
});
}
| engine/lib/web_ui/test/ui/text_style_test_env_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/ui/text_style_test_env_test.dart",
"repo_id": "engine",
"token_count": 409
} | 285 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:isolate';
import 'dart:ui';
import 'dart:io' show Platform;
@pragma('vm:external-name', 'PassMessage')
external void passMessage(String message);
bool didCallRegistrantBeforeEntrypoint = false;
// Test the Dart plugin registrant.
@pragma('vm:entry-point')
class _PluginRegistrant {
@pragma('vm:entry-point')
static void register() {
if (didCallRegistrantBeforeEntrypoint) {
throw '_registerPlugins is being called twice';
}
didCallRegistrantBeforeEntrypoint = true;
}
}
@pragma('vm:entry-point')
void mainForPluginRegistrantTest() {
if (didCallRegistrantBeforeEntrypoint) {
passMessage('_PluginRegistrant.register() was called');
} else {
passMessage('_PluginRegistrant.register() was not called');
}
}
void main() {}
void dartPluginRegistrantIsolate(SendPort sendPort) {
DartPluginRegistrant.ensureInitialized();
sendPort.send(didCallRegistrantBeforeEntrypoint);
}
void registerBackgroundIsolate(List args) {
SendPort sendPort = args[0] as SendPort;
RootIsolateToken token = args[1] as RootIsolateToken;
PlatformDispatcher.instance.registerBackgroundIsolate(token);
sendPort.send(didCallRegistrantBeforeEntrypoint);
}
@pragma('vm:entry-point')
void callDartPluginRegistrantFromBackgroundIsolate() async {
ReceivePort receivePort = ReceivePort();
Isolate isolate = await Isolate.spawn(dartPluginRegistrantIsolate, receivePort.sendPort);
bool didCallEntrypoint = await receivePort.first;
if (didCallEntrypoint) {
passMessage('_PluginRegistrant.register() was called on background isolate');
} else {
passMessage('_PluginRegistrant.register() was not called on background isolate');
}
isolate.kill();
}
void noDartPluginRegistrantIsolate(SendPort sendPort) {
sendPort.send(didCallRegistrantBeforeEntrypoint);
}
@pragma('vm:entry-point')
void dontCallDartPluginRegistrantFromBackgroundIsolate() async {
ReceivePort receivePort = ReceivePort();
Isolate isolate = await Isolate.spawn(noDartPluginRegistrantIsolate, receivePort.sendPort);
bool didCallEntrypoint = await receivePort.first;
if (didCallEntrypoint) {
passMessage('_PluginRegistrant.register() was called on background isolate');
} else {
passMessage('_PluginRegistrant.register() was not called on background isolate');
}
isolate.kill();
}
@pragma('vm:entry-point')
void registerBackgroundIsolateCallsDartPluginRegistrant() async {
ReceivePort receivePort = ReceivePort();
Isolate isolate = await Isolate.spawn(registerBackgroundIsolate, [receivePort.sendPort, RootIsolateToken.instance]);
bool didCallEntrypoint = await receivePort.first;
if (didCallEntrypoint) {
passMessage('_PluginRegistrant.register() was called on background isolate');
} else {
passMessage('_PluginRegistrant.register() was not called on background isolate');
}
isolate.kill();
}
| engine/runtime/fixtures/dart_tool/flutter_build/dart_plugin_registrant.dart/0 | {
"file_path": "engine/runtime/fixtures/dart_tool/flutter_build/dart_plugin_registrant.dart",
"repo_id": "engine",
"token_count": 934
} | 286 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/base64.h"
#include "fml/logging.h"
#include "gtest/gtest.h"
#include <string>
namespace flutter {
namespace testing {
TEST(Base64, EncodeStrings) {
auto test = [](const std::string& input, const std::string& output) {
char buffer[256];
size_t len = Base64::Encode(input.c_str(), input.length(), &buffer);
FML_CHECK(len <= 256);
ASSERT_EQ(len, Base64::EncodedSize(input.length()));
std::string actual(buffer, len);
ASSERT_STREQ(actual.c_str(), output.c_str());
};
// Some arbitrary strings
test("apple", "YXBwbGU=");
test("BANANA", "QkFOQU5B");
test("Cherry Pie", "Q2hlcnJ5IFBpZQ==");
test("fLoCcInAuCiNiHiLiPiLiFiCaTiOn",
"ZkxvQ2NJbkF1Q2lOaUhpTGlQaUxpRmlDYVRpT24=");
test("", "");
}
TEST(Base64, EncodeBytes) {
auto test = [](const uint8_t input[], size_t num, const std::string& output) {
char buffer[512];
size_t len = Base64::Encode(input, num, &buffer);
FML_CHECK(len <= 512);
ASSERT_EQ(len, Base64::EncodedSize(num));
std::string actual(buffer, len);
ASSERT_STREQ(actual.c_str(), output.c_str());
};
// Some arbitrary raw bytes
uint8_t e[] = {0x02, 0x71, 0x82, 0x81, 0x82, 0x84, 0x59};
test(e, sizeof(e), "AnGCgYKEWQ==");
uint8_t pi[] = {0x03, 0x24, 0x3F, 0x6A, 0x88, 0x85};
test(pi, sizeof(pi), "AyQ/aoiF");
uint8_t bytes[256];
for (int i = 0; i < 256; i++) {
bytes[i] = i;
}
test(bytes, sizeof(bytes),
"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gIS"
"IjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFV"
"WV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJ"
"iouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8v"
"b6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8P"
"Hy8/T19vf4+fr7/P3+/w==");
}
TEST(Base64, DecodeStringsSuccess) {
auto test = [](const std::string& input, const std::string& output) {
char buffer[256];
size_t len = 0;
auto err = Base64::Decode(input.c_str(), input.length(), &buffer, &len);
ASSERT_EQ(err, Base64::Error::kNone);
FML_CHECK(len <= 256);
std::string actual(buffer, len);
ASSERT_STREQ(actual.c_str(), output.c_str());
};
// Some arbitrary strings
test("ZGF0ZQ==", "date");
test("RWdncGxhbnQ=", "Eggplant");
test("RmlzaCAmIENoaXBz", "Fish & Chips");
test("U3VQZVJjQWxJZlJhR2lMaVN0SWNFeFBpQWxJZE9jSW9Vcw==",
"SuPeRcAlIfRaGiLiStIcExPiAlIdOcIoUs");
// Spaces are ignored
test("Y X Bwb GU=", "apple");
}
TEST(Base64, DecodeStringsHasErrors) {
auto test = [](const std::string& input, Base64::Error expectedError) {
char buffer[256];
size_t len = 0;
auto err = Base64::Decode(input.c_str(), input.length(), &buffer, &len);
ASSERT_EQ(err, expectedError) << input;
};
test("Nuts&Bolts", Base64::Error::kBadChar);
test("Error!", Base64::Error::kBadChar);
test(":", Base64::Error::kBadChar);
test("RmlzaCAmIENoaXBz=", Base64::Error::kBadPadding);
// Some cases of bad padding may be ignored due to an internal optimization
// test("ZGF0ZQ=", Base64::Error::kBadPadding);
// test("RWdncGxhbnQ", Base64::Error::kBadPadding);
}
TEST(Base64, DecodeBytes) {
auto test = [](const std::string& input, const uint8_t output[], size_t num) {
char buffer[256];
size_t len = 0;
auto err = Base64::Decode(input.c_str(), input.length(), &buffer, &len);
ASSERT_EQ(err, Base64::Error::kNone);
FML_CHECK(len <= 256);
ASSERT_EQ(num, len) << input;
for (int i = 0; i < int(len); i++) {
ASSERT_EQ(uint8_t(buffer[i]), output[i]) << input << i;
}
};
// Some arbitrary raw bytes, same as the byte output above
uint8_t e[] = {0x02, 0x71, 0x82, 0x81, 0x82, 0x84, 0x59};
test("AnGCgYKEWQ==", e, sizeof(e));
uint8_t pi[] = {0x03, 0x24, 0x3F, 0x6A, 0x88, 0x85};
test("AyQ/aoiF", pi, sizeof(pi));
}
} // namespace testing
} // namespace flutter | engine/shell/common/base64_unittests.cc/0 | {
"file_path": "engine/shell/common/base64_unittests.cc",
"repo_id": "engine",
"token_count": 1921
} | 287 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/resource_cache_limit_calculator.h"
namespace flutter {
size_t ResourceCacheLimitCalculator::GetResourceCacheMaxBytes() {
size_t max_bytes = 0;
size_t max_bytes_threshold = max_bytes_threshold_ > 0
? max_bytes_threshold_
: std::numeric_limits<size_t>::max();
std::vector<fml::WeakPtr<ResourceCacheLimitItem>> live_items;
for (const auto& item : items_) {
if (item) {
live_items.push_back(item);
max_bytes += item->GetResourceCacheLimit();
}
}
items_ = std::move(live_items);
return std::min(max_bytes, max_bytes_threshold);
}
} // namespace flutter
| engine/shell/common/resource_cache_limit_calculator.cc/0 | {
"file_path": "engine/shell/common/resource_cache_limit_calculator.cc",
"repo_id": "engine",
"token_count": 340
} | 288 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "shell_test_external_view_embedder.h"
namespace flutter {
ShellTestExternalViewEmbedder::ShellTestExternalViewEmbedder(
const EndFrameCallBack& end_frame_call_back,
PostPrerollResult post_preroll_result,
bool support_thread_merging)
: end_frame_call_back_(end_frame_call_back),
post_preroll_result_(post_preroll_result),
support_thread_merging_(support_thread_merging),
submitted_frame_count_(0) {}
void ShellTestExternalViewEmbedder::UpdatePostPrerollResult(
PostPrerollResult post_preroll_result) {
post_preroll_result_ = post_preroll_result;
}
int ShellTestExternalViewEmbedder::GetSubmittedFrameCount() {
return submitted_frame_count_;
}
SkISize ShellTestExternalViewEmbedder::GetLastSubmittedFrameSize() {
return last_submitted_frame_size_;
}
std::vector<int64_t> ShellTestExternalViewEmbedder::GetVisitedPlatformViews() {
return visited_platform_views_;
}
MutatorsStack ShellTestExternalViewEmbedder::GetStack(int64_t view_id) {
return mutators_stacks_[view_id];
}
// |ExternalViewEmbedder|
void ShellTestExternalViewEmbedder::CancelFrame() {}
// |ExternalViewEmbedder|
void ShellTestExternalViewEmbedder::BeginFrame(
GrDirectContext* context,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {}
// |ExternalViewEmbedder|
void ShellTestExternalViewEmbedder::PrepareFlutterView(
int64_t flutter_view_id,
SkISize frame_size,
double device_pixel_ratio) {
visited_platform_views_.clear();
mutators_stacks_.clear();
current_composition_params_.clear();
}
// |ExternalViewEmbedder|
void ShellTestExternalViewEmbedder::PrerollCompositeEmbeddedView(
int64_t view_id,
std::unique_ptr<EmbeddedViewParams> params) {
SkRect view_bounds = SkRect::Make(frame_size_);
auto view = std::make_unique<DisplayListEmbedderViewSlice>(view_bounds);
slices_.insert_or_assign(view_id, std::move(view));
}
// |ExternalViewEmbedder|
PostPrerollResult ShellTestExternalViewEmbedder::PostPrerollAction(
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
FML_DCHECK(raster_thread_merger);
return post_preroll_result_;
}
// |ExternalViewEmbedder|
void ShellTestExternalViewEmbedder::PushVisitedPlatformView(int64_t view_id) {
visited_platform_views_.push_back(view_id);
}
// |ExternalViewEmbedder|
void ShellTestExternalViewEmbedder::PushFilterToVisitedPlatformViews(
const std::shared_ptr<const DlImageFilter>& filter,
const SkRect& filter_rect) {
for (int64_t id : visited_platform_views_) {
EmbeddedViewParams params = current_composition_params_[id];
params.PushImageFilter(filter, filter_rect);
current_composition_params_[id] = params;
mutators_stacks_[id] = params.mutatorsStack();
}
}
DlCanvas* ShellTestExternalViewEmbedder::CompositeEmbeddedView(
int64_t view_id) {
return slices_[view_id]->canvas();
}
// |ExternalViewEmbedder|
void ShellTestExternalViewEmbedder::SubmitFlutterView(
GrDirectContext* context,
const std::shared_ptr<impeller::AiksContext>& aiks_context,
std::unique_ptr<SurfaceFrame> frame) {
if (!frame) {
return;
}
frame->Submit();
if (frame->SkiaSurface()) {
last_submitted_frame_size_ = SkISize::Make(frame->SkiaSurface()->width(),
frame->SkiaSurface()->height());
} else {
last_submitted_frame_size_ = SkISize::MakeEmpty();
}
submitted_frame_count_++;
}
// |ExternalViewEmbedder|
void ShellTestExternalViewEmbedder::EndFrame(
bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
end_frame_call_back_(should_resubmit_frame, raster_thread_merger);
}
// |ExternalViewEmbedder|
DlCanvas* ShellTestExternalViewEmbedder::GetRootCanvas() {
return nullptr;
}
bool ShellTestExternalViewEmbedder::SupportsDynamicThreadMerging() {
return support_thread_merging_;
}
} // namespace flutter
| engine/shell/common/shell_test_external_view_embedder.cc/0 | {
"file_path": "engine/shell/common/shell_test_external_view_embedder.cc",
"repo_id": "engine",
"token_count": 1474
} | 289 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_IMPELLER_H_
#define FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_IMPELLER_H_
#include "flutter/shell/common/snapshot_controller.h"
namespace flutter {
class SnapshotControllerImpeller : public SnapshotController {
public:
explicit SnapshotControllerImpeller(
const SnapshotController::Delegate& delegate)
: SnapshotController(delegate) {}
sk_sp<DlImage> MakeRasterSnapshot(sk_sp<DisplayList> display_list,
SkISize size) override;
sk_sp<SkImage> ConvertToRasterImage(sk_sp<SkImage> image) override;
private:
sk_sp<DlImage> DoMakeRasterSnapshot(const sk_sp<DisplayList>& display_list,
SkISize size);
FML_DISALLOW_COPY_AND_ASSIGN(SnapshotControllerImpeller);
};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_IMPELLER_H_
| engine/shell/common/snapshot_controller_impeller.h/0 | {
"file_path": "engine/shell/common/snapshot_controller_impeller.h",
"repo_id": "engine",
"token_count": 431
} | 290 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_COMMON_VSYNC_WAITER_FALLBACK_H_
#define FLUTTER_SHELL_COMMON_VSYNC_WAITER_FALLBACK_H_
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/time/time_point.h"
#include "flutter/shell/common/vsync_waiter.h"
namespace flutter {
/// A |VsyncWaiter| that will fire at 60 fps irrespective of the vsync.
class VsyncWaiterFallback final : public VsyncWaiter {
public:
explicit VsyncWaiterFallback(const TaskRunners& task_runners,
bool for_testing = false);
~VsyncWaiterFallback() override;
private:
fml::TimePoint phase_;
const bool for_testing_;
// |VsyncWaiter|
void AwaitVSync() override;
FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiterFallback);
};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_VSYNC_WAITER_FALLBACK_H_
| engine/shell/common/vsync_waiter_fallback.h/0 | {
"file_path": "engine/shell/common/vsync_waiter_fallback.h",
"repo_id": "engine",
"token_count": 388
} | 291 |
// 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_metal_impeller.h"
#import <Metal/Metal.h>
#import <QuartzCore/QuartzCore.h>
#include "flutter/common/settings.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/trace_event.h"
#include "impeller/display_list/dl_dispatcher.h"
#include "impeller/renderer/backend/metal/surface_mtl.h"
#include "impeller/typographer/backends/skia/typographer_context_skia.h"
static_assert(!__has_feature(objc_arc), "ARC must be disabled.");
namespace flutter {
static std::shared_ptr<impeller::Renderer> CreateImpellerRenderer(
std::shared_ptr<impeller::Context> context) {
auto renderer = std::make_shared<impeller::Renderer>(std::move(context));
if (!renderer->IsValid()) {
FML_LOG(ERROR) << "Could not create valid Impeller Renderer.";
return nullptr;
}
return renderer;
}
GPUSurfaceMetalImpeller::GPUSurfaceMetalImpeller(GPUSurfaceMetalDelegate* delegate,
const std::shared_ptr<impeller::Context>& context,
bool render_to_surface)
: delegate_(delegate),
render_target_type_(delegate->GetRenderTargetType()),
impeller_renderer_(CreateImpellerRenderer(context)),
aiks_context_(
std::make_shared<impeller::AiksContext>(impeller_renderer_ ? context : nullptr,
impeller::TypographerContextSkia::Make())),
render_to_surface_(render_to_surface) {
// If this preference is explicitly set, we allow for disabling partial repaint.
NSNumber* disablePartialRepaint =
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTDisablePartialRepaint"];
if (disablePartialRepaint != nil) {
disable_partial_repaint_ = disablePartialRepaint.boolValue;
}
}
GPUSurfaceMetalImpeller::~GPUSurfaceMetalImpeller() = default;
// |Surface|
bool GPUSurfaceMetalImpeller::IsValid() {
return !!aiks_context_ && aiks_context_->IsValid();
}
// |Surface|
std::unique_ptr<SurfaceFrame> GPUSurfaceMetalImpeller::AcquireFrame(const SkISize& frame_size) {
TRACE_EVENT0("impeller", "GPUSurfaceMetalImpeller::AcquireFrame");
if (!IsValid()) {
FML_LOG(ERROR) << "Metal surface was invalid.";
return nullptr;
}
if (frame_size.isEmpty()) {
FML_LOG(ERROR) << "Metal 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);
}
switch (render_target_type_) {
case MTLRenderTargetType::kCAMetalLayer:
return AcquireFrameFromCAMetalLayer(frame_size);
case MTLRenderTargetType::kMTLTexture:
return AcquireFrameFromMTLTexture(frame_size);
default:
FML_CHECK(false) << "Unknown MTLRenderTargetType type.";
}
return nullptr;
}
std::unique_ptr<SurfaceFrame> GPUSurfaceMetalImpeller::AcquireFrameFromCAMetalLayer(
const SkISize& frame_size) {
auto layer = delegate_->GetCAMetalLayer(frame_size);
if (!layer) {
FML_LOG(ERROR) << "Invalid CAMetalLayer given by the embedder.";
return nullptr;
}
auto* mtl_layer = (CAMetalLayer*)layer;
auto drawable = impeller::SurfaceMTL::GetMetalDrawableAndValidate(
impeller_renderer_->GetContext(), mtl_layer);
if (!drawable) {
return nullptr;
}
if (Settings::kSurfaceDataAccessible) {
last_texture_.reset([drawable.texture retain]);
}
id<MTLTexture> last_texture = static_cast<id<MTLTexture>>(last_texture_);
SurfaceFrame::SubmitCallback submit_callback =
fml::MakeCopyable([damage = damage_,
disable_partial_repaint = disable_partial_repaint_, //
renderer = impeller_renderer_, //
aiks_context = aiks_context_, //
drawable, //
last_texture //
](SurfaceFrame& surface_frame, DlCanvas* canvas) mutable -> bool {
if (!aiks_context) {
return false;
}
auto display_list = surface_frame.BuildDisplayList();
if (!display_list) {
FML_LOG(ERROR) << "Could not build display list for surface frame.";
return false;
}
if (!disable_partial_repaint && damage) {
uintptr_t texture = reinterpret_cast<uintptr_t>(last_texture);
for (auto& entry : *damage) {
if (entry.first != texture) {
// Accumulate damage for other framebuffers
if (surface_frame.submit_info().frame_damage) {
entry.second.join(*surface_frame.submit_info().frame_damage);
}
}
}
// Reset accumulated damage for current framebuffer
(*damage)[texture] = SkIRect::MakeEmpty();
}
std::optional<impeller::IRect> clip_rect;
if (surface_frame.submit_info().buffer_damage.has_value()) {
auto buffer_damage = surface_frame.submit_info().buffer_damage;
clip_rect = impeller::IRect::MakeXYWH(buffer_damage->x(), buffer_damage->y(),
buffer_damage->width(), buffer_damage->height());
}
auto surface = impeller::SurfaceMTL::MakeFromMetalLayerDrawable(renderer->GetContext(),
drawable, clip_rect);
if (clip_rect && clip_rect->IsEmpty()) {
return surface->Present();
}
impeller::IRect cull_rect = surface->coverage();
SkIRect sk_cull_rect = SkIRect::MakeWH(cull_rect.GetWidth(), cull_rect.GetHeight());
impeller::DlDispatcher impeller_dispatcher(cull_rect);
display_list->Dispatch(impeller_dispatcher, sk_cull_rect);
auto picture = impeller_dispatcher.EndRecordingAsPicture();
return renderer->Render(
std::move(surface),
fml::MakeCopyable([aiks_context, picture = std::move(picture)](
impeller::RenderTarget& render_target) -> bool {
return aiks_context->Render(picture, render_target, /*reset_host_buffer=*/true);
}));
});
SurfaceFrame::FramebufferInfo framebuffer_info;
framebuffer_info.supports_readback = true;
if (!disable_partial_repaint_) {
// Provide accumulated damage to rasterizer (area in current framebuffer that lags behind
// front buffer)
uintptr_t texture = reinterpret_cast<uintptr_t>(drawable.texture);
auto i = damage_->find(texture);
if (i != damage_->end()) {
framebuffer_info.existing_damage = i->second;
}
framebuffer_info.supports_partial_repaint = true;
}
return std::make_unique<SurfaceFrame>(nullptr, // surface
framebuffer_info, // framebuffer info
submit_callback, // submit callback
frame_size, // frame size
nullptr, // context result
true // display list fallback
);
}
std::unique_ptr<SurfaceFrame> GPUSurfaceMetalImpeller::AcquireFrameFromMTLTexture(
const SkISize& frame_size) {
GPUMTLTextureInfo texture_info = delegate_->GetMTLTexture(frame_size);
id<MTLTexture> mtl_texture = (id<MTLTexture>)(texture_info.texture);
if (!mtl_texture) {
FML_LOG(ERROR) << "Invalid MTLTexture given by the embedder.";
return nullptr;
}
if (Settings::kSurfaceDataAccessible) {
last_texture_.reset([mtl_texture retain]);
}
SurfaceFrame::SubmitCallback submit_callback =
fml::MakeCopyable([disable_partial_repaint = disable_partial_repaint_, //
damage = damage_,
renderer = impeller_renderer_, //
aiks_context = aiks_context_, //
texture_info, //
mtl_texture, //
delegate = delegate_ //
](SurfaceFrame& surface_frame, DlCanvas* canvas) mutable -> bool {
if (!aiks_context) {
return false;
}
auto display_list = surface_frame.BuildDisplayList();
if (!display_list) {
FML_LOG(ERROR) << "Could not build display list for surface frame.";
return false;
}
if (!disable_partial_repaint && damage) {
uintptr_t texture_ptr = reinterpret_cast<uintptr_t>(mtl_texture);
for (auto& entry : *damage) {
if (entry.first != texture_ptr) {
// Accumulate damage for other framebuffers
if (surface_frame.submit_info().frame_damage) {
entry.second.join(*surface_frame.submit_info().frame_damage);
}
}
}
// Reset accumulated damage for current framebuffer
(*damage)[texture_ptr] = SkIRect::MakeEmpty();
}
std::optional<impeller::IRect> clip_rect;
if (surface_frame.submit_info().buffer_damage.has_value()) {
auto buffer_damage = surface_frame.submit_info().buffer_damage;
clip_rect = impeller::IRect::MakeXYWH(buffer_damage->x(), buffer_damage->y(),
buffer_damage->width(), buffer_damage->height());
}
auto surface =
impeller::SurfaceMTL::MakeFromTexture(renderer->GetContext(), mtl_texture, clip_rect);
if (clip_rect && clip_rect->IsEmpty()) {
return surface->Present();
}
impeller::IRect cull_rect = surface->coverage();
SkIRect sk_cull_rect = SkIRect::MakeWH(cull_rect.GetWidth(), cull_rect.GetHeight());
impeller::DlDispatcher impeller_dispatcher(cull_rect);
display_list->Dispatch(impeller_dispatcher, sk_cull_rect);
auto picture = impeller_dispatcher.EndRecordingAsPicture();
bool render_result = renderer->Render(
std::move(surface),
fml::MakeCopyable([aiks_context, picture = std::move(picture)](
impeller::RenderTarget& render_target) -> bool {
return aiks_context->Render(picture, render_target, /*reset_host_buffer=*/true);
}));
if (!render_result) {
FML_LOG(ERROR) << "Failed to render Impeller frame";
return false;
}
return delegate->PresentTexture(texture_info);
});
SurfaceFrame::FramebufferInfo framebuffer_info;
framebuffer_info.supports_readback = true;
if (!disable_partial_repaint_) {
// Provide accumulated damage to rasterizer (area in current framebuffer that lags behind
// front buffer)
uintptr_t texture = reinterpret_cast<uintptr_t>(mtl_texture);
auto i = damage_->find(texture);
if (i != damage_->end()) {
framebuffer_info.existing_damage = i->second;
}
framebuffer_info.supports_partial_repaint = true;
}
return std::make_unique<SurfaceFrame>(nullptr, // surface
framebuffer_info, // framebuffer info
submit_callback, // submit callback
frame_size, // frame size
nullptr, // context result
true // display list fallback
);
}
// |Surface|
SkMatrix GPUSurfaceMetalImpeller::GetRootTransformation() const {
// This backend does not currently support root surface transformations. Just
// return identity.
return {};
}
// |Surface|
GrDirectContext* GPUSurfaceMetalImpeller::GetContext() {
return nullptr;
}
// |Surface|
std::unique_ptr<GLContextResult> GPUSurfaceMetalImpeller::MakeRenderContextCurrent() {
// This backend has no such concept.
return std::make_unique<GLContextDefaultResult>(true);
}
bool GPUSurfaceMetalImpeller::AllowsDrawingWhenGpuDisabled() const {
return delegate_->AllowsDrawingWhenGpuDisabled();
}
// |Surface|
bool GPUSurfaceMetalImpeller::EnableRasterCache() const {
return false;
}
// |Surface|
std::shared_ptr<impeller::AiksContext> GPUSurfaceMetalImpeller::GetAiksContext() const {
return aiks_context_;
}
Surface::SurfaceData GPUSurfaceMetalImpeller::GetSurfaceData() const {
if (!(last_texture_ && [last_texture_ conformsToProtocol:@protocol(MTLTexture)])) {
return {};
}
id<MTLTexture> texture = last_texture_.get();
int bytesPerPixel = 0;
std::string pixel_format;
switch (texture.pixelFormat) {
case MTLPixelFormatBGR10_XR:
bytesPerPixel = 4;
pixel_format = "MTLPixelFormatBGR10_XR";
break;
case MTLPixelFormatBGRA10_XR:
bytesPerPixel = 8;
pixel_format = "MTLPixelFormatBGRA10_XR";
break;
case MTLPixelFormatBGRA8Unorm:
bytesPerPixel = 4;
pixel_format = "MTLPixelFormatBGRA8Unorm";
break;
case MTLPixelFormatRGBA16Float:
bytesPerPixel = 8;
pixel_format = "MTLPixelFormatRGBA16Float";
break;
default:
return {};
}
// Zero initialized so that errors are easier to find at the cost of
// performance.
sk_sp<SkData> result =
SkData::MakeZeroInitialized(texture.width * texture.height * bytesPerPixel);
[texture getBytes:result->writable_data()
bytesPerRow:texture.width * bytesPerPixel
fromRegion:MTLRegionMake2D(0, 0, texture.width, texture.height)
mipmapLevel:0];
return {
.pixel_format = pixel_format,
.data = result,
};
}
} // namespace flutter
| engine/shell/gpu/gpu_surface_metal_impeller.mm/0 | {
"file_path": "engine/shell/gpu/gpu_surface_metal_impeller.mm",
"repo_id": "engine",
"token_count": 6188
} | 292 |
<?xml version="1.0" encoding="utf-8"?>
<!-- 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.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.app" android:versionCode="1" android:versionName="0.0.1">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="34" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
<application android:label="Flutter Shell" android:name="FlutterApplication" android:debuggable="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale"
android:hardwareAccelerated="true"
android:launchMode="standard"
android:name="FlutterActivity"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- Required for io.flutter.plugin.text.ProcessTextPlugin to query activities that can process text. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT" />
<data android:mimeType="text/plain" />
</intent>
</queries>
</manifest>
| engine/shell/platform/android/AndroidManifest.xml/0 | {
"file_path": "engine/shell/platform/android/AndroidManifest.xml",
"repo_id": "engine",
"token_count": 710
} | 293 |
// 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_ENVIRONMENT_GL_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_ENVIRONMENT_GL_H_
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/ref_counted.h"
#include <EGL/egl.h>
namespace flutter {
class AndroidEnvironmentGL
: public fml::RefCountedThreadSafe<AndroidEnvironmentGL> {
private:
// MakeRefCounted
AndroidEnvironmentGL();
// MakeRefCounted
~AndroidEnvironmentGL();
public:
bool IsValid() const;
EGLDisplay Display() const;
private:
EGLDisplay display_;
bool valid_ = false;
FML_FRIEND_MAKE_REF_COUNTED(AndroidEnvironmentGL);
FML_FRIEND_REF_COUNTED_THREAD_SAFE(AndroidEnvironmentGL);
FML_DISALLOW_COPY_AND_ASSIGN(AndroidEnvironmentGL);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_ENVIRONMENT_GL_H_
| engine/shell/platform/android/android_environment_gl.h/0 | {
"file_path": "engine/shell/platform/android/android_environment_gl.h",
"repo_id": "engine",
"token_count": 367
} | 294 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_APK_ASSET_PROVIDER_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_APK_ASSET_PROVIDER_H_
#include <android/asset_manager_jni.h>
#include <jni.h>
#include "flutter/assets/asset_resolver.h"
#include "flutter/fml/memory/ref_counted.h"
#include "flutter/fml/platform/android/scoped_java_ref.h"
namespace flutter {
class APKAssetProviderInternal {
public:
virtual std::unique_ptr<fml::Mapping> GetAsMapping(
const std::string& asset_name) const = 0;
protected:
virtual ~APKAssetProviderInternal() = default;
};
class APKAssetProvider final : public AssetResolver {
public:
explicit APKAssetProvider(JNIEnv* env,
jobject assetManager,
std::string directory);
explicit APKAssetProvider(std::shared_ptr<APKAssetProviderInternal> impl);
~APKAssetProvider() = default;
// Returns a new 'std::unique_ptr<APKAssetProvider>' with the same 'impl_' as
// this provider.
std::unique_ptr<APKAssetProvider> Clone() const;
// Obtain a raw pointer to the APKAssetProviderInternal.
//
// This method is intended for use in tests. Callers must not
// delete the returned pointer.
APKAssetProviderInternal* GetImpl() const { return impl_.get(); }
bool operator==(const AssetResolver& other) const override;
private:
std::shared_ptr<APKAssetProviderInternal> impl_;
// |flutter::AssetResolver|
bool IsValid() const override;
// |flutter::AssetResolver|
bool IsValidAfterAssetManagerChange() const override;
// |AssetResolver|
AssetResolver::AssetResolverType GetType() const override;
// |flutter::AssetResolver|
std::unique_ptr<fml::Mapping> GetAsMapping(
const std::string& asset_name) const override;
// |AssetResolver|
const APKAssetProvider* as_apk_asset_provider() const override {
return this;
}
FML_DISALLOW_COPY_AND_ASSIGN(APKAssetProvider);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_APK_ASSET_PROVIDER_H_
| engine/shell/platform/android/apk_asset_provider.h/0 | {
"file_path": "engine/shell/platform/android/apk_asset_provider.h",
"repo_id": "engine",
"token_count": 759
} | 295 |
# This file only exists to provide IDE support to Android Studio.
#
# See ./README.md for details.
android.useAndroidX=true
android.enableJetifier=true
| engine/shell/platform/android/gradle.properties/0 | {
"file_path": "engine/shell/platform/android/gradle.properties",
"repo_id": "engine",
"token_count": 43
} | 296 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.app;
import android.content.ComponentCallbacks2;
import android.content.Intent;
import android.os.Bundle;
import io.flutter.plugin.common.PluginRegistry.ActivityResultListener;
import io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener;
/**
* A collection of Android {@code Activity} methods that are relevant to the core operation of
* Flutter applications.
*
* <p>Application authors that use an activity other than {@link FlutterActivity} should forward all
* events herein from their activity to an instance of {@link FlutterActivityDelegate} in order to
* wire the activity up to the Flutter framework. This forwarding is already provided in {@code
* FlutterActivity}.
*/
public interface FlutterActivityEvents
extends ComponentCallbacks2, ActivityResultListener, RequestPermissionsResultListener {
/**
* @param savedInstanceState If the activity is being re-initialized after previously being shut
* down then this Bundle contains the data it most recently supplied in {@code
* onSaveInstanceState(Bundle)}.
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
void onCreate(Bundle savedInstanceState);
/**
* @param intent The new intent that was started for the activity.
* @see android.app.Activity#onNewIntent(Intent)
*/
void onNewIntent(Intent intent);
/** @see android.app.Activity#onPause() */
void onPause();
/** @see android.app.Activity#onStart() */
void onStart();
/** @see android.app.Activity#onResume() */
void onResume();
/** @see android.app.Activity#onPostResume() */
void onPostResume();
/** @see android.app.Activity#onDestroy() */
void onDestroy();
/** @see android.app.Activity#onStop() */
void onStop();
/**
* Invoked when the activity has detected the user's press of the back key.
*
* @return {@code true} if the listener handled the event; {@code false} to let the activity
* continue with its default back button handling.
* @see android.app.Activity#onBackPressed()
*/
boolean onBackPressed();
/** @see android.app.Activity#onUserLeaveHint() */
void onUserLeaveHint();
/**
* @param hasFocus True if the current activity window has focus.
* @see android.app.Activity#onWindowFocusChanged(boolean)
*/
void onWindowFocusChanged(boolean hasFocus);
}
| engine/shell/platform/android/io/flutter/app/FlutterActivityEvents.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/app/FlutterActivityEvents.java",
"repo_id": "engine",
"token_count": 729
} | 297 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.embedding.android;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Region;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.Log;
import io.flutter.embedding.engine.renderer.FlutterRenderer;
import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener;
import io.flutter.embedding.engine.renderer.RenderSurface;
/**
* Paints a Flutter UI on a {@link android.view.Surface}.
*
* <p>To begin rendering a Flutter UI, the owner of this {@code FlutterSurfaceView} must invoke
* {@link #attachToRenderer(FlutterRenderer)} with the desired {@link FlutterRenderer}.
*
* <p>To stop rendering a Flutter UI, the owner of this {@code FlutterSurfaceView} must invoke
* {@link #detachFromRenderer()}.
*
* <p>A {@code FlutterSurfaceView} is intended for situations where a developer needs to render a
* Flutter UI, but does not require any keyboard input, gesture input, accessibility integrations or
* any other interactivity beyond rendering. If standard interactivity is desired, consider using a
* {@link FlutterView} which provides all of these behaviors and utilizes a {@code
* FlutterSurfaceView} internally.
*/
public class FlutterSurfaceView extends SurfaceView implements RenderSurface {
private static final String TAG = "FlutterSurfaceView";
private final boolean renderTransparently;
private boolean isSurfaceAvailableForRendering = false;
private boolean isPaused = false;
@Nullable private FlutterRenderer flutterRenderer;
private boolean shouldNotify() {
return flutterRenderer != null && !isPaused;
}
// Connects the {@code Surface} beneath this {@code SurfaceView} with Flutter's native code.
// Callbacks are received by this Object and then those messages are forwarded to our
// FlutterRenderer, and then on to the JNI bridge over to native Flutter code.
private final SurfaceHolder.Callback surfaceCallback =
new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(@NonNull SurfaceHolder holder) {
Log.v(TAG, "SurfaceHolder.Callback.startRenderingToSurface()");
isSurfaceAvailableForRendering = true;
if (shouldNotify()) {
connectSurfaceToRenderer();
}
}
@Override
public void surfaceChanged(
@NonNull SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "SurfaceHolder.Callback.surfaceChanged()");
if (shouldNotify()) {
changeSurfaceSize(width, height);
}
}
@Override
public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
Log.v(TAG, "SurfaceHolder.Callback.stopRenderingToSurface()");
isSurfaceAvailableForRendering = false;
if (shouldNotify()) {
disconnectSurfaceFromRenderer();
}
}
};
private final FlutterUiDisplayListener flutterUiDisplayListener =
new FlutterUiDisplayListener() {
@Override
public void onFlutterUiDisplayed() {
Log.v(TAG, "onFlutterUiDisplayed()");
// Now that a frame is ready to display, take this SurfaceView from transparent to opaque.
setAlpha(1.0f);
if (flutterRenderer != null) {
flutterRenderer.removeIsDisplayingFlutterUiListener(this);
}
}
@Override
public void onFlutterUiNoLongerDisplayed() {
// no-op
}
};
/** Constructs a {@code FlutterSurfaceView} programmatically, without any XML attributes. */
public FlutterSurfaceView(@NonNull Context context) {
this(context, null, false);
}
/**
* Constructs a {@code FlutterSurfaceView} programmatically, without any XML attributes, and with
* control over whether or not this {@code FlutterSurfaceView} renders with transparency.
*/
public FlutterSurfaceView(@NonNull Context context, boolean renderTransparently) {
this(context, null, renderTransparently);
}
/** Constructs a {@code FlutterSurfaceView} in an XML-inflation-compliant manner. */
public FlutterSurfaceView(@NonNull Context context, @NonNull AttributeSet attrs) {
this(context, attrs, false);
}
private FlutterSurfaceView(
@NonNull Context context, @Nullable AttributeSet attrs, boolean renderTransparently) {
super(context, attrs);
this.renderTransparently = renderTransparently;
init();
}
private void init() {
// If transparency is desired then we'll enable a transparent pixel format and place
// our Window above everything else to get transparent background rendering.
if (renderTransparently) {
getHolder().setFormat(PixelFormat.TRANSPARENT);
setZOrderOnTop(true);
}
// Grab a reference to our underlying Surface and register callbacks with that Surface so we
// can monitor changes and forward those changes on to native Flutter code.
getHolder().addCallback(surfaceCallback);
// Keep this SurfaceView transparent until Flutter has a frame ready to render. This avoids
// displaying a black rectangle in our place.
setAlpha(0.0f);
}
// This is a work around for TalkBack.
// If Android decides that our layer is transparent because, e.g. the status-
// bar is transparent, TalkBack highlighting stops working.
// Explicitly telling Android this part of the region is not actually
// transparent makes TalkBack work again.
// See https://github.com/flutter/flutter/issues/73413 for context.
@Override
public boolean gatherTransparentRegion(Region region) {
if (getAlpha() < 1.0f) {
return false;
}
final int[] location = new int[2];
getLocationInWindow(location);
region.op(
location[0],
location[1],
location[0] + getRight() - getLeft(),
location[1] + getBottom() - getTop(),
Region.Op.DIFFERENCE);
return true;
}
@Nullable
@Override
public FlutterRenderer getAttachedRenderer() {
return flutterRenderer;
}
/**
* Invoked by the owner of this {@code FlutterSurfaceView} when it wants to begin rendering a
* Flutter UI to this {@code FlutterSurfaceView}.
*
* <p>If an Android {@link android.view.Surface} is available, this method will give that {@link
* android.view.Surface} to the given {@link FlutterRenderer} to begin rendering Flutter's UI to
* this {@code FlutterSurfaceView}.
*
* <p>If no Android {@link android.view.Surface} is available yet, this {@code FlutterSurfaceView}
* will wait until a {@link android.view.Surface} becomes available and then give that {@link
* android.view.Surface} to the given {@link FlutterRenderer} to begin rendering Flutter's UI to
* this {@code FlutterSurfaceView}.
*/
public void attachToRenderer(@NonNull FlutterRenderer flutterRenderer) {
Log.v(TAG, "Attaching to FlutterRenderer.");
if (this.flutterRenderer != null) {
Log.v(
TAG,
"Already connected to a FlutterRenderer. Detaching from old one and attaching to new"
+ " one.");
this.flutterRenderer.stopRenderingToSurface();
this.flutterRenderer.removeIsDisplayingFlutterUiListener(flutterUiDisplayListener);
}
this.flutterRenderer = flutterRenderer;
resume();
}
/**
* Invoked by the owner of this {@code FlutterSurfaceView} when it no longer wants to render a
* Flutter UI to this {@code FlutterSurfaceView}.
*
* <p>This method will cease any on-going rendering from Flutter to this {@code
* FlutterSurfaceView}.
*/
public void detachFromRenderer() {
if (flutterRenderer != null) {
// If we're attached to an Android window then we were rendering a Flutter UI. Now that
// this FlutterSurfaceView is detached from the FlutterRenderer, we need to stop rendering.
// TODO(mattcarroll): introduce a isRendererConnectedToSurface() to wrap "getWindowToken() !=
// null"
if (getWindowToken() != null) {
Log.v(TAG, "Disconnecting FlutterRenderer from Android surface.");
disconnectSurfaceFromRenderer();
}
pause();
// Make the SurfaceView invisible to avoid showing a black rectangle.
setAlpha(0.0f);
flutterRenderer.removeIsDisplayingFlutterUiListener(flutterUiDisplayListener);
flutterRenderer = null;
} else {
Log.w(TAG, "detachFromRenderer() invoked when no FlutterRenderer was attached.");
}
}
/**
* Invoked by the owner of this {@code FlutterSurfaceView} when it should pause rendering Flutter
* UI to this {@code FlutterSurfaceView}.
*/
public void pause() {
if (flutterRenderer == null) {
Log.w(TAG, "pause() invoked when no FlutterRenderer was attached.");
return;
}
isPaused = true;
}
public void resume() {
if (flutterRenderer == null) {
Log.w(TAG, "resume() invoked when no FlutterRenderer was attached.");
return;
}
this.flutterRenderer.addIsDisplayingFlutterUiListener(flutterUiDisplayListener);
// If we're already attached to an Android window then we're now attached to both a renderer
// and the Android window. We can begin rendering now.
if (isSurfaceAvailableForRendering) {
Log.v(
TAG,
"Surface is available for rendering. Connecting FlutterRenderer to Android surface.");
connectSurfaceToRenderer();
}
isPaused = false;
}
// FlutterRenderer and getSurfaceTexture() must both be non-null.
private void connectSurfaceToRenderer() {
if (flutterRenderer == null || getHolder() == null) {
throw new IllegalStateException(
"connectSurfaceToRenderer() should only be called when flutterRenderer and getHolder()"
+ " are non-null.");
}
// When connecting the surface to the renderer, it's possible that the surface is currently
// paused. For instance, when a platform view is displayed, the current FlutterSurfaceView
// is paused, and rendering continues in a FlutterImageView buffer while the platform view
// is displayed.
//
// startRenderingToSurface stops rendering to an active surface if it isn't paused.
flutterRenderer.startRenderingToSurface(getHolder().getSurface(), isPaused);
}
// FlutterRenderer must be non-null.
private void changeSurfaceSize(int width, int height) {
if (flutterRenderer == null) {
throw new IllegalStateException(
"changeSurfaceSize() should only be called when flutterRenderer is non-null.");
}
Log.v(
TAG,
"Notifying FlutterRenderer that Android surface size has changed to "
+ width
+ " x "
+ height);
flutterRenderer.surfaceChanged(width, height);
}
// FlutterRenderer must be non-null.
private void disconnectSurfaceFromRenderer() {
if (flutterRenderer == null) {
throw new IllegalStateException(
"disconnectSurfaceFromRenderer() should only be called when flutterRenderer is"
+ " non-null.");
}
flutterRenderer.stopRenderingToSurface();
}
} | engine/shell/platform/android/io/flutter/embedding/android/FlutterSurfaceView.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/android/FlutterSurfaceView.java",
"repo_id": "engine",
"token_count": 3971
} | 298 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.embedding.engine;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import java.util.HashMap;
import java.util.Map;
/**
* Static singleton cache that holds {@link io.flutter.embedding.engine.FlutterEngineGroup}
* instances identified by {@code String}s.
*
* <p>The ID of a given {@link io.flutter.embedding.engine.FlutterEngineGroup} can be whatever
* {@code String} is desired.
*
* <p>{@link io.flutter.embedding.android.FlutterActivity} and {@link
* io.flutter.embedding.android.FlutterFragment} use the {@code FlutterEngineGroupCache} singleton
* internally when instructed to use a cached {@link io.flutter.embedding.engine.FlutterEngineGroup}
* based on a given ID. See {@link
* io.flutter.embedding.android.FlutterActivity.NewEngineInGroupIntentBuilder} and {@link
* io.flutter.embedding.android.FlutterFragment#withNewEngineInGroup(String)} for related APIs.
*/
public class FlutterEngineGroupCache {
private static volatile FlutterEngineGroupCache instance;
/**
* Returns the static singleton instance of {@code FlutterEngineGroupCache}.
*
* <p>Creates a new instance if one does not yet exist.
*/
@NonNull
public static FlutterEngineGroupCache getInstance() {
if (instance == null) {
synchronized (FlutterEngineGroupCache.class) {
if (instance == null) {
instance = new FlutterEngineGroupCache();
}
}
}
return instance;
}
private final Map<String, FlutterEngineGroup> cachedEngineGroups = new HashMap<>();
@VisibleForTesting
/* package */ FlutterEngineGroupCache() {}
/**
* Returns {@code true} if a {@link io.flutter.embedding.engine.FlutterEngineGroup} in this cache
* is associated with the given {@code engineGroupId}.
*/
public boolean contains(@NonNull String engineGroupId) {
return cachedEngineGroups.containsKey(engineGroupId);
}
/**
* Returns the {@link io.flutter.embedding.engine.FlutterEngineGroup} in this cache that is
* associated with the given {@code engineGroupId}, or {@code null} is no such {@link
* io.flutter.embedding.engine.FlutterEngineGroup} exists.
*/
@Nullable
public FlutterEngineGroup get(@NonNull String engineGroupId) {
return cachedEngineGroups.get(engineGroupId);
}
/**
* Places the given {@link io.flutter.embedding.engine.FlutterEngineGroup} in this cache and
* associates it with the given {@code engineGroupId}.
*
* <p>If a {@link io.flutter.embedding.engine.FlutterEngineGroup} is null, that {@link
* io.flutter.embedding.engine.FlutterEngineGroup} is removed from this cache.
*/
public void put(@NonNull String engineGroupId, @Nullable FlutterEngineGroup engineGroup) {
if (engineGroup != null) {
cachedEngineGroups.put(engineGroupId, engineGroup);
} else {
cachedEngineGroups.remove(engineGroupId);
}
}
/**
* Removes any {@link io.flutter.embedding.engine.FlutterEngineGroup} that is currently in the
* cache that is identified by the given {@code engineGroupId}.
*/
public void remove(@NonNull String engineGroupId) {
put(engineGroupId, null);
}
/**
* Removes all {@link io.flutter.embedding.engine.FlutterEngineGroup}'s that are currently in the
* cache.
*/
public void clear() {
cachedEngineGroups.clear();
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/FlutterEngineGroupCache.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/FlutterEngineGroupCache.java",
"repo_id": "engine",
"token_count": 1147
} | 299 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.embedding.engine.plugins;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineGroup;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.platform.PlatformViewRegistry;
import io.flutter.view.TextureRegistry;
/**
* Interface to be implemented by all Flutter plugins.
*
* <p>A Flutter plugin allows Flutter developers to interact with a host platform, e.g., Android and
* iOS, via Dart code. It includes platform code, as well as Dart code. A plugin author is
* responsible for setting up an appropriate {@link io.flutter.plugin.common.MethodChannel} to
* communicate between platform code and Dart code.
*
* <p>A Flutter plugin has a lifecycle. First, a developer must add a {@code FlutterPlugin} to an
* instance of {@link io.flutter.embedding.engine.FlutterEngine}. To do this, obtain a {@link
* PluginRegistry} with {@link FlutterEngine#getPlugins()}, then call {@link
* PluginRegistry#add(FlutterPlugin)}, passing the instance of the Flutter plugin. During the call
* to {@link PluginRegistry#add(FlutterPlugin)}, the {@link
* io.flutter.embedding.engine.FlutterEngine} will invoke {@link
* #onAttachedToEngine(FlutterPluginBinding)} on the given {@code FlutterPlugin}. If the {@code
* FlutterPlugin} is removed from the {@link io.flutter.embedding.engine.FlutterEngine} via {@link
* PluginRegistry#remove(Class)}, or if the {@link io.flutter.embedding.engine.FlutterEngine} is
* destroyed, the {@link FlutterEngine} will invoke {@link
* FlutterPlugin#onDetachedFromEngine(FlutterPluginBinding)} on the given {@code FlutterPlugin}.
*
* <p>Once a {@code FlutterPlugin} is attached to a {@link
* io.flutter.embedding.engine.FlutterEngine}, the plugin's code is permitted to access and invoke
* methods on resources within the {@link FlutterPluginBinding} that the {@link
* io.flutter.embedding.engine.FlutterEngine} gave to the {@code FlutterPlugin} in {@link
* #onAttachedToEngine(FlutterPluginBinding)}. This includes, for example, the application {@link
* Context} for the running app.
*
* <p>The {@link FlutterPluginBinding} provided in {@link #onAttachedToEngine(FlutterPluginBinding)}
* is no longer valid after the execution of {@link #onDetachedFromEngine(FlutterPluginBinding)}. Do
* not access any properties of the {@link FlutterPluginBinding} after the completion of {@link
* #onDetachedFromEngine(FlutterPluginBinding)}.
*
* <p>To register a {@link io.flutter.plugin.common.MethodChannel}, obtain a {@link BinaryMessenger}
* via the {@link FlutterPluginBinding}.
*
* <p>An Android Flutter plugin may require access to app resources or other artifacts that can only
* be retrieved through a {@link Context}. Developers can access the application context via {@link
* FlutterPluginBinding#getApplicationContext()}.
*
* <p>Some plugins may require access to the {@code Activity} that is displaying a Flutter
* experience, or may need to react to {@code Activity} lifecycle events, e.g., {@code onCreate()},
* {@code onStart()}, {@code onResume()}, {@code onPause()}, {@code onStop()}, {@code onDestroy()}.
* Any such plugin should implement {@link
* io.flutter.embedding.engine.plugins.activity.ActivityAware} in addition to implementing {@code
* FlutterPlugin}. {@code ActivityAware} provides callback hooks that expose access to an associated
* {@code Activity} and its {@code Lifecycle}. All plugins must respect the possibility that a
* Flutter experience may never be associated with an {@code Activity}, e.g., when Flutter is used
* for background behavior. Additionally, all plugins must respect that a {@code Activity}s may come
* and go over time, thus requiring plugins to cleanup resources and recreate those resources as the
* {@code Activity} comes and goes.
*/
public interface FlutterPlugin {
/**
* This {@code FlutterPlugin} has been associated with a {@link
* io.flutter.embedding.engine.FlutterEngine} instance.
*
* <p>Relevant resources that this {@code FlutterPlugin} may need are provided via the {@code
* binding}. The {@code binding} may be cached and referenced until {@link
* #onDetachedFromEngine(FlutterPluginBinding)} is invoked and returns.
*/
void onAttachedToEngine(@NonNull FlutterPluginBinding binding);
/**
* This {@code FlutterPlugin} has been removed from a {@link
* io.flutter.embedding.engine.FlutterEngine} instance.
*
* <p>The {@code binding} passed to this method is the same instance that was passed in {@link
* #onAttachedToEngine(FlutterPluginBinding)}. It is provided again in this method as a
* convenience. The {@code binding} may be referenced during the execution of this method, but it
* must not be cached or referenced after this method returns.
*
* <p>{@code FlutterPlugin}s should release all resources in this method.
*/
void onDetachedFromEngine(@NonNull FlutterPluginBinding binding);
/**
* Resources made available to all plugins registered with a given {@link
* io.flutter.embedding.engine.FlutterEngine}.
*
* <p>The provided {@link BinaryMessenger} can be used to communicate with Dart code running in
* the Flutter context associated with this plugin binding.
*
* <p>Plugins that need to respond to {@code Lifecycle} events should implement the additional
* {@link io.flutter.embedding.engine.plugins.activity.ActivityAware} and/or {@link
* io.flutter.embedding.engine.plugins.service.ServiceAware} interfaces, where a {@link Lifecycle}
* reference can be obtained.
*/
class FlutterPluginBinding {
private final Context applicationContext;
private final FlutterEngine flutterEngine;
private final BinaryMessenger binaryMessenger;
private final TextureRegistry textureRegistry;
private final PlatformViewRegistry platformViewRegistry;
private final FlutterAssets flutterAssets;
private final FlutterEngineGroup group;
public FlutterPluginBinding(
@NonNull Context applicationContext,
@NonNull FlutterEngine flutterEngine,
@NonNull BinaryMessenger binaryMessenger,
@NonNull TextureRegistry textureRegistry,
@NonNull PlatformViewRegistry platformViewRegistry,
@NonNull FlutterAssets flutterAssets,
@Nullable FlutterEngineGroup group) {
this.applicationContext = applicationContext;
this.flutterEngine = flutterEngine;
this.binaryMessenger = binaryMessenger;
this.textureRegistry = textureRegistry;
this.platformViewRegistry = platformViewRegistry;
this.flutterAssets = flutterAssets;
this.group = group;
}
@NonNull
public Context getApplicationContext() {
return applicationContext;
}
/**
* @deprecated Use {@code getBinaryMessenger()}, {@code getTextureRegistry()}, or {@code
* getPlatformViewRegistry()} instead.
*/
@Deprecated
@NonNull
public FlutterEngine getFlutterEngine() {
return flutterEngine;
}
@NonNull
public BinaryMessenger getBinaryMessenger() {
return binaryMessenger;
}
@NonNull
public TextureRegistry getTextureRegistry() {
return textureRegistry;
}
@NonNull
public PlatformViewRegistry getPlatformViewRegistry() {
return platformViewRegistry;
}
@NonNull
public FlutterAssets getFlutterAssets() {
return flutterAssets;
}
/**
* Accessor for the {@link FlutterEngineGroup} used to create the {@link FlutterEngine} for the
* app.
*
* <p>This is useful in the rare case that a plugin has to spawn its own engine (for example,
* running an engine the background). The result is nullable since old versions of Flutter and
* custom setups may not have used a {@link FlutterEngineGroup}. Failing to use this when it is
* available will result in suboptimal performance and odd behaviors related to Dart isolate
* groups.
*/
@Nullable
public FlutterEngineGroup getEngineGroup() {
return group;
}
}
/** Provides Flutter plugins with access to Flutter asset information. */
interface FlutterAssets {
/**
* Returns the relative file path to the Flutter asset with the given name, including the file's
* extension, e.g., {@code "myImage.jpg"}.
*
* <p>The returned file path is relative to the Android app's standard assets directory.
* Therefore, the returned path is appropriate to pass to Android's {@code AssetManager}, but
* the path is not appropriate to load as an absolute path.
*/
String getAssetFilePathByName(@NonNull String assetFileName);
/**
* Same as {@link #getAssetFilePathByName(String)} but with added support for an explicit
* Android {@code packageName}.
*/
String getAssetFilePathByName(@NonNull String assetFileName, @NonNull String packageName);
/**
* Returns the relative file path to the Flutter asset with the given subpath, including the
* file's extension, e.g., {@code "/dir1/dir2/myImage.jpg"}.
*
* <p>The returned file path is relative to the Android app's standard assets directory.
* Therefore, the returned path is appropriate to pass to Android's {@code AssetManager}, but
* the path is not appropriate to load as an absolute path.
*/
String getAssetFilePathBySubpath(@NonNull String assetSubpath);
/**
* Same as {@link #getAssetFilePathBySubpath(String)} but with added support for an explicit
* Android {@code packageName}.
*/
String getAssetFilePathBySubpath(@NonNull String assetSubpath, @NonNull String packageName);
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/plugins/FlutterPlugin.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/FlutterPlugin.java",
"repo_id": "engine",
"token_count": 3044
} | 300 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.embedding.engine.plugins.shim;
import android.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
import io.flutter.FlutterInjector;
import io.flutter.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.platform.PlatformViewRegistry;
import io.flutter.view.FlutterView;
import io.flutter.view.TextureRegistry;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* A {@link PluginRegistry.Registrar} that is shimmed let old plugins use the new Android embedding
* and plugin API behind the scenes.
*
* <p>Instances of {@code ShimRegistrar}s are vended internally by a {@link ShimPluginRegistry}.
*/
class ShimRegistrar implements PluginRegistry.Registrar, FlutterPlugin, ActivityAware {
private static final String TAG = "ShimRegistrar";
private final Map<String, Object> globalRegistrarMap;
private final String pluginId;
private final Set<PluginRegistry.ViewDestroyListener> viewDestroyListeners = new HashSet<>();
private final Set<PluginRegistry.RequestPermissionsResultListener>
requestPermissionsResultListeners = new HashSet<>();
private final Set<PluginRegistry.ActivityResultListener> activityResultListeners =
new HashSet<>();
private final Set<PluginRegistry.NewIntentListener> newIntentListeners = new HashSet<>();
private final Set<PluginRegistry.UserLeaveHintListener> userLeaveHintListeners = new HashSet<>();
private final Set<PluginRegistry.WindowFocusChangedListener> WindowFocusChangedListeners =
new HashSet<>();
private FlutterPlugin.FlutterPluginBinding pluginBinding;
private ActivityPluginBinding activityPluginBinding;
public ShimRegistrar(@NonNull String pluginId, @NonNull Map<String, Object> globalRegistrarMap) {
this.pluginId = pluginId;
this.globalRegistrarMap = globalRegistrarMap;
}
@Override
public Activity activity() {
return activityPluginBinding != null ? activityPluginBinding.getActivity() : null;
}
@Override
public Context context() {
return pluginBinding != null ? pluginBinding.getApplicationContext() : null;
}
@Override
public Context activeContext() {
return activityPluginBinding == null ? context() : activity();
}
@Override
public BinaryMessenger messenger() {
return pluginBinding != null ? pluginBinding.getBinaryMessenger() : null;
}
@Override
public TextureRegistry textures() {
return pluginBinding != null ? pluginBinding.getTextureRegistry() : null;
}
@Override
public PlatformViewRegistry platformViewRegistry() {
return pluginBinding != null ? pluginBinding.getPlatformViewRegistry() : null;
}
@Override
public FlutterView view() {
throw new UnsupportedOperationException(
"The new embedding does not support the old FlutterView.");
}
@Override
public String lookupKeyForAsset(String asset) {
return FlutterInjector.instance().flutterLoader().getLookupKeyForAsset(asset);
}
@Override
public String lookupKeyForAsset(String asset, String packageName) {
return FlutterInjector.instance().flutterLoader().getLookupKeyForAsset(asset, packageName);
}
@Override
public PluginRegistry.Registrar publish(Object value) {
globalRegistrarMap.put(pluginId, value);
return this;
}
@Override
public PluginRegistry.Registrar addRequestPermissionsResultListener(
PluginRegistry.RequestPermissionsResultListener listener) {
requestPermissionsResultListeners.add(listener);
if (activityPluginBinding != null) {
activityPluginBinding.addRequestPermissionsResultListener(listener);
}
return this;
}
@Override
public PluginRegistry.Registrar addActivityResultListener(
PluginRegistry.ActivityResultListener listener) {
activityResultListeners.add(listener);
if (activityPluginBinding != null) {
activityPluginBinding.addActivityResultListener(listener);
}
return this;
}
@Override
public PluginRegistry.Registrar addNewIntentListener(PluginRegistry.NewIntentListener listener) {
newIntentListeners.add(listener);
if (activityPluginBinding != null) {
activityPluginBinding.addOnNewIntentListener(listener);
}
return this;
}
@Override
public PluginRegistry.Registrar addUserLeaveHintListener(
PluginRegistry.UserLeaveHintListener listener) {
userLeaveHintListeners.add(listener);
if (activityPluginBinding != null) {
activityPluginBinding.addOnUserLeaveHintListener(listener);
}
return this;
}
@Override
public PluginRegistry.Registrar addWindowFocusChangedListener(
PluginRegistry.WindowFocusChangedListener listener) {
WindowFocusChangedListeners.add(listener);
if (activityPluginBinding != null) {
activityPluginBinding.addOnWindowFocusChangedListener(listener);
}
return this;
}
@Override
@NonNull
public PluginRegistry.Registrar addViewDestroyListener(
@NonNull PluginRegistry.ViewDestroyListener listener) {
viewDestroyListeners.add(listener);
return this;
}
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
Log.v(TAG, "Attached to FlutterEngine.");
pluginBinding = binding;
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
Log.v(TAG, "Detached from FlutterEngine.");
for (PluginRegistry.ViewDestroyListener listener : viewDestroyListeners) {
// The following invocation might produce unexpected behavior in old plugins because
// we have no FlutterNativeView to pass to onViewDestroy(). This is a limitation of this shim.
listener.onViewDestroy(null);
}
pluginBinding = null;
activityPluginBinding = null;
}
@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
Log.v(TAG, "Attached to an Activity.");
activityPluginBinding = binding;
addExistingListenersToActivityPluginBinding();
}
@Override
public void onDetachedFromActivityForConfigChanges() {
Log.v(TAG, "Detached from an Activity for config changes.");
activityPluginBinding = null;
}
@Override
public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
Log.v(TAG, "Reconnected to an Activity after config changes.");
activityPluginBinding = binding;
addExistingListenersToActivityPluginBinding();
}
@Override
public void onDetachedFromActivity() {
Log.v(TAG, "Detached from an Activity.");
activityPluginBinding = null;
}
private void addExistingListenersToActivityPluginBinding() {
for (PluginRegistry.RequestPermissionsResultListener listener :
requestPermissionsResultListeners) {
activityPluginBinding.addRequestPermissionsResultListener(listener);
}
for (PluginRegistry.ActivityResultListener listener : activityResultListeners) {
activityPluginBinding.addActivityResultListener(listener);
}
for (PluginRegistry.NewIntentListener listener : newIntentListeners) {
activityPluginBinding.addOnNewIntentListener(listener);
}
for (PluginRegistry.UserLeaveHintListener listener : userLeaveHintListeners) {
activityPluginBinding.addOnUserLeaveHintListener(listener);
}
for (PluginRegistry.WindowFocusChangedListener listener : WindowFocusChangedListeners) {
activityPluginBinding.addOnWindowFocusChangedListener(listener);
}
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/plugins/shim/ShimRegistrar.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/shim/ShimRegistrar.java",
"repo_id": "engine",
"token_count": 2413
} | 301 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.embedding.engine.systemchannels;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.Log;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.StandardMethodCodec;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* System channel that sends 2-way communication between Flutter and Android to facilitate embedding
* of Android Views within a Flutter application.
*
* <p>Register a {@link PlatformViewsHandler} to implement the Android side of this channel.
*/
public class PlatformViewsChannel {
private static final String TAG = "PlatformViewsChannel";
private final MethodChannel channel;
private PlatformViewsHandler handler;
public void invokeViewFocused(int viewId) {
if (channel == null) {
return;
}
channel.invokeMethod("viewFocused", viewId);
}
private static String detailedExceptionString(Exception exception) {
return Log.getStackTraceString(exception);
}
private final MethodChannel.MethodCallHandler parsingHandler =
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
// If there is no handler to respond to this message then we don't need to
// parse it. Return.
if (handler == null) {
return;
}
Log.v(TAG, "Received '" + call.method + "' message.");
switch (call.method) {
case "create":
create(call, result);
break;
case "dispose":
dispose(call, result);
break;
case "resize":
resize(call, result);
break;
case "offset":
offset(call, result);
break;
case "touch":
touch(call, result);
break;
case "setDirection":
setDirection(call, result);
break;
case "clearFocus":
clearFocus(call, result);
break;
case "synchronizeToNativeViewHierarchy":
synchronizeToNativeViewHierarchy(call, result);
break;
default:
result.notImplemented();
}
}
private void create(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
final Map<String, Object> createArgs = call.arguments();
// TODO(egarciad): Remove the "hybrid" case.
final boolean usesPlatformViewLayer =
createArgs.containsKey("hybrid") && (boolean) createArgs.get("hybrid");
final ByteBuffer additionalParams =
createArgs.containsKey("params")
? ByteBuffer.wrap((byte[]) createArgs.get("params"))
: null;
try {
if (usesPlatformViewLayer) {
final PlatformViewCreationRequest request =
new PlatformViewCreationRequest(
(int) createArgs.get("id"),
(String) createArgs.get("viewType"),
0,
0,
0,
0,
(int) createArgs.get("direction"),
PlatformViewCreationRequest.RequestedDisplayMode.HYBRID_ONLY,
additionalParams);
handler.createForPlatformViewLayer(request);
result.success(null);
} else {
final boolean hybridFallback =
createArgs.containsKey("hybridFallback")
&& (boolean) createArgs.get("hybridFallback");
final PlatformViewCreationRequest.RequestedDisplayMode displayMode =
hybridFallback
? PlatformViewCreationRequest.RequestedDisplayMode
.TEXTURE_WITH_HYBRID_FALLBACK
: PlatformViewCreationRequest.RequestedDisplayMode
.TEXTURE_WITH_VIRTUAL_FALLBACK;
final PlatformViewCreationRequest request =
new PlatformViewCreationRequest(
(int) createArgs.get("id"),
(String) createArgs.get("viewType"),
createArgs.containsKey("top") ? (double) createArgs.get("top") : 0.0,
createArgs.containsKey("left") ? (double) createArgs.get("left") : 0.0,
(double) createArgs.get("width"),
(double) createArgs.get("height"),
(int) createArgs.get("direction"),
displayMode,
additionalParams);
long textureId = handler.createForTextureLayer(request);
if (textureId == PlatformViewsHandler.NON_TEXTURE_FALLBACK) {
if (!hybridFallback) {
throw new AssertionError(
"Platform view attempted to fall back to hybrid mode when not requested.");
}
// A fallback to hybrid mode is indicated with a null texture ID.
result.success(null);
} else {
result.success(textureId);
}
}
} catch (IllegalStateException exception) {
result.error("error", detailedExceptionString(exception), null);
}
}
private void dispose(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
Map<String, Object> disposeArgs = call.arguments();
int viewId = (int) disposeArgs.get("id");
try {
handler.dispose(viewId);
result.success(null);
} catch (IllegalStateException exception) {
result.error("error", detailedExceptionString(exception), null);
}
}
private void resize(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
Map<String, Object> resizeArgs = call.arguments();
PlatformViewResizeRequest resizeRequest =
new PlatformViewResizeRequest(
(int) resizeArgs.get("id"),
(double) resizeArgs.get("width"),
(double) resizeArgs.get("height"));
try {
handler.resize(
resizeRequest,
(PlatformViewBufferSize bufferSize) -> {
if (bufferSize == null) {
result.error("error", "Failed to resize the platform view", null);
} else {
final Map<String, Object> response = new HashMap<>();
response.put("width", (double) bufferSize.width);
response.put("height", (double) bufferSize.height);
result.success(response);
}
});
} catch (IllegalStateException exception) {
result.error("error", detailedExceptionString(exception), null);
}
}
private void offset(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
Map<String, Object> offsetArgs = call.arguments();
try {
handler.offset(
(int) offsetArgs.get("id"),
(double) offsetArgs.get("top"),
(double) offsetArgs.get("left"));
result.success(null);
} catch (IllegalStateException exception) {
result.error("error", detailedExceptionString(exception), null);
}
}
private void touch(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
List<Object> args = call.arguments();
PlatformViewTouch touch =
new PlatformViewTouch(
(int) args.get(0),
(Number) args.get(1),
(Number) args.get(2),
(int) args.get(3),
(int) args.get(4),
args.get(5),
args.get(6),
(int) args.get(7),
(int) args.get(8),
(float) (double) args.get(9),
(float) (double) args.get(10),
(int) args.get(11),
(int) args.get(12),
(int) args.get(13),
(int) args.get(14),
((Number) args.get(15)).longValue());
try {
handler.onTouch(touch);
result.success(null);
} catch (IllegalStateException exception) {
result.error("error", detailedExceptionString(exception), null);
}
}
private void setDirection(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
Map<String, Object> setDirectionArgs = call.arguments();
int newDirectionViewId = (int) setDirectionArgs.get("id");
int direction = (int) setDirectionArgs.get("direction");
try {
handler.setDirection(newDirectionViewId, direction);
result.success(null);
} catch (IllegalStateException exception) {
result.error("error", detailedExceptionString(exception), null);
}
}
private void clearFocus(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
int viewId = call.arguments();
try {
handler.clearFocus(viewId);
result.success(null);
} catch (IllegalStateException exception) {
result.error("error", detailedExceptionString(exception), null);
}
}
private void synchronizeToNativeViewHierarchy(
@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
boolean yes = call.arguments();
try {
handler.synchronizeToNativeViewHierarchy(yes);
result.success(null);
} catch (IllegalStateException exception) {
result.error("error", detailedExceptionString(exception), null);
}
}
};
/**
* Constructs a {@code PlatformViewsChannel} 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 PlatformViewsChannel(@NonNull DartExecutor dartExecutor) {
channel =
new MethodChannel(dartExecutor, "flutter/platform_views", StandardMethodCodec.INSTANCE);
channel.setMethodCallHandler(parsingHandler);
}
/**
* Sets the {@link PlatformViewsHandler} which receives all events and requests that are parsed
* from the underlying platform views channel.
*/
public void setPlatformViewsHandler(@Nullable PlatformViewsHandler handler) {
this.handler = handler;
}
/**
* Handler that receives platform view messages sent from Flutter to Android through a given
* {@link PlatformViewsChannel}.
*
* <p>To register a {@code PlatformViewsHandler} with a {@link PlatformViewsChannel}, see {@link
* PlatformViewsChannel#setPlatformViewsHandler(PlatformViewsHandler)}.
*/
public interface PlatformViewsHandler {
/*
* The ID returned by {@code createForTextureLayer} to indicate that the requested texture mode
* was not available and the view creation fell back to {@code PlatformViewLayer} mode.
*
* This can only be returned if the {@link PlatformViewCreationRequest} sets
* {@code TEXTURE_WITH_HYBRID_FALLBACK} as the requested display mode.
*/
static final long NON_TEXTURE_FALLBACK = -2;
/**
* The Flutter application would like to display a new Android {@code View}, i.e., platform
* view.
*
* <p>The Android View is added to the view hierarchy. This view is rendered in the Flutter
* framework by a PlatformViewLayer.
*
* @param request The metadata sent from the framework.
*/
void createForPlatformViewLayer(@NonNull PlatformViewCreationRequest request);
/**
* The Flutter application would like to display a new Android {@code View}, i.e., platform
* view.
*
* <p>The Android View is added to the view hierarchy. This view is rendered in the Flutter
* framework by a TextureLayer.
*
* @param request The metadata sent from the framework.
* @return The texture ID.
*/
long createForTextureLayer(@NonNull PlatformViewCreationRequest request);
/** The Flutter application would like to dispose of an existing Android {@code View}. */
void dispose(int viewId);
/**
* The Flutter application would like to resize an existing Android {@code View}.
*
* @param request The request to resize the platform view.
* @param onComplete Once the resize is completed, this is the handler to notify the size of the
* platform view buffer.
*/
void resize(
@NonNull PlatformViewResizeRequest request, @NonNull PlatformViewBufferResized onComplete);
/**
* The Flutter application would like to change the offset of an existing Android {@code View}.
*/
void offset(int viewId, double top, double left);
/**
* The user touched a platform view within Flutter.
*
* <p>Touch data is reported in {@code touch}.
*/
void onTouch(@NonNull PlatformViewTouch touch);
/**
* The Flutter application would like to change the layout direction of an existing Android
* {@code View}, i.e., platform view.
*/
// TODO(mattcarroll): Introduce an annotation for @TextureId
void setDirection(int viewId, int direction);
/** Clears the focus from the platform view with a give id if it is currently focused. */
void clearFocus(int viewId);
/**
* Whether the render surface of {@code FlutterView} should be converted to a {@code
* FlutterImageView} when a {@code PlatformView} is added.
*
* <p>This is done to syncronize the rendering of the PlatformView and the FlutterView. Defaults
* to true.
*/
void synchronizeToNativeViewHierarchy(boolean yes);
}
/** Request sent from Flutter to create a new platform view. */
public static class PlatformViewCreationRequest {
/** Platform view display modes that can be requested at creation time. */
public enum RequestedDisplayMode {
/** Use Texture Layer if possible, falling back to Virtual Display if not. */
TEXTURE_WITH_VIRTUAL_FALLBACK,
/** Use Texture Layer if possible, falling back to Hybrid Composition if not. */
TEXTURE_WITH_HYBRID_FALLBACK,
/** Use Hybrid Composition in all cases. */
HYBRID_ONLY,
}
/** The ID of the platform view as seen by the Flutter side. */
public final int viewId;
/** The type of Android {@code View} to create for this platform view. */
@NonNull public final String viewType;
/** The density independent width to display the platform view. */
public final double logicalWidth;
/** The density independent height to display the platform view. */
public final double logicalHeight;
/** The density independent top position to display the platform view. */
public final double logicalTop;
/** The density independent left position to display the platform view. */
public final double logicalLeft;
/**
* The layout direction of the new platform view.
*
* <p>See {@link android.view.View#LAYOUT_DIRECTION_LTR} and {@link
* android.view.View#LAYOUT_DIRECTION_RTL}
*/
public final int direction;
public final RequestedDisplayMode displayMode;
/** Custom parameters that are unique to the desired platform view. */
@Nullable public final ByteBuffer params;
/** Creates a request to construct a platform view. */
public PlatformViewCreationRequest(
int viewId,
@NonNull String viewType,
double logicalTop,
double logicalLeft,
double logicalWidth,
double logicalHeight,
int direction,
@Nullable ByteBuffer params) {
this(
viewId,
viewType,
logicalTop,
logicalLeft,
logicalWidth,
logicalHeight,
direction,
RequestedDisplayMode.TEXTURE_WITH_VIRTUAL_FALLBACK,
params);
}
/** Creates a request to construct a platform view with the given display mode. */
public PlatformViewCreationRequest(
int viewId,
@NonNull String viewType,
double logicalTop,
double logicalLeft,
double logicalWidth,
double logicalHeight,
int direction,
RequestedDisplayMode displayMode,
@Nullable ByteBuffer params) {
this.viewId = viewId;
this.viewType = viewType;
this.logicalTop = logicalTop;
this.logicalLeft = logicalLeft;
this.logicalWidth = logicalWidth;
this.logicalHeight = logicalHeight;
this.direction = direction;
this.displayMode = displayMode;
this.params = params;
}
}
/** Request sent from Flutter to resize a platform view. */
public static class PlatformViewResizeRequest {
/** The ID of the platform view as seen by the Flutter side. */
public final int viewId;
/** The new density independent width to display the platform view. */
public final double newLogicalWidth;
/** The new density independent height to display the platform view. */
public final double newLogicalHeight;
public PlatformViewResizeRequest(int viewId, double newLogicalWidth, double newLogicalHeight) {
this.viewId = viewId;
this.newLogicalWidth = newLogicalWidth;
this.newLogicalHeight = newLogicalHeight;
}
}
/** The platform view buffer size. */
public static class PlatformViewBufferSize {
/** The width of the screen buffer. */
public final int width;
/** The height of the screen buffer. */
public final int height;
public PlatformViewBufferSize(int width, int height) {
this.width = width;
this.height = height;
}
}
/** Allows to notify when a platform view buffer has been resized. */
public interface PlatformViewBufferResized {
void run(@Nullable PlatformViewBufferSize bufferSize);
}
/** The state of a touch event in Flutter within a platform view. */
public static class PlatformViewTouch {
/** The ID of the platform view as seen by the Flutter side. */
public final int viewId;
/** The amount of time that the touch has been pressed. */
@NonNull public final Number downTime;
/** TODO(mattcarroll): javadoc */
@NonNull public final Number eventTime;
public final int action;
/** The number of pointers (e.g, fingers) involved in the touch event. */
public final int pointerCount;
/** Properties for each pointer, encoded in a raw format. */
@NonNull public final Object rawPointerPropertiesList;
/** Coordinates for each pointer, encoded in a raw format. */
@NonNull public final Object rawPointerCoords;
/** TODO(mattcarroll): javadoc */
public final int metaState;
/** TODO(mattcarroll): javadoc */
public final int buttonState;
/** Coordinate precision along the x-axis. */
public final float xPrecision;
/** Coordinate precision along the y-axis. */
public final float yPrecision;
/** TODO(mattcarroll): javadoc */
public final int deviceId;
/** TODO(mattcarroll): javadoc */
public final int edgeFlags;
/** TODO(mattcarroll): javadoc */
public final int source;
/** TODO(mattcarroll): javadoc */
public final int flags;
/** TODO(iskakaushik): javadoc */
public final long motionEventId;
public PlatformViewTouch(
int viewId,
@NonNull Number downTime,
@NonNull Number eventTime,
int action,
int pointerCount,
@NonNull Object rawPointerPropertiesList,
@NonNull Object rawPointerCoords,
int metaState,
int buttonState,
float xPrecision,
float yPrecision,
int deviceId,
int edgeFlags,
int source,
int flags,
long motionEventId) {
this.viewId = viewId;
this.downTime = downTime;
this.eventTime = eventTime;
this.action = action;
this.pointerCount = pointerCount;
this.rawPointerPropertiesList = rawPointerPropertiesList;
this.rawPointerCoords = rawPointerCoords;
this.metaState = metaState;
this.buttonState = buttonState;
this.xPrecision = xPrecision;
this.yPrecision = yPrecision;
this.deviceId = deviceId;
this.edgeFlags = edgeFlags;
this.source = source;
this.flags = flags;
this.motionEventId = motionEventId;
}
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/PlatformViewsChannel.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/PlatformViewsChannel.java",
"repo_id": "engine",
"token_count": 8566
} | 302 |
package io.flutter.plugin.common;
import androidx.annotation.Nullable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONUtil {
private JSONUtil() {}
/**
* Convert the Json java representation to Java objects. Particularly used for converting
* JSONArray and JSONObject to Lists and Maps.
*/
@Nullable
public static Object unwrap(@Nullable Object o) {
if (JSONObject.NULL.equals(o) || o == null) {
return null;
}
if (o instanceof Boolean
|| o instanceof Byte
|| o instanceof Character
|| o instanceof Double
|| o instanceof Float
|| o instanceof Integer
|| o instanceof Long
|| o instanceof Short
|| o instanceof String) {
return o;
}
try {
if (o instanceof JSONArray) {
List<Object> list = new ArrayList<>();
JSONArray array = (JSONArray) o;
for (int i = 0; i < array.length(); i++) {
list.add(unwrap(array.get(i)));
}
return list;
}
if (o instanceof JSONObject) {
Map<String, Object> map = new HashMap<>();
JSONObject jsonObject = (JSONObject) o;
Iterator<String> keyIterator = jsonObject.keys();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
map.put(key, unwrap(jsonObject.get(key)));
}
return map;
}
} catch (Exception ignored) {
}
return null;
}
/** Backport of {@link JSONObject#wrap(Object)} for use on pre-KitKat systems. */
@Nullable
public static Object wrap(@Nullable Object o) {
if (o == null) {
return JSONObject.NULL;
}
if (o instanceof JSONArray || o instanceof JSONObject) {
return o;
}
if (o.equals(JSONObject.NULL)) {
return o;
}
try {
if (o instanceof Collection) {
JSONArray result = new JSONArray();
for (Object e : (Collection) o) result.put(wrap(e));
return result;
} else if (o.getClass().isArray()) {
JSONArray result = new JSONArray();
int length = Array.getLength(o);
for (int i = 0; i < length; i++) result.put(wrap(Array.get(o, i)));
return result;
}
if (o instanceof Map) {
JSONObject result = new JSONObject();
for (Map.Entry<?, ?> entry : ((Map<?, ?>) o).entrySet())
result.put((String) entry.getKey(), wrap(entry.getValue()));
return result;
}
if (o instanceof Boolean
|| o instanceof Byte
|| o instanceof Character
|| o instanceof Double
|| o instanceof Float
|| o instanceof Integer
|| o instanceof Long
|| o instanceof Short
|| o instanceof String) {
return o;
}
if (o.getClass().getPackage().getName().startsWith("java.")) {
return o.toString();
}
} catch (Exception ignored) {
}
return null;
}
}
| engine/shell/platform/android/io/flutter/plugin/common/JSONUtil.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/common/JSONUtil.java",
"repo_id": "engine",
"token_count": 1320
} | 303 |
// 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.localization;
import static io.flutter.Build.API_LEVELS;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.LocaleList;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import io.flutter.embedding.engine.systemchannels.LocalizationChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/** Android implementation of the localization plugin. */
public class LocalizationPlugin {
@NonNull private final LocalizationChannel localizationChannel;
@NonNull private final Context context;
@SuppressLint({
"AppBundleLocaleChanges",
"DiscouragedApi"
}) // This is optionally turned on by apps.
@VisibleForTesting
final LocalizationChannel.LocalizationMessageHandler localizationMessageHandler =
new LocalizationChannel.LocalizationMessageHandler() {
@Override
public String getStringResource(@NonNull String key, @Nullable String localeString) {
Context localContext = context;
String stringToReturn = null;
Locale savedLocale = null;
if (localeString != null) {
Locale locale = localeFromString(localeString);
Configuration config = new Configuration(context.getResources().getConfiguration());
config.setLocale(locale);
localContext = context.createConfigurationContext(config);
}
String packageName = context.getPackageName();
int resId = localContext.getResources().getIdentifier(key, "string", packageName);
if (resId != 0) {
// 0 means the resource is not found.
stringToReturn = localContext.getResources().getString(resId);
}
return stringToReturn;
}
};
public LocalizationPlugin(
@NonNull Context context, @NonNull LocalizationChannel localizationChannel) {
this.context = context;
this.localizationChannel = localizationChannel;
this.localizationChannel.setLocalizationMessageHandler(localizationMessageHandler);
}
/**
* Computes the {@link Locale} in supportedLocales that best matches the user's preferred locales.
*
* <p>FlutterEngine must be non-null when this method is invoked.
*/
@SuppressWarnings("deprecation")
@Nullable
public Locale resolveNativeLocale(@Nullable List<Locale> supportedLocales) {
if (supportedLocales == null || supportedLocales.isEmpty()) {
return null;
}
// Android improved the localization resolution algorithms after API 24 (7.0, Nougat).
// See https://developer.android.com/guide/topics/resources/multilingual-support
//
// LanguageRange and Locale.lookup was added in API 26 and is the preferred way to
// select a locale. Pre-API 26, we implement a manual locale resolution.
if (Build.VERSION.SDK_INT >= API_LEVELS.API_26) {
// Modern locale resolution using LanguageRange
// https://developer.android.com/guide/topics/resources/multilingual-support#postN
List<Locale.LanguageRange> languageRanges = new ArrayList<>();
LocaleList localeList = context.getResources().getConfiguration().getLocales();
int localeCount = localeList.size();
for (int index = 0; index < localeCount; ++index) {
Locale locale = localeList.get(index);
// Convert locale string into language range format.
String fullRange = locale.getLanguage();
if (!locale.getScript().isEmpty()) {
fullRange += "-" + locale.getScript();
}
if (!locale.getCountry().isEmpty()) {
fullRange += "-" + locale.getCountry();
}
languageRanges.add(new Locale.LanguageRange(fullRange));
languageRanges.add(new Locale.LanguageRange(locale.getLanguage()));
languageRanges.add(new Locale.LanguageRange(locale.getLanguage() + "-*"));
}
Locale platformResolvedLocale = Locale.lookup(languageRanges, supportedLocales);
if (platformResolvedLocale != null) {
return platformResolvedLocale;
}
return supportedLocales.get(0);
} else if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) {
// Modern locale resolution without languageRange
// https://developer.android.com/guide/topics/resources/multilingual-support#postN
LocaleList localeList = context.getResources().getConfiguration().getLocales();
for (int index = 0; index < localeList.size(); ++index) {
Locale preferredLocale = localeList.get(index);
// Look for exact match.
for (Locale locale : supportedLocales) {
if (preferredLocale.equals(locale)) {
return locale;
}
}
// Look for exact language only match.
for (Locale locale : supportedLocales) {
if (preferredLocale.getLanguage().equals(locale.toLanguageTag())) {
return locale;
}
}
// Look for any locale with matching language.
for (Locale locale : supportedLocales) {
if (preferredLocale.getLanguage().equals(locale.getLanguage())) {
return locale;
}
}
}
return supportedLocales.get(0);
}
// Legacy locale resolution
// https://developer.android.com/guide/topics/resources/multilingual-support#preN
Locale preferredLocale = context.getResources().getConfiguration().locale;
if (preferredLocale != null) {
// Look for exact match.
for (Locale locale : supportedLocales) {
if (preferredLocale.equals(locale)) {
return locale;
}
}
// Look for exact language only match.
for (Locale locale : supportedLocales) {
if (preferredLocale.getLanguage().equals(locale.toString())) {
return locale;
}
}
}
return supportedLocales.get(0);
}
/**
* Send the current {@link Locale} configuration to Flutter.
*
* <p>FlutterEngine must be non-null when this method is invoked.
*/
@SuppressWarnings("deprecation")
public void sendLocalesToFlutter(@NonNull Configuration config) {
List<Locale> locales = new ArrayList<>();
if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) {
LocaleList localeList = config.getLocales();
int localeCount = localeList.size();
for (int index = 0; index < localeCount; ++index) {
Locale locale = localeList.get(index);
locales.add(locale);
}
} else {
locales.add(config.locale);
}
localizationChannel.sendLocales(locales);
}
/**
* Computes the {@link Locale} from the provided {@code String} with format
* language[-script][-region][-...], where script is an alphabet string of length 4, and region is
* either an alphabet string of length 2 or a digit string of length 3.
*/
@NonNull
public static Locale localeFromString(@NonNull String localeString) {
// Normalize the locale string, replace all underscores with hyphens.
localeString = localeString.replace('_', '-');
// Pre-API 21, we fall back to manually parsing the locale tag.
String parts[] = localeString.split("-", -1);
// Assume the first part is always the language code.
String languageCode = parts[0];
String scriptCode = "";
String countryCode = "";
int index = 1;
if (parts.length > index && parts[index].length() == 4) {
scriptCode = parts[index];
index++;
}
if (parts.length > index && parts[index].length() >= 2 && parts[index].length() <= 3) {
countryCode = parts[index];
index++;
}
// Ignore the rest of the locale for this purpose.
return new Locale(languageCode, countryCode, scriptCode);
}
}
| engine/shell/platform/android/io/flutter/plugin/localization/LocalizationPlugin.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/localization/LocalizationPlugin.java",
"repo_id": "engine",
"token_count": 2851
} | 304 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugin.platform;
import static io.flutter.Build.API_LEVELS;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowMetrics;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import io.flutter.Log;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
/**
* A static proxy handler for a WindowManager with custom overrides.
*
* <p>The presentation's window manager delegates all calls to the default window manager.
* WindowManager#addView calls triggered by views that are attached to the virtual display are
* crashing (see: https://github.com/flutter/flutter/issues/20714). This was triggered when
* selecting text in an embedded WebView (as the selection handles are implemented as popup
* windows).
*
* <p>This static proxy overrides the addView, removeView, removeViewImmediate, and updateViewLayout
* methods to prevent these crashes, and forwards all other calls to the delegate.
*
* <p>This is an abstract class because some clients of Flutter compile the Android embedding with
* the Android System SDK, which has additional abstract methods that need to be overriden.
*/
abstract class SingleViewWindowManager implements WindowManager {
private static final String TAG = "PlatformViewsController";
final WindowManager delegate;
SingleViewFakeWindowViewGroup fakeWindowRootView;
SingleViewWindowManager(
WindowManager delegate, SingleViewFakeWindowViewGroup fakeWindowViewGroup) {
this.delegate = delegate;
fakeWindowRootView = fakeWindowViewGroup;
}
@Override
@Deprecated
public Display getDefaultDisplay() {
return delegate.getDefaultDisplay();
}
@Override
public void removeViewImmediate(View view) {
if (fakeWindowRootView == null) {
Log.w(TAG, "Embedded view called removeViewImmediate while detached from presentation");
return;
}
view.clearAnimation();
fakeWindowRootView.removeView(view);
}
@Override
public void addView(View view, ViewGroup.LayoutParams params) {
if (fakeWindowRootView == null) {
Log.w(TAG, "Embedded view called addView while detached from presentation");
return;
}
fakeWindowRootView.addView(view, params);
}
@Override
public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
if (fakeWindowRootView == null) {
Log.w(TAG, "Embedded view called updateViewLayout while detached from presentation");
return;
}
fakeWindowRootView.updateViewLayout(view, params);
}
@Override
public void removeView(View view) {
if (fakeWindowRootView == null) {
Log.w(TAG, "Embedded view called removeView while detached from presentation");
return;
}
fakeWindowRootView.removeView(view);
}
@RequiresApi(api = API_LEVELS.API_30)
@NonNull
@Override
public WindowMetrics getCurrentWindowMetrics() {
return delegate.getCurrentWindowMetrics();
}
@RequiresApi(api = API_LEVELS.API_30)
@NonNull
@Override
public WindowMetrics getMaximumWindowMetrics() {
return delegate.getMaximumWindowMetrics();
}
@RequiresApi(api = API_LEVELS.API_31)
@Override
public boolean isCrossWindowBlurEnabled() {
return delegate.isCrossWindowBlurEnabled();
}
@RequiresApi(api = API_LEVELS.API_31)
@Override
public void addCrossWindowBlurEnabledListener(@NonNull Consumer<Boolean> listener) {
delegate.addCrossWindowBlurEnabledListener(listener);
}
@RequiresApi(api = API_LEVELS.API_31)
@Override
public void addCrossWindowBlurEnabledListener(
@NonNull Executor executor, @NonNull Consumer<Boolean> listener) {
delegate.addCrossWindowBlurEnabledListener(executor, listener);
}
@RequiresApi(api = API_LEVELS.API_31)
@Override
public void removeCrossWindowBlurEnabledListener(@NonNull Consumer<Boolean> listener) {
delegate.removeCrossWindowBlurEnabledListener(listener);
}
}
| engine/shell/platform/android/io/flutter/plugin/platform/SingleViewWindowManager.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/platform/SingleViewWindowManager.java",
"repo_id": "engine",
"token_count": 1252
} | 305 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import android.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.UiThread;
import io.flutter.Log;
import io.flutter.app.FlutterPluginRegistry;
import io.flutter.embedding.engine.FlutterEngine.EngineLifecycleListener;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener;
import io.flutter.plugin.common.*;
import java.nio.ByteBuffer;
/**
* @deprecated {@link io.flutter.embedding.android.FlutterView} is the new API that now replaces
* this class. See https://flutter.dev/go/android-project-migration for more migration details.
*/
@Deprecated
public class FlutterNativeView implements BinaryMessenger {
private static final String TAG = "FlutterNativeView";
private final FlutterPluginRegistry mPluginRegistry;
private final DartExecutor dartExecutor;
private FlutterView mFlutterView;
private final FlutterJNI mFlutterJNI;
private final Context mContext;
private boolean applicationIsRunning;
private final FlutterUiDisplayListener flutterUiDisplayListener =
new FlutterUiDisplayListener() {
@Override
public void onFlutterUiDisplayed() {
if (mFlutterView == null) {
return;
}
mFlutterView.onFirstFrame();
}
@Override
public void onFlutterUiNoLongerDisplayed() {
// no-op
}
};
public FlutterNativeView(@NonNull Context context) {
this(context, false);
}
public FlutterNativeView(@NonNull Context context, boolean isBackgroundView) {
if (isBackgroundView) {
Log.w(TAG, "'isBackgroundView' is no longer supported and will be ignored");
}
mContext = context;
mPluginRegistry = new FlutterPluginRegistry(this, context);
mFlutterJNI = new FlutterJNI();
mFlutterJNI.addIsDisplayingFlutterUiListener(flutterUiDisplayListener);
this.dartExecutor = new DartExecutor(mFlutterJNI, context.getAssets());
mFlutterJNI.addEngineLifecycleListener(new EngineLifecycleListenerImpl());
attach(this);
assertAttached();
}
public void detachFromFlutterView() {
mPluginRegistry.detach();
mFlutterView = null;
}
public void destroy() {
mPluginRegistry.destroy();
dartExecutor.onDetachedFromJNI();
mFlutterView = null;
mFlutterJNI.removeIsDisplayingFlutterUiListener(flutterUiDisplayListener);
mFlutterJNI.detachFromNativeAndReleaseResources();
applicationIsRunning = false;
}
@NonNull
public DartExecutor getDartExecutor() {
return dartExecutor;
}
@NonNull
public FlutterPluginRegistry getPluginRegistry() {
return mPluginRegistry;
}
public void attachViewAndActivity(FlutterView flutterView, Activity activity) {
mFlutterView = flutterView;
mPluginRegistry.attach(flutterView, activity);
}
public boolean isAttached() {
return mFlutterJNI.isAttached();
}
public void assertAttached() {
if (!isAttached()) throw new AssertionError("Platform view is not attached");
}
public void runFromBundle(FlutterRunArguments args) {
if (args.entrypoint == null) {
throw new AssertionError("An entrypoint must be specified");
}
assertAttached();
if (applicationIsRunning)
throw new AssertionError("This Flutter engine instance is already running an application");
mFlutterJNI.runBundleAndSnapshotFromLibrary(
args.bundlePath,
args.entrypoint,
args.libraryPath,
mContext.getResources().getAssets(),
null);
applicationIsRunning = true;
}
public boolean isApplicationRunning() {
return applicationIsRunning;
}
@Deprecated
public static String getObservatoryUri() {
return FlutterJNI.getVMServiceUri();
}
public static String getVMServiceUri() {
return FlutterJNI.getVMServiceUri();
}
@Override
@UiThread
public TaskQueue makeBackgroundTaskQueue(TaskQueueOptions options) {
return dartExecutor.getBinaryMessenger().makeBackgroundTaskQueue(options);
}
@Override
@UiThread
public void send(String channel, ByteBuffer message) {
dartExecutor.getBinaryMessenger().send(channel, message);
}
@Override
@UiThread
public void send(String channel, ByteBuffer message, BinaryReply callback) {
if (!isAttached()) {
Log.d(TAG, "FlutterView.send called on a detached view, channel=" + channel);
return;
}
dartExecutor.getBinaryMessenger().send(channel, message, callback);
}
@Override
@UiThread
public void setMessageHandler(String channel, BinaryMessageHandler handler) {
dartExecutor.getBinaryMessenger().setMessageHandler(channel, handler);
}
@Override
@UiThread
public void setMessageHandler(String channel, BinaryMessageHandler handler, TaskQueue taskQueue) {
dartExecutor.getBinaryMessenger().setMessageHandler(channel, handler, taskQueue);
}
@Override
public void enableBufferingIncomingMessages() {}
@Override
public void disableBufferingIncomingMessages() {}
/*package*/ FlutterJNI getFlutterJNI() {
return mFlutterJNI;
}
private void attach(FlutterNativeView view) {
mFlutterJNI.attachToNative();
dartExecutor.onAttachedToJNI();
}
private final class EngineLifecycleListenerImpl implements EngineLifecycleListener {
// Called by native to notify right before the engine is restarted (cold reload).
@SuppressWarnings("unused")
public void onPreEngineRestart() {
if (mFlutterView != null) {
mFlutterView.resetAccessibilityTree();
}
if (mPluginRegistry == null) {
return;
}
mPluginRegistry.onPreEngineRestart();
}
public void onEngineWillDestroy() {
// The old embedding doesn't actually have a FlutterEngine. It interacts with the JNI
// directly.
}
}
}
| engine/shell/platform/android/io/flutter/view/FlutterNativeView.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/view/FlutterNativeView.java",
"repo_id": "engine",
"token_count": 2061
} | 306 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <android/hardware_buffer_jni.h>
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/platform/android/scoped_java_ref.h"
#include "flutter/lib/ui/window/platform_message.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/snapshot_surface_producer.h"
#include "flutter/shell/platform/android/context/android_context.h"
#include "flutter/shell/platform/android/jni/platform_view_android_jni.h"
#include "flutter/shell/platform/android/platform_message_handler_android.h"
#include "flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h"
#include "flutter/shell/platform/android/surface/android_native_window.h"
#include "flutter/shell/platform/android/surface/android_surface.h"
namespace flutter {
class AndroidSurfaceFactoryImpl : public AndroidSurfaceFactory {
public:
AndroidSurfaceFactoryImpl(const std::shared_ptr<AndroidContext>& context,
bool enable_impeller);
~AndroidSurfaceFactoryImpl() override;
std::unique_ptr<AndroidSurface> CreateSurface() override;
private:
const std::shared_ptr<AndroidContext>& android_context_;
const bool enable_impeller_;
};
class PlatformViewAndroid final : public PlatformView {
public:
static bool Register(JNIEnv* env);
PlatformViewAndroid(PlatformView::Delegate& delegate,
const flutter::TaskRunners& task_runners,
const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade,
bool use_software_rendering,
uint8_t msaa_samples);
//----------------------------------------------------------------------------
/// @brief Creates a new PlatformViewAndroid but using an existing
/// Android GPU context to create new surfaces. This maximizes
/// resource sharing between 2 PlatformViewAndroids of 2 Shells.
///
PlatformViewAndroid(
PlatformView::Delegate& delegate,
const flutter::TaskRunners& task_runners,
const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade,
const std::shared_ptr<flutter::AndroidContext>& android_context);
~PlatformViewAndroid() override;
void NotifyCreated(fml::RefPtr<AndroidNativeWindow> native_window);
void NotifySurfaceWindowChanged(
fml::RefPtr<AndroidNativeWindow> native_window);
void NotifyChanged(const SkISize& size);
// |PlatformView|
void NotifyDestroyed() override;
void DispatchPlatformMessage(JNIEnv* env,
std::string name,
jobject message_data,
jint message_position,
jint response_id);
void DispatchEmptyPlatformMessage(JNIEnv* env,
std::string name,
jint response_id);
void DispatchSemanticsAction(JNIEnv* env,
jint id,
jint action,
jobject args,
jint args_position);
void RegisterExternalTexture(
int64_t texture_id,
const fml::jni::ScopedJavaGlobalRef<jobject>& surface_texture);
void RegisterImageTexture(
int64_t texture_id,
const fml::jni::ScopedJavaGlobalRef<jobject>& image_texture_entry);
// |PlatformView|
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|
void UpdateAssetResolverByType(
std::unique_ptr<AssetResolver> updated_asset_resolver,
AssetResolver::AssetResolverType type) override;
const std::shared_ptr<AndroidContext>& GetAndroidContext() {
return android_context_;
}
std::shared_ptr<PlatformMessageHandler> GetPlatformMessageHandler()
const override {
return platform_message_handler_;
}
private:
const std::shared_ptr<PlatformViewAndroidJNI> jni_facade_;
std::shared_ptr<AndroidContext> android_context_;
std::shared_ptr<AndroidSurfaceFactoryImpl> surface_factory_;
PlatformViewAndroidDelegate platform_view_android_delegate_;
std::unique_ptr<AndroidSurface> android_surface_;
std::shared_ptr<PlatformMessageHandlerAndroid> platform_message_handler_;
// |PlatformView|
void UpdateSemantics(
flutter::SemanticsNodeUpdates update,
flutter::CustomAccessibilityActionUpdates actions) override;
// |PlatformView|
void HandlePlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message) override;
// |PlatformView|
void OnPreEngineRestart() const override;
// |PlatformView|
std::unique_ptr<VsyncWaiter> CreateVSyncWaiter() override;
// |PlatformView|
std::unique_ptr<Surface> CreateRenderingSurface() override;
// |PlatformView|
std::shared_ptr<ExternalViewEmbedder> CreateExternalViewEmbedder() override;
// |PlatformView|
std::unique_ptr<SnapshotSurfaceProducer> CreateSnapshotSurfaceProducer()
override;
// |PlatformView|
sk_sp<GrDirectContext> CreateResourceContext() const override;
// |PlatformView|
void ReleaseResourceContext() const override;
// |PlatformView|
std::shared_ptr<impeller::Context> GetImpellerContext() const override;
// |PlatformView|
std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocales(
const std::vector<std::string>& supported_locale_data) override;
// |PlatformView|
void RequestDartDeferredLibrary(intptr_t loading_unit_id) override;
void InstallFirstFrameCallback();
void FireFirstFrameCallback();
double GetScaledFontSize(double unscaled_font_size,
int configuration_id) const override;
FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewAndroid);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_
| engine/shell/platform/android/platform_view_android.h/0 | {
"file_path": "engine/shell/platform/android/platform_view_android.h",
"repo_id": "engine",
"token_count": 2442
} | 307 |
package io.flutter.embedding.android;
import static io.flutter.Build.API_LEVELS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import android.annotation.TargetApi;
import android.graphics.SurfaceTexture;
import android.view.Surface;
import android.view.TextureView;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
@TargetApi(API_LEVELS.API_30)
public class FlutterTextureViewTest {
@Test
public void surfaceTextureListenerReleasesRenderer() {
final FlutterTextureView textureView =
new FlutterTextureView(ApplicationProvider.getApplicationContext());
final Surface mockRenderSurface = mock(Surface.class);
textureView.setRenderSurface(mockRenderSurface);
final TextureView.SurfaceTextureListener listener = textureView.getSurfaceTextureListener();
listener.onSurfaceTextureDestroyed(mock(SurfaceTexture.class));
verify(mockRenderSurface).release();
}
}
| engine/shell/platform/android/test/io/flutter/embedding/android/FlutterTextureViewTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/android/FlutterTextureViewTest.java",
"repo_id": "engine",
"token_count": 371
} | 308 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.embedding.engine.deferredcomponents;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.embedding.engine.loader.ApplicationInfoLoader;
import java.io.File;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
public class PlayStoreDeferredComponentManagerTest {
private class TestFlutterJNI extends FlutterJNI {
public int loadDartDeferredLibraryCalled = 0;
public int updateAssetManagerCalled = 0;
public int deferredComponentInstallFailureCalled = 0;
public String[] searchPaths;
public int loadingUnitId;
public AssetManager assetManager;
public String assetBundlePath;
public TestFlutterJNI() {}
@Override
public void loadDartDeferredLibrary(int loadingUnitId, @NonNull String[] searchPaths) {
loadDartDeferredLibraryCalled++;
this.searchPaths = searchPaths;
this.loadingUnitId = loadingUnitId;
}
@Override
public void updateJavaAssetManager(
@NonNull AssetManager assetManager, @NonNull String assetBundlePath) {
updateAssetManagerCalled++;
this.loadingUnitId = loadingUnitId;
this.assetManager = assetManager;
this.assetBundlePath = assetBundlePath;
}
@Override
public void deferredComponentInstallFailure(
int loadingUnitId, @NonNull String error, boolean isTransient) {
deferredComponentInstallFailureCalled++;
}
}
// Skips the download process to directly call the loadAssets and loadDartLibrary methods.
private class TestPlayStoreDeferredComponentManager extends PlayStoreDeferredComponentManager {
public TestPlayStoreDeferredComponentManager(Context context, FlutterJNI jni) {
super(context, jni);
}
@Override
public void installDeferredComponent(int loadingUnitId, String componentName) {
// Override this to skip the online SplitInstallManager portion.
loadAssets(loadingUnitId, componentName);
loadDartLibrary(loadingUnitId, componentName);
}
}
@SuppressWarnings("deprecation")
// getApplicationInfo
private Context createSpyContext(Bundle metadata) throws NameNotFoundException {
Context spyContext = spy(ApplicationProvider.getApplicationContext());
doReturn(spyContext).when(spyContext).createPackageContext(any(), anyInt());
if (metadata == null) {
metadata = new Bundle();
}
PackageManager packageManager = mock(PackageManager.class);
ApplicationInfo applicationInfo = mock(ApplicationInfo.class);
applicationInfo.metaData = metadata;
applicationInfo.splitSourceDirs = new String[1];
applicationInfo.splitSourceDirs[0] = "some.invalid.apk";
when(packageManager.getApplicationInfo(any(String.class), any(int.class)))
.thenReturn(applicationInfo);
doReturn(packageManager).when(spyContext).getPackageManager();
doReturn(applicationInfo).when(spyContext).getApplicationInfo();
return spyContext;
}
@Test
public void downloadCallsJNIFunctions() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Context spyContext = createSpyContext(null);
doReturn(null).when(spyContext).getAssets();
String soTestFilename = "libapp.so-123.part.so";
String soTestPath = "test/path/" + soTestFilename;
doReturn(new File(soTestPath)).when(spyContext).getFilesDir();
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
jni.setDeferredComponentManager(playStoreManager);
assertEquals(jni.loadingUnitId, 0);
playStoreManager.installDeferredComponent(123, "TestModuleName");
assertEquals(jni.loadDartDeferredLibraryCalled, 1);
assertEquals(jni.updateAssetManagerCalled, 1);
assertEquals(jni.deferredComponentInstallFailureCalled, 0);
assertEquals(jni.searchPaths[0], soTestFilename);
assertTrue(jni.searchPaths[1].endsWith(soTestPath));
assertEquals(jni.searchPaths.length, 2);
assertEquals(jni.loadingUnitId, 123);
assertEquals(jni.assetBundlePath, "flutter_assets");
}
@Test
public void downloadCallsJNIFunctionsWithFilenameFromManifest() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Bundle bundle = new Bundle();
bundle.putString(ApplicationInfoLoader.PUBLIC_AOT_SHARED_LIBRARY_NAME, "custom_name.so");
bundle.putString(ApplicationInfoLoader.PUBLIC_FLUTTER_ASSETS_DIR_KEY, "custom_assets");
Context spyContext = createSpyContext(bundle);
doReturn(null).when(spyContext).getAssets();
String soTestFilename = "custom_name.so-123.part.so";
String soTestPath = "test/path/" + soTestFilename;
doReturn(new File(soTestPath)).when(spyContext).getFilesDir();
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
jni.setDeferredComponentManager(playStoreManager);
assertEquals(jni.loadingUnitId, 0);
playStoreManager.installDeferredComponent(123, "TestModuleName");
assertEquals(jni.loadDartDeferredLibraryCalled, 1);
assertEquals(jni.updateAssetManagerCalled, 1);
assertEquals(jni.deferredComponentInstallFailureCalled, 0);
assertEquals(jni.searchPaths[0], soTestFilename);
assertTrue(jni.searchPaths[1].endsWith(soTestPath));
assertEquals(jni.searchPaths.length, 2);
assertEquals(jni.loadingUnitId, 123);
assertEquals(jni.assetBundlePath, "custom_assets");
}
@Test
public void downloadCallsJNIFunctionsWithSharedLibraryNameFromManifest()
throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Bundle bundle = new Bundle();
bundle.putString(PlayStoreDeferredComponentManager.MAPPING_KEY, "123:module:custom_name.so");
bundle.putString(ApplicationInfoLoader.PUBLIC_FLUTTER_ASSETS_DIR_KEY, "custom_assets");
Context spyContext = createSpyContext(bundle);
doReturn(null).when(spyContext).getAssets();
String soTestFilename = "custom_name.so";
String soTestPath = "test/path/" + soTestFilename;
doReturn(new File(soTestPath)).when(spyContext).getFilesDir();
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
jni.setDeferredComponentManager(playStoreManager);
assertEquals(jni.loadingUnitId, 0);
playStoreManager.installDeferredComponent(123, "TestModuleName");
assertEquals(jni.loadDartDeferredLibraryCalled, 1);
assertEquals(jni.updateAssetManagerCalled, 1);
assertEquals(jni.deferredComponentInstallFailureCalled, 0);
assertEquals(jni.searchPaths[0], soTestFilename);
assertTrue(jni.searchPaths[1].endsWith(soTestPath));
assertEquals(jni.searchPaths.length, 2);
assertEquals(jni.loadingUnitId, 123);
assertEquals(jni.assetBundlePath, "custom_assets");
}
@Test
public void manifestMappingHandlesBaseModuleEmptyString() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Bundle bundle = new Bundle();
bundle.putString(
PlayStoreDeferredComponentManager.MAPPING_KEY, "123:module:custom_name.so,3:,4:");
bundle.putString(ApplicationInfoLoader.PUBLIC_FLUTTER_ASSETS_DIR_KEY, "custom_assets");
Context spyContext = createSpyContext(bundle);
doReturn(null).when(spyContext).getAssets();
String soTestFilename = "libapp.so-3.part.so";
String soTestPath = "test/path/" + soTestFilename;
doReturn(new File(soTestPath)).when(spyContext).getFilesDir();
PlayStoreDeferredComponentManager playStoreManager =
new PlayStoreDeferredComponentManager(spyContext, jni);
jni.setDeferredComponentManager(playStoreManager);
assertEquals(jni.loadingUnitId, 0);
playStoreManager.installDeferredComponent(3, null);
assertEquals(jni.loadDartDeferredLibraryCalled, 1);
assertEquals(jni.updateAssetManagerCalled, 0); // no assets to load for base
assertEquals(jni.deferredComponentInstallFailureCalled, 0);
assertEquals(jni.searchPaths[0], soTestFilename);
assertTrue(jni.searchPaths[1].endsWith(soTestPath));
assertEquals(jni.searchPaths.length, 2);
assertEquals(jni.loadingUnitId, 3);
}
@Test
public void searchPathsAddsApks() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Context spyContext = createSpyContext(null);
doReturn(null).when(spyContext).getAssets();
String apkTestPath = "test/path/TestModuleName_armeabi_v7a.apk";
doReturn(new File(apkTestPath)).when(spyContext).getFilesDir();
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
jni.setDeferredComponentManager(playStoreManager);
assertEquals(jni.loadingUnitId, 0);
playStoreManager.installDeferredComponent(123, "TestModuleName");
assertEquals(jni.loadDartDeferredLibraryCalled, 1);
assertEquals(jni.updateAssetManagerCalled, 1);
assertEquals(jni.deferredComponentInstallFailureCalled, 0);
assertEquals(jni.searchPaths[0], "libapp.so-123.part.so");
assertTrue(jni.searchPaths[1].endsWith(apkTestPath + "!lib/armeabi-v7a/libapp.so-123.part.so"));
assertEquals(jni.searchPaths.length, 2);
assertEquals(jni.loadingUnitId, 123);
}
@Test
public void searchPathsSearchesSplitConfig() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Context spyContext = createSpyContext(null);
doReturn(null).when(spyContext).getAssets();
String apkTestPath = "test/path/split_config.armeabi_v7a.apk";
doReturn(new File(apkTestPath)).when(spyContext).getFilesDir();
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
jni.setDeferredComponentManager(playStoreManager);
assertEquals(jni.loadingUnitId, 0);
playStoreManager.installDeferredComponent(123, "TestModuleName");
assertEquals(jni.loadDartDeferredLibraryCalled, 1);
assertEquals(jni.updateAssetManagerCalled, 1);
assertEquals(jni.deferredComponentInstallFailureCalled, 0);
assertEquals(jni.searchPaths[0], "libapp.so-123.part.so");
assertTrue(jni.searchPaths[1].endsWith(apkTestPath + "!lib/armeabi-v7a/libapp.so-123.part.so"));
assertEquals(jni.searchPaths.length, 2);
assertEquals(jni.loadingUnitId, 123);
}
@Test
public void invalidSearchPathsAreIgnored() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Context spyContext = createSpyContext(null);
doReturn(null).when(spyContext).getAssets();
String apkTestPath = "test/path/invalidpath.apk";
doReturn(new File(apkTestPath)).when(spyContext).getFilesDir();
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
jni.setDeferredComponentManager(playStoreManager);
assertEquals(jni.loadingUnitId, 0);
playStoreManager.installDeferredComponent(123, "TestModuleName");
assertEquals(jni.loadDartDeferredLibraryCalled, 1);
assertEquals(jni.updateAssetManagerCalled, 1);
assertEquals(jni.deferredComponentInstallFailureCalled, 0);
assertEquals(jni.searchPaths[0], "libapp.so-123.part.so");
assertEquals(jni.searchPaths.length, 1);
assertEquals(jni.loadingUnitId, 123);
}
@Test
public void assetManagerUpdateInvoked() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Context spyContext = createSpyContext(null);
doReturn(null).when(spyContext).getAssets();
AssetManager assetManager = spyContext.getAssets();
String apkTestPath = "blah doesn't matter here";
doReturn(new File(apkTestPath)).when(spyContext).getFilesDir();
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
jni.setDeferredComponentManager(playStoreManager);
assertEquals(jni.loadingUnitId, 0);
playStoreManager.installDeferredComponent(123, "TestModuleName");
assertEquals(jni.loadDartDeferredLibraryCalled, 1);
assertEquals(jni.updateAssetManagerCalled, 1);
assertEquals(jni.deferredComponentInstallFailureCalled, 0);
assertEquals(jni.assetManager, assetManager);
}
@Test
public void stateGetterReturnsUnknowByDefault() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Context spyContext = createSpyContext(null);
doReturn(null).when(spyContext).getAssets();
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
assertEquals(playStoreManager.getDeferredComponentInstallState(-1, "invalidName"), "unknown");
}
@Test
public void loadingUnitMappingFindsMatch() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Bundle bundle = new Bundle();
bundle.putString(PlayStoreDeferredComponentManager.MAPPING_KEY, "2:module1,5:module2");
Context spyContext = createSpyContext(bundle);
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
assertTrue(playStoreManager.uninstallDeferredComponent(5, null));
assertTrue(playStoreManager.uninstallDeferredComponent(2, null));
assertFalse(playStoreManager.uninstallDeferredComponent(3, null));
}
@Test
public void assetOnlyMappingParses() throws NameNotFoundException {
TestFlutterJNI jni = new TestFlutterJNI();
Bundle bundle = new Bundle();
bundle.putString(PlayStoreDeferredComponentManager.MAPPING_KEY, "");
Context spyContext = createSpyContext(bundle);
TestPlayStoreDeferredComponentManager playStoreManager =
new TestPlayStoreDeferredComponentManager(spyContext, jni);
}
}
| engine/shell/platform/android/test/io/flutter/embedding/engine/deferredcomponents/PlayStoreDeferredComponentManagerTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/deferredcomponents/PlayStoreDeferredComponentManagerTest.java",
"repo_id": "engine",
"token_count": 5032
} | 309 |
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 androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
@Config(
manifest = Config.NONE,
shadows = {})
@RunWith(AndroidJUnit4.class)
@TargetApi(API_LEVELS.API_24)
public class TextInputChannelTest {
@Test
public void setEditableSizeAndTransformCompletes() throws JSONException {
TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class));
textInputChannel.setTextInputMethodHandler(mock(TextInputChannel.TextInputMethodHandler.class));
JSONObject arguments = new JSONObject();
arguments.put("width", 100.0);
arguments.put("height", 20.0);
arguments.put("transform", new JSONArray(new double[16]));
MethodCall call = new MethodCall("TextInput.setEditableSizeAndTransform", arguments);
MethodChannel.Result result = mock(MethodChannel.Result.class);
textInputChannel.parsingMethodHandler.onMethodCall(call, result);
verify(result).success(null);
}
}
| engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/TextInputChannelTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/TextInputChannelTest.java",
"repo_id": "engine",
"token_count": 484
} | 310 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugin.platform;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.os.SystemClock;
import android.view.MotionEvent;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class PlatformOverlayViewTest {
private final Context ctx = ApplicationProvider.getApplicationContext();
@Test
public void platformOverlayView_forwardsHover() {
final AccessibilityEventsDelegate mockAccessibilityDelegate =
mock(AccessibilityEventsDelegate.class);
when(mockAccessibilityDelegate.onAccessibilityHoverEvent(any(), eq(true))).thenReturn(true);
final int size = 10;
final PlatformOverlayView imageView =
new PlatformOverlayView(ctx, size, size, mockAccessibilityDelegate);
MotionEvent event =
MotionEvent.obtain(
SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_HOVER_MOVE,
size / 2,
size / 2,
0);
imageView.onHoverEvent(event);
verify(mockAccessibilityDelegate, times(1)).onAccessibilityHoverEvent(event, true);
}
}
| engine/shell/platform/android/test/io/flutter/plugin/platform/PlatformOverlayViewTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/plugin/platform/PlatformOverlayViewTest.java",
"repo_id": "engine",
"token_count": 577
} | 311 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.hardware.display.DisplayManager;
import android.os.Looper;
import android.view.Display;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.embedding.engine.FlutterJNI;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
public class VsyncWaiterTest {
@Before
public void setUp() {
VsyncWaiter.reset();
}
@Test
public void itSetsFpsBelowApi17() {
FlutterJNI mockFlutterJNI = mock(FlutterJNI.class);
VsyncWaiter waiter = VsyncWaiter.getInstance(10.0f, mockFlutterJNI);
verify(mockFlutterJNI, times(1)).setRefreshRateFPS(10.0f);
waiter.init();
ArgumentCaptor<FlutterJNI.AsyncWaitForVsyncDelegate> delegateCaptor =
ArgumentCaptor.forClass(FlutterJNI.AsyncWaitForVsyncDelegate.class);
verify(mockFlutterJNI, times(1)).setAsyncWaitForVsyncDelegate(delegateCaptor.capture());
delegateCaptor.getValue().asyncWaitForVsync(1);
shadowOf(Looper.getMainLooper()).idle();
verify(mockFlutterJNI, times(1)).onVsync(anyLong(), eq(1000000000l / 10l), eq(1l));
}
@Test
public void itSetsFpsWhenDisplayManagerUpdates() {
FlutterJNI mockFlutterJNI = mock(FlutterJNI.class);
DisplayManager mockDisplayManager = mock(DisplayManager.class);
Display mockDisplay = mock(Display.class);
ArgumentCaptor<VsyncWaiter.DisplayListener> displayListenerCaptor =
ArgumentCaptor.forClass(VsyncWaiter.DisplayListener.class);
when(mockDisplayManager.getDisplay(Display.DEFAULT_DISPLAY)).thenReturn(mockDisplay);
VsyncWaiter waiter = VsyncWaiter.getInstance(mockDisplayManager, mockFlutterJNI);
verify(mockDisplayManager, times(1))
.registerDisplayListener(displayListenerCaptor.capture(), isNull());
when(mockDisplay.getRefreshRate()).thenReturn(90.0f);
displayListenerCaptor.getValue().onDisplayChanged(Display.DEFAULT_DISPLAY);
verify(mockFlutterJNI, times(1)).setRefreshRateFPS(90.0f);
waiter.init();
ArgumentCaptor<FlutterJNI.AsyncWaitForVsyncDelegate> delegateCaptor =
ArgumentCaptor.forClass(FlutterJNI.AsyncWaitForVsyncDelegate.class);
verify(mockFlutterJNI, times(1)).setAsyncWaitForVsyncDelegate(delegateCaptor.capture());
delegateCaptor.getValue().asyncWaitForVsync(1);
shadowOf(Looper.getMainLooper()).idle();
verify(mockFlutterJNI, times(1)).onVsync(anyLong(), eq(1000000000l / 90l), eq(1l));
when(mockDisplay.getRefreshRate()).thenReturn(60.0f);
displayListenerCaptor.getValue().onDisplayChanged(Display.DEFAULT_DISPLAY);
verify(mockFlutterJNI, times(1)).setRefreshRateFPS(60.0f);
delegateCaptor.getValue().asyncWaitForVsync(1);
shadowOf(Looper.getMainLooper()).idle();
verify(mockFlutterJNI, times(1)).onVsync(anyLong(), eq(1000000000l / 60l), eq(1l));
}
@Test
public void itSetsFpsWhenDisplayManagerDoesNotUpdate() {
FlutterJNI mockFlutterJNI = mock(FlutterJNI.class);
DisplayManager mockDisplayManager = mock(DisplayManager.class);
Display mockDisplay = mock(Display.class);
when(mockDisplayManager.getDisplay(Display.DEFAULT_DISPLAY)).thenReturn(mockDisplay);
when(mockDisplay.getRefreshRate()).thenReturn(90.0f);
VsyncWaiter waiter = VsyncWaiter.getInstance(mockDisplayManager, mockFlutterJNI);
verify(mockDisplayManager, times(1)).registerDisplayListener(any(), isNull());
verify(mockFlutterJNI, times(1)).setRefreshRateFPS(90.0f);
}
}
| engine/shell/platform/android/test/io/flutter/view/VsyncWaiterTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/view/VsyncWaiterTest.java",
"repo_id": "engine",
"token_count": 1499
} | 312 |
This code is intended to be built into plugins and applications to provide
higher-level, C++ abstractions for interacting with the Flutter library.
Over time, the goal is to move more of this code into the library in a way that
provides a usable ABI (e.g., does not use standard library in the interfaces).
Note that this wrapper is still in early stages. Expect significant churn in
both the APIs and the structure of the wrapper (e.g., the exact set of files
that need to be built).
| engine/shell/platform/common/client_wrapper/README/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/README",
"repo_id": "engine",
"token_count": 116
} | 313 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_H_
#include <memory>
#include <string>
#include "event_sink.h"
namespace flutter {
class EncodableValue;
template <typename T = EncodableValue>
struct StreamHandlerError {
const std::string error_code;
const std::string error_message;
const std::unique_ptr<T> error_details;
StreamHandlerError(const std::string& error_code,
const std::string& error_message,
std::unique_ptr<T>&& error_details)
: error_code(error_code),
error_message(error_message),
error_details(std::move(error_details)) {}
};
// Handler for stream setup and teardown requests.
// Implementations must be prepared to accept sequences of alternating calls to
// OnListen() and OnCancel(). Implementations should ideally consume no
// resources when the last such call is not OnListen(). In typical situations,
// this means that the implementation should register itself with
// platform-specific event sources OnListen() and deregister again OnCancel().
template <typename T = EncodableValue>
class StreamHandler {
public:
StreamHandler() = default;
virtual ~StreamHandler() = default;
// Prevent copying.
StreamHandler(StreamHandler const&) = delete;
StreamHandler& operator=(StreamHandler const&) = delete;
// Handles a request to set up an event stream. Returns nullptr on success,
// or an error on failure.
// |arguments| is stream configuration arguments and
// |events| is an EventSink for emitting events to the Flutter receiver.
std::unique_ptr<StreamHandlerError<T>> OnListen(
const T* arguments,
std::unique_ptr<EventSink<T>>&& events) {
return OnListenInternal(arguments, std::move(events));
}
// Handles a request to tear down the most recently created event stream.
// Returns nullptr on success, or an error on failure.
// |arguments| is stream configuration arguments.
std::unique_ptr<StreamHandlerError<T>> OnCancel(const T* arguments) {
return OnCancelInternal(arguments);
}
protected:
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<StreamHandlerError<T>> OnListenInternal(
const T* arguments,
std::unique_ptr<EventSink<T>>&& events) = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<StreamHandlerError<T>> OnCancelInternal(
const T* arguments) = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_H_
| engine/shell/platform/common/client_wrapper/include/flutter/event_stream_handler.h/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/include/flutter/event_stream_handler.h",
"repo_id": "engine",
"token_count": 921
} | 314 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h"
#include <functional>
#include <string>
#include "gtest/gtest.h"
namespace flutter {
// Tests that unset handlers don't cause crashes.
TEST(MethodChannelTest, NoHandlers) {
MethodResultFunctions<int> result(nullptr, nullptr, nullptr);
result.Success();
result.Error("error");
result.NotImplemented();
}
// Tests that Success calls through to handler.
TEST(MethodChannelTest, Success) {
bool called = false;
int value = 1;
MethodResultFunctions<int> result(
[&called, value](const int* i) {
called = true;
EXPECT_EQ(*i, value);
},
nullptr, nullptr);
result.Success(value);
EXPECT_TRUE(called);
}
// Tests that Error calls through to handler.
TEST(MethodChannelTest, Error) {
bool called = false;
std::string error_code = "a";
std::string error_message = "b";
int error_details = 1;
MethodResultFunctions<int> result(
nullptr,
[&called, error_code, error_message, error_details](
const std::string& code, const std::string& message,
const int* details) {
called = true;
EXPECT_EQ(code, error_code);
EXPECT_EQ(message, error_message);
EXPECT_EQ(*details, error_details);
},
nullptr);
result.Error(error_code, error_message, error_details);
EXPECT_TRUE(called);
}
// Tests that NotImplemented calls through to handler.
TEST(MethodChannelTest, NotImplemented) {
bool called = false;
MethodResultFunctions<int> result(nullptr, nullptr,
[&called]() { called = true; });
result.NotImplemented();
EXPECT_TRUE(called);
}
} // namespace flutter
| engine/shell/platform/common/client_wrapper/method_result_functions_unittests.cc/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/method_result_functions_unittests.cc",
"repo_id": "engine",
"token_count": 698
} | 315 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter_platform_node_delegate.h"
#include <utility>
#include "flutter/shell/platform/common/accessibility_bridge.h"
#include "flutter/third_party/accessibility/ax/ax_action_data.h"
#include "flutter/third_party/accessibility/ax/ax_tree_manager_map.h"
#include "flutter/third_party/accessibility/gfx/geometry/rect_conversions.h"
namespace flutter {
FlutterPlatformNodeDelegate::FlutterPlatformNodeDelegate() = default;
FlutterPlatformNodeDelegate::~FlutterPlatformNodeDelegate() = default;
void FlutterPlatformNodeDelegate::Init(std::weak_ptr<OwnerBridge> bridge,
ui::AXNode* node) {
bridge_ = std::move(bridge);
ax_node_ = node;
}
ui::AXNode* FlutterPlatformNodeDelegate::GetAXNode() const {
return ax_node_;
}
bool FlutterPlatformNodeDelegate::AccessibilityPerformAction(
const ui::AXActionData& data) {
AccessibilityNodeId target = ax_node_->id();
auto bridge_ptr = bridge_.lock();
BASE_DCHECK(bridge_ptr);
switch (data.action) {
case ax::mojom::Action::kDoDefault:
bridge_ptr->DispatchAccessibilityAction(
target, FlutterSemanticsAction::kFlutterSemanticsActionTap, {});
return true;
case ax::mojom::Action::kFocus:
bridge_ptr->SetLastFocusedId(target);
bridge_ptr->DispatchAccessibilityAction(
target,
FlutterSemanticsAction::
kFlutterSemanticsActionDidGainAccessibilityFocus,
{});
return true;
case ax::mojom::Action::kScrollToMakeVisible:
bridge_ptr->DispatchAccessibilityAction(
target, FlutterSemanticsAction::kFlutterSemanticsActionShowOnScreen,
{});
return true;
// TODO(chunhtai): support more actions.
default:
return false;
}
return false;
}
const ui::AXNodeData& FlutterPlatformNodeDelegate::GetData() const {
return ax_node_->data();
}
gfx::NativeViewAccessible FlutterPlatformNodeDelegate::GetParent() {
if (!ax_node_->parent()) {
return nullptr;
}
auto bridge_ptr = bridge_.lock();
BASE_DCHECK(bridge_ptr);
return bridge_ptr->GetNativeAccessibleFromId(ax_node_->parent()->id());
}
gfx::NativeViewAccessible FlutterPlatformNodeDelegate::GetFocus() {
auto bridge_ptr = bridge_.lock();
BASE_DCHECK(bridge_ptr);
AccessibilityNodeId last_focused = bridge_ptr->GetLastFocusedId();
if (last_focused == ui::AXNode::kInvalidAXID) {
return nullptr;
}
return bridge_ptr->GetNativeAccessibleFromId(last_focused);
}
int FlutterPlatformNodeDelegate::GetChildCount() const {
return static_cast<int>(ax_node_->GetUnignoredChildCount());
}
gfx::NativeViewAccessible FlutterPlatformNodeDelegate::ChildAtIndex(int index) {
auto bridge_ptr = bridge_.lock();
BASE_DCHECK(bridge_ptr);
AccessibilityNodeId child = ax_node_->GetUnignoredChildAtIndex(index)->id();
return bridge_ptr->GetNativeAccessibleFromId(child);
}
gfx::Rect FlutterPlatformNodeDelegate::GetBoundsRect(
const ui::AXCoordinateSystem coordinate_system,
const ui::AXClippingBehavior clipping_behavior,
ui::AXOffscreenResult* offscreen_result) const {
auto bridge_ptr = bridge_.lock();
BASE_DCHECK(bridge_ptr);
// TODO(chunhtai): We need to apply screen dpr in here.
// https://github.com/flutter/flutter/issues/74283
const bool clip_bounds =
clipping_behavior == ui::AXClippingBehavior::kClipped;
bool offscreen = false;
gfx::RectF bounds =
bridge_ptr->RelativeToGlobalBounds(ax_node_, offscreen, clip_bounds);
if (offscreen_result != nullptr) {
*offscreen_result = offscreen ? ui::AXOffscreenResult::kOffscreen
: ui::AXOffscreenResult::kOnscreen;
}
return gfx::ToEnclosingRect(bounds);
}
std::weak_ptr<FlutterPlatformNodeDelegate::OwnerBridge>
FlutterPlatformNodeDelegate::GetOwnerBridge() const {
return bridge_;
}
ui::AXPlatformNode* FlutterPlatformNodeDelegate::GetPlatformNode() const {
return nullptr;
}
gfx::NativeViewAccessible
FlutterPlatformNodeDelegate::GetLowestPlatformAncestor() const {
auto bridge_ptr = bridge_.lock();
BASE_DCHECK(bridge_ptr);
auto lowest_platform_ancestor = ax_node_->GetLowestPlatformAncestor();
if (lowest_platform_ancestor) {
return bridge_ptr->GetNativeAccessibleFromId(
ax_node_->GetLowestPlatformAncestor()->id());
}
return nullptr;
}
ui::AXNodePosition::AXPositionInstance
FlutterPlatformNodeDelegate::CreateTextPositionAt(int offset) const {
return ui::AXNodePosition::CreatePosition(*ax_node_, offset);
}
ui::AXPlatformNode* FlutterPlatformNodeDelegate::GetFromNodeID(
int32_t node_id) {
ui::AXTreeManager* tree_manager =
ui::AXTreeManagerMap::GetInstance().GetManager(
ax_node_->tree()->GetAXTreeID());
AccessibilityBridge* platform_manager =
static_cast<AccessibilityBridge*>(tree_manager);
return platform_manager->GetPlatformNodeFromTree(node_id);
}
ui::AXPlatformNode* FlutterPlatformNodeDelegate::GetFromTreeIDAndNodeID(
const ui::AXTreeID& tree_id,
int32_t node_id) {
ui::AXTreeManager* tree_manager =
ui::AXTreeManagerMap::GetInstance().GetManager(tree_id);
AccessibilityBridge* platform_manager =
static_cast<AccessibilityBridge*>(tree_manager);
return platform_manager->GetPlatformNodeFromTree(node_id);
}
const ui::AXTree::Selection FlutterPlatformNodeDelegate::GetUnignoredSelection()
const {
return ax_node_->GetUnignoredSelection();
}
} // namespace flutter
| engine/shell/platform/common/flutter_platform_node_delegate.cc/0 | {
"file_path": "engine/shell/platform/common/flutter_platform_node_delegate.cc",
"repo_id": "engine",
"token_count": 2007
} | 316 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/common/path_utils.h"
#include "gtest/gtest.h"
namespace flutter {
// Tests that GetExecutableDirectory returns a valid, absolute path.
TEST(PathUtilsTest, ExecutableDirector) {
std::filesystem::path exe_directory = GetExecutableDirectory();
#if defined(__linux__) || defined(_WIN32)
EXPECT_EQ(exe_directory.empty(), false);
EXPECT_EQ(exe_directory.is_absolute(), true);
#else
// On platforms where it's not implemented, it should indicate that
// by returning an empty path.
EXPECT_EQ(exe_directory.empty(), true);
#endif
}
} // namespace flutter
| engine/shell/platform/common/path_utils_unittests.cc/0 | {
"file_path": "engine/shell/platform/common/path_utils_unittests.cc",
"repo_id": "engine",
"token_count": 234
} | 317 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/common/text_range.h"
#include "gtest/gtest.h"
namespace flutter {
TEST(TextRange, TextRangeFromPositionZero) {
TextRange range(0);
EXPECT_EQ(range.base(), size_t(0));
EXPECT_EQ(range.extent(), size_t(0));
EXPECT_EQ(range.start(), size_t(0));
EXPECT_EQ(range.end(), size_t(0));
EXPECT_EQ(range.length(), size_t(0));
EXPECT_EQ(range.position(), size_t(0));
EXPECT_TRUE(range.collapsed());
}
TEST(TextRange, TextRangeFromPositionNonZero) {
TextRange range(3);
EXPECT_EQ(range.base(), size_t(3));
EXPECT_EQ(range.extent(), size_t(3));
EXPECT_EQ(range.start(), size_t(3));
EXPECT_EQ(range.end(), size_t(3));
EXPECT_EQ(range.length(), size_t(0));
EXPECT_EQ(range.position(), size_t(3));
EXPECT_TRUE(range.collapsed());
}
TEST(TextRange, TextRangeFromRange) {
TextRange range(3, 7);
EXPECT_EQ(range.base(), size_t(3));
EXPECT_EQ(range.extent(), size_t(7));
EXPECT_EQ(range.start(), size_t(3));
EXPECT_EQ(range.end(), size_t(7));
EXPECT_EQ(range.length(), size_t(4));
EXPECT_FALSE(range.collapsed());
}
TEST(TextRange, TextRangeFromReversedRange) {
TextRange range(7, 3);
EXPECT_EQ(range.base(), size_t(7));
EXPECT_EQ(range.extent(), size_t(3));
EXPECT_EQ(range.start(), size_t(3));
EXPECT_EQ(range.end(), size_t(7));
EXPECT_EQ(range.length(), size_t(4));
EXPECT_FALSE(range.collapsed());
}
TEST(TextRange, SetBase) {
TextRange range(3, 7);
range.set_base(4);
EXPECT_EQ(range.base(), size_t(4));
EXPECT_EQ(range.extent(), size_t(7));
}
TEST(TextRange, SetBaseReversed) {
TextRange range(7, 3);
range.set_base(5);
EXPECT_EQ(range.base(), size_t(5));
EXPECT_EQ(range.extent(), size_t(3));
}
TEST(TextRange, SetExtent) {
TextRange range(3, 7);
range.set_extent(6);
EXPECT_EQ(range.base(), size_t(3));
EXPECT_EQ(range.extent(), size_t(6));
}
TEST(TextRange, SetExtentReversed) {
TextRange range(7, 3);
range.set_extent(4);
EXPECT_EQ(range.base(), size_t(7));
EXPECT_EQ(range.extent(), size_t(4));
}
TEST(TextRange, SetStart) {
TextRange range(3, 7);
range.set_start(5);
EXPECT_EQ(range.base(), size_t(5));
EXPECT_EQ(range.extent(), size_t(7));
}
TEST(TextRange, SetStartReversed) {
TextRange range(7, 3);
range.set_start(5);
EXPECT_EQ(range.base(), size_t(7));
EXPECT_EQ(range.extent(), size_t(5));
}
TEST(TextRange, SetEnd) {
TextRange range(3, 7);
range.set_end(6);
EXPECT_EQ(range.base(), size_t(3));
EXPECT_EQ(range.extent(), size_t(6));
}
TEST(TextRange, SetEndReversed) {
TextRange range(7, 3);
range.set_end(5);
EXPECT_EQ(range.base(), size_t(5));
EXPECT_EQ(range.extent(), size_t(3));
}
TEST(TextRange, ContainsPreStartPosition) {
TextRange range(2, 6);
EXPECT_FALSE(range.Contains(1));
}
TEST(TextRange, ContainsStartPosition) {
TextRange range(2, 6);
EXPECT_TRUE(range.Contains(2));
}
TEST(TextRange, ContainsMiddlePosition) {
TextRange range(2, 6);
EXPECT_TRUE(range.Contains(3));
EXPECT_TRUE(range.Contains(4));
}
TEST(TextRange, ContainsEndPosition) {
TextRange range(2, 6);
EXPECT_TRUE(range.Contains(6));
}
TEST(TextRange, ContainsPostEndPosition) {
TextRange range(2, 6);
EXPECT_FALSE(range.Contains(7));
}
TEST(TextRange, ContainsPreStartPositionReversed) {
TextRange range(6, 2);
EXPECT_FALSE(range.Contains(1));
}
TEST(TextRange, ContainsStartPositionReversed) {
TextRange range(6, 2);
EXPECT_TRUE(range.Contains(2));
}
TEST(TextRange, ContainsMiddlePositionReversed) {
TextRange range(6, 2);
EXPECT_TRUE(range.Contains(3));
EXPECT_TRUE(range.Contains(4));
}
TEST(TextRange, ContainsEndPositionReversed) {
TextRange range(6, 2);
EXPECT_TRUE(range.Contains(6));
}
TEST(TextRange, ContainsPostEndPositionReversed) {
TextRange range(6, 2);
EXPECT_FALSE(range.Contains(7));
}
TEST(TextRange, ContainsRangePreStartPosition) {
TextRange range(2, 6);
EXPECT_FALSE(range.Contains(TextRange(0, 1)));
}
TEST(TextRange, ContainsRangeSpanningStartPosition) {
TextRange range(2, 6);
EXPECT_FALSE(range.Contains(TextRange(1, 3)));
}
TEST(TextRange, ContainsRangeStartPosition) {
TextRange range(2, 6);
EXPECT_TRUE(range.Contains(TextRange(2)));
}
TEST(TextRange, ContainsRangeMiddlePosition) {
TextRange range(2, 6);
EXPECT_TRUE(range.Contains(TextRange(3, 4)));
EXPECT_TRUE(range.Contains(TextRange(4, 5)));
}
TEST(TextRange, ContainsRangeEndPosition) {
TextRange range(2, 6);
EXPECT_TRUE(range.Contains(TextRange(6)));
}
TEST(TextRange, ContainsRangeSpanningEndPosition) {
TextRange range(2, 6);
EXPECT_FALSE(range.Contains(TextRange(5, 7)));
}
TEST(TextRange, ContainsRangePostEndPosition) {
TextRange range(2, 6);
EXPECT_FALSE(range.Contains(TextRange(6, 7)));
}
TEST(TextRange, ContainsRangePreStartPositionReversed) {
TextRange range(6, 2);
EXPECT_FALSE(range.Contains(TextRange(0, 1)));
}
TEST(TextRange, ContainsRangeSpanningStartPositionReversed) {
TextRange range(6, 2);
EXPECT_FALSE(range.Contains(TextRange(1, 3)));
}
TEST(TextRange, ContainsRangeStartPositionReversed) {
TextRange range(6, 2);
EXPECT_TRUE(range.Contains(TextRange(2)));
}
TEST(TextRange, ContainsRangeMiddlePositionReversed) {
TextRange range(6, 2);
EXPECT_TRUE(range.Contains(TextRange(3, 4)));
EXPECT_TRUE(range.Contains(TextRange(4, 5)));
}
TEST(TextRange, ContainsRangeSpanningEndPositionReversed) {
TextRange range(6, 2);
EXPECT_FALSE(range.Contains(TextRange(5, 7)));
}
TEST(TextRange, ContainsRangeEndPositionReversed) {
TextRange range(6, 2);
EXPECT_TRUE(range.Contains(TextRange(5)));
}
TEST(TextRange, ContainsRangePostEndPositionReversed) {
TextRange range(6, 2);
EXPECT_FALSE(range.Contains(TextRange(6, 7)));
}
TEST(TextRange, ReversedForwardRange) {
TextRange range(2, 6);
EXPECT_FALSE(range.reversed());
}
TEST(TextRange, ReversedCollapsedRange) {
TextRange range(2, 2);
EXPECT_FALSE(range.reversed());
}
TEST(TextRange, ReversedReversedRange) {
TextRange range(6, 2);
EXPECT_TRUE(range.reversed());
}
} // namespace flutter
| engine/shell/platform/common/text_range_unittests.cc/0 | {
"file_path": "engine/shell/platform/common/text_range_unittests.cc",
"repo_id": "engine",
"token_count": 2535
} | 318 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERMACROS_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERMACROS_H_
#if defined(FLUTTER_FRAMEWORK)
#define FLUTTER_DARWIN_EXPORT __attribute__((visibility("default")))
#else // defined(FLUTTER_SDK)
#define FLUTTER_DARWIN_EXPORT
#endif // defined(FLUTTER_SDK)
#ifndef NS_ASSUME_NONNULL_BEGIN
#define NS_ASSUME_NONNULL_BEGIN _Pragma("clang assume_nonnull begin")
#define NS_ASSUME_NONNULL_END _Pragma("clang assume_nonnull end")
#endif // defined(NS_ASSUME_NONNULL_BEGIN)
/**
* Indicates that the API has been deprecated for the specified reason. Code
* that uses the deprecated API will continue to work as before. However, the
* API will soon become unavailable and users are encouraged to immediately take
* the appropriate action mentioned in the deprecation message and the BREAKING
* CHANGES section present in the Flutter.h umbrella header.
*/
#define FLUTTER_DEPRECATED(msg) __attribute__((__deprecated__(msg)))
/**
* Indicates that the previously deprecated API is now unavailable. Code that
* uses the API will not work and the declaration of the API is only a stub
* meant to display the given message detailing the actions for the user to take
* immediately.
*/
#define FLUTTER_UNAVAILABLE(msg) __attribute__((__unavailable__(msg)))
#if __has_feature(objc_arc)
#define FLUTTER_ASSERT_ARC
#define FLUTTER_ASSERT_NOT_ARC #error ARC must be disabled !
#else
#define FLUTTER_ASSERT_ARC #error ARC must be enabled !
#define FLUTTER_ASSERT_NOT_ARC
#endif
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERMACROS_H_
| engine/shell/platform/darwin/common/framework/Headers/FlutterMacros.h/0 | {
"file_path": "engine/shell/platform/darwin/common/framework/Headers/FlutterMacros.h",
"repo_id": "engine",
"token_count": 607
} | 319 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h"
#include "gtest/gtest.h"
FLUTTER_ASSERT_ARC
TEST(FlutterStringCodec, CanEncodeAndDecodeNil) {
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
ASSERT_TRUE([codec encode:nil] == nil);
ASSERT_TRUE([codec decode:nil] == nil);
}
TEST(FlutterStringCodec, CanEncodeAndDecodeEmptyString) {
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
ASSERT_TRUE([[codec encode:@""] isEqualTo:[NSData data]]);
ASSERT_TRUE([[codec decode:[NSData data]] isEqualTo:@""]);
}
TEST(FlutterStringCodec, CanEncodeAndDecodeAsciiString) {
NSString* value = @"hello world";
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterStringCodec, CanEncodeAndDecodeNonAsciiString) {
NSString* value = @"hello \u263A world";
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterStringCodec, CanEncodeAndDecodeNonBMPString) {
NSString* value = @"hello \U0001F602 world";
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterJSONCodec, ThrowsOnInvalidEncode) {
NSString* value = [[NSString alloc] initWithBytes:"\xdf\xff"
length:2
encoding:NSUTF16StringEncoding];
FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance];
EXPECT_EXIT([codec encode:value], testing::KilledBySignal(SIGABRT), "failed to convert to UTF8");
}
TEST(FlutterJSONCodec, CanDecodeZeroLength) {
FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance];
ASSERT_TRUE([codec decode:[NSData data]] == nil);
}
TEST(FlutterJSONCodec, ThrowsOnInvalidDecode) {
NSString* value = @"{{{";
FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance];
EXPECT_EXIT([codec decode:[value dataUsingEncoding:value.fastestEncoding]],
testing::KilledBySignal(SIGABRT), "No string key for value in object around line 1");
}
TEST(FlutterJSONCodec, CanEncodeAndDecodeNil) {
FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance];
ASSERT_TRUE([codec encode:nil] == nil);
ASSERT_TRUE([codec decode:nil] == nil);
}
TEST(FlutterJSONCodec, CanEncodeAndDecodeArray) {
NSArray* value = @[ [NSNull null], @"hello", @3.14, @47, @{@"a" : @"nested"} ];
FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSArray* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterJSONCodec, CanEncodeAndDecodeDictionary) {
NSDictionary* value = @{@"a" : @3.14, @"b" : @47, @"c" : [NSNull null], @"d" : @[ @"nested" ]};
FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSDictionary* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
| engine/shell/platform/darwin/common/framework/Source/flutter_codecs_unittest.mm/0 | {
"file_path": "engine/shell/platform/darwin/common/framework/Source/flutter_codecs_unittest.mm",
"repo_id": "engine",
"token_count": 1312
} | 320 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "FlutterBinaryMessenger.h"
#import "FlutterDartProject.h"
#import "FlutterMacros.h"
#import "FlutterPlugin.h"
#import "FlutterTexture.h"
@class FlutterViewController;
NS_ASSUME_NONNULL_BEGIN
/**
* The dart entrypoint that is associated with `main()`. This is to be used as an argument to the
* `runWithEntrypoint*` methods.
*/
// NOLINTNEXTLINE(readability-identifier-naming)
extern NSString* const FlutterDefaultDartEntrypoint;
/**
* The default Flutter initial route ("/").
*/
// NOLINTNEXTLINE(readability-identifier-naming)
extern NSString* const FlutterDefaultInitialRoute;
/**
* The FlutterEngine class coordinates a single instance of execution for a
* `FlutterDartProject`. It may have zero or one `FlutterViewController` at a
* time, which can be specified via `-setViewController:`.
* `FlutterViewController`'s `initWithEngine` initializer will automatically call
* `-setViewController:` for itself.
*
* A FlutterEngine can be created independently of a `FlutterViewController` for
* headless execution. It can also persist across the lifespan of multiple
* `FlutterViewController` instances to maintain state and/or asynchronous tasks
* (such as downloading a large file).
*
* A FlutterEngine can also be used to prewarm the Dart execution environment and reduce the
* latency of showing the Flutter screen when a `FlutterViewController` is created and presented.
* See http://flutter.dev/docs/development/add-to-app/performance for more details on loading
* performance.
*
* Alternatively, you can simply create a new `FlutterViewController` with only a
* `FlutterDartProject`. That `FlutterViewController` will internally manage its
* own instance of a FlutterEngine, but will not guarantee survival of the engine
* beyond the life of the ViewController.
*
* A newly initialized FlutterEngine will not actually run a Dart Isolate until
* either `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI` is invoked.
* One of these methods must be invoked before calling `-setViewController:`.
*/
FLUTTER_DARWIN_EXPORT
@interface FlutterEngine : NSObject <FlutterPluginRegistry>
/**
* Default initializer for a FlutterEngine.
*
* Threads created by this FlutterEngine will appear as "FlutterEngine #" in
* Instruments. The prefix can be customized using `initWithName`.
*
* The engine will execute the project located in the bundle with the identifier
* "io.flutter.flutter.app" (the default for Flutter projects).
*
* A newly initialized engine will not run until either `-runWithEntrypoint:` or
* `-runWithEntrypoint:libraryURI:` is called.
*
* FlutterEngine created with this method will have allowHeadlessExecution set to `YES`.
* This means that the engine will continue to run regardless of whether a `FlutterViewController`
* is attached to it or not, until `-destroyContext:` is called or the process finishes.
*/
- (instancetype)init;
/**
* Initialize this FlutterEngine.
*
* The engine will execute the project located in the bundle with the identifier
* "io.flutter.flutter.app" (the default for Flutter projects).
*
* A newly initialized engine will not run until either `-runWithEntrypoint:` or
* `-runWithEntrypoint:libraryURI:` is called.
*
* FlutterEngine created with this method will have allowHeadlessExecution set to `YES`.
* This means that the engine will continue to run regardless of whether a `FlutterViewController`
* is attached to it or not, until `-destroyContext:` is called or the process finishes.
*
* @param labelPrefix The label prefix used to identify threads for this instance. Should
* be unique across FlutterEngine instances, and is used in instrumentation to label
* the threads used by this FlutterEngine.
*/
- (instancetype)initWithName:(NSString*)labelPrefix;
/**
* Initialize this FlutterEngine with a `FlutterDartProject`.
*
* If the FlutterDartProject is not specified, the FlutterEngine will attempt to locate
* the project in a default location (the flutter_assets folder in the iOS application
* bundle).
*
* A newly initialized engine will not run the `FlutterDartProject` until either
* `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI:` is called.
*
* FlutterEngine created with this method will have allowHeadlessExecution set to `YES`.
* This means that the engine will continue to run regardless of whether a `FlutterViewController`
* is attached to it or not, until `-destroyContext:` is called or the process finishes.
*
* @param labelPrefix The label prefix used to identify threads for this instance. Should
* be unique across FlutterEngine instances, and is used in instrumentation to label
* the threads used by this FlutterEngine.
* @param project The `FlutterDartProject` to run.
*/
- (instancetype)initWithName:(NSString*)labelPrefix project:(nullable FlutterDartProject*)project;
/**
* Initialize this FlutterEngine with a `FlutterDartProject`.
*
* If the FlutterDartProject is not specified, the FlutterEngine will attempt to locate
* the project in a default location (the flutter_assets folder in the iOS application
* bundle).
*
* A newly initialized engine will not run the `FlutterDartProject` until either
* `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI:` is called.
*
* @param labelPrefix The label prefix used to identify threads for this instance. Should
* be unique across FlutterEngine instances, and is used in instrumentation to label
* the threads used by this FlutterEngine.
* @param project The `FlutterDartProject` to run.
* @param allowHeadlessExecution Whether or not to allow this instance to continue
* running after passing a nil `FlutterViewController` to `-setViewController:`.
*/
- (instancetype)initWithName:(NSString*)labelPrefix
project:(nullable FlutterDartProject*)project
allowHeadlessExecution:(BOOL)allowHeadlessExecution;
/**
* Initialize this FlutterEngine with a `FlutterDartProject`.
*
* If the FlutterDartProject is not specified, the FlutterEngine will attempt to locate
* the project in a default location (the flutter_assets folder in the iOS application
* bundle).
*
* A newly initialized engine will not run the `FlutterDartProject` until either
* `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI:` is called.
*
* @param labelPrefix The label prefix used to identify threads for this instance. Should
* be unique across FlutterEngine instances, and is used in instrumentation to label
* the threads used by this FlutterEngine.
* @param project The `FlutterDartProject` to run.
* @param allowHeadlessExecution Whether or not to allow this instance to continue
* running after passing a nil `FlutterViewController` to `-setViewController:`.
* @param restorationEnabled Whether state restoration is enabled. When true, the framework will
* wait for the attached view controller to provide restoration data.
*/
- (instancetype)initWithName:(NSString*)labelPrefix
project:(nullable FlutterDartProject*)project
allowHeadlessExecution:(BOOL)allowHeadlessExecution
restorationEnabled:(BOOL)restorationEnabled NS_DESIGNATED_INITIALIZER;
/**
* Runs a Dart program on an Isolate from the main Dart library (i.e. the library that
* contains `main()`), using `main()` as the entrypoint (the default for Flutter projects),
* and using "/" (the default route) as the initial route.
*
* The first call to this method will create a new Isolate. Subsequent calls will return
* immediately and have no effect.
*
* @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.
*/
- (BOOL)run;
/**
* Runs a Dart program on an Isolate from the main Dart library (i.e. the library that
* contains `main()`), using "/" (the default route) as the initial route.
*
* The first call to this method will create a new Isolate. Subsequent calls will return
* immediately and have no effect.
*
* @param entrypoint The name of a top-level function from the same Dart
* library that contains the app's main() function. If this is FlutterDefaultDartEntrypoint (or
* nil) it will default to `main()`. If it is not the app's main() function, that function must
* be decorated with `@pragma(vm:entry-point)` to ensure the method is not tree-shaken by the Dart
* compiler.
* @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.
*/
- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint;
/**
* Runs a Dart program on an Isolate from the main Dart library (i.e. the library that
* contains `main()`).
*
* The first call to this method will create a new Isolate. Subsequent calls will return
* immediately and have no effect.
*
* @param entrypoint The name of a top-level function from the same Dart
* library that contains the app's main() function. If this is FlutterDefaultDartEntrypoint (or
* nil), it will default to `main()`. If it is not the app's main() function, that function must
* be decorated with `@pragma(vm:entry-point)` to ensure the method is not tree-shaken by the Dart
* compiler.
* @param initialRoute The name of the initial Flutter `Navigator` `Route` to load. If this is
* FlutterDefaultInitialRoute (or nil), it will default to the "/" route.
* @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.
*/
- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint
initialRoute:(nullable NSString*)initialRoute;
/**
* Runs a Dart program on an Isolate using the specified entrypoint and Dart library,
* which may not be the same as the library containing the Dart program's `main()` function.
*
* The first call to this method will create a new Isolate. Subsequent calls will return
* immediately and have no effect.
*
* @param entrypoint The name of a top-level function from a Dart library. If this is
* FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's
* main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the
* method is not tree-shaken by the Dart compiler.
* @param uri The URI of the Dart library which contains the entrypoint method
* (example "package:foo_package/main.dart"). If nil, this will default to
* the same library as the `main()` function in the Dart program.
* @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.
*/
- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint libraryURI:(nullable NSString*)uri;
/**
* Runs a Dart program on an Isolate using the specified entrypoint and Dart library,
* which may not be the same as the library containing the Dart program's `main()` function.
*
* The first call to this method will create a new Isolate. Subsequent calls will return
* immediately and have no effect.
*
* @param entrypoint The name of a top-level function from a Dart library. If this is
* FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's
* main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the
* method is not tree-shaken by the Dart compiler.
* @param libraryURI The URI of the Dart library which contains the entrypoint
* method (example "package:foo_package/main.dart"). If nil, this will
* default to the same library as the `main()` function in the Dart program.
* @param initialRoute The name of the initial Flutter `Navigator` `Route` to load. If this is
* FlutterDefaultInitialRoute (or nil), it will default to the "/" route.
* @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.
*/
- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint
libraryURI:(nullable NSString*)libraryURI
initialRoute:(nullable NSString*)initialRoute;
/**
* Runs a Dart program on an Isolate using the specified entrypoint and Dart library,
* which may not be the same as the library containing the Dart program's `main()` function.
*
* The first call to this method will create a new Isolate. Subsequent calls will return
* immediately and have no effect.
*
* @param entrypoint The name of a top-level function from a Dart library. If this is
* FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's
* main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the
* method is not tree-shaken by the Dart compiler.
* @param libraryURI The URI of the Dart library which contains the entrypoint
* method (example "package:foo_package/main.dart"). If nil, this will
* default to the same library as the `main()` function in the Dart program.
* @param initialRoute The name of the initial Flutter `Navigator` `Route` to load. If this is
* FlutterDefaultInitialRoute (or nil), it will default to the "/" route.
* @param entrypointArgs Arguments passed as a list of string to Dart's entrypoint function.
* @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.
*/
- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint
libraryURI:(nullable NSString*)libraryURI
initialRoute:(nullable NSString*)initialRoute
entrypointArgs:(nullable NSArray<NSString*>*)entrypointArgs;
/**
* Destroy running context for an engine.
*
* This method can be used to force the FlutterEngine object to release all resources.
* After sending this message, the object will be in an unusable state until it is deallocated.
* Accessing properties or sending messages to it will result in undefined behavior or runtime
* errors.
*/
- (void)destroyContext;
/**
* Ensures that Flutter will generate a semantics tree.
*
* This is enabled by default if certain accessibility services are turned on by
* the user, or when using a Simulator. This method allows a user to turn
* semantics on when they would not ordinarily be generated and the performance
* overhead is not a concern, e.g. for UI testing. Note that semantics should
* never be programmatically turned off, as it would potentially disable
* accessibility services an end user has requested.
*
* This method must only be called after launching the engine via
* `-runWithEntrypoint:` or `-runWithEntryPoint:libraryURI`.
*
* Although this method returns synchronously, it does not guarantee that a
* semantics tree is actually available when the method returns. It
* synchronously ensures that the next frame the Flutter framework creates will
* have a semantics tree.
*
* You can subscribe to semantics updates via `NSNotificationCenter` by adding
* an observer for the name `FlutterSemanticsUpdateNotification`. The `object`
* parameter will be the `FlutterViewController` associated with the semantics
* update. This will asynchronously fire after a semantics tree has actually
* built (which may be some time after the frame has been rendered).
*/
- (void)ensureSemanticsEnabled;
/**
* Sets the `FlutterViewController` for this instance. The FlutterEngine must be
* running (e.g. a successful call to `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI`)
* before calling this method. Callers may pass nil to remove the viewController
* and have the engine run headless in the current process.
*
* A FlutterEngine can only have one `FlutterViewController` at a time. If there is
* already a `FlutterViewController` associated with this instance, this method will replace
* the engine's current viewController with the newly specified one.
*
* Setting the viewController will signal the engine to start animations and drawing, and unsetting
* it will signal the engine to stop animations and drawing. However, neither will impact the state
* of the Dart program's execution.
*/
@property(nonatomic, weak) FlutterViewController* viewController;
/**
* The `FlutterMethodChannel` used for localization related platform messages, such as
* setting the locale.
*
* Can be nil after `destroyContext` is called.
*/
@property(nonatomic, readonly, nullable) FlutterMethodChannel* localizationChannel;
/**
* The `FlutterMethodChannel` used for navigation related platform messages.
*
* Can be nil after `destroyContext` is called.
*
* @see [Navigation
* Channel](https://api.flutter.dev/flutter/services/SystemChannels/navigation-constant.html)
* @see [Navigator Widget](https://api.flutter.dev/flutter/widgets/Navigator-class.html)
*/
@property(nonatomic, readonly) FlutterMethodChannel* navigationChannel;
/**
* The `FlutterMethodChannel` used for restoration related platform messages.
*
* Can be nil after `destroyContext` is called.
*
* @see [Restoration
* Channel](https://api.flutter.dev/flutter/services/SystemChannels/restoration-constant.html)
*/
@property(nonatomic, readonly) FlutterMethodChannel* restorationChannel;
/**
* The `FlutterMethodChannel` used for core platform messages, such as
* information about the screen orientation.
*
* Can be nil after `destroyContext` is called.
*/
@property(nonatomic, readonly) FlutterMethodChannel* platformChannel;
/**
* The `FlutterMethodChannel` used to communicate text input events to the
* Dart Isolate.
*
* Can be nil after `destroyContext` is called.
*
* @see [Text Input
* Channel](https://api.flutter.dev/flutter/services/SystemChannels/textInput-constant.html)
*/
@property(nonatomic, readonly) FlutterMethodChannel* textInputChannel;
/**
* The `FlutterBasicMessageChannel` used to communicate app lifecycle events
* to the Dart Isolate.
*
* Can be nil after `destroyContext` is called.
*
* @see [Lifecycle
* Channel](https://api.flutter.dev/flutter/services/SystemChannels/lifecycle-constant.html)
*/
@property(nonatomic, readonly) FlutterBasicMessageChannel* lifecycleChannel;
/**
* The `FlutterBasicMessageChannel` used for communicating system events, such as
* memory pressure events.
*
* Can be nil after `destroyContext` is called.
*
* @see [System
* Channel](https://api.flutter.dev/flutter/services/SystemChannels/system-constant.html)
*/
@property(nonatomic, readonly) FlutterBasicMessageChannel* systemChannel;
/**
* The `FlutterBasicMessageChannel` used for communicating user settings such as
* clock format and text scale.
*
* Can be nil after `destroyContext` is called.
*/
@property(nonatomic, readonly) FlutterBasicMessageChannel* settingsChannel;
/**
* The `FlutterBasicMessageChannel` used for communicating key events
* from physical keyboards
*
* Can be nil after `destroyContext` is called.
*/
@property(nonatomic, readonly) FlutterBasicMessageChannel* keyEventChannel;
/**
* The depcreated `NSURL` of the Dart VM Service for the service isolate.
*
* This is only set in debug and profile runtime modes, and only after the
* Dart VM Service is ready. In release mode or before the Dart VM Service has
* started, it returns `nil`.
*/
@property(nonatomic, readonly, nullable)
NSURL* observatoryUrl FLUTTER_DEPRECATED("Use vmServiceUrl instead");
/**
* The `NSURL` of the Dart VM Service for the service isolate.
*
* This is only set in debug and profile runtime modes, and only after the
* Dart VM Service is ready. In release mode or before the Dart VM Service has
* started, it returns `nil`.
*/
@property(nonatomic, readonly, nullable) NSURL* vmServiceUrl;
/**
* The `FlutterBinaryMessenger` associated with this FlutterEngine (used for communicating with
* channels).
*/
@property(nonatomic, readonly) NSObject<FlutterBinaryMessenger>* binaryMessenger;
/**
* The `FlutterTextureRegistry` associated with this FlutterEngine (used to register textures).
*/
@property(nonatomic, readonly) NSObject<FlutterTextureRegistry>* textureRegistry;
/**
* The UI Isolate ID of the engine.
*
* This property will be nil if the engine is not running.
*/
@property(nonatomic, readonly, copy, nullable) NSString* isolateId;
/**
* Whether or not GPU calls are allowed.
*
* Typically this is set when the app is backgrounded and foregrounded.
*/
@property(nonatomic, assign) BOOL isGpuDisabled;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_
| engine/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h",
"repo_id": "engine",
"token_count": 5696
} | 321 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Foundation/Foundation.h>
#import <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h"
FLUTTER_ASSERT_ARC;
#define XCTAssertStrEqual(value, expected) \
XCTAssertTrue([value isEqualToString:expected], \
@"String \"%@\" not equal to the expected value of \"%@\"", value, expected)
using namespace flutter::testing;
API_AVAILABLE(ios(13.4))
@interface FlutterChannelKeyResponderTest : XCTestCase
@property(copy, nonatomic) FlutterUIPressProxy* testKeyDownEvent API_AVAILABLE(ios(13.4));
@property(copy, nonatomic) FlutterUIPressProxy* testKeyUpEvent API_AVAILABLE(ios(13.4));
@end
@implementation FlutterChannelKeyResponderTest
- (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.");
}
_testKeyDownEvent = keyDownEvent(UIKeyboardHIDUsageKeyboardA, 0x0, 0.0f, "a", "a");
_testKeyUpEvent = keyUpEvent(UIKeyboardHIDUsageKeyboardA, 0x0, 0.0f);
}
- (void)tearDown API_AVAILABLE(ios(13.4)) {
_testKeyDownEvent = nil;
_testKeyUpEvent = nil;
}
- (void)testBasicKeyEvent API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<id>* messages = [[NSMutableArray<id> alloc] init];
__block BOOL next_response = TRUE;
__block NSMutableArray<NSNumber*>* responses = [[NSMutableArray<NSNumber*> alloc] init];
id mockKeyEventChannel = OCMStrictClassMock([FlutterBasicMessageChannel class]);
OCMStub([mockKeyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]])
.andDo((^(NSInvocation* invocation) {
[invocation retainArguments];
NSDictionary* message;
[invocation getArgument:&message atIndex:2];
[messages addObject:message];
FlutterReply callback;
[invocation getArgument:&callback atIndex:3];
NSDictionary* keyMessage = @{
@"handled" : @(next_response),
};
callback(keyMessage);
}));
// Key down
FlutterChannelKeyResponder* responder =
[[FlutterChannelKeyResponder alloc] initWithChannel:mockKeyEventChannel];
[responder handlePress:_testKeyDownEvent
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
XCTAssertEqual([messages count], 1u);
XCTAssertStrEqual([messages lastObject][@"keymap"], @"ios");
XCTAssertStrEqual([messages lastObject][@"type"], @"keydown");
XCTAssertEqual([[messages lastObject][@"keyCode"] intValue], UIKeyboardHIDUsageKeyboardA);
XCTAssertEqual([[messages lastObject][@"modifiers"] intValue], 0x0);
XCTAssertStrEqual([messages lastObject][@"characters"], @"a");
XCTAssertStrEqual([messages lastObject][@"charactersIgnoringModifiers"], @"a");
XCTAssertEqual([responses count], 1u);
XCTAssertEqual([[responses lastObject] boolValue], TRUE);
[messages removeAllObjects];
[responses removeAllObjects];
// Key up
next_response = FALSE;
[responder handlePress:_testKeyUpEvent
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
XCTAssertEqual([messages count], 1u);
XCTAssertStrEqual([messages lastObject][@"keymap"], @"ios");
XCTAssertStrEqual([messages lastObject][@"type"], @"keyup");
XCTAssertEqual([[messages lastObject][@"keyCode"] intValue], UIKeyboardHIDUsageKeyboardA);
XCTAssertEqual([[messages lastObject][@"modifiers"] intValue], 0x0);
XCTAssertEqual([responses count], 1u);
XCTAssertEqual([[responses lastObject] boolValue], FALSE);
[messages removeAllObjects];
[responses removeAllObjects];
}
- (void)testEmptyResponseIsTakenAsHandled API_AVAILABLE(ios(13.4)) {
__block NSMutableArray<id>* messages = [[NSMutableArray<id> alloc] init];
__block NSMutableArray<NSNumber*>* responses = [[NSMutableArray<NSNumber*> alloc] init];
id mockKeyEventChannel = OCMStrictClassMock([FlutterBasicMessageChannel class]);
OCMStub([mockKeyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]])
.andDo((^(NSInvocation* invocation) {
[invocation retainArguments];
NSDictionary* message;
[invocation getArgument:&message atIndex:2];
[messages addObject:message];
FlutterReply callback;
[invocation getArgument:&callback atIndex:3];
callback(nullptr);
}));
FlutterChannelKeyResponder* responder =
[[FlutterChannelKeyResponder alloc] initWithChannel:mockKeyEventChannel];
[responder handlePress:_testKeyDownEvent
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
XCTAssertEqual([messages count], 1u);
XCTAssertStrEqual([messages lastObject][@"keymap"], @"ios");
XCTAssertStrEqual([messages lastObject][@"type"], @"keydown");
XCTAssertEqual([[messages lastObject][@"keyCode"] intValue], UIKeyboardHIDUsageKeyboardA);
XCTAssertEqual([[messages lastObject][@"modifiers"] intValue], 0x0);
XCTAssertStrEqual([messages lastObject][@"characters"], @"a");
XCTAssertStrEqual([messages lastObject][@"charactersIgnoringModifiers"], @"a");
XCTAssertEqual([responses count], 1u);
XCTAssertEqual([[responses lastObject] boolValue], TRUE);
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponderTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponderTest.mm",
"repo_id": "engine",
"token_count": 2152
} | 322 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERFAKEKEYEVENTS_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERFAKEKEYEVENTS_H_
#import <Foundation/Foundation.h>
#import <OCMock/OCMock.h>
#import <UIKit/UIKit.h>
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h"
API_AVAILABLE(ios(13.4))
@interface FakeUIPressProxy : FlutterUIPressProxy
- (instancetype)initWithData:(UIPressPhase)phase
key:(UIKey*)key
type:(UIEventType)type
timestamp:(NSTimeInterval)timestamp 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));
@property(nonatomic, readonly) UIPressPhase dataPhase;
@property(nonatomic, readonly) UIKey* dataKey;
@property(nonatomic, readonly) UIEventType dataType;
@property(nonatomic, readonly) NSTimeInterval dataTimestamp;
@end
API_AVAILABLE(ios(13.4))
@interface FakeUIKey : UIKey
- (instancetype)initWithData:(UIKeyboardHIDUsage)keyCode
modifierFlags:(UIKeyModifierFlags)modifierFlags
characters:(NSString*)characters
charactersIgnoringModifiers:(NSString*)charactersIgnoringModifiers API_AVAILABLE(ios(13.4));
- (UIKeyboardHIDUsage)keyCode;
- (UIKeyModifierFlags)modifierFlags;
- (NSString*)characters;
- (NSString*)charactersIgnoringModifiers;
@property(assign, nonatomic) UIKeyboardHIDUsage dataKeyCode;
@property(assign, nonatomic) UIKeyModifierFlags dataModifierFlags;
@property(readwrite, nonatomic) NSString* dataCharacters;
@property(readwrite, nonatomic) NSString* dataCharactersIgnoringModifiers;
@end
namespace flutter {
namespace testing {
extern FlutterUIPressProxy* keyDownEvent(UIKeyboardHIDUsage keyCode,
UIKeyModifierFlags modifierFlags = 0x0,
NSTimeInterval timestamp = 0.0f,
const char* characters = "",
const char* charactersIgnoringModifiers = "")
API_AVAILABLE(ios(13.4));
extern FlutterUIPressProxy* keyUpEvent(UIKeyboardHIDUsage keyCode,
UIKeyModifierFlags modifierFlags = 0x0,
NSTimeInterval timestamp = 0.0f,
const char* characters = "",
const char* charactersIgnoringModifiers = "")
API_AVAILABLE(ios(13.4));
extern FlutterUIPressProxy* keyEventWithPhase(UIPressPhase phase,
UIKeyboardHIDUsage keyCode,
UIKeyModifierFlags modifierFlags = 0x0,
NSTimeInterval timestamp = 0.0f,
const char* characters = "",
const char* charactersIgnoringModifiers = "")
API_AVAILABLE(ios(13.4));
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERFAKEKEYEVENTS_H_
| engine/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h",
"repo_id": "engine",
"token_count": 1638
} | 323 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
#import "flutter/fml/platform/darwin/weak_nsobject.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h"
#import "flutter/shell/platform/darwin/ios/platform_view_ios.h"
FLUTTER_ASSERT_ARC
@interface FlutterPlatformPluginTest : XCTestCase
@end
@interface FlutterPlatformPlugin ()
- (BOOL)isLiveTextInputAvailable;
- (void)searchWeb:(NSString*)searchTerm;
- (void)showLookUpViewController:(NSString*)term;
- (void)showShareViewController:(NSString*)content;
@end
@interface UIViewController ()
- (void)presentViewController:(UIViewController*)viewControllerToPresent
animated:(BOOL)flag
completion:(void (^)(void))completion;
@end
@implementation FlutterPlatformPluginTest
- (void)testSearchWebInvokedWithEscapedTerm {
id mockApplication = OCMClassMock([UIApplication class]);
OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
[engine runWithEntrypoint:nil];
XCTestExpectation* invokeExpectation =
[self expectationWithDescription:@"Web search launched with escaped search term"];
FlutterPlatformPlugin* plugin =
[[FlutterPlatformPlugin alloc] initWithEngine:_weakFactory->GetWeakNSObject()];
FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin);
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"SearchWeb.invoke"
arguments:@"Testing Word!"];
FlutterResult result = ^(id result) {
OCMVerify([mockPlugin searchWeb:@"Testing Word!"]);
#if not APPLICATION_EXTENSION_API_ONLY
OCMVerify([mockApplication openURL:[NSURL URLWithString:@"x-web-search://?Testing%20Word!"]
options:@{}
completionHandler:nil]);
#endif
[invokeExpectation fulfill];
};
[mockPlugin handleMethodCall:methodCall result:result];
[self waitForExpectationsWithTimeout:1 handler:nil];
[mockApplication stopMocking];
}
- (void)testSearchWebInvokedWithNonEscapedTerm {
id mockApplication = OCMClassMock([UIApplication class]);
OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
[engine runWithEntrypoint:nil];
XCTestExpectation* invokeExpectation =
[self expectationWithDescription:@"Web search launched with non escaped search term"];
FlutterPlatformPlugin* plugin =
[[FlutterPlatformPlugin alloc] initWithEngine:_weakFactory->GetWeakNSObject()];
FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin);
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"SearchWeb.invoke"
arguments:@"Test"];
FlutterResult result = ^(id result) {
OCMVerify([mockPlugin searchWeb:@"Test"]);
#if not APPLICATION_EXTENSION_API_ONLY
OCMVerify([mockApplication openURL:[NSURL URLWithString:@"x-web-search://?Test"]
options:@{}
completionHandler:nil]);
#endif
[invokeExpectation fulfill];
};
[mockPlugin handleMethodCall:methodCall result:result];
[self waitForExpectationsWithTimeout:1 handler:nil];
[mockApplication stopMocking];
}
- (void)testLookUpCallInitiated {
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
XCTestExpectation* presentExpectation =
[self expectationWithDescription:@"Look Up view controller presented"];
FlutterViewController* engineViewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
FlutterViewController* mockEngineViewController = OCMPartialMock(engineViewController);
FlutterPlatformPlugin* plugin =
[[FlutterPlatformPlugin alloc] initWithEngine:_weakFactory->GetWeakNSObject()];
FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin);
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"LookUp.invoke"
arguments:@"Test"];
FlutterResult result = ^(id result) {
OCMVerify([mockEngineViewController
presentViewController:[OCMArg isKindOfClass:[UIReferenceLibraryViewController class]]
animated:YES
completion:nil]);
[presentExpectation fulfill];
};
[mockPlugin handleMethodCall:methodCall result:result];
[self waitForExpectationsWithTimeout:2 handler:nil];
}
- (void)testShareScreenInvoked {
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
XCTestExpectation* presentExpectation =
[self expectationWithDescription:@"Share view controller presented"];
FlutterViewController* engineViewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
FlutterViewController* mockEngineViewController = OCMPartialMock(engineViewController);
OCMStub([mockEngineViewController
presentViewController:[OCMArg isKindOfClass:[UIActivityViewController class]]
animated:YES
completion:nil]);
FlutterPlatformPlugin* plugin =
[[FlutterPlatformPlugin alloc] initWithEngine:_weakFactory->GetWeakNSObject()];
FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin);
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"Share.invoke"
arguments:@"Test"];
FlutterResult result = ^(id result) {
OCMVerify([mockEngineViewController
presentViewController:[OCMArg isKindOfClass:[UIActivityViewController class]]
animated:YES
completion:nil]);
[presentExpectation fulfill];
};
[mockPlugin handleMethodCall:methodCall result:result];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testShareScreenInvokedOnIPad {
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
XCTestExpectation* presentExpectation =
[self expectationWithDescription:@"Share view controller presented on iPad"];
FlutterViewController* engineViewController = [[FlutterViewController alloc] initWithEngine:engine
nibName:nil
bundle:nil];
FlutterViewController* mockEngineViewController = OCMPartialMock(engineViewController);
OCMStub([mockEngineViewController
presentViewController:[OCMArg isKindOfClass:[UIActivityViewController class]]
animated:YES
completion:nil]);
id mockTraitCollection = OCMClassMock([UITraitCollection class]);
OCMStub([mockTraitCollection userInterfaceIdiom]).andReturn(UIUserInterfaceIdiomPad);
FlutterPlatformPlugin* plugin =
[[FlutterPlatformPlugin alloc] initWithEngine:_weakFactory->GetWeakNSObject()];
FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin);
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"Share.invoke"
arguments:@"Test"];
FlutterResult result = ^(id result) {
OCMVerify([mockEngineViewController
presentViewController:[OCMArg isKindOfClass:[UIActivityViewController class]]
animated:YES
completion:nil]);
[presentExpectation fulfill];
};
[mockPlugin handleMethodCall:methodCall result:result];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testClipboardHasCorrectStrings {
[UIPasteboard generalPasteboard].string = nil;
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
FlutterPlatformPlugin* plugin =
[[FlutterPlatformPlugin alloc] initWithEngine:_weakFactory->GetWeakNSObject()];
XCTestExpectation* setStringExpectation = [self expectationWithDescription:@"setString"];
FlutterResult resultSet = ^(id result) {
[setStringExpectation fulfill];
};
FlutterMethodCall* methodCallSet =
[FlutterMethodCall methodCallWithMethodName:@"Clipboard.setData"
arguments:@{@"text" : @"some string"}];
[plugin handleMethodCall:methodCallSet result:resultSet];
[self waitForExpectationsWithTimeout:1 handler:nil];
XCTestExpectation* hasStringsExpectation = [self expectationWithDescription:@"hasStrings"];
FlutterResult result = ^(id result) {
XCTAssertTrue([result[@"value"] boolValue]);
[hasStringsExpectation fulfill];
};
FlutterMethodCall* methodCall =
[FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil];
[plugin handleMethodCall:methodCall result:result];
[self waitForExpectationsWithTimeout:1 handler:nil];
XCTestExpectation* getDataExpectation = [self expectationWithDescription:@"getData"];
FlutterResult getDataResult = ^(id result) {
XCTAssertEqualObjects(result[@"text"], @"some string");
[getDataExpectation fulfill];
};
FlutterMethodCall* methodCallGetData =
[FlutterMethodCall methodCallWithMethodName:@"Clipboard.getData" arguments:@"text/plain"];
[plugin handleMethodCall:methodCallGetData result:getDataResult];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testClipboardSetDataToNullDoNotCrash {
[UIPasteboard generalPasteboard].string = nil;
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
FlutterPlatformPlugin* plugin =
[[FlutterPlatformPlugin alloc] initWithEngine:_weakFactory->GetWeakNSObject()];
XCTestExpectation* setStringExpectation = [self expectationWithDescription:@"setData"];
FlutterResult resultSet = ^(id result) {
[setStringExpectation fulfill];
};
FlutterMethodCall* methodCallSet =
[FlutterMethodCall methodCallWithMethodName:@"Clipboard.setData"
arguments:@{@"text" : [NSNull null]}];
[plugin handleMethodCall:methodCallSet result:resultSet];
XCTestExpectation* getDataExpectation = [self expectationWithDescription:@"getData"];
FlutterResult result = ^(id result) {
XCTAssertEqualObjects(result[@"text"], @"null");
[getDataExpectation fulfill];
};
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"Clipboard.getData"
arguments:@"text/plain"];
[plugin handleMethodCall:methodCall result:result];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testPopSystemNavigator {
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
FlutterViewController* flutterViewController =
[[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
UINavigationController* navigationController =
[[UINavigationController alloc] initWithRootViewController:flutterViewController];
UITabBarController* tabBarController = [[UITabBarController alloc] init];
tabBarController.viewControllers = @[ navigationController ];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
FlutterPlatformPlugin* plugin =
[[FlutterPlatformPlugin alloc] initWithEngine:_weakFactory->GetWeakNSObject()];
id navigationControllerMock = OCMPartialMock(navigationController);
OCMStub([navigationControllerMock popViewControllerAnimated:YES]);
// Set some string to the pasteboard.
XCTestExpectation* navigationPopCalled = [self expectationWithDescription:@"SystemNavigator.pop"];
FlutterResult resultSet = ^(id result) {
[navigationPopCalled fulfill];
};
FlutterMethodCall* methodCallSet =
[FlutterMethodCall methodCallWithMethodName:@"SystemNavigator.pop" arguments:@(YES)];
[plugin handleMethodCall:methodCallSet result:resultSet];
[self waitForExpectationsWithTimeout:1 handler:nil];
OCMVerify([navigationControllerMock popViewControllerAnimated:YES]);
[flutterViewController deregisterNotifications];
}
- (void)testWhetherDeviceHasLiveTextInputInvokeCorrectly {
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
XCTestExpectation* invokeExpectation =
[self expectationWithDescription:@"isLiveTextInputAvailableInvoke"];
FlutterPlatformPlugin* plugin =
[[FlutterPlatformPlugin alloc] initWithEngine:_weakFactory->GetWeakNSObject()];
FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin);
FlutterMethodCall* methodCall =
[FlutterMethodCall methodCallWithMethodName:@"LiveText.isLiveTextInputAvailable"
arguments:nil];
FlutterResult result = ^(id result) {
OCMVerify([mockPlugin isLiveTextInputAvailable]);
[invokeExpectation fulfill];
};
[mockPlugin handleMethodCall:methodCall result:result];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testViewControllerBasedStatusBarHiddenUpdate {
id bundleMock = OCMPartialMock([NSBundle mainBundle]);
OCMStub([bundleMock objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"])
.andReturn(@YES);
{
// Enabling system UI overlays to update status bar.
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
FlutterViewController* flutterViewController =
[[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
XCTAssertFalse(flutterViewController.prefersStatusBarHidden);
// Update to hidden.
FlutterPlatformPlugin* plugin = [engine platformPlugin];
XCTestExpectation* enableSystemUIOverlaysCalled =
[self expectationWithDescription:@"setEnabledSystemUIOverlays"];
FlutterResult resultSet = ^(id result) {
[enableSystemUIOverlaysCalled fulfill];
};
FlutterMethodCall* methodCallSet =
[FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays"
arguments:@[ @"SystemUiOverlay.bottom" ]];
[plugin handleMethodCall:methodCallSet result:resultSet];
[self waitForExpectationsWithTimeout:1 handler:nil];
XCTAssertTrue(flutterViewController.prefersStatusBarHidden);
// Update to shown.
XCTestExpectation* enableSystemUIOverlaysCalled2 =
[self expectationWithDescription:@"setEnabledSystemUIOverlays"];
FlutterResult resultSet2 = ^(id result) {
[enableSystemUIOverlaysCalled2 fulfill];
};
FlutterMethodCall* methodCallSet2 =
[FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays"
arguments:@[ @"SystemUiOverlay.top" ]];
[plugin handleMethodCall:methodCallSet2 result:resultSet2];
[self waitForExpectationsWithTimeout:1 handler:nil];
XCTAssertFalse(flutterViewController.prefersStatusBarHidden);
[flutterViewController deregisterNotifications];
}
{
// Enable system UI mode to update status bar.
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
FlutterViewController* flutterViewController =
[[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
XCTAssertFalse(flutterViewController.prefersStatusBarHidden);
// Update to hidden.
FlutterPlatformPlugin* plugin = [engine platformPlugin];
XCTestExpectation* enableSystemUIModeCalled =
[self expectationWithDescription:@"setEnabledSystemUIMode"];
FlutterResult resultSet = ^(id result) {
[enableSystemUIModeCalled fulfill];
};
FlutterMethodCall* methodCallSet =
[FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIMode"
arguments:@"SystemUiMode.immersive"];
[plugin handleMethodCall:methodCallSet result:resultSet];
[self waitForExpectationsWithTimeout:1 handler:nil];
XCTAssertTrue(flutterViewController.prefersStatusBarHidden);
// Update to shown.
XCTestExpectation* enableSystemUIModeCalled2 =
[self expectationWithDescription:@"setEnabledSystemUIMode"];
FlutterResult resultSet2 = ^(id result) {
[enableSystemUIModeCalled2 fulfill];
};
FlutterMethodCall* methodCallSet2 =
[FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIMode"
arguments:@"SystemUiMode.edgeToEdge"];
[plugin handleMethodCall:methodCallSet2 result:resultSet2];
[self waitForExpectationsWithTimeout:1 handler:nil];
XCTAssertFalse(flutterViewController.prefersStatusBarHidden);
[flutterViewController deregisterNotifications];
}
[bundleMock stopMocking];
}
- (void)testStatusBarHiddenUpdate {
id bundleMock = OCMPartialMock([NSBundle mainBundle]);
OCMStub([bundleMock objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"])
.andReturn(@NO);
id mockApplication = OCMClassMock([UIApplication class]);
OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
// Enabling system UI overlays to update status bar.
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
FlutterViewController* flutterViewController =
[[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
// Update to hidden.
FlutterPlatformPlugin* plugin = [engine platformPlugin];
XCTestExpectation* enableSystemUIOverlaysCalled =
[self expectationWithDescription:@"setEnabledSystemUIOverlays"];
FlutterResult resultSet = ^(id result) {
[enableSystemUIOverlaysCalled fulfill];
};
FlutterMethodCall* methodCallSet =
[FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays"
arguments:@[ @"SystemUiOverlay.bottom" ]];
[plugin handleMethodCall:methodCallSet result:resultSet];
[self waitForExpectationsWithTimeout:1 handler:nil];
#if not APPLICATION_EXTENSION_API_ONLY
OCMVerify([mockApplication setStatusBarHidden:YES]);
#endif
// Update to shown.
XCTestExpectation* enableSystemUIOverlaysCalled2 =
[self expectationWithDescription:@"setEnabledSystemUIOverlays"];
FlutterResult resultSet2 = ^(id result) {
[enableSystemUIOverlaysCalled2 fulfill];
};
FlutterMethodCall* methodCallSet2 =
[FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays"
arguments:@[ @"SystemUiOverlay.top" ]];
[plugin handleMethodCall:methodCallSet2 result:resultSet2];
[self waitForExpectationsWithTimeout:1 handler:nil];
#if not APPLICATION_EXTENSION_API_ONLY
OCMVerify([mockApplication setStatusBarHidden:NO]);
#endif
[flutterViewController deregisterNotifications];
[mockApplication stopMocking];
[bundleMock stopMocking];
}
- (void)testStatusBarStyle {
id bundleMock = OCMPartialMock([NSBundle mainBundle]);
OCMStub([bundleMock objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"])
.andReturn(@NO);
id mockApplication = OCMClassMock([UIApplication class]);
OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil];
[engine runWithEntrypoint:nil];
FlutterViewController* flutterViewController =
[[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory =
std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(engine);
XCTAssertFalse(flutterViewController.prefersStatusBarHidden);
FlutterPlatformPlugin* plugin = [engine platformPlugin];
XCTestExpectation* enableSystemUIModeCalled =
[self expectationWithDescription:@"setSystemUIOverlayStyle"];
FlutterResult resultSet = ^(id result) {
[enableSystemUIModeCalled fulfill];
};
FlutterMethodCall* methodCallSet =
[FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setSystemUIOverlayStyle"
arguments:@{@"statusBarBrightness" : @"Brightness.dark"}];
[plugin handleMethodCall:methodCallSet result:resultSet];
[self waitForExpectationsWithTimeout:1 handler:nil];
#if not APPLICATION_EXTENSION_API_ONLY
OCMVerify([mockApplication setStatusBarStyle:UIStatusBarStyleLightContent]);
#endif
[flutterViewController deregisterNotifications];
[mockApplication stopMocking];
[bundleMock stopMocking];
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformPluginTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformPluginTest.mm",
"repo_id": "engine",
"token_count": 8617
} | 324 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTDELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTDELEGATE_H_
#import <Foundation/Foundation.h>
@class FlutterTextInputPlugin;
@class FlutterTextInputView;
typedef NS_ENUM(NSInteger, FlutterTextInputAction) {
// NOLINTBEGIN(readability-identifier-naming)
FlutterTextInputActionUnspecified,
FlutterTextInputActionDone,
FlutterTextInputActionGo,
FlutterTextInputActionSend,
FlutterTextInputActionSearch,
FlutterTextInputActionNext,
FlutterTextInputActionContinue,
FlutterTextInputActionJoin,
FlutterTextInputActionRoute,
FlutterTextInputActionEmergencyCall,
FlutterTextInputActionNewline,
// NOLINTEND(readability-identifier-naming)
};
typedef NS_ENUM(NSInteger, FlutterFloatingCursorDragState) {
// NOLINTBEGIN(readability-identifier-naming)
FlutterFloatingCursorDragStateStart,
FlutterFloatingCursorDragStateUpdate,
FlutterFloatingCursorDragStateEnd,
// NOLINTEND(readability-identifier-naming)
};
@protocol FlutterTextInputDelegate <NSObject>
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
updateEditingClient:(int)client
withState:(NSDictionary*)state;
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
updateEditingClient:(int)client
withState:(NSDictionary*)state
withTag:(NSString*)tag;
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
updateEditingClient:(int)client
withDelta:(NSDictionary*)state;
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
performAction:(FlutterTextInputAction)action
withClient:(int)client;
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
updateFloatingCursor:(FlutterFloatingCursorDragState)state
withClient:(int)client
withPosition:(NSDictionary*)point;
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
showAutocorrectionPromptRectForStart:(NSUInteger)start
end:(NSUInteger)end
withClient:(int)client;
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView showToolbar:(int)client;
- (void)flutterTextInputViewScribbleInteractionBegan:(FlutterTextInputView*)textInputView;
- (void)flutterTextInputViewScribbleInteractionFinished:(FlutterTextInputView*)textInputView;
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
insertTextPlaceholderWithSize:(CGSize)size
withClient:(int)client;
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView removeTextPlaceholder:(int)client;
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
didResignFirstResponderWithTextInputClient:(int)client;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTDELEGATE_H_
| engine/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h",
"repo_id": "engine",
"token_count": 1199
} | 325 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
#include <Metal/Metal.h>
#include "flutter/common/settings.h"
#include "flutter/common/task_runners.h"
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/fml/platform/darwin/cf_utils.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/trace_event.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/rasterizer.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/ios/ios_surface_software.h"
#include "third_party/skia/include/utils/mac/SkCGUtils.h"
@implementation FlutterView {
id<FlutterViewEngineDelegate> _delegate;
BOOL _isWideGamutEnabled;
}
- (instancetype)init {
NSAssert(NO, @"FlutterView must initWithDelegate");
return nil;
}
- (instancetype)initWithFrame:(CGRect)frame {
NSAssert(NO, @"FlutterView must initWithDelegate");
return nil;
}
- (instancetype)initWithCoder:(NSCoder*)aDecoder {
NSAssert(NO, @"FlutterView must initWithDelegate");
return nil;
}
- (UIScreen*)screen {
if (@available(iOS 13.0, *)) {
return self.window.windowScene.screen;
}
return UIScreen.mainScreen;
}
- (MTLPixelFormat)pixelFormat {
if ([self.layer isKindOfClass:NSClassFromString(@"CAMetalLayer")]) {
// It is a known Apple bug that CAMetalLayer incorrectly reports its supported
// SDKs. It is, in fact, available since iOS 8.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
CAMetalLayer* layer = (CAMetalLayer*)self.layer;
return layer.pixelFormat;
}
return MTLPixelFormatBGRA8Unorm;
}
- (BOOL)isWideGamutSupported {
if (![_delegate isUsingImpeller]) {
return NO;
}
FML_DCHECK(self.screen);
// This predicates the decision on the capabilities of the iOS device's
// display. This means external displays will not support wide gamut if the
// device's display doesn't support it. It practice that should be never.
return self.screen.traitCollection.displayGamut != UIDisplayGamutSRGB;
}
- (instancetype)initWithDelegate:(id<FlutterViewEngineDelegate>)delegate
opaque:(BOOL)opaque
enableWideGamut:(BOOL)isWideGamutEnabled {
if (delegate == nil) {
NSLog(@"FlutterView delegate was nil.");
[self release];
return nil;
}
self = [super initWithFrame:CGRectNull];
if (self) {
_delegate = delegate;
_isWideGamutEnabled = isWideGamutEnabled;
self.layer.opaque = opaque;
// This line is necessary. CoreAnimation(or UIKit) may take this to do
// something to compute the final frame presented on screen, if we don't set this,
// it will make it take long time for us to take next CAMetalDrawable and will
// cause constant junk during rendering.
self.backgroundColor = UIColor.clearColor;
}
return self;
}
static void PrintWideGamutWarningOnce() {
static BOOL did_print = NO;
if (did_print) {
return;
}
FML_DLOG(WARNING) << "Rendering wide gamut colors is turned on but isn't "
"supported, downgrading the color gamut to sRGB.";
did_print = YES;
}
- (void)layoutSubviews {
if ([self.layer isKindOfClass:NSClassFromString(@"CAMetalLayer")]) {
// It is a known Apple bug that CAMetalLayer incorrectly reports its supported
// SDKs. It is, in fact, available since iOS 8.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
CAMetalLayer* layer = (CAMetalLayer*)self.layer;
#pragma clang diagnostic pop
CGFloat screenScale = self.screen.scale;
layer.allowsGroupOpacity = YES;
layer.contentsScale = screenScale;
layer.rasterizationScale = screenScale;
layer.framebufferOnly = flutter::Settings::kSurfaceDataAccessible ? NO : YES;
BOOL isWideGamutSupported = self.isWideGamutSupported;
if (_isWideGamutEnabled && isWideGamutSupported) {
CGColorSpaceRef srgb = CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB);
layer.colorspace = srgb;
CFRelease(srgb);
// MTLPixelFormatRGBA16Float was chosen since it is compatible with
// impeller's offscreen buffers which need to have transparency. Also,
// F16 was chosen over BGRA10_XR since Skia does not support decoding
// BGRA10_XR.
layer.pixelFormat = MTLPixelFormatRGBA16Float;
} else if (_isWideGamutEnabled && !isWideGamutSupported) {
PrintWideGamutWarningOnce();
}
}
[super layoutSubviews];
}
static BOOL _forceSoftwareRendering;
+ (BOOL)forceSoftwareRendering {
return _forceSoftwareRendering;
}
+ (void)setForceSoftwareRendering:(BOOL)forceSoftwareRendering {
_forceSoftwareRendering = forceSoftwareRendering;
}
+ (Class)layerClass {
return flutter::GetCoreAnimationLayerClassForRenderingAPI(
flutter::GetRenderingAPIForProcess(FlutterView.forceSoftwareRendering));
}
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context {
TRACE_EVENT0("flutter", "SnapshotFlutterView");
if (layer != self.layer || context == nullptr) {
return;
}
auto screenshot = [_delegate takeScreenshot:flutter::Rasterizer::ScreenshotType::UncompressedImage
asBase64Encoded:NO];
if (!screenshot.data || screenshot.data->isEmpty() || screenshot.frame_size.isEmpty()) {
return;
}
NSData* data = [NSData dataWithBytes:const_cast<void*>(screenshot.data->data())
length:screenshot.data->size()];
fml::CFRef<CGDataProviderRef> image_data_provider(
CGDataProviderCreateWithCFData(reinterpret_cast<CFDataRef>(data)));
fml::CFRef<CGColorSpaceRef> colorspace(CGColorSpaceCreateDeviceRGB());
// Defaults for RGBA8888.
size_t bits_per_component = 8u;
size_t bits_per_pixel = 32u;
size_t bytes_per_row_multiplier = 4u;
CGBitmapInfo bitmap_info =
static_cast<CGBitmapInfo>(static_cast<uint32_t>(kCGImageAlphaPremultipliedLast) |
static_cast<uint32_t>(kCGBitmapByteOrder32Big));
switch (screenshot.pixel_format) {
case flutter::Rasterizer::ScreenshotFormat::kUnknown:
case flutter::Rasterizer::ScreenshotFormat::kR8G8B8A8UNormInt:
// Assume unknown is Skia and is RGBA8888. Keep defaults.
break;
case flutter::Rasterizer::ScreenshotFormat::kB8G8R8A8UNormInt:
// Treat this as little endian with the alpha first so that it's read backwards.
bitmap_info =
static_cast<CGBitmapInfo>(static_cast<uint32_t>(kCGImageAlphaPremultipliedFirst) |
static_cast<uint32_t>(kCGBitmapByteOrder32Little));
break;
case flutter::Rasterizer::ScreenshotFormat::kR16G16B16A16Float:
bits_per_component = 16u;
bits_per_pixel = 64u;
bytes_per_row_multiplier = 8u;
bitmap_info =
static_cast<CGBitmapInfo>(static_cast<uint32_t>(kCGImageAlphaPremultipliedLast) |
static_cast<uint32_t>(kCGBitmapFloatComponents) |
static_cast<uint32_t>(kCGBitmapByteOrder16Little));
break;
}
fml::CFRef<CGImageRef> image(CGImageCreate(
screenshot.frame_size.width(), // size_t width
screenshot.frame_size.height(), // size_t height
bits_per_component, // size_t bitsPerComponent
bits_per_pixel, // size_t bitsPerPixel,
bytes_per_row_multiplier * screenshot.frame_size.width(), // size_t bytesPerRow
colorspace, // CGColorSpaceRef space
bitmap_info, // CGBitmapInfo bitmapInfo
image_data_provider, // CGDataProviderRef provider
nullptr, // const CGFloat* decode
false, // bool shouldInterpolate
kCGRenderingIntentDefault // CGColorRenderingIntent intent
));
const CGRect frame_rect =
CGRectMake(0.0, 0.0, screenshot.frame_size.width(), screenshot.frame_size.height());
CGContextSaveGState(context);
// If the CGContext is not a bitmap based context, this returns zero.
CGFloat height = CGBitmapContextGetHeight(context);
if (height == 0) {
height = CGFloat(screenshot.frame_size.height());
}
CGContextTranslateCTM(context, 0.0, height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, frame_rect, image);
CGContextRestoreGState(context);
}
- (BOOL)isAccessibilityElement {
// iOS does not provide an API to query whether the voice control
// is turned on or off. It is likely at least one of the assitive
// technologies is turned on if this method is called. If we do
// not catch it in notification center, we will catch it here.
//
// TODO(chunhtai): Remove this workaround once iOS provides an
// API to query whether voice control is enabled.
// https://github.com/flutter/flutter/issues/76808.
[_delegate flutterViewAccessibilityDidCall];
return NO;
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterView.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterView.mm",
"repo_id": "engine",
"token_count": 3744
} | 326 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
#include "flutter/fml/raster_thread_merger.h"
#include "flutter/fml/thread.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h"
FLUTTER_ASSERT_ARC
namespace {
fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) {
auto thread = std::make_unique<fml::Thread>(name);
auto runner = thread->GetTaskRunner();
return runner;
}
} // namespace
@interface VSyncClient (Testing)
- (CADisplayLink*)getDisplayLink;
- (void)onDisplayLink:(CADisplayLink*)link;
@end
@interface VsyncWaiterIosTest : XCTestCase
@end
@implementation VsyncWaiterIosTest
- (void)testSetAllowPauseAfterVsyncCorrect {
auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest");
VSyncClient* vsyncClient = [[VSyncClient alloc]
initWithTaskRunner:thread_task_runner
callback:[](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {}];
CADisplayLink* link = [vsyncClient getDisplayLink];
vsyncClient.allowPauseAfterVsync = NO;
[vsyncClient await];
[vsyncClient onDisplayLink:link];
XCTAssertFalse(link.isPaused);
vsyncClient.allowPauseAfterVsync = YES;
[vsyncClient await];
[vsyncClient onDisplayLink:link];
XCTAssertTrue(link.isPaused);
}
- (void)testSetCorrectVariableRefreshRates {
auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest");
auto callback = [](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {};
id bundleMock = OCMPartialMock([NSBundle mainBundle]);
OCMStub([bundleMock objectForInfoDictionaryKey:@"CADisableMinimumFrameDurationOnPhone"])
.andReturn(@YES);
id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]];
double maxFrameRate = 120;
[[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate];
VSyncClient* vsyncClient = [[VSyncClient alloc] initWithTaskRunner:thread_task_runner
callback:callback];
CADisplayLink* link = [vsyncClient getDisplayLink];
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, maxFrameRate / 2, 0.1);
} else {
XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, maxFrameRate, 0.1);
}
}
- (void)testDoNotSetVariableRefreshRatesIfCADisableMinimumFrameDurationOnPhoneIsNotOn {
auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest");
auto callback = [](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {};
id bundleMock = OCMPartialMock([NSBundle mainBundle]);
OCMStub([bundleMock objectForInfoDictionaryKey:@"CADisableMinimumFrameDurationOnPhone"])
.andReturn(@NO);
id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]];
double maxFrameRate = 120;
[[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate];
VSyncClient* vsyncClient = [[VSyncClient alloc] initWithTaskRunner:thread_task_runner
callback:callback];
CADisplayLink* link = [vsyncClient getDisplayLink];
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, 0, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, 0, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, 0, 0.1);
} else {
XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, 0, 0.1);
}
}
- (void)testDoNotSetVariableRefreshRatesIfCADisableMinimumFrameDurationOnPhoneIsNotSet {
auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest");
auto callback = [](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {};
id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]];
double maxFrameRate = 120;
[[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate];
VSyncClient* vsyncClient = [[VSyncClient alloc] initWithTaskRunner:thread_task_runner
callback:callback];
CADisplayLink* link = [vsyncClient getDisplayLink];
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, 0, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, 0, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, 0, 0.1);
} else {
XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, 0, 0.1);
}
}
- (void)testAwaitAndPauseWillWorkCorrectly {
auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest");
VSyncClient* vsyncClient = [[VSyncClient alloc]
initWithTaskRunner:thread_task_runner
callback:[](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {}];
CADisplayLink* link = [vsyncClient getDisplayLink];
XCTAssertTrue(link.isPaused);
[vsyncClient await];
XCTAssertFalse(link.isPaused);
[vsyncClient pause];
XCTAssertTrue(link.isPaused);
}
- (void)testRefreshRateUpdatedTo80WhenThraedsMerge {
auto platform_thread_task_runner = CreateNewThread("Platform");
auto raster_thread_task_runner = CreateNewThread("Raster");
auto ui_thread_task_runner = CreateNewThread("UI");
auto io_thread_task_runner = CreateNewThread("IO");
auto task_runners =
flutter::TaskRunners("test", platform_thread_task_runner, raster_thread_task_runner,
ui_thread_task_runner, io_thread_task_runner);
id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]];
double maxFrameRate = 120;
[[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate];
[[[mockDisplayLinkManager stub] andReturnValue:@(YES)] maxRefreshRateEnabledOnIPhone];
auto vsync_waiter = flutter::VsyncWaiterIOS(task_runners);
fml::scoped_nsobject<VSyncClient> vsyncClient = vsync_waiter.GetVsyncClient();
CADisplayLink* link = [vsyncClient.get() getDisplayLink];
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, maxFrameRate / 2, 0.1);
} else {
XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, maxFrameRate, 0.1);
}
const auto merger = fml::RasterThreadMerger::CreateOrShareThreadMerger(
nullptr, platform_thread_task_runner->GetTaskQueueId(),
raster_thread_task_runner->GetTaskQueueId());
merger->MergeWithLease(5);
vsync_waiter.AwaitVSync();
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, 80, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, 80, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, 60, 0.1);
} else {
XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, 80, 0.1);
}
merger->UnMergeNowIfLastOne();
vsync_waiter.AwaitVSync();
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, maxFrameRate / 2, 0.1);
} else {
XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, maxFrameRate, 0.1);
}
if (@available(iOS 14.0, *)) {
// Fake response that we are running on Mac.
id processInfo = [NSProcessInfo processInfo];
id processInfoPartialMock = OCMPartialMock(processInfo);
bool iOSAppOnMac = true;
[OCMStub([processInfoPartialMock isiOSAppOnMac]) andReturnValue:OCMOCK_VALUE(iOSAppOnMac)];
merger->MergeWithLease(5);
vsync_waiter.AwaitVSync();
// On Mac, framerate should be uncapped.
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, maxFrameRate / 2, 0.1);
} else {
XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, 80, 0.1);
}
merger->UnMergeNowIfLastOne();
vsync_waiter.AwaitVSync();
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, maxFrameRate, 0.1);
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, maxFrameRate / 2, 0.1);
} else {
XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, maxFrameRate, 0.1);
}
}
}
@end
| engine/shell/platform/darwin/ios/framework/Source/VsyncWaiterIosTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/VsyncWaiterIosTest.mm",
"repo_id": "engine",
"token_count": 3411
} | 327 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h"
#include <utility>
#include <Foundation/Foundation.h>
#include <UIKit/UIKit.h>
#include <mach/mach_time.h>
#include "flutter/common/task_runners.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/memory/task_runner_checker.h"
#include "flutter/fml/trace_event.h"
// When calculating refresh rate diffrence, anything within 0.1 fps is ignored.
const static double kRefreshRateDiffToIgnore = 0.1;
namespace flutter {
VsyncWaiterIOS::VsyncWaiterIOS(const flutter::TaskRunners& task_runners)
: VsyncWaiter(task_runners) {
auto callback = [this](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {
const fml::TimePoint start_time = recorder->GetVsyncStartTime();
const fml::TimePoint target_time = recorder->GetVsyncTargetTime();
FireCallback(start_time, target_time, true);
};
client_ =
fml::scoped_nsobject{[[VSyncClient alloc] initWithTaskRunner:task_runners_.GetUITaskRunner()
callback:callback]};
max_refresh_rate_ = [DisplayLinkManager displayRefreshRate];
}
VsyncWaiterIOS::~VsyncWaiterIOS() {
// This way, we will get no more callbacks from the display link that holds a weak (non-nilling)
// reference to this C++ object.
[client_.get() invalidate];
}
void VsyncWaiterIOS::AwaitVSync() {
double new_max_refresh_rate = [DisplayLinkManager displayRefreshRate];
if (fml::TaskRunnerChecker::RunsOnTheSameThread(
task_runners_.GetRasterTaskRunner()->GetTaskQueueId(),
task_runners_.GetPlatformTaskRunner()->GetTaskQueueId())) {
BOOL isRunningOnMac = NO;
if (@available(iOS 14.0, *)) {
isRunningOnMac = [NSProcessInfo processInfo].iOSAppOnMac;
}
if (!isRunningOnMac) {
// Pressure tested on iPhone 13 pro, the oldest iPhone that supports refresh rate greater than
// 60fps. A flutter app can handle fast scrolling on 80 fps with 6 PlatformViews in the scene
// at the same time.
new_max_refresh_rate = 80;
}
}
if (fabs(new_max_refresh_rate - max_refresh_rate_) > kRefreshRateDiffToIgnore) {
max_refresh_rate_ = new_max_refresh_rate;
[client_.get() setMaxRefreshRate:max_refresh_rate_];
}
[client_.get() await];
}
// |VariableRefreshRateReporter|
double VsyncWaiterIOS::GetRefreshRate() const {
return [client_.get() getRefreshRate];
}
fml::scoped_nsobject<VSyncClient> VsyncWaiterIOS::GetVsyncClient() const {
return client_;
}
} // namespace flutter
@implementation VSyncClient {
flutter::VsyncWaiter::Callback callback_;
fml::scoped_nsobject<CADisplayLink> display_link_;
double current_refresh_rate_;
}
- (instancetype)initWithTaskRunner:(fml::RefPtr<fml::TaskRunner>)task_runner
callback:(flutter::VsyncWaiter::Callback)callback {
self = [super init];
if (self) {
current_refresh_rate_ = [DisplayLinkManager displayRefreshRate];
_allowPauseAfterVsync = YES;
callback_ = std::move(callback);
display_link_ = fml::scoped_nsobject<CADisplayLink> {
[[CADisplayLink displayLinkWithTarget:self selector:@selector(onDisplayLink:)] retain]
};
display_link_.get().paused = YES;
[self setMaxRefreshRate:[DisplayLinkManager displayRefreshRate]];
task_runner->PostTask([client = [self retain]]() {
[client->display_link_.get() addToRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[client release];
});
}
return self;
}
- (void)setMaxRefreshRate:(double)refreshRate {
if (!DisplayLinkManager.maxRefreshRateEnabledOnIPhone) {
return;
}
double maxFrameRate = fmax(refreshRate, 60);
double minFrameRate = fmax(maxFrameRate / 2, 60);
if (@available(iOS 15.0, *)) {
display_link_.get().preferredFrameRateRange =
CAFrameRateRangeMake(minFrameRate, maxFrameRate, maxFrameRate);
} else {
display_link_.get().preferredFramesPerSecond = maxFrameRate;
}
}
- (void)await {
display_link_.get().paused = NO;
}
- (void)pause {
display_link_.get().paused = YES;
}
- (void)onDisplayLink:(CADisplayLink*)link {
CFTimeInterval delay = CACurrentMediaTime() - link.timestamp;
fml::TimePoint frame_start_time = fml::TimePoint::Now() - fml::TimeDelta::FromSecondsF(delay);
CFTimeInterval duration = link.targetTimestamp - link.timestamp;
fml::TimePoint frame_target_time = frame_start_time + fml::TimeDelta::FromSecondsF(duration);
TRACE_EVENT2_INT("flutter", "PlatformVsync", "frame_start_time",
frame_start_time.ToEpochDelta().ToMicroseconds(), "frame_target_time",
frame_target_time.ToEpochDelta().ToMicroseconds());
std::unique_ptr<flutter::FrameTimingsRecorder> recorder =
std::make_unique<flutter::FrameTimingsRecorder>();
current_refresh_rate_ = round(1 / (frame_target_time - frame_start_time).ToSecondsF());
recorder->RecordVsync(frame_start_time, frame_target_time);
if (_allowPauseAfterVsync) {
display_link_.get().paused = YES;
}
callback_(std::move(recorder));
}
- (void)invalidate {
[display_link_.get() invalidate];
}
- (void)dealloc {
[self invalidate];
[super dealloc];
}
- (double)getRefreshRate {
return current_refresh_rate_;
}
- (CADisplayLink*)getDisplayLink {
return display_link_.get();
}
@end
@implementation DisplayLinkManager
+ (double)displayRefreshRate {
fml::scoped_nsobject<CADisplayLink> display_link = fml::scoped_nsobject<CADisplayLink> {
[[CADisplayLink displayLinkWithTarget:[[[DisplayLinkManager alloc] init] autorelease]
selector:@selector(onDisplayLink:)] retain]
};
display_link.get().paused = YES;
auto preferredFPS = display_link.get().preferredFramesPerSecond;
// From Docs:
// The default value for preferredFramesPerSecond is 0. When this value is 0, the preferred
// frame rate is equal to the maximum refresh rate of the display, as indicated by the
// maximumFramesPerSecond property.
if (preferredFPS != 0) {
return preferredFPS;
}
return [UIScreen mainScreen].maximumFramesPerSecond;
}
- (void)onDisplayLink:(CADisplayLink*)link {
// no-op.
}
+ (BOOL)maxRefreshRateEnabledOnIPhone {
return [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CADisableMinimumFrameDurationOnPhone"]
boolValue];
}
@end
| engine/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.mm",
"repo_id": "engine",
"token_count": 2440
} | 328 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_METAL_IMPELLER_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_METAL_IMPELLER_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/gpu/gpu_surface_metal_delegate.h"
#include "flutter/shell/platform/darwin/ios/ios_surface.h"
@class CAMetalLayer;
namespace impeller {
class Context;
} // namespace impeller
namespace flutter {
class SK_API_AVAILABLE_CA_METAL_LAYER IOSSurfaceMetalImpeller final
: public IOSSurface,
public GPUSurfaceMetalDelegate {
public:
IOSSurfaceMetalImpeller(const fml::scoped_nsobject<CAMetalLayer>& layer,
const std::shared_ptr<IOSContext>& context);
// |IOSSurface|
~IOSSurfaceMetalImpeller();
private:
fml::scoped_nsobject<CAMetalLayer> layer_;
const std::shared_ptr<impeller::Context> impeller_context_;
bool is_valid_ = false;
// |IOSSurface|
bool IsValid() const override;
// |IOSSurface|
void UpdateStorageSizeIfNecessary() override;
// |IOSSurface|
std::unique_ptr<Surface> CreateGPUSurface(GrDirectContext* gr_context) override;
// |GPUSurfaceMetalDelegate|
GPUCAMetalLayerHandle GetCAMetalLayer(const SkISize& frame_info) const override;
// |GPUSurfaceMetalDelegate|
bool PresentDrawable(GrMTLHandle drawable) const override;
// |GPUSurfaceMetalDelegate|
GPUMTLTextureInfo GetMTLTexture(const SkISize& frame_info) const override;
// |GPUSurfaceMetalDelegate|
bool PresentTexture(GPUMTLTextureInfo texture) const override;
// |GPUSurfaceMetalDelegate|
bool AllowsDrawingWhenGpuDisabled() const override;
FML_DISALLOW_COPY_AND_ASSIGN(IOSSurfaceMetalImpeller);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_METAL_IMPELLER_H_
| engine/shell/platform/darwin/ios/ios_surface_metal_impeller.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/ios_surface_metal_impeller.h",
"repo_id": "engine",
"token_count": 734
} | 329 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERAPPLIFECYCLEDELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERAPPLIFECYCLEDELEGATE_H_
#import <Cocoa/Cocoa.h>
#include <Foundation/Foundation.h>
#import "FlutterMacros.h"
NS_ASSUME_NONNULL_BEGIN
#pragma mark -
/**
* Protocol for listener of lifecycle events from the NSApplication, typically a
* FlutterPlugin.
*/
FLUTTER_DARWIN_EXPORT
@protocol FlutterAppLifecycleDelegate <NSObject>
@optional
/**
* Called when the |FlutterAppDelegate| gets the applicationWillFinishLaunching
* notification.
*/
- (void)handleWillFinishLaunching:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationDidFinishLaunching
* notification.
*/
- (void)handleDidFinishLaunching:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationWillBecomeActive
* notification.
*/
- (void)handleWillBecomeActive:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationDidBecomeActive
* notification.
*/
- (void)handleDidBecomeActive:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationWillResignActive
* notification.
*/
- (void)handleWillResignActive:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationWillResignActive
* notification.
*/
- (void)handleDidResignActive:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationWillHide
* notification.
*/
- (void)handleWillHide:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationDidHide
* notification.
*/
- (void)handleDidHide:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationWillUnhide
* notification.
*/
- (void)handleWillUnhide:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationDidUnhide
* notification.
*/
- (void)handleDidUnhide:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationDidUnhide
* notification.
*/
- (void)handleDidChangeScreenParameters:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the applicationDidUnhide
* notification.
*/
- (void)handleDidChangeOcclusionState:(NSNotification*)notification;
/**
* Called when the |FlutterAppDelegate| gets the application:openURLs:
* callback.
*
* Implementers should return YES if they handle the URLs, otherwise NO.
* Delegates will be called in order of registration, and once a delegate
* returns YES, no further delegates will reiceve this callback.
*/
- (BOOL)handleOpenURLs:(NSArray<NSURL*>*)urls;
/**
* Called when the |FlutterAppDelegate| gets the applicationWillTerminate
* notification.
*
* Applications should not rely on always receiving all possible notifications.
*
* For example, if the application is killed with a task manager, a kill signal,
* the user pulls the power from the device, or there is a rapid unscheduled
* disassembly of the device, no notification will be sent before the
* application is suddenly terminated, and this notification may be skipped.
*/
- (void)handleWillTerminate:(NSNotification*)notification;
@end
#pragma mark -
/**
* Propagates `NSAppDelegate` callbacks to registered delegates.
*/
FLUTTER_DARWIN_EXPORT
@interface FlutterAppLifecycleRegistrar : NSObject <FlutterAppLifecycleDelegate>
/**
* Registers `delegate` to receive lifecycle callbacks via this
* FlutterAppLifecycleDelegate as long as it is alive.
*
* `delegate` will only be referenced weakly.
*/
- (void)addDelegate:(NSObject<FlutterAppLifecycleDelegate>*)delegate;
/**
* Unregisters `delegate` so that it will no longer receive life cycle callbacks
* via this FlutterAppLifecycleDelegate.
*
* `delegate` will only be referenced weakly.
*/
- (void)removeDelegate:(NSObject<FlutterAppLifecycleDelegate>*)delegate;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERAPPLIFECYCLEDELEGATE_H_
| engine/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h",
"repo_id": "engine",
"token_count": 1310
} | 330 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERAPPLIFECYCLEDELEGATE_INTERNAL_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERAPPLIFECYCLEDELEGATE_INTERNAL_H_
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h"
@interface FlutterAppLifecycleRegistrar ()
/**
* Registered delegates. Exposed to allow FlutterAppDelegate to share the delegate list for
* handling non-notification delegation.
*/
@property(nonatomic, strong) NSPointerArray* delegates;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERAPPLIFECYCLEDELEGATE_INTERNAL_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate_Internal.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate_Internal.h",
"repo_id": "engine",
"token_count": 295
} | 331 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Foundation/Foundation.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.h"
#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h"
#import "flutter/testing/testing.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"
// A wrap to convert FlutterKeyEvent to a ObjC class.
@interface TestKeyEvent : NSObject
@property(nonatomic) FlutterKeyEvent* data;
@property(nonatomic) FlutterKeyEventCallback callback;
@property(nonatomic) void* userData;
- (nonnull instancetype)initWithEvent:(const FlutterKeyEvent*)event
callback:(nullable FlutterKeyEventCallback)callback
userData:(nullable void*)userData;
- (BOOL)hasCallback;
- (void)respond:(BOOL)handled;
@end
@implementation TestKeyEvent
- (instancetype)initWithEvent:(const FlutterKeyEvent*)event
callback:(nullable FlutterKeyEventCallback)callback
userData:(nullable void*)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, sizeof(character));
_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 flutter::testing {
namespace {
constexpr uint64_t kKeyCodeKeyA = 0x00;
constexpr uint64_t kKeyCodeKeyW = 0x0d;
constexpr uint64_t kKeyCodeShiftLeft = 0x38;
constexpr uint64_t kKeyCodeShiftRight = 0x3c;
constexpr uint64_t kKeyCodeCapsLock = 0x39;
constexpr uint64_t kKeyCodeNumpad1 = 0x53;
constexpr uint64_t kKeyCodeF1 = 0x7a;
constexpr uint64_t kKeyCodeAltRight = 0x3d;
using namespace ::flutter::testing::keycodes;
typedef void (^ResponseCallback)(bool handled);
NSEvent* keyEvent(NSEventType type,
NSEventModifierFlags modifierFlags,
NSString* characters,
NSString* charactersIgnoringModifiers,
BOOL isARepeat,
unsigned short keyCode) {
return [NSEvent keyEventWithType:type
location:NSZeroPoint
modifierFlags:modifierFlags
timestamp:0
windowNumber:0
context:nil
characters:characters
charactersIgnoringModifiers:charactersIgnoringModifiers
isARepeat:isARepeat
keyCode:keyCode];
}
NSEvent* keyEvent(NSEventType type,
NSTimeInterval timestamp,
NSEventModifierFlags modifierFlags,
NSString* characters,
NSString* charactersIgnoringModifiers,
BOOL isARepeat,
unsigned short keyCode) {
return [NSEvent keyEventWithType:type
location:NSZeroPoint
modifierFlags:modifierFlags
timestamp:timestamp
windowNumber:0
context:nil
characters:characters
charactersIgnoringModifiers:charactersIgnoringModifiers
isARepeat:isARepeat
keyCode:keyCode];
}
} // namespace
// Test the most basic key events.
//
// Press, hold, and release key A on an US keyboard.
TEST(FlutterEmbedderKeyResponderUnittests, BasicKeyEvent) {
__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 handleEvent:keyEvent(NSEventTypeKeyDown, 123.0f, 0x100, @"a", @"a", FALSE, 0)
callback:^(BOOL handled) {
last_handled = handled;
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->timestamp, 123000000.0f);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, FALSE);
EXPECT_TRUE([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
last_handled = FALSE;
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", TRUE, kKeyCodeKeyA)
callback:^(BOOL handled) {
last_handled = handled;
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeRepeat);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, FALSE);
EXPECT_TRUE([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
last_handled = TRUE;
[responder handleEvent:keyEvent(NSEventTypeKeyUp, 124.0f, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled) {
last_handled = handled;
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->timestamp, 124000000.0f);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_EQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, TRUE);
EXPECT_TRUE([[events lastObject] hasCallback]);
[[events lastObject] respond:FALSE]; // Check if responding FALSE works
EXPECT_EQ(last_handled, FALSE);
[events removeAllObjects];
}
TEST(FlutterEmbedderKeyResponderUnittests, NonAsciiCharacters) {
__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
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x80140, @"", @"", FALSE, kKeyCodeAltRight)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalAltRight);
EXPECT_EQ(event->logical, kLogicalAltRight);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[events removeAllObjects];
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x80140, @"∑", @"w", FALSE, kKeyCodeKeyW)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyW);
EXPECT_EQ(event->logical, kLogicalKeyW);
EXPECT_STREQ(event->character, "∑");
EXPECT_EQ(event->synthesized, false);
[events removeAllObjects];
[responder handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeAltRight)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalAltRight);
EXPECT_EQ(event->logical, kLogicalAltRight);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[events removeAllObjects];
[responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x100, @"w", @"w", FALSE, kKeyCodeKeyW)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyW);
EXPECT_EQ(event->logical, kLogicalKeyW);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[events removeAllObjects];
}
TEST(FlutterEmbedderKeyResponderUnittests, MultipleCharacters) {
__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 handleEvent:keyEvent(NSEventTypeKeyDown, 0, @"àn", @"àn", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, 0x1400000000ull);
EXPECT_STREQ(event->character, "àn");
EXPECT_EQ(event->synthesized, false);
[events removeAllObjects];
[responder handleEvent:keyEvent(NSEventTypeKeyUp, 0, @"a", @"a", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, 0x1400000000ull);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[events removeAllObjects];
}
TEST(FlutterEmbedderKeyResponderUnittests, SynthesizeForDuplicateDownEvent) {
__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 = TRUE;
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled) {
last_handled = handled;
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, TRUE);
[[events lastObject] respond:FALSE];
EXPECT_EQ(last_handled, FALSE);
[events removeAllObjects];
last_handled = TRUE;
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"à", @"à", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled) {
last_handled = handled;
}];
EXPECT_EQ([events count], 2u);
event = [events firstObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, NULL);
EXPECT_EQ(event->synthesized, true);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, 0xE0ull /* à */);
EXPECT_STREQ(event->character, "à");
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:FALSE];
EXPECT_EQ(last_handled, FALSE);
[events removeAllObjects];
}
TEST(FlutterEmbedderKeyResponderUnittests, IgnoreDuplicateUpEvent) {
__block NSMutableArray<TestKeyEvent*>* events = [[NSMutableArray<TestKeyEvent*> alloc] init];
FlutterKeyEvent* event;
__block BOOL last_handled = TRUE;
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 handleEvent:keyEvent(NSEventTypeKeyUp, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled) {
last_handled = handled;
}];
EXPECT_EQ([events count], 1u);
EXPECT_EQ(last_handled, TRUE);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->physical, 0ull);
EXPECT_EQ(event->logical, 0ull);
EXPECT_FALSE([[events lastObject] hasCallback]);
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
}
TEST(FlutterEmbedderKeyResponderUnittests, ConvertAbruptRepeatEventsToDown) {
__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 = TRUE;
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", TRUE, kKeyCodeKeyA)
callback:^(BOOL handled) {
last_handled = handled;
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, TRUE);
[[events lastObject] respond:FALSE];
EXPECT_EQ(last_handled, FALSE);
[events removeAllObjects];
}
// Press L shift, A, then release L shift then A, on an US keyboard.
//
// This is special because the characters for the A key will change in this
// process.
TEST(FlutterEmbedderKeyResponderUnittests, ToggleModifiersDuringKeyTap) {
__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 handleEvent:keyEvent(NSEventTypeFlagsChanged, 123.0f, 0x20104, @"", @"", FALSE,
kKeyCodeShiftRight)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->timestamp, 123000000.0f);
EXPECT_EQ(event->physical, kPhysicalShiftRight);
EXPECT_EQ(event->logical, kLogicalShiftRight);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x20104, @"A", @"A", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "A");
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x20104, @"A", @"A", TRUE, kKeyCodeKeyA)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeRepeat);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "A");
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftRight)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftRight);
EXPECT_EQ(event->logical, kLogicalShiftRight);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", TRUE, kKeyCodeKeyA)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeRepeat);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
[events removeAllObjects];
[responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(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.
TEST(FlutterEmbedderKeyResponderUnittests, SpecialModiferFlags) {
__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]];
}];
// Keydown: Numpad1, F1, KeyA, ShiftLeft
// Then KeyUp: Numpad1, F1, KeyA, ShiftLeft
// Numpad 1
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x200100, @"1", @"1", FALSE, kKeyCodeNumpad1)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalNumpad1);
EXPECT_EQ(event->logical, kLogicalNumpad1);
EXPECT_STREQ(event->character, "1");
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// F1
[responder
handleEvent:keyEvent(NSEventTypeKeyDown, 0x800100, @"\uf704", @"\uf704", FALSE, kKeyCodeF1)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalF1);
EXPECT_EQ(event->logical, kLogicalF1);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// KeyA
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "a");
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// ShiftLeft
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// Numpad 1
[responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x220102, @"1", @"1", FALSE, kKeyCodeNumpad1)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalNumpad1);
EXPECT_EQ(event->logical, kLogicalNumpad1);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// F1
[responder
handleEvent:keyEvent(NSEventTypeKeyUp, 0x820102, @"\uF704", @"\uF704", FALSE, kKeyCodeF1)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalF1);
EXPECT_EQ(event->logical, kLogicalF1);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// KeyA
[responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x20102, @"a", @"a", FALSE, kKeyCodeKeyA)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
// ShiftLeft
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
}
TEST(FlutterEmbedderKeyResponderUnittests, IdentifyLeftAndRightModifiers) {
__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
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20106, @"", @"", FALSE, kKeyCodeShiftRight)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftRight);
EXPECT_EQ(event->logical, kLogicalShiftRight);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20104, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftRight)
callback:^(BOOL handled){
}];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftRight);
EXPECT_EQ(event->logical, kLogicalShiftRight);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
[[events lastObject] respond:TRUE];
[events removeAllObjects];
}
// Process various cases where pair modifier key events are missed, and the
// responder has to "guess" how to synchronize states.
//
// In the following comments, parentheses indicate missed events, while
// asterisks indicate synthesized events.
TEST(FlutterEmbedderKeyResponderUnittests, SynthesizeMissedModifierEvents) {
__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]];
}];
// Case 1:
// In: L down, (L up), L down, L up
// Out: L down, L up
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:keyEventCallback];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, FALSE);
EXPECT_TRUE([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:keyEventCallback];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->physical, 0u);
EXPECT_EQ(event->logical, 0u);
EXPECT_FALSE([[events lastObject] hasCallback]);
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:keyEventCallback];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, FALSE);
EXPECT_TRUE([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
// Case 2:
// In: (L down), L up
// Out:
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:keyEventCallback];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->physical, 0u);
EXPECT_EQ(event->logical, 0u);
EXPECT_FALSE([[events lastObject] hasCallback]);
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
// Case 3:
// In: L down, (L up), (R down), R up
// Out: L down, *L up
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:keyEventCallback];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, FALSE);
EXPECT_TRUE([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftRight)
callback:keyEventCallback];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, true);
// The primary event is automatically replied with TRUE, unrelated to the received event.
EXPECT_EQ(last_handled, TRUE);
EXPECT_FALSE([[events lastObject] hasCallback]);
[events removeAllObjects];
// Case 4:
// In: L down, R down, (L up), R up
// Out: L down, R down *L up & R up
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft)
callback:keyEventCallback];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, FALSE);
EXPECT_TRUE([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20106, @"", @"", FALSE, kKeyCodeShiftRight)
callback:keyEventCallback];
EXPECT_EQ([events count], 1u);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftRight);
EXPECT_EQ(event->logical, kLogicalShiftRight);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, FALSE);
EXPECT_TRUE([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftRight)
callback:keyEventCallback];
EXPECT_EQ([events count], 2u);
event = [events firstObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, true);
EXPECT_FALSE([[events firstObject] hasCallback]);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftRight);
EXPECT_EQ(event->logical, kLogicalShiftRight);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_EQ(last_handled, FALSE);
EXPECT_TRUE([[events lastObject] hasCallback]);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
}
TEST(FlutterEmbedderKeyResponderUnittests, SynthesizeMissedModifierEventsInNormalEvents) {
__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]];
}];
// In: (LShift down), A down, (LShift up), A up
// Out: *LS down & A down, *LS up & A up
last_handled = FALSE;
[responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x20102, @"A", @"A", FALSE, kKeyCodeKeyA)
callback:keyEventCallback];
EXPECT_EQ([events count], 2u);
event = [events firstObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, true);
EXPECT_FALSE([[events firstObject] hasCallback]);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "A");
EXPECT_EQ(event->synthesized, false);
EXPECT_TRUE([[events lastObject] hasCallback]);
EXPECT_EQ(last_handled, FALSE);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
last_handled = FALSE;
[responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA)
callback:keyEventCallback];
EXPECT_EQ([events count], 2u);
event = [events firstObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalShiftLeft);
EXPECT_EQ(event->logical, kLogicalShiftLeft);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, true);
EXPECT_FALSE([[events firstObject] hasCallback]);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_TRUE([[events lastObject] hasCallback]);
EXPECT_EQ(last_handled, FALSE);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
}
TEST(FlutterEmbedderKeyResponderUnittests, ConvertCapsLockEvents) {
__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]];
}];
// In: CapsLock down
// Out: CapsLock down & *CapsLock Up
last_handled = FALSE;
[responder
handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x10100, @"", @"", FALSE, kKeyCodeCapsLock)
callback:keyEventCallback];
EXPECT_EQ([events count], 2u);
event = [events firstObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalCapsLock);
EXPECT_EQ(event->logical, kLogicalCapsLock);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_TRUE([[events firstObject] hasCallback]);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalCapsLock);
EXPECT_EQ(event->logical, kLogicalCapsLock);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, true);
EXPECT_FALSE([[events lastObject] hasCallback]);
EXPECT_EQ(last_handled, FALSE);
[[events firstObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
// In: CapsLock up
// Out: CapsLock down & *CapsLock Up
last_handled = FALSE;
[responder handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeCapsLock)
callback:keyEventCallback];
EXPECT_EQ([events count], 2u);
event = [events firstObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalCapsLock);
EXPECT_EQ(event->logical, kLogicalCapsLock);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, false);
EXPECT_TRUE([[events firstObject] hasCallback]);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalCapsLock);
EXPECT_EQ(event->logical, kLogicalCapsLock);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, true);
EXPECT_FALSE([[events lastObject] hasCallback]);
EXPECT_EQ(last_handled, FALSE);
[[events firstObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
}
// Press the CapsLock key when CapsLock state is desynchronized
TEST(FlutterEmbedderKeyResponderUnittests, SynchronizeCapsLockStateOnCapsLock) {
__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]];
}];
// In: CapsLock down
// Out: (empty)
last_handled = FALSE;
[responder handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeCapsLock)
callback:keyEventCallback];
EXPECT_EQ([events count], 1u);
EXPECT_EQ(last_handled, TRUE);
event = [events lastObject].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->physical, 0ull);
EXPECT_EQ(event->logical, 0ull);
EXPECT_FALSE([[events lastObject] hasCallback]);
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
}
// Press the CapsLock key when CapsLock state is desynchronized
TEST(FlutterEmbedderKeyResponderUnittests, SynchronizeCapsLockStateOnNormalKey) {
__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 handleEvent:keyEvent(NSEventTypeKeyDown, 0x10100, @"A", @"a", FALSE, kKeyCodeKeyA)
callback:keyEventCallback];
EXPECT_EQ([events count], 3u);
event = events[0].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalCapsLock);
EXPECT_EQ(event->logical, kLogicalCapsLock);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, true);
EXPECT_FALSE([events[0] hasCallback]);
event = events[1].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeUp);
EXPECT_EQ(event->physical, kPhysicalCapsLock);
EXPECT_EQ(event->logical, kLogicalCapsLock);
EXPECT_STREQ(event->character, nullptr);
EXPECT_EQ(event->synthesized, true);
EXPECT_FALSE([events[1] hasCallback]);
event = events[2].data;
ASSERT_NE(event, nullptr);
EXPECT_EQ(event->type, kFlutterKeyEventTypeDown);
EXPECT_EQ(event->physical, kPhysicalKeyA);
EXPECT_EQ(event->logical, kLogicalKeyA);
EXPECT_STREQ(event->character, "A");
EXPECT_EQ(event->synthesized, false);
EXPECT_TRUE([events[2] hasCallback]);
EXPECT_EQ(last_handled, FALSE);
[[events lastObject] respond:TRUE];
EXPECT_EQ(last_handled, TRUE);
[events removeAllObjects];
}
} // namespace flutter::testing
| engine/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponderTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponderTest.mm",
"repo_id": "engine",
"token_count": 18983
} | 332 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERSURFACEMANAGER_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERSURFACEMANAGER_H_
#import <Cocoa/Cocoa.h>
#import <QuartzCore/QuartzCore.h>
#include <vector>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h"
/**
* Surface with additional properties needed for presenting.
*/
@interface FlutterSurfacePresentInfo : NSObject
@property(readwrite, strong, nonatomic, nonnull) FlutterSurface* surface;
@property(readwrite, nonatomic) CGPoint offset;
@property(readwrite, nonatomic) size_t zIndex;
@property(readwrite, nonatomic) std::vector<FlutterRect> paintRegion;
@end
@protocol FlutterSurfaceManagerDelegate <NSObject>
/*
* Schedules the block on the platform thread and blocks until the block is executed.
* Provided `frameSize` is used to unblock the platform thread if it waits for
* a certain frame size during resizing.
*/
- (void)onPresent:(CGSize)frameSize withBlock:(nonnull dispatch_block_t)block;
@end
/**
* FlutterSurfaceManager is responsible for providing and presenting Core Animation render
* surfaces and managing sublayers.
*
* Owned by `FlutterView`.
*/
@interface FlutterSurfaceManager : NSObject
/**
* Initializes and returns a surface manager that renders to a child layer (referred to as the
* content layer) of the containing layer.
*/
- (nullable instancetype)initWithDevice:(nonnull id<MTLDevice>)device
commandQueue:(nonnull id<MTLCommandQueue>)commandQueue
layer:(nonnull CALayer*)containingLayer
delegate:(nonnull id<FlutterSurfaceManagerDelegate>)delegate;
/**
* Returns a back buffer surface of the given size to which Flutter can render content.
* A cached surface will be returned if available; otherwise a new one will be created.
*
* Must be called on raster thread.
*/
- (nonnull FlutterSurface*)surfaceForSize:(CGSize)size;
/**
* Sets the provided surfaces as contents of FlutterView. Will create, update and
* remove sublayers as needed.
*
* Must be called on raster thread. This will schedule a commit on the platform thread and block the
* raster thread until the commit is done. The `notify` block will be invoked on the platform thread
* and can be used to perform additional work, such as mutating platform views. It is guaranteed be
* called in the same CATransaction.
*/
- (void)presentSurfaces:(nonnull NSArray<FlutterSurfacePresentInfo*>*)surfaces
atTime:(CFTimeInterval)presentationTime
notify:(nullable dispatch_block_t)notify;
@end
/**
* Cache of back buffers to prevent unnecessary IOSurface allocations.
*/
@interface FlutterBackBufferCache : NSObject
/**
* Removes surface with given size from cache (if available) and returns it.
*/
- (nullable FlutterSurface*)removeSurfaceForSize:(CGSize)size;
/**
* Removes all cached surfaces replacing them with new ones.
*/
- (void)replaceSurfaces:(nonnull NSArray<FlutterSurface*>*)surfaces;
/**
* Returns number of surfaces currently in cache. Used for tests.
*/
- (NSUInteger)count;
@end
/**
* Interface to internal properties used for testing.
*/
@interface FlutterSurfaceManager (Private)
@property(readonly, nonatomic, nonnull) FlutterBackBufferCache* backBufferCache;
@property(readonly, nonatomic, nonnull) NSArray<FlutterSurface*>* frontSurfaces;
@property(readonly, nonatomic, nonnull) NSArray<CALayer*>* layers;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERSURFACEMANAGER_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h",
"repo_id": "engine",
"token_count": 1214
} | 333 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#include "./KeyCodeMap_Internal.h"
// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT
// This file is generated by
// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not
// be edited directly.
//
// Edit the template
// flutter/flutter:dev/tools/gen_keycodes/data/keyboard_map_macos_cc.tmpl
// instead.
//
// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information.
namespace flutter {
const uint64_t kValueMask = 0x000ffffffff;
const uint64_t kUnicodePlane = 0x00000000000;
const uint64_t kMacosPlane = 0x01400000000;
const NSDictionary* keyCodeToPhysicalKey = @{
@0x00000000 : @0x00070004, // keyA
@0x00000001 : @0x00070016, // keyS
@0x00000002 : @0x00070007, // keyD
@0x00000003 : @0x00070009, // keyF
@0x00000004 : @0x0007000b, // keyH
@0x00000005 : @0x0007000a, // keyG
@0x00000006 : @0x0007001d, // keyZ
@0x00000007 : @0x0007001b, // keyX
@0x00000008 : @0x00070006, // keyC
@0x00000009 : @0x00070019, // keyV
@0x0000000a : @0x00070064, // intlBackslash
@0x0000000b : @0x00070005, // keyB
@0x0000000c : @0x00070014, // keyQ
@0x0000000d : @0x0007001a, // keyW
@0x0000000e : @0x00070008, // keyE
@0x0000000f : @0x00070015, // keyR
@0x00000010 : @0x0007001c, // keyY
@0x00000011 : @0x00070017, // keyT
@0x00000012 : @0x0007001e, // digit1
@0x00000013 : @0x0007001f, // digit2
@0x00000014 : @0x00070020, // digit3
@0x00000015 : @0x00070021, // digit4
@0x00000016 : @0x00070023, // digit6
@0x00000017 : @0x00070022, // digit5
@0x00000018 : @0x0007002e, // equal
@0x00000019 : @0x00070026, // digit9
@0x0000001a : @0x00070024, // digit7
@0x0000001b : @0x0007002d, // minus
@0x0000001c : @0x00070025, // digit8
@0x0000001d : @0x00070027, // digit0
@0x0000001e : @0x00070030, // bracketRight
@0x0000001f : @0x00070012, // keyO
@0x00000020 : @0x00070018, // keyU
@0x00000021 : @0x0007002f, // bracketLeft
@0x00000022 : @0x0007000c, // keyI
@0x00000023 : @0x00070013, // keyP
@0x00000024 : @0x00070028, // enter
@0x00000025 : @0x0007000f, // keyL
@0x00000026 : @0x0007000d, // keyJ
@0x00000027 : @0x00070034, // quote
@0x00000028 : @0x0007000e, // keyK
@0x00000029 : @0x00070033, // semicolon
@0x0000002a : @0x00070031, // backslash
@0x0000002b : @0x00070036, // comma
@0x0000002c : @0x00070038, // slash
@0x0000002d : @0x00070011, // keyN
@0x0000002e : @0x00070010, // keyM
@0x0000002f : @0x00070037, // period
@0x00000030 : @0x0007002b, // tab
@0x00000031 : @0x0007002c, // space
@0x00000032 : @0x00070035, // backquote
@0x00000033 : @0x0007002a, // backspace
@0x00000035 : @0x00070029, // escape
@0x00000036 : @0x000700e7, // metaRight
@0x00000037 : @0x000700e3, // metaLeft
@0x00000038 : @0x000700e1, // shiftLeft
@0x00000039 : @0x00070039, // capsLock
@0x0000003a : @0x000700e2, // altLeft
@0x0000003b : @0x000700e0, // controlLeft
@0x0000003c : @0x000700e5, // shiftRight
@0x0000003d : @0x000700e6, // altRight
@0x0000003e : @0x000700e4, // controlRight
@0x0000003f : @0x00000012, // fn
@0x00000040 : @0x0007006c, // f17
@0x00000041 : @0x00070063, // numpadDecimal
@0x00000043 : @0x00070055, // numpadMultiply
@0x00000045 : @0x00070057, // numpadAdd
@0x00000047 : @0x00070053, // numLock
@0x00000048 : @0x00070080, // audioVolumeUp
@0x00000049 : @0x00070081, // audioVolumeDown
@0x0000004a : @0x0007007f, // audioVolumeMute
@0x0000004b : @0x00070054, // numpadDivide
@0x0000004c : @0x00070058, // numpadEnter
@0x0000004e : @0x00070056, // numpadSubtract
@0x0000004f : @0x0007006d, // f18
@0x00000050 : @0x0007006e, // f19
@0x00000051 : @0x00070067, // numpadEqual
@0x00000052 : @0x00070062, // numpad0
@0x00000053 : @0x00070059, // numpad1
@0x00000054 : @0x0007005a, // numpad2
@0x00000055 : @0x0007005b, // numpad3
@0x00000056 : @0x0007005c, // numpad4
@0x00000057 : @0x0007005d, // numpad5
@0x00000058 : @0x0007005e, // numpad6
@0x00000059 : @0x0007005f, // numpad7
@0x0000005a : @0x0007006f, // f20
@0x0000005b : @0x00070060, // numpad8
@0x0000005c : @0x00070061, // numpad9
@0x0000005d : @0x00070089, // intlYen
@0x0000005e : @0x00070087, // intlRo
@0x0000005f : @0x00070085, // numpadComma
@0x00000060 : @0x0007003e, // f5
@0x00000061 : @0x0007003f, // f6
@0x00000062 : @0x00070040, // f7
@0x00000063 : @0x0007003c, // f3
@0x00000064 : @0x00070041, // f8
@0x00000065 : @0x00070042, // f9
@0x00000066 : @0x00070091, // lang2
@0x00000067 : @0x00070044, // f11
@0x00000068 : @0x00070090, // lang1
@0x00000069 : @0x00070068, // f13
@0x0000006a : @0x0007006b, // f16
@0x0000006b : @0x00070069, // f14
@0x0000006d : @0x00070043, // f10
@0x0000006e : @0x00070065, // contextMenu
@0x0000006f : @0x00070045, // f12
@0x00000071 : @0x0007006a, // f15
@0x00000072 : @0x00070049, // insert
@0x00000073 : @0x0007004a, // home
@0x00000074 : @0x0007004b, // pageUp
@0x00000075 : @0x0007004c, // delete
@0x00000076 : @0x0007003d, // f4
@0x00000077 : @0x0007004d, // end
@0x00000078 : @0x0007003b, // f2
@0x00000079 : @0x0007004e, // pageDown
@0x0000007a : @0x0007003a, // f1
@0x0000007b : @0x00070050, // arrowLeft
@0x0000007c : @0x0007004f, // arrowRight
@0x0000007d : @0x00070051, // arrowDown
@0x0000007e : @0x00070052, // arrowUp
};
const NSDictionary* keyCodeToLogicalKey = @{
@0x00000024 : @0x0010000000d, // Enter -> enter
@0x00000030 : @0x00100000009, // Tab -> tab
@0x00000033 : @0x00100000008, // Backspace -> backspace
@0x00000035 : @0x0010000001b, // Escape -> escape
@0x00000036 : @0x00200000107, // MetaRight -> metaRight
@0x00000037 : @0x00200000106, // MetaLeft -> metaLeft
@0x00000038 : @0x00200000102, // ShiftLeft -> shiftLeft
@0x00000039 : @0x00100000104, // CapsLock -> capsLock
@0x0000003a : @0x00200000104, // AltLeft -> altLeft
@0x0000003b : @0x00200000100, // ControlLeft -> controlLeft
@0x0000003c : @0x00200000103, // ShiftRight -> shiftRight
@0x0000003d : @0x00200000105, // AltRight -> altRight
@0x0000003e : @0x00200000101, // ControlRight -> controlRight
@0x0000003f : @0x00100000106, // Fn -> fn
@0x00000040 : @0x00100000811, // F17 -> f17
@0x00000041 : @0x0020000022e, // NumpadDecimal -> numpadDecimal
@0x00000043 : @0x0020000022a, // NumpadMultiply -> numpadMultiply
@0x00000045 : @0x0020000022b, // NumpadAdd -> numpadAdd
@0x00000047 : @0x0010000010a, // NumLock -> numLock
@0x00000048 : @0x00100000a10, // AudioVolumeUp -> audioVolumeUp
@0x00000049 : @0x00100000a0f, // AudioVolumeDown -> audioVolumeDown
@0x0000004a : @0x00100000a11, // AudioVolumeMute -> audioVolumeMute
@0x0000004b : @0x0020000022f, // NumpadDivide -> numpadDivide
@0x0000004c : @0x0020000020d, // NumpadEnter -> numpadEnter
@0x0000004e : @0x0020000022d, // NumpadSubtract -> numpadSubtract
@0x0000004f : @0x00100000812, // F18 -> f18
@0x00000050 : @0x00100000813, // F19 -> f19
@0x00000051 : @0x0020000023d, // NumpadEqual -> numpadEqual
@0x00000052 : @0x00200000230, // Numpad0 -> numpad0
@0x00000053 : @0x00200000231, // Numpad1 -> numpad1
@0x00000054 : @0x00200000232, // Numpad2 -> numpad2
@0x00000055 : @0x00200000233, // Numpad3 -> numpad3
@0x00000056 : @0x00200000234, // Numpad4 -> numpad4
@0x00000057 : @0x00200000235, // Numpad5 -> numpad5
@0x00000058 : @0x00200000236, // Numpad6 -> numpad6
@0x00000059 : @0x00200000237, // Numpad7 -> numpad7
@0x0000005a : @0x00100000814, // F20 -> f20
@0x0000005b : @0x00200000238, // Numpad8 -> numpad8
@0x0000005c : @0x00200000239, // Numpad9 -> numpad9
@0x0000005d : @0x00200000022, // IntlYen -> intlYen
@0x0000005e : @0x00200000021, // IntlRo -> intlRo
@0x0000005f : @0x0020000022c, // NumpadComma -> numpadComma
@0x00000060 : @0x00100000805, // F5 -> f5
@0x00000061 : @0x00100000806, // F6 -> f6
@0x00000062 : @0x00100000807, // F7 -> f7
@0x00000063 : @0x00100000803, // F3 -> f3
@0x00000064 : @0x00100000808, // F8 -> f8
@0x00000065 : @0x00100000809, // F9 -> f9
@0x00000066 : @0x00200000011, // Lang2 -> lang2
@0x00000067 : @0x0010000080b, // F11 -> f11
@0x00000068 : @0x00200000010, // Lang1 -> lang1
@0x00000069 : @0x0010000080d, // F13 -> f13
@0x0000006a : @0x00100000810, // F16 -> f16
@0x0000006b : @0x0010000080e, // F14 -> f14
@0x0000006d : @0x0010000080a, // F10 -> f10
@0x0000006e : @0x00100000505, // ContextMenu -> contextMenu
@0x0000006f : @0x0010000080c, // F12 -> f12
@0x00000071 : @0x0010000080f, // F15 -> f15
@0x00000072 : @0x00100000407, // Insert -> insert
@0x00000073 : @0x00100000306, // Home -> home
@0x00000074 : @0x00100000308, // PageUp -> pageUp
@0x00000075 : @0x0010000007f, // Delete -> delete
@0x00000076 : @0x00100000804, // F4 -> f4
@0x00000077 : @0x00100000305, // End -> end
@0x00000078 : @0x00100000802, // F2 -> f2
@0x00000079 : @0x00100000307, // PageDown -> pageDown
@0x0000007a : @0x00100000801, // F1 -> f1
@0x0000007b : @0x00100000302, // ArrowLeft -> arrowLeft
@0x0000007c : @0x00100000303, // ArrowRight -> arrowRight
@0x0000007d : @0x00100000301, // ArrowDown -> arrowDown
@0x0000007e : @0x00100000304, // ArrowUp -> arrowUp
};
const NSDictionary* keyCodeToModifierFlag = @{
@0x00000038 : @(kModifierFlagShiftLeft),
@0x0000003c : @(kModifierFlagShiftRight),
@0x0000003b : @(kModifierFlagControlLeft),
@0x0000003e : @(kModifierFlagControlRight),
@0x0000003a : @(kModifierFlagAltLeft),
@0x0000003d : @(kModifierFlagAltRight),
@0x00000037 : @(kModifierFlagMetaLeft),
@0x00000036 : @(kModifierFlagMetaRight),
};
const NSDictionary* modifierFlagToKeyCode = @{
@(kModifierFlagShiftLeft) : @0x00000038,
@(kModifierFlagShiftRight) : @0x0000003c,
@(kModifierFlagControlLeft) : @0x0000003b,
@(kModifierFlagControlRight) : @0x0000003e,
@(kModifierFlagAltLeft) : @0x0000003a,
@(kModifierFlagAltRight) : @0x0000003d,
@(kModifierFlagMetaLeft) : @0x00000037,
@(kModifierFlagMetaRight) : @0x00000036,
};
const uint64_t kCapsLockPhysicalKey = 0x00070039;
const uint64_t kCapsLockLogicalKey = 0x100000104;
const std::vector<LayoutGoal> kLayoutGoals = {
LayoutGoal{0x31, 0x20, false}, // Space
LayoutGoal{0x27, 0x22, false}, // Quote
LayoutGoal{0x2b, 0x2c, false}, // Comma
LayoutGoal{0x1b, 0x2d, false}, // Minus
LayoutGoal{0x2f, 0x2e, false}, // Period
LayoutGoal{0x2c, 0x2f, false}, // Slash
LayoutGoal{0x1d, 0x30, true}, // Digit0
LayoutGoal{0x12, 0x31, true}, // Digit1
LayoutGoal{0x13, 0x32, true}, // Digit2
LayoutGoal{0x14, 0x33, true}, // Digit3
LayoutGoal{0x15, 0x34, true}, // Digit4
LayoutGoal{0x17, 0x35, true}, // Digit5
LayoutGoal{0x16, 0x36, true}, // Digit6
LayoutGoal{0x1a, 0x37, true}, // Digit7
LayoutGoal{0x1c, 0x38, true}, // Digit8
LayoutGoal{0x19, 0x39, true}, // Digit9
LayoutGoal{0x29, 0x3b, false}, // Semicolon
LayoutGoal{0x18, 0x3d, false}, // Equal
LayoutGoal{0x21, 0x5b, false}, // BracketLeft
LayoutGoal{0x2a, 0x5c, false}, // Backslash
LayoutGoal{0x1e, 0x5d, false}, // BracketRight
LayoutGoal{0x32, 0x60, false}, // Backquote
LayoutGoal{0x00, 0x61, true}, // KeyA
LayoutGoal{0x0b, 0x62, true}, // KeyB
LayoutGoal{0x08, 0x63, true}, // KeyC
LayoutGoal{0x02, 0x64, true}, // KeyD
LayoutGoal{0x0e, 0x65, true}, // KeyE
LayoutGoal{0x03, 0x66, true}, // KeyF
LayoutGoal{0x05, 0x67, true}, // KeyG
LayoutGoal{0x04, 0x68, true}, // KeyH
LayoutGoal{0x22, 0x69, true}, // KeyI
LayoutGoal{0x26, 0x6a, true}, // KeyJ
LayoutGoal{0x28, 0x6b, true}, // KeyK
LayoutGoal{0x25, 0x6c, true}, // KeyL
LayoutGoal{0x2e, 0x6d, true}, // KeyM
LayoutGoal{0x2d, 0x6e, true}, // KeyN
LayoutGoal{0x1f, 0x6f, true}, // KeyO
LayoutGoal{0x23, 0x70, true}, // KeyP
LayoutGoal{0x0c, 0x71, true}, // KeyQ
LayoutGoal{0x0f, 0x72, true}, // KeyR
LayoutGoal{0x01, 0x73, true}, // KeyS
LayoutGoal{0x11, 0x74, true}, // KeyT
LayoutGoal{0x20, 0x75, true}, // KeyU
LayoutGoal{0x09, 0x76, true}, // KeyV
LayoutGoal{0x0d, 0x77, true}, // KeyW
LayoutGoal{0x07, 0x78, true}, // KeyX
LayoutGoal{0x10, 0x79, true}, // KeyY
LayoutGoal{0x06, 0x7a, true}, // KeyZ
LayoutGoal{0x0a, 0x200000020, false}, // IntlBackslash
};
} // namespace flutter
| engine/shell/platform/darwin/macos/framework/Source/KeyCodeMap.g.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/KeyCodeMap.g.mm",
"repo_id": "engine",
"token_count": 6285
} | 334 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Linker script that exports the minimal symbols required for the embedder library
{
global:
Flutter*;
__Flutter*;
kFlutter*;
kDartIsolateSnapshotData;
kDartIsolateSnapshotInstructions;
kDartVmSnapshotData;
kDartVmSnapshotInstructions;
local:
*;
};
| engine/shell/platform/embedder/embedder_exports.lst/0 | {
"file_path": "engine/shell/platform/embedder/embedder_exports.lst",
"repo_id": "engine",
"token_count": 157
} | 335 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_PLATFORM_MESSAGE_RESPONSE_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_PLATFORM_MESSAGE_RESPONSE_H_
#include "flutter/fml/macros.h"
#include "flutter/fml/task_runner.h"
#include "flutter/lib/ui/window/platform_message_response.h"
namespace flutter {
//------------------------------------------------------------------------------
/// @brief The platform message response subclass for responses to messages
/// from the embedder to the framework. Message responses are
/// fulfilled by the framework.
class EmbedderPlatformMessageResponse : public PlatformMessageResponse {
public:
using Callback = std::function<void(const uint8_t* data, size_t size)>;
//----------------------------------------------------------------------------
/// @param[in] runner The task runner on which to execute the callback.
/// The response will be initiated by the framework on
/// the UI thread.
/// @param[in] callback The callback that communicates to the embedder the
/// contents of the response sent by the framework back
/// to the emebder.
EmbedderPlatformMessageResponse(fml::RefPtr<fml::TaskRunner> runner,
const Callback& callback);
//----------------------------------------------------------------------------
/// @brief Destroys the message response. Can be called on any thread.
/// Does not execute unfulfilled callbacks.
///
~EmbedderPlatformMessageResponse() override;
private:
fml::RefPtr<fml::TaskRunner> runner_;
Callback callback_;
// |PlatformMessageResponse|
void Complete(std::unique_ptr<fml::Mapping> data) override;
// |PlatformMessageResponse|
void CompleteEmpty() override;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderPlatformMessageResponse);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_PLATFORM_MESSAGE_RESPONSE_H_
| engine/shell/platform/embedder/embedder_platform_message_response.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_platform_message_response.h",
"repo_id": "engine",
"token_count": 747
} | 336 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/embedder/embedder_surface_gl_impeller.h"
#include <utility>
#include "impeller/entity/gles/entity_shaders_gles.h"
#include "impeller/entity/gles/framebuffer_blend_shaders_gles.h"
#include "impeller/entity/gles/modern_shaders_gles.h"
#include "impeller/renderer/backend/gles/context_gles.h"
#include "impeller/renderer/backend/gles/proc_table_gles.h"
#if IMPELLER_ENABLE_3D
#include "impeller/scene/shaders/gles/scene_shaders_gles.h" // nogncheck
#endif // IMPELLER_ENABLE_3D
namespace flutter {
class ReactorWorker final : public impeller::ReactorGLES::Worker {
public:
ReactorWorker() = default;
// |ReactorGLES::Worker|
bool CanReactorReactOnCurrentThreadNow(
const impeller::ReactorGLES& reactor) const override {
impeller::ReaderLock lock(mutex_);
auto found = reactions_allowed_.find(std::this_thread::get_id());
if (found == reactions_allowed_.end()) {
return false;
}
return found->second;
}
void SetReactionsAllowedOnCurrentThread(bool allowed) {
impeller::WriterLock lock(mutex_);
reactions_allowed_[std::this_thread::get_id()] = allowed;
}
private:
mutable impeller::RWMutex mutex_;
std::map<std::thread::id, bool> reactions_allowed_ IPLR_GUARDED_BY(mutex_);
FML_DISALLOW_COPY_AND_ASSIGN(ReactorWorker);
};
EmbedderSurfaceGLImpeller::EmbedderSurfaceGLImpeller(
EmbedderSurfaceGL::GLDispatchTable gl_dispatch_table,
bool fbo_reset_after_present,
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder)
: gl_dispatch_table_(std::move(gl_dispatch_table)),
fbo_reset_after_present_(fbo_reset_after_present),
external_view_embedder_(std::move(external_view_embedder)),
worker_(std::make_shared<ReactorWorker>()) {
// Make sure all required members of the dispatch table are checked.
if (!gl_dispatch_table_.gl_make_current_callback ||
!gl_dispatch_table_.gl_clear_current_callback ||
!gl_dispatch_table_.gl_present_callback ||
!gl_dispatch_table_.gl_fbo_callback ||
!gl_dispatch_table_.gl_populate_existing_damage ||
!gl_dispatch_table_.gl_proc_resolver) {
return;
}
// Certain GL backends need to made current before any GL
// state can be accessed.
gl_dispatch_table_.gl_make_current_callback();
std::vector<std::shared_ptr<fml::Mapping>> shader_mappings = {
std::make_shared<fml::NonOwnedMapping>(
impeller_entity_shaders_gles_data,
impeller_entity_shaders_gles_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_modern_shaders_gles_data,
impeller_modern_shaders_gles_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_framebuffer_blend_shaders_gles_data,
impeller_framebuffer_blend_shaders_gles_length),
#if IMPELLER_ENABLE_3D
std::make_shared<fml::NonOwnedMapping>(
impeller_scene_shaders_gles_data, impeller_scene_shaders_gles_length),
#endif // IMPELLER_ENABLE_3D
};
auto gl = std::make_unique<impeller::ProcTableGLES>(
gl_dispatch_table_.gl_proc_resolver);
if (!gl->IsValid()) {
return;
}
impeller_context_ = impeller::ContextGLES::Create(
std::move(gl), shader_mappings, /*enable_gpu_tracing=*/false);
if (!impeller_context_) {
FML_LOG(ERROR) << "Could not create Impeller context.";
return;
}
auto worker_id = impeller_context_->AddReactorWorker(worker_);
if (!worker_id.has_value()) {
FML_LOG(ERROR) << "Could not add reactor worker.";
return;
}
gl_dispatch_table_.gl_clear_current_callback();
FML_LOG(IMPORTANT) << "Using the Impeller rendering backend (OpenGL).";
valid_ = true;
}
EmbedderSurfaceGLImpeller::~EmbedderSurfaceGLImpeller() = default;
// |EmbedderSurface|
bool EmbedderSurfaceGLImpeller::IsValid() const {
return valid_;
}
// |GPUSurfaceGLDelegate|
std::unique_ptr<GLContextResult>
EmbedderSurfaceGLImpeller::GLContextMakeCurrent() {
worker_->SetReactionsAllowedOnCurrentThread(true);
return std::make_unique<GLContextDefaultResult>(
gl_dispatch_table_.gl_make_current_callback());
}
// |GPUSurfaceGLDelegate|
bool EmbedderSurfaceGLImpeller::GLContextClearCurrent() {
worker_->SetReactionsAllowedOnCurrentThread(false);
return gl_dispatch_table_.gl_clear_current_callback();
}
// |GPUSurfaceGLDelegate|
bool EmbedderSurfaceGLImpeller::GLContextPresent(
const GLPresentInfo& present_info) {
// Pass the present information to the embedder present callback.
return gl_dispatch_table_.gl_present_callback(present_info);
}
// |GPUSurfaceGLDelegate|
GLFBOInfo EmbedderSurfaceGLImpeller::GLContextFBO(
GLFrameInfo frame_info) const {
// Get the FBO ID using the gl_fbo_callback and then get exiting damage by
// passing that ID to the gl_populate_existing_damage.
return gl_dispatch_table_.gl_populate_existing_damage(
gl_dispatch_table_.gl_fbo_callback(frame_info));
}
// |GPUSurfaceGLDelegate|
bool EmbedderSurfaceGLImpeller::GLContextFBOResetAfterPresent() const {
return fbo_reset_after_present_;
}
// |GPUSurfaceGLDelegate|
SkMatrix EmbedderSurfaceGLImpeller::GLContextSurfaceTransformation() const {
auto callback = gl_dispatch_table_.gl_surface_transformation_callback;
if (!callback) {
SkMatrix matrix;
matrix.setIdentity();
return matrix;
}
return callback();
}
// |GPUSurfaceGLDelegate|
EmbedderSurfaceGL::GLProcResolver EmbedderSurfaceGLImpeller::GetGLProcResolver()
const {
return gl_dispatch_table_.gl_proc_resolver;
}
// |GPUSurfaceGLDelegate|
SurfaceFrame::FramebufferInfo
EmbedderSurfaceGLImpeller::GLContextFramebufferInfo() const {
// Enable partial repaint by default on the embedders.
auto info = SurfaceFrame::FramebufferInfo{};
info.supports_readback = true;
info.supports_partial_repaint =
gl_dispatch_table_.gl_populate_existing_damage != nullptr;
return info;
}
// |EmbedderSurface|
std::unique_ptr<Surface> EmbedderSurfaceGLImpeller::CreateGPUSurface() {
// Ensure that the GL context is current before creating the GPU surface.
// GPUSurfaceGLImpeller initialization will set up shader pipelines, and the
// current thread needs to be able to execute reactor operations.
GLContextMakeCurrent();
return std::make_unique<GPUSurfaceGLImpeller>(
this, // GPU surface GL delegate
impeller_context_, // Impeller context
!external_view_embedder_ // render to surface
);
}
// |EmbedderSurface|
std::shared_ptr<impeller::Context>
EmbedderSurfaceGLImpeller::CreateImpellerContext() const {
return impeller_context_;
}
// |EmbedderSurface|
sk_sp<GrDirectContext> EmbedderSurfaceGLImpeller::CreateResourceContext()
const {
if (gl_dispatch_table_.gl_make_resource_current_callback()) {
worker_->SetReactionsAllowedOnCurrentThread(true);
} else {
FML_DLOG(ERROR) << "Could not make the resource context current.";
worker_->SetReactionsAllowedOnCurrentThread(false);
}
return nullptr;
}
} // namespace flutter
| engine/shell/platform/embedder/embedder_surface_gl_impeller.cc/0 | {
"file_path": "engine/shell/platform/embedder/embedder_surface_gl_impeller.cc",
"repo_id": "engine",
"token_count": 2646
} | 337 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_FROZEN_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_FROZEN_H_
#include "flutter/shell/platform/embedder/embedder.h"
// NO CHANGES ARE PERMITTED TO THE STRUCTS IN THIS FILE.
//
// This file contains the subset of the embedder API that is "frozen".
// "Frozen" APIs are locked and must not be modified to guarantee
// forward and backward ABI compatibility. The order, type, and size
// of the struct members below must remain the same, and members must
// not be added nor removed.
//
// This file serves as a "golden test" for structs in embedder.h
// and contains a snapshot of the expected "frozen" API. Tests
// then verify that these structs match the actual embedder API.
namespace flutter {
namespace testing {
// New members must not be added to `FlutterTransformation`
// as it would break the ABI of `FlutterSemanticsNode`.
// See: https://github.com/flutter/flutter/issues/121176
typedef struct {
double scaleX;
double skewX;
double transX;
double skewY;
double scaleY;
double transY;
double pers0;
double pers1;
double pers2;
} FrozenFlutterTransformation;
// New members must not be added to `FlutterRect` as it would
// break the ABI of `FlutterSemanticsNode` and `FlutterDamage`.
// See: https://github.com/flutter/flutter/issues/121176
// See: https://github.com/flutter/flutter/issues/121347
typedef struct {
double left;
double top;
double right;
double bottom;
} FrozenFlutterRect;
// New members must not be added to `FlutterPoint` as it would
// break the ABI of `FlutterLayer`.
typedef struct {
double x;
double y;
} FrozenFlutterPoint;
// New members must not be added to `FlutterDamage` as it would
// break the ABI of `FlutterPresentInfo`.
typedef struct {
size_t struct_size;
size_t num_rects;
FrozenFlutterRect* damage;
} FrozenFlutterDamage;
// New members must not be added to `FlutterSemanticsNode`
// as it would break the ABI of `FlutterSemanticsUpdate`.
// See: https://github.com/flutter/flutter/issues/121176
typedef struct {
size_t struct_size;
int32_t id;
FlutterSemanticsFlag flags;
FlutterSemanticsAction actions;
int32_t text_selection_base;
int32_t text_selection_extent;
int32_t scroll_child_count;
int32_t scroll_index;
double scroll_position;
double scroll_extent_max;
double scroll_extent_min;
double elevation;
double thickness;
const char* label;
const char* hint;
const char* value;
const char* increased_value;
const char* decreased_value;
FlutterTextDirection text_direction;
FrozenFlutterRect rect;
FrozenFlutterTransformation transform;
size_t child_count;
const int32_t* children_in_traversal_order;
const int32_t* children_in_hit_test_order;
size_t custom_accessibility_actions_count;
const int32_t* custom_accessibility_actions;
FlutterPlatformViewIdentifier platform_view_id;
const char* tooltip;
} FrozenFlutterSemanticsNode;
// New members must not be added to `FlutterSemanticsCustomAction`
// as it would break the ABI of `FlutterSemanticsUpdate`.
// See: https://github.com/flutter/flutter/issues/121176
typedef struct {
size_t struct_size;
int32_t id;
FlutterSemanticsAction override_action;
const char* label;
const char* hint;
} FrozenFlutterSemanticsCustomAction;
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_FROZEN_H_
| engine/shell/platform/embedder/tests/embedder_frozen.h/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_frozen.h",
"repo_id": "engine",
"token_count": 1172
} | 338 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#include <cstring>
#include <string>
#include <utility>
#include <vector>
#include "embedder.h"
#include "embedder_engine.h"
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/shell/platform/embedder/tests/embedder_config_builder.h"
#include "flutter/shell/platform/embedder/tests/embedder_test.h"
#include "flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.h"
#include "flutter/shell/platform/embedder/tests/embedder_unittests_util.h"
#include "flutter/testing/testing.h"
// CREATE_NATIVE_ENTRY is leaky by design
// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape)
namespace flutter {
namespace testing {
using EmbedderTest = testing::EmbedderTest;
////////////////////////////////////////////////////////////////////////////////
// Notice: Other Vulkan unit tests exist in embedder_gl_unittests.cc.
// See https://github.com/flutter/flutter/issues/134322
////////////////////////////////////////////////////////////////////////////////
namespace {
struct VulkanProcInfo {
decltype(vkGetInstanceProcAddr)* get_instance_proc_addr = nullptr;
decltype(vkGetDeviceProcAddr)* get_device_proc_addr = nullptr;
decltype(vkQueueSubmit)* queue_submit_proc_addr = nullptr;
bool did_call_queue_submit = false;
};
static_assert(std::is_trivially_destructible_v<VulkanProcInfo>);
VulkanProcInfo g_vulkan_proc_info;
VkResult QueueSubmit(VkQueue queue,
uint32_t submitCount,
const VkSubmitInfo* pSubmits,
VkFence fence) {
FML_DCHECK(g_vulkan_proc_info.queue_submit_proc_addr != nullptr);
g_vulkan_proc_info.did_call_queue_submit = true;
return g_vulkan_proc_info.queue_submit_proc_addr(queue, submitCount, pSubmits,
fence);
}
template <size_t N>
int StrcmpFixed(const char* str1, const char (&str2)[N]) {
return strncmp(str1, str2, N - 1);
}
PFN_vkVoidFunction GetDeviceProcAddr(VkDevice device, const char* pName) {
FML_DCHECK(g_vulkan_proc_info.get_device_proc_addr != nullptr);
if (StrcmpFixed(pName, "vkQueueSubmit") == 0) {
g_vulkan_proc_info.queue_submit_proc_addr =
reinterpret_cast<decltype(vkQueueSubmit)*>(
g_vulkan_proc_info.get_device_proc_addr(device, pName));
return reinterpret_cast<PFN_vkVoidFunction>(QueueSubmit);
}
return g_vulkan_proc_info.get_device_proc_addr(device, pName);
}
PFN_vkVoidFunction GetInstanceProcAddr(VkInstance instance, const char* pName) {
FML_DCHECK(g_vulkan_proc_info.get_instance_proc_addr != nullptr);
if (StrcmpFixed(pName, "vkGetDeviceProcAddr") == 0) {
g_vulkan_proc_info.get_device_proc_addr =
reinterpret_cast<decltype(vkGetDeviceProcAddr)*>(
g_vulkan_proc_info.get_instance_proc_addr(instance, pName));
return reinterpret_cast<PFN_vkVoidFunction>(GetDeviceProcAddr);
}
return g_vulkan_proc_info.get_instance_proc_addr(instance, pName);
}
template <typename T, typename U>
struct CheckSameSignature : std::false_type {};
template <typename Ret, typename... Args>
struct CheckSameSignature<Ret(Args...), Ret(Args...)> : std::true_type {};
static_assert(CheckSameSignature<decltype(GetInstanceProcAddr),
decltype(vkGetInstanceProcAddr)>::value);
static_assert(CheckSameSignature<decltype(GetDeviceProcAddr),
decltype(vkGetDeviceProcAddr)>::value);
static_assert(
CheckSameSignature<decltype(QueueSubmit), decltype(vkQueueSubmit)>::value);
} // namespace
TEST_F(EmbedderTest, CanSwapOutVulkanCalls) {
auto& context = GetEmbedderContext(EmbedderTestContextType::kVulkanContext);
fml::AutoResetWaitableEvent latch;
context.AddIsolateCreateCallback([&latch]() { latch.Signal(); });
EmbedderConfigBuilder builder(context);
builder.SetVulkanRendererConfig(
SkISize::Make(1024, 1024),
[](void* user_data, FlutterVulkanInstanceHandle instance,
const char* name) -> void* {
if (StrcmpFixed(name, "vkGetInstanceProcAddr") == 0) {
g_vulkan_proc_info.get_instance_proc_addr =
reinterpret_cast<decltype(vkGetInstanceProcAddr)*>(
EmbedderTestContextVulkan::InstanceProcAddr(user_data,
instance, name));
return reinterpret_cast<void*>(GetInstanceProcAddr);
}
return EmbedderTestContextVulkan::InstanceProcAddr(user_data, instance,
name);
});
auto engine = builder.LaunchEngine();
ASSERT_TRUE(engine.is_valid());
// Wait for the root isolate to launch.
latch.Wait();
engine.reset();
EXPECT_TRUE(g_vulkan_proc_info.did_call_queue_submit);
}
} // namespace testing
} // namespace flutter
// NOLINTEND(clang-analyzer-core.StackAddressEscape)
| engine/shell/platform/embedder/tests/embedder_vk_unittests.cc/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_vk_unittests.cc",
"repo_id": "engine",
"token_count": 2049
} | 339 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of zircon;
// ignore_for_file: native_function_body_in_non_sdk_code
// ignore_for_file: public_member_api_docs
typedef AsyncWaitCallback = void Function(int status, int pending);
@pragma('vm:entry-point')
base class HandleWaiter extends NativeFieldWrapperClass1 {
// Private constructor.
@pragma('vm:entry-point')
HandleWaiter._();
@pragma('vm:external-name', 'HandleWaiter_Cancel')
external void cancel();
}
| engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_waiter.dart/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_waiter.dart",
"repo_id": "engine",
"token_count": 188
} | 340 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_SYSTEM_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_SYSTEM_H_
#include <zircon/syscalls.h>
#include "handle.h"
#include "handle_disposition.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 {
class System : public fml::RefCountedThreadSafe<System>,
public tonic::DartWrappable {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_REF_COUNTED_THREAD_SAFE(System);
FML_FRIEND_MAKE_REF_COUNTED(System);
public:
static Dart_Handle ChannelCreate(uint32_t options);
static Dart_Handle ChannelFromFile(std::string path);
static zx_status_t ChannelWrite(fml::RefPtr<Handle> channel,
const tonic::DartByteData& data,
std::vector<Handle*> handles);
static zx_status_t ChannelWriteEtc(
fml::RefPtr<Handle> channel,
const tonic::DartByteData& data,
std::vector<HandleDisposition*> handle_dispositions);
// TODO(ianloic): Add ChannelRead
static Dart_Handle ChannelQueryAndRead(fml::RefPtr<Handle> channel);
static Dart_Handle ChannelQueryAndReadEtc(fml::RefPtr<Handle> channel);
static Dart_Handle EventpairCreate(uint32_t options);
static Dart_Handle SocketCreate(uint32_t options);
static Dart_Handle SocketWrite(fml::RefPtr<Handle> socket,
const tonic::DartByteData& data,
int options);
static Dart_Handle SocketRead(fml::RefPtr<Handle> socket, size_t size);
static Dart_Handle VmoCreate(uint64_t size, uint32_t options);
static Dart_Handle VmoFromFile(std::string path);
static Dart_Handle VmoGetSize(fml::RefPtr<Handle> vmo);
static zx_status_t VmoSetSize(fml::RefPtr<Handle> vmo, uint64_t size);
static zx_status_t VmoWrite(fml::RefPtr<Handle> vmo,
uint64_t offset,
const tonic::DartByteData& data);
static Dart_Handle VmoRead(fml::RefPtr<Handle> vmo,
uint64_t offset,
size_t size);
static Dart_Handle VmoMap(fml::RefPtr<Handle> vmo);
static uint64_t ClockGetMonotonic();
static void RegisterNatives(tonic::DartLibraryNatives* natives);
static zx_status_t ConnectToService(std::string path,
fml::RefPtr<Handle> channel);
private:
static void VmoMapFinalizer(void* isolate_callback_data, void* peer);
};
} // namespace dart
} // namespace zircon
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_SYSTEM_H_
| engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h",
"repo_id": "engine",
"token_count": 1249
} | 341 |
name: zircon_ffi
environment:
sdk: '>=3.2.0-0 <4.0.0'
dependencies:
ffi: ^1.0.0
dev_dependencies:
ffigen: ^3.0.0
lints: ^1.0.1
ffigen:
name: ZirconFFIBindings
description: Bindings for `dart:zircon_ffi`.
output: 'lib/zircon_ffi.dart'
headers:
entry-points:
- 'basic_types.h'
- 'channel.h'
- 'clock.h'
- 'dart_dl.h'
- 'handle.h'
functions:
include:
- 'zircon_dart_.*'
macros:
include:
- nothing
enums:
include:
- nothing
unnamed-enums:
include:
- nothing
globals:
include:
- nothing
structs:
include:
- 'zircon_dart_.*'
dependency-only: opaque
compiler-opts:
- '-I../../../../../../third_party/dart/runtime'
| engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/pubspec.yaml/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/pubspec.yaml",
"repo_id": "engine",
"token_count": 380
} | 342 |
# 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.
# The presence of this file is necessary in order to use the dart_library
# template in BUILD.gn.
environment:
sdk: '>=3.2.0-0 <4.0.0'
| engine/shell/platform/fuchsia/dart_runner/embedder/pubspec.yaml/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/embedder/pubspec.yaml",
"repo_id": "engine",
"token_count": 94
} | 343 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <dart/test/cpp/fidl.h>
#include <fuchsia/tracing/provider/cpp/fidl.h>
#include <lib/async-loop/testing/cpp/real_loop.h>
#include <lib/sys/component/cpp/testing/realm_builder.h>
#include <lib/sys/component/cpp/testing/realm_builder_types.h>
#include "flutter/fml/logging.h"
#include "gtest/gtest.h"
namespace dart_jit_runner_testing::testing {
namespace {
// Types imported for the realm_builder library
using component_testing::ChildOptions;
using component_testing::ChildRef;
using component_testing::Directory;
using component_testing::ParentRef;
using component_testing::Protocol;
using component_testing::RealmBuilder;
using component_testing::RealmRoot;
using component_testing::Route;
constexpr auto kDartRunnerEnvironment = "dart_runner_env";
constexpr auto kDartJitRunner = "dart_jit_runner";
constexpr auto kDartJitRunnerRef = ChildRef{kDartJitRunner};
constexpr auto kDartJitRunnerUrl =
"fuchsia-pkg://fuchsia.com/oot_dart_jit_runner#meta/"
"dart_jit_runner.cm";
constexpr auto kDartJitEchoServer = "dart_jit_echo_server";
constexpr auto kDartJitEchoServerRef = ChildRef{kDartJitEchoServer};
constexpr auto kDartJitEchoServerUrl =
"fuchsia-pkg://fuchsia.com/dart_jit_echo_server#meta/"
"dart_jit_echo_server.cm";
class RealmBuilderTest : public ::loop_fixture::RealLoop,
public ::testing::Test {
public:
RealmBuilderTest() = default;
};
TEST_F(RealmBuilderTest, DartRunnerStartsUp) {
auto realm_builder = RealmBuilder::Create();
// Add Dart JIT runner as a child of RealmBuilder
realm_builder.AddChild(kDartJitRunner, kDartJitRunnerUrl);
// Add environment providing the Dart JIT runner
fuchsia::component::decl::Environment dart_runner_environment;
dart_runner_environment.set_name(kDartRunnerEnvironment);
dart_runner_environment.set_extends(
fuchsia::component::decl::EnvironmentExtends::REALM);
dart_runner_environment.set_runners({});
auto environment_runners = dart_runner_environment.mutable_runners();
fuchsia::component::decl::RunnerRegistration dart_jit_runner_reg;
dart_jit_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild(
fuchsia::component::decl::ChildRef{.name = kDartJitRunner}));
dart_jit_runner_reg.set_source_name(kDartJitRunner);
dart_jit_runner_reg.set_target_name(kDartJitRunner);
environment_runners->push_back(std::move(dart_jit_runner_reg));
auto realm_decl = realm_builder.GetRealmDecl();
if (!realm_decl.has_environments()) {
realm_decl.set_environments({});
}
auto realm_environments = realm_decl.mutable_environments();
realm_environments->push_back(std::move(dart_runner_environment));
realm_builder.ReplaceRealmDecl(std::move(realm_decl));
// Add Dart server component as a child of Realm Builder
realm_builder.AddChild(kDartJitEchoServer, kDartJitEchoServerUrl,
ChildOptions{.environment = kDartRunnerEnvironment});
// Route base capabilities to the Dart JIT runner
realm_builder.AddRoute(
Route{.capabilities = {Protocol{"fuchsia.logger.LogSink"},
Protocol{"fuchsia.tracing.provider.Registry"},
Protocol{"fuchsia.posix.socket.Provider"},
Protocol{"fuchsia.intl.PropertyProvider"},
Protocol{"fuchsia.inspect.InspectSink"},
Directory{"config-data"}},
.source = ParentRef(),
.targets = {kDartJitRunnerRef, kDartJitEchoServerRef}});
// Route the Echo FIDL protocol, this allows the Dart echo server to
// communicate with the Realm Builder
realm_builder.AddRoute(Route{.capabilities = {Protocol{"dart.test.Echo"}},
.source = kDartJitEchoServerRef,
.targets = {ParentRef()}});
// Build the Realm with the provided child and protocols
auto realm = realm_builder.Build(dispatcher());
FML_LOG(INFO) << "Realm built: " << realm.component().GetChildName();
// Connect to the Dart echo server
auto echo = realm.component().ConnectSync<dart::test::Echo>();
fidl::StringPtr response;
// Attempt to ping the Dart echo server for a response
echo->EchoString("hello", &response);
ASSERT_EQ(response, "hello");
}
} // namespace
} // namespace dart_jit_runner_testing::testing
| engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/dart-jit-runner-integration-test.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/dart-jit-runner-integration-test.cc",
"repo_id": "engine",
"token_count": 1671
} | 344 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/fuchsia/flutter/canvas_spy.h"
#include "gtest/gtest.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace flutter {
namespace testing {
TEST(CanvasSpyTest, DrawingIsTracked) {
SkPictureRecorder picture_recorder;
SkCanvas* canvas = picture_recorder.beginRecording(100, 100);
CanvasSpy canvas_spy = CanvasSpy(canvas);
DlCanvas* spy = canvas_spy.GetSpyingCanvas();
ASSERT_FALSE(canvas_spy.DidDrawIntoCanvas());
spy->Translate(128, 128);
spy->Clear(DlColor::kTransparent());
ASSERT_FALSE(canvas_spy.DidDrawIntoCanvas());
DlPaint paint;
spy->DrawCircle({0, 0}, 60, paint);
ASSERT_TRUE(canvas_spy.DidDrawIntoCanvas());
}
TEST(CanvasSpyTest, SpiedCanvasIsDrawing) {
auto actual_surface =
SkSurfaces::Raster(SkImageInfo::MakeN32Premul(100, 100));
SkCanvas* actual_canvas = actual_surface->getCanvas();
auto expected_surface =
SkSurfaces::Raster(SkImageInfo::MakeN32Premul(100, 100));
SkCanvas* expected_canvas = expected_surface->getCanvas();
CanvasSpy canvas_spy = CanvasSpy(actual_canvas);
SkCanvas* spy = canvas_spy.GetRawSpyingCanvas();
SkNWayCanvas multi_canvas = SkNWayCanvas(100, 100);
multi_canvas.addCanvas(spy);
multi_canvas.addCanvas(expected_canvas);
multi_canvas.clipRect(SkRect::MakeWH(100, 100));
multi_canvas.clear(SK_ColorRED);
multi_canvas.scale(.5, .5);
multi_canvas.clipRect(SkRect::MakeWH(100, 100));
multi_canvas.clear(SK_ColorBLUE);
ASSERT_TRUE(canvas_spy.DidDrawIntoCanvas());
SkPixmap actual;
SkPixmap expected;
ASSERT_TRUE(actual_surface->peekPixels(&actual));
ASSERT_TRUE(expected_surface->peekPixels(&expected));
const auto size = actual.rowBytes() * actual.height();
ASSERT_NE(size, 0u);
ASSERT_EQ(::memcmp(actual.addr(), expected.addr(), size), 0);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/fuchsia/flutter/canvas_spy_unittests.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/canvas_spy_unittests.cc",
"repo_id": "engine",
"token_count": 783
} | 345 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FOCUS_DELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FOCUS_DELEGATE_H_
#include <fuchsia/ui/views/cpp/fidl.h>
#include <unordered_map>
#include "flutter/fml/macros.h"
#include "flutter/lib/ui/window/platform_message.h"
#include "third_party/rapidjson/include/rapidjson/document.h"
namespace flutter_runner {
class FocusDelegate {
public:
FocusDelegate(fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused,
fuchsia::ui::views::FocuserHandle focuser)
: view_ref_focused_(view_ref_focused.Bind()), focuser_(focuser.Bind()) {}
/// Continuously watches the host viewRef for focus events, invoking a
/// callback each time.
///
/// The callback is invoked on each Watch() call, which consumes the callback
/// argument. Hence, the callback argument must be copyable, so that a copy
/// can be freely moved into the Watch() call.
///
/// This method can only be called once.
void WatchLoop(std::function<void(bool)> callback);
/// Handles the following focus-related platform message requests:
/// View.focus.getCurrent
/// - Completes with the FocusDelegate's most recent focus state, either
/// [true] or [false].
/// View.focus.getNext
/// - Completes with the FocusDelegate's next focus state, either [true] or
/// [false].
/// - Only one outstanding request may exist at a time. Any others will be
/// completed with [null].
/// View.focus.request
/// - Attempts to give focus for a given viewRef. Completes with [0] on
/// success, or [fuchsia::ui::views::Error] on failure.
///
/// Returns false if a malformed/invalid request needs to be completed empty.
bool HandlePlatformMessage(
rapidjson::Value request,
fml::RefPtr<flutter::PlatformMessageResponse> response);
void OnChildViewViewRef(uint64_t view_id,
fuchsia::ui::views::ViewRef view_ref);
void OnDisposeChildView(uint64_t view_id);
private:
fuchsia::ui::views::ViewRefFocusedPtr view_ref_focused_;
fuchsia::ui::views::FocuserPtr focuser_;
std::unordered_map<uint64_t /*fuchsia::ui::composition::ContentId*/,
fuchsia::ui::views::ViewRef>
child_view_view_refs_;
std::function<void(fuchsia::ui::views::FocusState)> watch_loop_;
bool is_focused_ = false;
fml::RefPtr<flutter::PlatformMessageResponse> next_focus_request_;
void Complete(fml::RefPtr<flutter::PlatformMessageResponse> response,
std::string value);
/// Completes a platform message request by attempting to give focus for a
/// given view.
bool RequestFocusById(uint64_t view_id,
fml::RefPtr<flutter::PlatformMessageResponse> response);
bool RequestFocusByViewRef(
fuchsia::ui::views::ViewRef view_ref,
fml::RefPtr<flutter::PlatformMessageResponse> response);
FML_DISALLOW_COPY_AND_ASSIGN(FocusDelegate);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FOCUS_DELEGATE_H_
| engine/shell/platform/fuchsia/flutter/focus_delegate.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/focus_delegate.h",
"repo_id": "engine",
"token_count": 1141
} | 346 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_LOGGING_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_LOGGING_H_
#include "flutter/fml/logging.h"
namespace flutter_runner {
// Use to mark logs published via the syslog API.
#define LOG_TAG "flutter-runner"
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_LOGGING_H_
| engine/shell/platform/fuchsia/flutter/logging.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/logging.h",
"repo_id": "engine",
"token_count": 194
} | 347 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_PROGRAM_METADATA_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_PROGRAM_METADATA_H_
#include <optional>
#include <string>
namespace flutter_runner {
/// The metadata that can be passed by a Flutter component via
/// the `program` field.
struct ProgramMetadata {
/// The path where data for the Flutter component should
/// be stored.
std::string data_path = "";
/// The path where assets for the Flutter component should
/// be stored.
///
/// TODO(fxb/89246): No components appear to be using this field. We
/// may be able to get rid of this.
std::string assets_path = "";
/// The preferred heap size for the Flutter component in megabytes.
std::optional<int64_t> old_gen_heap_size = std::nullopt;
/// A list of additional directories that we will expose in out/
std::vector<std::string> expose_dirs;
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_PROGRAM_METADATA_H_
| engine/shell/platform/fuchsia/flutter/program_metadata.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/program_metadata.h",
"repo_id": "engine",
"token_count": 377
} | 348 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TASK_RUNNER_ADAPTER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TASK_RUNNER_ADAPTER_H_
#include <lib/async/dispatcher.h>
#include "flutter/fml/task_runner.h"
namespace flutter_runner {
fml::RefPtr<fml::TaskRunner> CreateFMLTaskRunner(
async_dispatcher_t* dispatcher);
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TASK_RUNNER_ADAPTER_H_
| engine/shell/platform/fuchsia/flutter/task_runner_adapter.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/task_runner_adapter.h",
"repo_id": "engine",
"token_count": 237
} | 349 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/fuchsia/flutter/flatland_connection.h"
#include <fuchsia/scenic/scheduling/cpp/fidl.h>
#include <fuchsia/ui/composition/cpp/fidl.h>
#include <lib/async-testing/test_loop.h>
#include <lib/async/cpp/task.h>
#include <string>
#include <vector>
#include "flutter/fml/logging.h"
#include "flutter/fml/time/time_delta.h"
#include "flutter/fml/time/time_point.h"
#include "gtest/gtest.h"
#include "fakes/scenic/fake_flatland.h"
namespace flutter_runner::testing {
namespace {
std::string GetCurrentTestName() {
return ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
void AwaitVsyncChecked(FlatlandConnection& flatland_connection,
bool& condition_variable,
fml::TimeDelta expected_frame_delta) {
flatland_connection.AwaitVsync(
[&condition_variable,
expected_frame_delta = std::move(expected_frame_delta)](
fml::TimePoint frame_start, fml::TimePoint frame_end) {
EXPECT_EQ(frame_end.ToEpochDelta() - frame_start.ToEpochDelta(),
expected_frame_delta);
condition_variable = true;
});
}
void AwaitVsyncChecked(FlatlandConnection& flatland_connection,
bool& condition_variable,
fml::TimePoint expected_frame_end) {
flatland_connection.AwaitVsync(
[&condition_variable, expected_frame_end = std::move(expected_frame_end)](
fml::TimePoint frame_start, fml::TimePoint frame_end) {
EXPECT_EQ(frame_end, expected_frame_end);
condition_variable = true;
});
}
std::vector<fuchsia::scenic::scheduling::PresentationInfo>
CreateFuturePresentationInfos(const fml::TimePoint& presentation_time_1,
const fml::TimePoint& presentation_time_2) {
fuchsia::scenic::scheduling::PresentationInfo info_1;
info_1.set_presentation_time(
presentation_time_1.ToEpochDelta().ToNanoseconds());
std::vector<fuchsia::scenic::scheduling::PresentationInfo> infos;
infos.push_back(std::move(info_1));
fuchsia::scenic::scheduling::PresentationInfo info_2;
info_2.set_presentation_time(
presentation_time_2.ToEpochDelta().ToNanoseconds());
infos.push_back(std::move(info_2));
return infos;
}
} // namespace
class FlatlandConnectionTest : public ::testing::Test {
protected:
FlatlandConnectionTest()
: session_subloop_(loop_.StartNewLoop()),
flatland_handle_(
fake_flatland_.ConnectFlatland(session_subloop_->dispatcher())) {}
~FlatlandConnectionTest() override = default;
async::TestLoop& loop() { return loop_; }
FakeFlatland& fake_flatland() { return fake_flatland_; }
fidl::InterfaceHandle<fuchsia::ui::composition::Flatland>
TakeFlatlandHandle() {
FML_CHECK(flatland_handle_.is_valid());
return std::move(flatland_handle_);
}
// Syntactic sugar for OnNextFrameBegin
void OnNextFrameBegin(int num_present_credits,
const fml::TimePoint& presentation_time_1,
const fml::TimePoint& presentation_time_2) {
fuchsia::ui::composition::OnNextFrameBeginValues on_next_frame_begin_values;
on_next_frame_begin_values.set_additional_present_credits(
num_present_credits);
on_next_frame_begin_values.set_future_presentation_infos(
CreateFuturePresentationInfos(presentation_time_1,
presentation_time_2));
fake_flatland().FireOnNextFrameBeginEvent(
std::move(on_next_frame_begin_values));
}
void OnNextFrameBegin(int num_present_credits) {
const auto now = fml::TimePoint::Now();
const auto kPresentationTime1 = now + fml::TimeDelta::FromSeconds(100);
const auto kPresentationTime2 = now + fml::TimeDelta::FromSeconds(200);
OnNextFrameBegin(num_present_credits, kPresentationTime1,
kPresentationTime2);
}
private:
async::TestLoop loop_;
std::unique_ptr<async::LoopInterface> session_subloop_;
FakeFlatland fake_flatland_;
fidl::InterfaceHandle<fuchsia::ui::composition::Flatland> flatland_handle_;
};
TEST_F(FlatlandConnectionTest, Initialization) {
// Create the FlatlandConnection but don't pump the loop. No FIDL calls are
// completed yet.
const std::string debug_name = GetCurrentTestName();
flutter_runner::FlatlandConnection flatland_connection(
debug_name, TakeFlatlandHandle(), []() { FAIL(); },
[](auto...) { FAIL(); });
EXPECT_EQ(fake_flatland().debug_name(), "");
// Simulate an AwaitVsync that returns immediately.
bool await_vsync_fired = false;
AwaitVsyncChecked(flatland_connection, await_vsync_fired,
kInitialFlatlandVsyncOffset);
EXPECT_TRUE(await_vsync_fired);
// Ensure the debug name is set.
loop().RunUntilIdle();
EXPECT_EQ(fake_flatland().debug_name(), debug_name);
}
TEST_F(FlatlandConnectionTest, FlatlandDisconnect) {
// Set up a callback which allows sensing of the error state.
bool error_fired = false;
fml::closure on_session_error = [&error_fired]() { error_fired = true; };
// Create the FlatlandConnection but don't pump the loop. No FIDL calls are
// completed yet.
flutter_runner::FlatlandConnection flatland_connection(
GetCurrentTestName(), TakeFlatlandHandle(), std::move(on_session_error),
[](auto...) { FAIL(); });
EXPECT_FALSE(error_fired);
// Simulate a flatland disconnection, then Pump the loop. The error callback
// will fire.
fake_flatland().Disconnect(
fuchsia::ui::composition::FlatlandError::BAD_OPERATION);
loop().RunUntilIdle();
EXPECT_TRUE(error_fired);
}
TEST_F(FlatlandConnectionTest, BasicPresent) {
// Set up callbacks which allow sensing of how many presents were handled.
size_t presents_called = 0u;
zx_handle_t release_fence_handle;
fake_flatland().SetPresentHandler([&presents_called,
&release_fence_handle](auto present_args) {
presents_called++;
release_fence_handle = present_args.release_fences().empty()
? ZX_HANDLE_INVALID
: present_args.release_fences().front().get();
});
// Set up a callback which allows sensing of how many vsync's
// (`OnFramePresented` events) were handled.
size_t vsyncs_handled = 0u;
on_frame_presented_event on_frame_presented = [&vsyncs_handled](auto...) {
vsyncs_handled++;
};
// Create the FlatlandConnection but don't pump the loop. No FIDL calls are
// completed yet.
flutter_runner::FlatlandConnection flatland_connection(
GetCurrentTestName(), TakeFlatlandHandle(), []() { FAIL(); },
std::move(on_frame_presented));
EXPECT_EQ(presents_called, 0u);
EXPECT_EQ(vsyncs_handled, 0u);
// Pump the loop. Nothing is called.
loop().RunUntilIdle();
EXPECT_EQ(presents_called, 0u);
EXPECT_EQ(vsyncs_handled, 0u);
// Simulate an AwaitVsync that comes after the first call.
bool await_vsync_fired = false;
AwaitVsyncChecked(flatland_connection, await_vsync_fired,
kInitialFlatlandVsyncOffset);
EXPECT_TRUE(await_vsync_fired);
// Call Present and Pump the loop; `Present` and its callback is called. No
// release fence should be queued.
await_vsync_fired = false;
zx::event first_release_fence;
zx::event::create(0, &first_release_fence);
const zx_handle_t first_release_fence_handle = first_release_fence.get();
flatland_connection.EnqueueReleaseFence(std::move(first_release_fence));
flatland_connection.Present();
loop().RunUntilIdle();
EXPECT_EQ(presents_called, 1u);
EXPECT_EQ(release_fence_handle, ZX_HANDLE_INVALID);
EXPECT_EQ(vsyncs_handled, 0u);
EXPECT_FALSE(await_vsync_fired);
// Fire the `OnNextFrameBegin` event. AwaitVsync should be fired.
const auto now = fml::TimePoint::Now();
const auto kPresentationTime1 = now + fml::TimeDelta::FromSeconds(100);
const auto kPresentationTime2 = now + fml::TimeDelta::FromSeconds(200);
fuchsia::ui::composition::OnNextFrameBeginValues on_next_frame_begin_values;
on_next_frame_begin_values.set_additional_present_credits(3);
on_next_frame_begin_values.set_future_presentation_infos(
CreateFuturePresentationInfos(kPresentationTime1, kPresentationTime2));
fake_flatland().FireOnNextFrameBeginEvent(
std::move(on_next_frame_begin_values));
loop().RunUntilIdle();
AwaitVsyncChecked(flatland_connection, await_vsync_fired, kPresentationTime1);
EXPECT_TRUE(await_vsync_fired);
// Fire the `OnFramePresented` event associated with the first `Present`,
fake_flatland().FireOnFramePresentedEvent(
fuchsia::scenic::scheduling::FramePresentedInfo());
loop().RunUntilIdle();
EXPECT_EQ(vsyncs_handled, 1u);
// Call Present for a second time and Pump the loop; `Present` and its
// callback is called. Release fences for the earlier present is used.
await_vsync_fired = false;
flatland_connection.Present();
loop().RunUntilIdle();
EXPECT_EQ(presents_called, 2u);
EXPECT_EQ(release_fence_handle, first_release_fence_handle);
// AwaitVsync should be fired with the second present.
await_vsync_fired = false;
AwaitVsyncChecked(flatland_connection, await_vsync_fired, kPresentationTime2);
EXPECT_TRUE(await_vsync_fired);
}
TEST_F(FlatlandConnectionTest, AwaitVsyncsBeforeOnNextFrameBegin) {
// Set up callbacks which allow sensing of how many presents were handled.
size_t presents_called = 0u;
fake_flatland().SetPresentHandler(
[&presents_called](auto present_args) { presents_called++; });
// Create the FlatlandConnection but don't pump the loop. No FIDL calls are
// completed yet.
flutter_runner::FlatlandConnection flatland_connection(
GetCurrentTestName(), TakeFlatlandHandle(), []() { FAIL(); },
[](auto...) {});
EXPECT_EQ(presents_called, 0u);
// Pump the loop. Nothing is called.
loop().RunUntilIdle();
EXPECT_EQ(presents_called, 0u);
// Simulate an AwaitVsync that comes before the first Present.
bool await_vsync_callback_fired = false;
AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired,
kInitialFlatlandVsyncOffset);
EXPECT_TRUE(await_vsync_callback_fired);
// AwaitVsync that comes before the first Present.
bool await_vsync_secondary_callback_fired = false;
flatland_connection.AwaitVsyncForSecondaryCallback(
[&await_vsync_secondary_callback_fired](fml::TimePoint frame_start,
fml::TimePoint frame_end) {
await_vsync_secondary_callback_fired = true;
});
EXPECT_TRUE(await_vsync_secondary_callback_fired);
}
TEST_F(FlatlandConnectionTest, RunsOutOfFuturePresentationInfos) {
// Set up callbacks which allow sensing of how many presents were handled.
size_t presents_called = 0u;
fake_flatland().SetPresentHandler(
[&presents_called](auto present_args) { presents_called++; });
// Set up a callback which allows sensing of how many vsync's
// (`OnFramePresented` events) were handled.
size_t vsyncs_handled = 0u;
on_frame_presented_event on_frame_presented = [&vsyncs_handled](auto...) {
vsyncs_handled++;
};
// Create the FlatlandConnection but don't pump the loop. No FIDL calls are
// completed yet.
flutter_runner::FlatlandConnection flatland_connection(
GetCurrentTestName(), TakeFlatlandHandle(), []() { FAIL(); },
std::move(on_frame_presented));
EXPECT_EQ(presents_called, 0u);
EXPECT_EQ(vsyncs_handled, 0u);
// Pump the loop. Nothing is called.
loop().RunUntilIdle();
EXPECT_EQ(presents_called, 0u);
EXPECT_EQ(vsyncs_handled, 0u);
// Simulate an AwaitVsync that comes before the first Present.
bool await_vsync_callback_fired = false;
AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired,
kInitialFlatlandVsyncOffset);
EXPECT_TRUE(await_vsync_callback_fired);
// Queue Present.
flatland_connection.Present();
loop().RunUntilIdle();
EXPECT_EQ(presents_called, 1u);
// Fire the `OnNextFrameBegin` event. AwaitVsync callback should be fired with
// the first presentation time.
await_vsync_callback_fired = false;
const auto kPresentationTime1 =
fml::TimePoint::Now() + fml::TimeDelta::FromSeconds(123);
const auto kVsyncInterval = fml::TimeDelta::FromSeconds(234);
const auto kPresentationTime2 = kPresentationTime1 + kVsyncInterval;
OnNextFrameBegin(1, kPresentationTime1, kPresentationTime2);
loop().RunUntilIdle();
AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired,
kPresentationTime1);
EXPECT_TRUE(await_vsync_callback_fired);
// Second consecutive AwaitVsync callback should be fired with
// the second presentation time.
await_vsync_callback_fired = false;
AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired,
kPresentationTime2);
EXPECT_TRUE(await_vsync_callback_fired);
// Another AwaitVsync callback should be fired with vsync_interval.
await_vsync_callback_fired = false;
AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired,
kPresentationTime2 + kVsyncInterval);
EXPECT_TRUE(await_vsync_callback_fired);
}
TEST_F(FlatlandConnectionTest, PresentCreditExhaustion) {
// Set up callbacks which allow sensing of how many presents were handled.
size_t num_presents_called = 0u;
size_t num_release_fences = 0u;
size_t num_acquire_fences = 0u;
auto reset_test_counters = [&num_presents_called, &num_acquire_fences,
&num_release_fences]() {
num_presents_called = 0u;
num_release_fences = 0u;
num_acquire_fences = 0u;
};
fake_flatland().SetPresentHandler(
[&num_presents_called, &num_acquire_fences, &num_release_fences](
fuchsia::ui::composition::PresentArgs present_args) {
num_presents_called++;
num_acquire_fences = present_args.acquire_fences().size();
num_release_fences = present_args.release_fences().size();
});
// Create the FlatlandConnection but don't pump the loop. No FIDL calls are
// completed yet.
on_frame_presented_event on_frame_presented = [](auto...) {};
flutter_runner::FlatlandConnection flatland_connection(
GetCurrentTestName(), TakeFlatlandHandle(), []() { FAIL(); },
std::move(on_frame_presented));
EXPECT_EQ(num_presents_called, 0u);
// Pump the loop. Nothing is called.
loop().RunUntilIdle();
EXPECT_EQ(num_presents_called, 0u);
// Simulate an AwaitVsync that comes before the first Present.
flatland_connection.AwaitVsync([](fml::TimePoint, fml::TimePoint) {});
loop().RunUntilIdle();
EXPECT_EQ(num_presents_called, 0u);
// This test uses a fire callback that triggers Present() with a single
// acquire and release fence in order to approximate the behavior of the real
// flutter fire callback and let us drive presents with ONFBs
auto fire_callback = [dispatcher = loop().dispatcher(), &flatland_connection](
fml::TimePoint frame_start,
fml::TimePoint frame_end) {
async::PostTask(dispatcher, [&flatland_connection]() {
zx::event acquire_fence;
zx::event::create(0, &acquire_fence);
zx::event release_fence;
zx::event::create(0, &release_fence);
flatland_connection.EnqueueAcquireFence(std::move(acquire_fence));
flatland_connection.EnqueueReleaseFence(std::move(release_fence));
flatland_connection.Present();
});
};
// Call Await Vsync with a callback that triggers Present and consumes the one
// and only present credit we start with.
reset_test_counters();
flatland_connection.AwaitVsync(fire_callback);
loop().RunUntilIdle();
EXPECT_EQ(num_presents_called, 1u);
EXPECT_EQ(num_acquire_fences, 1u);
EXPECT_EQ(num_release_fences, 0u);
// Do it again, but this time we should not get a present because the client
// has exhausted its present credits.
reset_test_counters();
flatland_connection.AwaitVsync(fire_callback);
OnNextFrameBegin(0);
loop().RunUntilIdle();
EXPECT_EQ(num_presents_called, 0u);
// Supply a present credit but dont set a new fire callback. Fire callback
// from previous ONFB should fire and trigger a Present()
reset_test_counters();
OnNextFrameBegin(1);
loop().RunUntilIdle();
EXPECT_EQ(num_presents_called, 1u);
EXPECT_EQ(num_acquire_fences, 1u);
EXPECT_EQ(num_release_fences, 1u);
// From here on we are testing handling of a race condition where a fire
// callback is fired but another ONFB arrives before the present from the
// first fire callback comes in, causing present_credits to be negative
// within Present().
uint num_onfb = 5;
uint num_deferred_callbacks = 0;
// This callback will accumulate num_onfb+1 calls before firing all
// of their presents at once.
auto accumulating_fire_callback = [&](fml::TimePoint frame_start,
fml::TimePoint frame_end) {
num_deferred_callbacks++;
if (num_deferred_callbacks > num_onfb) {
fml::TimePoint now = fml::TimePoint::Now();
for (uint i = 0; i < num_onfb + 1; i++) {
fire_callback(now, now);
num_deferred_callbacks--;
}
}
};
reset_test_counters();
for (uint i = 0; i < num_onfb; i++) {
flatland_connection.AwaitVsync(accumulating_fire_callback);
// only supply a present credit on the first call. Since Presents are being
// deferred this credit will not be used up, but we need a credit to call
// the accumulating_fire_callback
OnNextFrameBegin(i == 0 ? 1 : 0);
loop().RunUntilIdle();
EXPECT_EQ(num_presents_called, 0u);
}
// This is the num_onfb+1 call to accumulating_fire_callback which triggers
// all of the "racing" presents to fire. the first one should be fired,
// but the other num_onfb Presents should be deferred.
flatland_connection.AwaitVsync(accumulating_fire_callback);
OnNextFrameBegin(0);
loop().RunUntilIdle();
EXPECT_EQ(num_presents_called, 1u);
EXPECT_EQ(num_acquire_fences, 1u);
EXPECT_EQ(num_release_fences, 1u);
// Supply a present credit, but pass an empty lambda to AwaitVsync so
// that it doesnt call Present(). Should get a deferred present with
// all the accumulate acuire fences
reset_test_counters();
flatland_connection.AwaitVsync([](fml::TimePoint, fml::TimePoint) {});
OnNextFrameBegin(1);
loop().RunUntilIdle();
EXPECT_EQ(num_presents_called, 1u);
EXPECT_EQ(num_acquire_fences, num_onfb);
EXPECT_EQ(num_release_fences, 1u);
// Pump another frame to check that release fences accumulate as expected
reset_test_counters();
flatland_connection.AwaitVsync(fire_callback);
OnNextFrameBegin(1);
loop().RunUntilIdle();
EXPECT_EQ(num_presents_called, 1u);
EXPECT_EQ(num_acquire_fences, 1u);
EXPECT_EQ(num_release_fences, num_onfb);
}
} // namespace flutter_runner::testing
| engine/shell/platform/fuchsia/flutter/tests/flatland_connection_unittests.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/flatland_connection_unittests.cc",
"repo_id": "engine",
"token_count": 7082
} | 350 |
# mouse-input
`mouse-input-test` exercises mouse input through a child view (in this case, the `mouse-input-view` Dart component) and
asserting the location as well as what button was used (mouse down, mouse up, wheel, etc) during the event. We do this by
attaching the child view, injecting mouse input, and validating that the view reports the event back with the expected
payload.
```shell
Injecting the mouse input
[mouse-input-test.cm] INFO: [portable_ui_test.cc(227)] Injecting mouse input
View receives the event
[flutter_jit_runner] INFO: mouse-input-view.cm(flutter): mouse-input-view received input: PointerData(embedderId: 0, timeStamp: 23:18:05.031003, change: PointerChange.add, kind: PointerDeviceKind.mouse, signalKind: PointerSignalKind.none, device: 4294967295, pointerIdentifier: 0, physicalX: 641.4656372070312, physicalY: 402.9313049316406, physicalDeltaX: 0.0, physicalDeltaY: 0.0, buttons: 0, synthesized: true, pressure: 0.0, pressureMin: 0.0, pressureMax: 0.0, distance: 0.0, distanceMax: 0.0, size: 0.0, radiusMajor: 0.0, radiusMinor: 0.0, radiusMin: 0.0, radiusMax: 0.0, orientation: 0.0, tilt: 0.0, platformData: 0, scrollDeltaX: 0.0, scrollDeltaY: 0.0, panX: 0.0, panY: 0.0, panDeltaX: 0.0, panDeltaY: 0.0, scale: 0.0, rotation: 0.0)
Successfully received response from view
[mouse-input-test.cm] INFO: [mouse-input-test.cc(120)] Received MouseInput event
[mouse-input-test.cm] INFO: [mouse-input-test.cc(207)] Client received mouse change at (641.466, 402.931) with buttons 0.
[mouse-input-test.cm] INFO: [mouse-input-test.cc(211)] Expected mouse change is at approximately (641, 402) with buttons 0.
```
## Running the Test
Reference the Flutter integration test [documentation](https://github.com/flutter/engine/blob/main/shell/platform/fuchsia/flutter/tests/integration/README.md) at `//flutter/shell/platform/fuchsia/flutter/tests/integration/README.md`
## Playing around with `mouse-input-view`
Build Fuchsia with `terminal.qemu-x64`
```shell
fx set terminal.qemu-x64 && fx build
```
Build flutter/engine
```shell
$ENGINE_DIR/flutter/tools/gn --fuchsia --no-lto && ninja -C $ENGINE_DIR/out/fuchsia_debug_x64 flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input:tests
```
Start a Fuchsia package server
```shell
cd "$FUCHSIA_DIR"
fx serve
```
Publish `mouse-input-view`
```shell
$FUCHSIA_DIR/.jiri_root/bin/fx pm publish -a -repo $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files -f $ENGINE_DIR/out/fuchsia_debug_x64/gen/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/mouse-input-view/mouse-input-view.far
```
Launch Fuchsia emulator in a graphical environment
```shell
ffx emu start
```
**Before proceeding, make sure you have successfully completed the "Set a Password" screen**
Add `mouse-input-view`
```shell
ffx session add fuchsia-pkg://fuchsia.com/mouse-input-view#meta/mouse-input-view.cm
```
| engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/README.md/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/README.md",
"repo_id": "engine",
"token_count": 1019
} | 351 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/tools/fuchsia/dart/dart_library.gni")
import("//flutter/tools/fuchsia/flutter/flutter_component.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/component.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/package.gni")
dart_library("lib") {
package_name = "embedding-flutter-view"
sources = [ "embedding-flutter-view.dart" ]
deps = [
"//flutter/shell/platform/fuchsia/dart:args",
"//flutter/shell/platform/fuchsia/dart:vector_math",
]
}
flutter_component("component") {
testonly = true
component_name = "embedding-flutter-view"
manifest = rebase_path("meta/embedding-flutter-view.cml")
main_package = "embedding-flutter-view"
main_dart = "embedding-flutter-view.dart"
deps = [ ":lib" ]
}
fuchsia_package("package") {
testonly = true
package_name = "embedding-flutter-view"
deps = [ ":component" ]
}
| engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/BUILD.gn/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/BUILD.gn",
"repo_id": "engine",
"token_count": 413
} | 352 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_SCREENSHOT_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_SCREENSHOT_H_
#include <lib/zx/vmo.h>
#include <zircon/status.h>
#include <cmath>
#include <iostream>
#include <map>
#include <tuple>
#include <vector>
namespace fuchsia_test_utils {
// Represents a Pixel in BGRA format.
// Uses the sRGB color space.
struct Pixel {
uint8_t blue = 0;
uint8_t green = 0;
uint8_t red = 0;
uint8_t alpha = 0;
Pixel(uint8_t blue, uint8_t green, uint8_t red, uint8_t alpha)
: blue(blue), green(green), red(red), alpha(alpha) {}
bool operator==(const Pixel& rhs) const {
return blue == rhs.blue && green == rhs.green && red == rhs.red &&
alpha == rhs.alpha;
}
inline bool operator!=(const Pixel& rhs) const { return !(*this == rhs); }
bool operator<(const Pixel& other) const {
return std::tie(blue, green, red, alpha) <
std::tie(other.blue, other.green, other.red, other.alpha);
}
};
std::ostream& operator<<(std::ostream& stream, const Pixel& pixel);
// Helper class to get information about a screenshot returned by
// |fuchsia.ui.composition.Screenshot| protocol.
class Screenshot {
public:
// BGRA format.
inline static const Pixel kBlack = Pixel(0, 0, 0, 255);
inline static const Pixel kBlue = Pixel(255, 0, 0, 255);
inline static const Pixel kRed = Pixel(0, 0, 255, 255);
inline static const Pixel kMagenta = Pixel(255, 0, 255, 255);
inline static const Pixel kGreen = Pixel(0, 255, 0, 255);
// Params:-
// |screenshot_vmo| - The VMO returned by
// fuchsia.ui.composition.Screenshot.Take representing the screenshot data.
// |width|, |height| - Width and height of the physical display in pixels as
// returned by |fuchsia.ui.display.singleton.Info|.
// |rotation| - The display rotation value in degrees. The width and the
// height of the screenshot are flipped if this value is 90 or 270 degrees,
// as the screenshot shows how content is seen by the user.
Screenshot(const zx::vmo& screenshot_vmo,
uint64_t width,
uint64_t height,
int rotation);
// Returns the |Pixel| located at (x,y) coordinates. |x| and |y| should range
// from [0,width_) and [0,height_) respectively.
//
// (0,0)________________width_____________(w-1,0)
// | | |
// | | y |h
// | x | |e
// |-----------------------X |i
// | |g
// | |h
// | |t
// |_________________________________|
// (0,h-1) screenshot (w-1,h-1)
//
// Clients should only use this function to get the pixel data.
Pixel GetPixelAt(uint64_t x, uint64_t y) const;
// Counts the frequencies of each color in a screenshot.
std::map<Pixel, uint32_t> Histogram() const;
// Returns a 2D vector of size |height_ * width_|. Each value in the vector
// corresponds to a pixel in the screenshot.
std::vector<std::vector<Pixel>> screenshot() const { return screenshot_; }
uint64_t width() const { return width_; }
uint64_t height() const { return height_; }
private:
// Populates |screenshot_| by converting the linear array of bytes in
// |screenshot_vmo| of size |kBytesPerPixel * width_ * height_| to a 2D vector
// of |Pixel|s of size |height_ * width_|.
void ExtractScreenshotFromVMO(uint8_t* screenshot_vmo);
// Returns the |Pixel|s in the |row_index| row of the screenshot.
std::vector<Pixel> GetPixelsInRow(uint8_t* screenshot_vmo, size_t row_index);
uint64_t width_ = 0;
uint64_t height_ = 0;
std::vector<std::vector<Pixel>> screenshot_;
};
} // namespace fuchsia_test_utils
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_SCREENSHOT_H_
| engine/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.h",
"repo_id": "engine",
"token_count": 1643
} | 353 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "vulkan_surface.h"
#include <fuchsia/sysmem/cpp/fidl.h>
#include <lib/async/default.h>
#include <algorithm>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "runtime/dart/utils/inlines.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkSurfaceProps.h"
#include "third_party/skia/include/gpu/GrBackendSemaphore.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"
#include "vulkan/vulkan_fuchsia.h"
#define LOG_AND_RETURN(cond, msg) \
if (cond) { \
FML_LOG(ERROR) << msg; \
return false; \
}
namespace flutter_runner {
namespace {
constexpr SkColorType kSkiaColorType = kRGBA_8888_SkColorType;
constexpr VkFormat kVulkanFormat = VK_FORMAT_R8G8B8A8_UNORM;
constexpr VkImageCreateFlags kVulkanImageCreateFlags = 0;
// TODO: We should only keep usages that are actually required by Skia.
constexpr VkImageUsageFlags kVkImageUsage =
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
const VkSysmemColorSpaceFUCHSIA kSrgbColorSpace = {
.sType = VK_STRUCTURE_TYPE_SYSMEM_COLOR_SPACE_FUCHSIA,
.pNext = nullptr,
.colorSpace = static_cast<uint32_t>(fuchsia::sysmem::ColorSpaceType::SRGB),
};
} // namespace
bool VulkanSurface::CreateVulkanImage(vulkan::VulkanProvider& vulkan_provider,
const SkISize& size,
VulkanImage* out_vulkan_image) {
TRACE_EVENT0("flutter", "CreateVulkanImage");
FML_CHECK(!size.isEmpty());
FML_CHECK(out_vulkan_image != nullptr);
out_vulkan_image->vk_collection_image_create_info = {
.sType = VK_STRUCTURE_TYPE_BUFFER_COLLECTION_IMAGE_CREATE_INFO_FUCHSIA,
.pNext = nullptr,
.collection = collection_,
.index = 0,
};
out_vulkan_image->vk_image_create_info = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = &out_vulkan_image->vk_collection_image_create_info,
.flags = kVulkanImageCreateFlags,
.imageType = VK_IMAGE_TYPE_2D,
.format = kVulkanFormat,
.extent = VkExtent3D{static_cast<uint32_t>(size.width()),
static_cast<uint32_t>(size.height()), 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = kVkImageUsage,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
const VkImageFormatConstraintsInfoFUCHSIA format_constraints = {
.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_CONSTRAINTS_INFO_FUCHSIA,
.pNext = nullptr,
.imageCreateInfo = out_vulkan_image->vk_image_create_info,
.requiredFormatFeatures = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT,
.flags = {},
.sysmemPixelFormat = {},
.colorSpaceCount = 1,
.pColorSpaces = &kSrgbColorSpace,
};
const VkImageConstraintsInfoFUCHSIA image_constraints = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CONSTRAINTS_INFO_FUCHSIA,
.pNext = nullptr,
.formatConstraintsCount = 1,
.pFormatConstraints = &format_constraints,
.bufferCollectionConstraints =
{
.sType =
VK_STRUCTURE_TYPE_BUFFER_COLLECTION_CONSTRAINTS_INFO_FUCHSIA,
.pNext = nullptr,
.minBufferCount = 1,
// Using the default value 0 means that we don't have any other
// constraints except for the minimum buffer count.
.maxBufferCount = 0,
.minBufferCountForCamping = 0,
.minBufferCountForDedicatedSlack = 0,
.minBufferCountForSharedSlack = 0,
},
.flags = {},
};
if (VK_CALL_LOG_ERROR(
vulkan_provider.vk().SetBufferCollectionImageConstraintsFUCHSIA(
vulkan_provider.vk_device(), collection_, &image_constraints)) !=
VK_SUCCESS) {
return false;
}
{
VkImage vk_image = VK_NULL_HANDLE;
if (VK_CALL_LOG_ERROR(vulkan_provider.vk().CreateImage(
vulkan_provider.vk_device(),
&out_vulkan_image->vk_image_create_info, nullptr, &vk_image)) !=
VK_SUCCESS) {
return false;
}
out_vulkan_image->vk_image = vulkan::VulkanHandle<VkImage_T*>{
vk_image, [&vulkan_provider = vulkan_provider](VkImage image) {
vulkan_provider.vk().DestroyImage(vulkan_provider.vk_device(), image,
NULL);
}};
}
vulkan_provider.vk().GetImageMemoryRequirements(
vulkan_provider.vk_device(), out_vulkan_image->vk_image,
&out_vulkan_image->vk_memory_requirements);
return true;
}
VulkanSurface::VulkanSurface(
vulkan::VulkanProvider& vulkan_provider,
fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
sk_sp<GrDirectContext> context,
const SkISize& size)
: vulkan_provider_(vulkan_provider), wait_(this) {
FML_CHECK(flatland_allocator.is_bound());
FML_CHECK(context != nullptr);
if (!AllocateDeviceMemory(sysmem_allocator, flatland_allocator,
std::move(context), size)) {
FML_LOG(ERROR) << "VulkanSurface: Could not allocate device memory.";
return;
}
if (!CreateFences()) {
FML_LOG(ERROR) << "VulkanSurface: Could not create signal fences.";
return;
}
std::fill(size_history_.begin(), size_history_.end(), SkISize::MakeEmpty());
wait_.set_object(release_event_.get());
wait_.set_trigger(ZX_EVENT_SIGNALED);
Reset();
valid_ = true;
}
VulkanSurface::~VulkanSurface() {
if (release_image_callback_) {
release_image_callback_();
}
wait_.Cancel();
wait_.set_object(ZX_HANDLE_INVALID);
}
bool VulkanSurface::IsValid() const {
return valid_;
}
SkISize VulkanSurface::GetSize() const {
if (!valid_) {
return SkISize::Make(0, 0);
}
return SkISize::Make(sk_surface_->width(), sk_surface_->height());
}
vulkan::VulkanHandle<VkSemaphore> VulkanSurface::SemaphoreFromEvent(
const zx::event& event) const {
VkResult result;
VkSemaphore semaphore;
zx::event semaphore_event;
zx_status_t status = event.duplicate(ZX_RIGHT_SAME_RIGHTS, &semaphore_event);
if (status != ZX_OK) {
FML_LOG(ERROR) << "VulkanSurface: Failed to duplicate semaphore event";
return vulkan::VulkanHandle<VkSemaphore>();
}
VkSemaphoreCreateInfo create_info = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
};
result = VK_CALL_LOG_ERROR(vulkan_provider_.vk().CreateSemaphore(
vulkan_provider_.vk_device(), &create_info, nullptr, &semaphore));
if (result != VK_SUCCESS) {
return vulkan::VulkanHandle<VkSemaphore>();
}
VkImportSemaphoreZirconHandleInfoFUCHSIA import_info = {
.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_ZIRCON_HANDLE_INFO_FUCHSIA,
.pNext = nullptr,
.semaphore = semaphore,
.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_ZIRCON_EVENT_BIT_FUCHSIA,
.zirconHandle = static_cast<uint32_t>(semaphore_event.release())};
result = VK_CALL_LOG_ERROR(
vulkan_provider_.vk().ImportSemaphoreZirconHandleFUCHSIA(
vulkan_provider_.vk_device(), &import_info));
if (result != VK_SUCCESS) {
return vulkan::VulkanHandle<VkSemaphore>();
}
return vulkan::VulkanHandle<VkSemaphore>(
semaphore, [&vulkan_provider = vulkan_provider_](VkSemaphore semaphore) {
vulkan_provider.vk().DestroySemaphore(vulkan_provider.vk_device(),
semaphore, nullptr);
});
}
bool VulkanSurface::CreateFences() {
if (zx::event::create(0, &acquire_event_) != ZX_OK) {
FML_LOG(ERROR) << "VulkanSurface: Failed to create acquire event";
return false;
}
acquire_semaphore_ = SemaphoreFromEvent(acquire_event_);
if (!acquire_semaphore_) {
FML_LOG(ERROR) << "VulkanSurface: Failed to create acquire semaphore";
return false;
}
if (zx::event::create(0, &release_event_) != ZX_OK) {
FML_LOG(ERROR) << "VulkanSurface: Failed to create release event";
return false;
}
command_buffer_fence_ = vulkan_provider_.CreateFence();
return true;
}
bool VulkanSurface::AllocateDeviceMemory(
fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
sk_sp<GrDirectContext> context,
const SkISize& size) {
if (size.isEmpty()) {
FML_LOG(ERROR)
<< "VulkanSurface: Failed to allocate surface, size is empty";
return false;
}
fuchsia::sysmem::BufferCollectionTokenSyncPtr vulkan_token;
zx_status_t status =
sysmem_allocator->AllocateSharedCollection(vulkan_token.NewRequest());
LOG_AND_RETURN(status != ZX_OK,
"VulkanSurface: Failed to allocate collection");
fuchsia::sysmem::BufferCollectionTokenSyncPtr scenic_token;
status = vulkan_token->Duplicate(std::numeric_limits<uint32_t>::max(),
scenic_token.NewRequest());
LOG_AND_RETURN(status != ZX_OK,
"VulkanSurface: Failed to duplicate collection token");
status = vulkan_token->Sync();
LOG_AND_RETURN(status != ZX_OK,
"VulkanSurface: Failed to sync collection token");
fuchsia::ui::composition::BufferCollectionExportToken export_token;
status = zx::eventpair::create(0, &export_token.value, &import_token_.value);
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";
}
});
VkBufferCollectionCreateInfoFUCHSIA import_info{
.sType = VK_STRUCTURE_TYPE_BUFFER_COLLECTION_CREATE_INFO_FUCHSIA,
.pNext = nullptr,
.collectionToken = vulkan_token.Unbind().TakeChannel().release(),
};
VkBufferCollectionFUCHSIA collection;
if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().CreateBufferCollectionFUCHSIA(
vulkan_provider_.vk_device(), &import_info, nullptr, &collection)) !=
VK_SUCCESS) {
return false;
}
collection_ = vulkan::VulkanHandle<VkBufferCollectionFUCHSIA_T*>{
collection, [&vulkan_provider =
vulkan_provider_](VkBufferCollectionFUCHSIA collection) {
vulkan_provider.vk().DestroyBufferCollectionFUCHSIA(
vulkan_provider.vk_device(), collection, nullptr);
}};
VulkanImage vulkan_image;
LOG_AND_RETURN(!CreateVulkanImage(vulkan_provider_, size, &vulkan_image),
"VulkanSurface: Failed to create VkImage");
vulkan_image_ = std::move(vulkan_image);
const VkMemoryRequirements& memory_requirements =
vulkan_image_.vk_memory_requirements;
VkImageCreateInfo& image_create_info = vulkan_image_.vk_image_create_info;
VkBufferCollectionPropertiesFUCHSIA properties{
.sType = VK_STRUCTURE_TYPE_BUFFER_COLLECTION_PROPERTIES_FUCHSIA};
if (VK_CALL_LOG_ERROR(
vulkan_provider_.vk().GetBufferCollectionPropertiesFUCHSIA(
vulkan_provider_.vk_device(), collection_, &properties)) !=
VK_SUCCESS) {
return false;
}
VkImportMemoryBufferCollectionFUCHSIA import_memory_info = {
.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_BUFFER_COLLECTION_FUCHSIA,
.pNext = nullptr,
.collection = collection_,
.index = 0,
};
auto bits = memory_requirements.memoryTypeBits & properties.memoryTypeBits;
FML_DCHECK(bits != 0);
VkMemoryAllocateInfo allocation_info = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = &import_memory_info,
.allocationSize = memory_requirements.size,
.memoryTypeIndex = static_cast<uint32_t>(__builtin_ctz(bits)),
};
{
TRACE_EVENT1("flutter", "vkAllocateMemory", "allocationSize",
allocation_info.allocationSize);
VkDeviceMemory vk_memory = VK_NULL_HANDLE;
if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().AllocateMemory(
vulkan_provider_.vk_device(), &allocation_info, NULL,
&vk_memory)) != VK_SUCCESS) {
return false;
}
vk_memory_ = vulkan::VulkanHandle<VkDeviceMemory_T*>{
vk_memory,
[&vulkan_provider = vulkan_provider_](VkDeviceMemory memory) {
vulkan_provider.vk().FreeMemory(vulkan_provider.vk_device(), memory,
NULL);
}};
vk_memory_info_ = allocation_info;
}
// Bind image memory.
if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().BindImageMemory(
vulkan_provider_.vk_device(), vulkan_image_.vk_image, vk_memory_,
0)) != VK_SUCCESS) {
return false;
}
return SetupSkiaSurface(std::move(context), size, kSkiaColorType,
image_create_info, memory_requirements);
}
bool VulkanSurface::SetupSkiaSurface(sk_sp<GrDirectContext> context,
const SkISize& size,
SkColorType color_type,
const VkImageCreateInfo& image_create_info,
const VkMemoryRequirements& memory_reqs) {
FML_CHECK(context != nullptr);
GrVkAlloc alloc;
alloc.fMemory = vk_memory_;
alloc.fOffset = 0;
alloc.fSize = memory_reqs.size;
alloc.fFlags = 0;
GrVkImageInfo image_info;
image_info.fImage = vulkan_image_.vk_image;
image_info.fAlloc = alloc;
image_info.fImageTiling = image_create_info.tiling;
image_info.fImageLayout = image_create_info.initialLayout;
image_info.fFormat = image_create_info.format;
image_info.fImageUsageFlags = image_create_info.usage;
image_info.fSampleCount = 1;
image_info.fLevelCount = image_create_info.mipLevels;
auto sk_render_target =
GrBackendRenderTargets::MakeVk(size.width(), size.height(), image_info);
SkSurfaceProps sk_surface_props(0, kUnknown_SkPixelGeometry);
auto sk_surface =
SkSurfaces::WrapBackendRenderTarget(context.get(), //
sk_render_target, //
kTopLeft_GrSurfaceOrigin, //
color_type, //
SkColorSpace::MakeSRGB(), //
&sk_surface_props //
);
if (!sk_surface || sk_surface->getCanvas() == nullptr) {
FML_LOG(ERROR)
<< "VulkanSurface: SkSurfaces::WrapBackendRenderTarget failed";
return false;
}
sk_surface_ = std::move(sk_surface);
return true;
}
void VulkanSurface::SetImageId(uint32_t image_id) {
FML_CHECK(image_id_ == 0);
image_id_ = image_id;
}
uint32_t VulkanSurface::GetImageId() {
return image_id_;
}
sk_sp<SkSurface> VulkanSurface::GetSkiaSurface() const {
return valid_ ? sk_surface_ : nullptr;
}
fuchsia::ui::composition::BufferCollectionImportToken
VulkanSurface::GetBufferCollectionImportToken() {
fuchsia::ui::composition::BufferCollectionImportToken import_dup;
import_token_.value.duplicate(ZX_RIGHT_SAME_RIGHTS, &import_dup.value);
return import_dup;
}
zx::event VulkanSurface::GetAcquireFence() {
zx::event fence;
acquire_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence);
return fence;
}
zx::event VulkanSurface::GetReleaseFence() {
zx::event fence;
release_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence);
return fence;
}
void VulkanSurface::SetReleaseImageCallback(
ReleaseImageCallback release_image_callback) {
release_image_callback_ = release_image_callback;
}
size_t VulkanSurface::AdvanceAndGetAge() {
size_history_[size_history_index_] = GetSize();
size_history_index_ = (size_history_index_ + 1) % kSizeHistorySize;
age_++;
return age_;
}
bool VulkanSurface::FlushSessionAcquireAndReleaseEvents() {
age_ = 0;
return true;
}
void VulkanSurface::SignalWritesFinished(
const std::function<void(void)>& on_writes_committed) {
FML_CHECK(on_writes_committed);
if (!valid_) {
on_writes_committed();
return;
}
FML_CHECK(pending_on_writes_committed_ == nullptr)
<< "Attempted to signal a write on the surface when the "
"previous write has not yet been acknowledged by the "
"compositor.";
pending_on_writes_committed_ = on_writes_committed;
}
void VulkanSurface::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.";
}
VkFence fence = command_buffer_fence_;
if (command_buffer_) {
VK_CALL_LOG_FATAL(vulkan_provider_.vk().WaitForFences(
vulkan_provider_.vk_device(), 1, &fence, VK_TRUE, UINT64_MAX));
command_buffer_.reset();
}
VK_CALL_LOG_ERROR(vulkan_provider_.vk().ResetFences(
vulkan_provider_.vk_device(), 1, &fence));
// Need to make a new acquire semaphore every frame or else validation layers
// get confused about why no one is waiting on it in this VkInstance
acquire_semaphore_.Reset();
acquire_semaphore_ = SemaphoreFromEvent(acquire_event_);
if (!acquire_semaphore_) {
FML_LOG(ERROR) << "failed to create acquire semaphore";
}
wait_.Begin(async_get_default_dispatcher());
// It is safe for the caller to collect the surface in the callback.
auto callback = pending_on_writes_committed_;
pending_on_writes_committed_ = nullptr;
if (callback) {
callback();
}
}
void VulkanSurface::OnHandleReady(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/vulkan_surface.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/vulkan_surface.cc",
"repo_id": "engine",
"token_count": 8171
} | 354 |
// 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 "handle_exception.h"
#include <fuchsia/feedback/cpp/fidl.h>
#include <fuchsia/mem/cpp/fidl.h>
#include <lib/zx/vmo.h>
#include <sys/types.h>
#include <zircon/status.h>
#include <string>
#include "flutter/fml/logging.h"
#include "third_party/tonic/converter/dart_converter.h"
namespace {
static bool SetStackTrace(const std::string& data,
fuchsia::feedback::RuntimeCrashReport* report) {
uint64_t num_bytes = data.size();
zx::vmo vmo;
if (zx::vmo::create(num_bytes, 0u, &vmo) < 0) {
return false;
}
if (num_bytes > 0) {
if (vmo.write(data.data(), 0, num_bytes) < 0) {
return false;
}
}
fuchsia::mem::Buffer buffer;
buffer.vmo = std::move(vmo);
buffer.size = num_bytes;
report->set_exception_stack_trace(std::move(buffer));
return true;
}
fuchsia::feedback::CrashReport BuildCrashReport(
const std::string& component_url,
const std::string& error,
const std::string& stack_trace) {
// The runtime type has already been pre-pended to the error message so we
// expect the format to be '$RuntimeType: $Message'.
std::string error_type;
std::string error_message;
const size_t delimiter_pos = error.find_first_of(':');
if (delimiter_pos == std::string::npos) {
FML_LOG(ERROR) << "error parsing Dart exception: expected format "
"'$RuntimeType: $Message', got '"
<< error << "'";
// We still need to specify a type, otherwise the stack trace does not
// show up in the crash server UI.
error_type = "UnknownError";
error_message = error;
} else {
error_type = error.substr(0, delimiter_pos);
error_message =
error.substr(delimiter_pos + 2 /*to get rid of the leading ': '*/);
}
// Truncate error message to the maximum length allowed for the crash_reporter
// FIDL call
error_message = error_message.substr(
0, fuchsia::feedback::MAX_EXCEPTION_MESSAGE_LENGTH - 1);
fuchsia::feedback::RuntimeCrashReport dart_report;
dart_report.set_exception_type(error_type);
dart_report.set_exception_message(error_message);
if (!SetStackTrace(stack_trace, &dart_report)) {
FML_LOG(ERROR) << "Failed to convert Dart stack trace to VMO";
}
fuchsia::feedback::SpecificCrashReport specific_report;
specific_report.set_dart(std::move(dart_report));
fuchsia::feedback::CrashReport report;
report.set_program_name(component_url);
report.set_specific_report(std::move(specific_report));
report.set_is_fatal(false);
return report;
}
} // namespace
namespace dart_utils {
void HandleIfException(std::shared_ptr<::sys::ServiceDirectory> services,
const std::string& component_url,
Dart_Handle result) {
if (!Dart_IsError(result) || !Dart_ErrorHasException(result)) {
return;
}
const std::string error =
tonic::StdStringFromDart(Dart_ToString(Dart_ErrorGetException(result)));
const std::string stack_trace =
tonic::StdStringFromDart(Dart_ToString(Dart_ErrorGetStackTrace(result)));
return HandleException(services, component_url, error, stack_trace);
}
void HandleException(std::shared_ptr<::sys::ServiceDirectory> services,
const std::string& component_url,
const std::string& error,
const std::string& stack_trace) {
fuchsia::feedback::CrashReport crash_report =
BuildCrashReport(component_url, error, stack_trace);
fuchsia::feedback::CrashReporterPtr crash_reporter =
services->Connect<fuchsia::feedback::CrashReporter>();
crash_reporter->FileReport(
std::move(crash_report),
[](fuchsia::feedback::CrashReporter_FileReport_Result result) {
if (result.is_err()) {
FML_LOG(ERROR) << "Failed to report Dart exception: "
<< static_cast<uint32_t>(result.err());
}
});
}
} // namespace dart_utils
| engine/shell/platform/fuchsia/runtime/dart/utils/handle_exception.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/handle_exception.cc",
"repo_id": "engine",
"token_count": 1594
} | 355 |
# 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/testing/testing.gni")
_public_headers = [ "public/flutter_glfw.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_glfw_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("flutter_glfw_headers") {
public = _public_headers
public_deps = [ "//flutter/shell/platform/common:common_cpp_library_headers" ]
configs +=
[ "//flutter/shell/platform/common:desktop_library_implementation" ]
public_configs =
[ "//flutter/shell/platform/common:relative_flutter_library_headers" ]
}
source_set("flutter_glfw") {
public = [ "system_utils.h" ]
sources = [
"event_loop.cc",
"event_loop.h",
"flutter_glfw.cc",
"glfw_event_loop.cc",
"glfw_event_loop.h",
"headless_event_loop.cc",
"headless_event_loop.h",
"key_event_handler.cc",
"key_event_handler.h",
"keyboard_hook_handler.h",
"platform_handler.cc",
"platform_handler.h",
"system_utils.cc",
"text_input_plugin.cc",
"text_input_plugin.h",
]
configs +=
[ "//flutter/shell/platform/common:desktop_library_implementation" ]
deps = [
":flutter_glfw_headers",
"//flutter/shell/platform/common:common_cpp",
"//flutter/shell/platform/common:common_cpp_input",
"//flutter/shell/platform/common/client_wrapper:client_wrapper",
"//flutter/shell/platform/embedder:embedder_as_internal_library",
"//flutter/shell/platform/glfw/client_wrapper:client_wrapper_glfw",
"//flutter/third_party/glfw",
"//flutter/third_party/rapidjson",
]
if (is_linux) {
libs = [ "GL" ]
configs += [ "//flutter/shell/platform/linux/config:x11" ]
} else if (is_mac) {
frameworks = [
"CoreVideo.framework",
"IOKit.framework",
]
}
}
test_fixtures("flutter_glfw_fixtures") {
fixtures = []
}
executable("flutter_glfw_unittests") {
testonly = true
sources = [ "system_utils_test.cc" ]
deps = [
":flutter_glfw",
":flutter_glfw_fixtures",
"//flutter/shell/platform/embedder:embedder_headers",
"//flutter/testing",
]
}
copy("publish_headers_glfw") {
sources = _public_headers
outputs = [ "$root_out_dir/{{source_file_part}}" ]
# The GLFW header assumes the presence of the common headers.
deps = [ "//flutter/shell/platform/common:publish_headers" ]
}
| engine/shell/platform/glfw/BUILD.gn/0 | {
"file_path": "engine/shell/platform/glfw/BUILD.gn",
"repo_id": "engine",
"token_count": 1075
} | 356 |
// 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_GLFW_EVENT_LOOP_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_EVENT_LOOP_H_
#include <chrono>
#include <deque>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include "flutter/shell/platform/embedder/embedder.h"
namespace flutter {
// An abstract event loop.
class EventLoop {
public:
using TaskExpiredCallback = std::function<void(const FlutterTask*)>;
// Creates an event loop running on the given thread, calling
// |on_task_expired| to run tasks.
EventLoop(std::thread::id main_thread_id,
const TaskExpiredCallback& on_task_expired);
virtual ~EventLoop();
// Disallow copy.
EventLoop(const EventLoop&) = delete;
EventLoop& operator=(const EventLoop&) = delete;
// Returns if the current thread is the thread used by this event loop.
bool RunsTasksOnCurrentThread() const;
// Waits for the next event, processes it, and returns.
//
// Expired engine events, if any, are processed as well. The optional
// timeout should only be used when events not managed by this loop need to be
// processed in a polling manner.
void WaitForEvents(
std::chrono::nanoseconds max_wait = std::chrono::nanoseconds::max());
// Posts a Flutter engine task to the event loop for delayed execution.
void PostTask(FlutterTask flutter_task, uint64_t flutter_target_time_nanos);
protected:
using TaskTimePoint = std::chrono::steady_clock::time_point;
// Returns the timepoint corresponding to a Flutter task time.
static TaskTimePoint TimePointFromFlutterTime(
uint64_t flutter_target_time_nanos);
// Returns the mutex used to control the task queue. Subclasses may safely
// lock this mutex in the abstract methods below.
std::mutex& GetTaskQueueMutex() { return task_queue_mutex_; }
// Waits until the given time, or a Wake() call.
virtual void WaitUntil(const TaskTimePoint& time) = 0;
// Wakes the main thread from a WaitUntil call.
virtual void Wake() = 0;
struct Task {
uint64_t order;
TaskTimePoint fire_time;
FlutterTask task;
struct Comparer {
bool operator()(const Task& a, const Task& b) {
if (a.fire_time == b.fire_time) {
return a.order > b.order;
}
return a.fire_time > b.fire_time;
}
};
};
std::thread::id main_thread_id_;
TaskExpiredCallback on_task_expired_;
std::mutex task_queue_mutex_;
std::priority_queue<Task, std::deque<Task>, Task::Comparer> task_queue_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_EVENT_LOOP_H_
| engine/shell/platform/glfw/event_loop.h/0 | {
"file_path": "engine/shell/platform/glfw/event_loop.h",
"repo_id": "engine",
"token_count": 928
} | 357 |
// 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_GLFW_TEXT_INPUT_PLUGIN_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_TEXT_INPUT_PLUGIN_H_
#include <map>
#include <memory>
#include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/method_channel.h"
#include "flutter/shell/platform/common/text_input_model.h"
#include "flutter/shell/platform/glfw/keyboard_hook_handler.h"
#include "flutter/shell/platform/glfw/public/flutter_glfw.h"
#include "rapidjson/document.h"
namespace flutter {
// Implements a text input plugin.
//
// Specifically handles window events within GLFW.
class TextInputPlugin : public KeyboardHookHandler {
public:
explicit TextInputPlugin(flutter::BinaryMessenger* messenger);
virtual ~TextInputPlugin();
// |KeyboardHookHandler|
void KeyboardHook(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) override;
// |KeyboardHookHandler|
void CharHook(GLFWwindow* window, unsigned int code_point) override;
private:
// Sends the current state of the given model to the Flutter engine.
void SendStateUpdate(const TextInputModel& model);
// Sends an action triggered by the Enter key to the Flutter engine.
void EnterPressed(TextInputModel* model);
// Called when a method is called on |channel_|;
void HandleMethodCall(
const flutter::MethodCall<rapidjson::Document>& method_call,
std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result);
// The MethodChannel used for communication with the Flutter engine.
std::unique_ptr<flutter::MethodChannel<rapidjson::Document>> channel_;
// The active client id.
int client_id_ = 0;
// The active model. nullptr if not set.
std::unique_ptr<TextInputModel> active_model_;
// Keyboard type of the client. See available options:
// https://api.flutter.dev/flutter/services/TextInputType-class.html
std::string input_type_;
// An action requested by the user on the input client. See available options:
// https://api.flutter.dev/flutter/services/TextInputAction-class.html
std::string input_action_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_TEXT_INPUT_PLUGIN_H_
| engine/shell/platform/glfw/text_input_plugin.h/0 | {
"file_path": "engine/shell/platform/glfw/text_input_plugin.h",
"repo_id": "engine",
"token_count": 839
} | 358 |
// 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_LINUX_FL_BINARY_MESSENGER_PRIVATE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_BINARY_MESSENGER_PRIVATE_H_
#include <glib-object.h>
#include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h"
G_BEGIN_DECLS
/**
* fl_binary_messenger_new:
* @engine: The #FlEngine to communicate with.
*
* Creates a new #FlBinaryMessenger. The binary messenger will take control of
* the engines platform message handler.
*
* Returns: a new #FlBinaryMessenger.
*/
FlBinaryMessenger* fl_binary_messenger_new(FlEngine* engine);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_BINARY_MESSENGER_PRIVATE_H_
| engine/shell/platform/linux/fl_binary_messenger_private.h/0 | {
"file_path": "engine/shell/platform/linux/fl_binary_messenger_private.h",
"repo_id": "engine",
"token_count": 300
} | 359 |
// 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/linux/public/flutter_linux/fl_json_method_codec.h"
#include <cstring>
#include "flutter/shell/platform/linux/fl_method_codec_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_message_codec.h"
#include "gtest/gtest.h"
// Converts a binary blob to a string.
static gchar* message_to_text(GBytes* message) {
size_t data_length;
const gchar* data =
static_cast<const gchar*>(g_bytes_get_data(message, &data_length));
return g_strndup(data, data_length);
}
// Converts a string to a binary blob.
static GBytes* text_to_message(const gchar* text) {
return g_bytes_new(text, strlen(text));
}
// Encodes a method call using JsonMethodCodec to a UTF-8 string.
static gchar* encode_method_call(const gchar* name, FlValue* args) {
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_method_call(
FL_METHOD_CODEC(codec), name, args, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
return message_to_text(message);
}
// Encodes a success envelope response using JsonMethodCodec to a UTF-8 string.
static gchar* encode_success_envelope(FlValue* result) {
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_success_envelope(
FL_METHOD_CODEC(codec), result, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
return message_to_text(message);
}
// Encodes a error envelope response using JsonMethodCodec to a UTF8 string.
static gchar* encode_error_envelope(const gchar* error_code,
const gchar* error_message,
FlValue* details) {
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_error_envelope(
FL_METHOD_CODEC(codec), error_code, error_message, details, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
return message_to_text(message);
}
// Decodes a method call using JsonMethodCodec with a UTF8 string.
static void decode_method_call(const char* text, gchar** name, FlValue** args) {
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
g_autoptr(GBytes) data = text_to_message(text);
g_autoptr(GError) error = nullptr;
gboolean result = fl_method_codec_decode_method_call(
FL_METHOD_CODEC(codec), data, name, args, &error);
EXPECT_TRUE(result);
EXPECT_EQ(error, nullptr);
}
// Decodes a method call using JsonMethodCodec. Expect the given error.
static void decode_error_method_call(const char* text,
GQuark domain,
gint code) {
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
g_autoptr(GBytes) data = text_to_message(text);
g_autoptr(GError) error = nullptr;
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
gboolean result = fl_method_codec_decode_method_call(
FL_METHOD_CODEC(codec), data, &name, &args, &error);
EXPECT_FALSE(result);
EXPECT_EQ(name, nullptr);
EXPECT_EQ(args, nullptr);
EXPECT_TRUE(g_error_matches(error, domain, code));
}
// Decodes a response using JsonMethodCodec. Expect the response is a result.
static void decode_response_with_success(const char* text, FlValue* result) {
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
g_autoptr(GBytes) message = text_to_message(text);
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
ASSERT_NE(response, nullptr);
EXPECT_EQ(error, nullptr);
ASSERT_TRUE(FL_IS_METHOD_SUCCESS_RESPONSE(response));
EXPECT_TRUE(fl_value_equal(fl_method_success_response_get_result(
FL_METHOD_SUCCESS_RESPONSE(response)),
result));
}
// Decodes a response using JsonMethodCodec. Expect the response contains the
// given error.
static void decode_response_with_error(const char* text,
const gchar* code,
const gchar* error_message,
FlValue* details) {
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
g_autoptr(GBytes) message = text_to_message(text);
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
ASSERT_NE(response, nullptr);
EXPECT_EQ(error, nullptr);
ASSERT_TRUE(FL_IS_METHOD_ERROR_RESPONSE(response));
EXPECT_STREQ(
fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(response)),
code);
if (error_message == nullptr) {
EXPECT_EQ(fl_method_error_response_get_message(
FL_METHOD_ERROR_RESPONSE(response)),
nullptr);
} else {
EXPECT_STREQ(fl_method_error_response_get_message(
FL_METHOD_ERROR_RESPONSE(response)),
error_message);
}
if (details == nullptr) {
EXPECT_EQ(fl_method_error_response_get_details(
FL_METHOD_ERROR_RESPONSE(response)),
nullptr);
} else {
EXPECT_TRUE(fl_value_equal(fl_method_error_response_get_details(
FL_METHOD_ERROR_RESPONSE(response)),
details));
}
}
// Decode a response using JsonMethodCodec. Expect the given error.
static void decode_error_response(const char* text, GQuark domain, gint code) {
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
g_autoptr(GBytes) message = text_to_message(text);
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
EXPECT_EQ(response, nullptr);
EXPECT_TRUE(g_error_matches(error, domain, code));
}
TEST(FlJsonMethodCodecTest, EncodeMethodCallNullptrArgs) {
g_autofree gchar* text = encode_method_call("hello", nullptr);
EXPECT_STREQ(text, "{\"method\":\"hello\",\"args\":null}");
}
TEST(FlJsonMethodCodecTest, EncodeMethodCallNullArgs) {
g_autoptr(FlValue) value = fl_value_new_null();
g_autofree gchar* text = encode_method_call("hello", value);
EXPECT_STREQ(text, "{\"method\":\"hello\",\"args\":null}");
}
TEST(FlJsonMethodCodecTest, EncodeMethodCallStringArgs) {
g_autoptr(FlValue) args = fl_value_new_string("world");
g_autofree gchar* text = encode_method_call("hello", args);
EXPECT_STREQ(text, "{\"method\":\"hello\",\"args\":\"world\"}");
}
TEST(FlJsonMethodCodecTest, EncodeMethodCallListArgs) {
g_autoptr(FlValue) args = fl_value_new_list();
fl_value_append_take(args, fl_value_new_string("count"));
fl_value_append_take(args, fl_value_new_int(42));
g_autofree gchar* text = encode_method_call("hello", args);
EXPECT_STREQ(text, "{\"method\":\"hello\",\"args\":[\"count\",42]}");
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallNoArgs) {
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
decode_method_call("{\"method\":\"hello\"}", &name, &args);
EXPECT_STREQ(name, "hello");
ASSERT_EQ(args, nullptr);
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallNullArgs) {
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
decode_method_call("{\"method\":\"hello\",\"args\":null}", &name, &args);
EXPECT_STREQ(name, "hello");
ASSERT_EQ(fl_value_get_type(args), FL_VALUE_TYPE_NULL);
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallStringArgs) {
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
decode_method_call("{\"method\":\"hello\",\"args\":\"world\"}", &name, &args);
EXPECT_STREQ(name, "hello");
ASSERT_EQ(fl_value_get_type(args), FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(args), "world");
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallListArgs) {
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
decode_method_call("{\"method\":\"hello\",\"args\":[\"count\",42]}", &name,
&args);
EXPECT_STREQ(name, "hello");
ASSERT_EQ(fl_value_get_type(args), FL_VALUE_TYPE_LIST);
EXPECT_EQ(fl_value_get_length(args), static_cast<size_t>(2));
FlValue* arg0 = fl_value_get_list_value(args, 0);
ASSERT_EQ(fl_value_get_type(arg0), FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(arg0), "count");
FlValue* arg1 = fl_value_get_list_value(args, 1);
ASSERT_EQ(fl_value_get_type(arg1), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(arg1), 42);
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallNoData) {
decode_error_method_call("", FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON);
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallNoMethodOrArgs) {
decode_error_method_call("{}", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED);
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallInvalidJson) {
decode_error_method_call("X", FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON);
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallWrongType) {
decode_error_method_call("42", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED);
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallNoMethod) {
decode_error_method_call("{\"args\":\"world\"}", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED);
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallNoTerminator) {
decode_error_method_call("{\"method\":\"hello\",\"args\":\"world\"",
FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON);
}
TEST(FlJsonMethodCodecTest, DecodeMethodCallExtraData) {
decode_error_method_call("{\"method\":\"hello\"}XXX",
FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON);
}
TEST(FlJsonMethodCodecTest, EncodeSuccessEnvelopeNullptr) {
g_autofree gchar* text = encode_success_envelope(nullptr);
EXPECT_STREQ(text, "[null]");
}
TEST(FlJsonMethodCodecTest, EncodeSuccessEnvelopeNull) {
g_autoptr(FlValue) result = fl_value_new_null();
g_autofree gchar* text = encode_success_envelope(result);
EXPECT_STREQ(text, "[null]");
}
TEST(FlJsonMethodCodecTest, EncodeSuccessEnvelopeString) {
g_autoptr(FlValue) result = fl_value_new_string("hello");
g_autofree gchar* text = encode_success_envelope(result);
EXPECT_STREQ(text, "[\"hello\"]");
}
TEST(FlJsonMethodCodecTest, EncodeSuccessEnvelopeList) {
g_autoptr(FlValue) result = fl_value_new_list();
fl_value_append_take(result, fl_value_new_string("count"));
fl_value_append_take(result, fl_value_new_int(42));
g_autofree gchar* text = encode_success_envelope(result);
EXPECT_STREQ(text, "[[\"count\",42]]");
}
TEST(FlJsonMethodCodecTest, EncodeErrorEnvelopeEmptyCode) {
g_autofree gchar* text = encode_error_envelope("", nullptr, nullptr);
EXPECT_STREQ(text, "[\"\",null,null]");
}
TEST(FlJsonMethodCodecTest, EncodeErrorEnvelopeNonMessageOrDetails) {
g_autofree gchar* text = encode_error_envelope("error", nullptr, nullptr);
EXPECT_STREQ(text, "[\"error\",null,null]");
}
TEST(FlJsonMethodCodecTest, EncodeErrorEnvelopeMessage) {
g_autofree gchar* text = encode_error_envelope("error", "message", nullptr);
EXPECT_STREQ(text, "[\"error\",\"message\",null]");
}
TEST(FlJsonMethodCodecTest, EncodeErrorEnvelopeDetails) {
g_autoptr(FlValue) details = fl_value_new_list();
fl_value_append_take(details, fl_value_new_string("count"));
fl_value_append_take(details, fl_value_new_int(42));
g_autofree gchar* text = encode_error_envelope("error", nullptr, details);
EXPECT_STREQ(text, "[\"error\",null,[\"count\",42]]");
}
TEST(FlJsonMethodCodecTest, EncodeErrorEnvelopeMessageAndDetails) {
g_autoptr(FlValue) details = fl_value_new_list();
fl_value_append_take(details, fl_value_new_string("count"));
fl_value_append_take(details, fl_value_new_int(42));
g_autofree gchar* text = encode_error_envelope("error", "message", details);
EXPECT_STREQ(text, "[\"error\",\"message\",[\"count\",42]]");
}
TEST(FlJsonMethodCodecTest, DecodeResponseSuccessNull) {
g_autoptr(FlValue) result = fl_value_new_null();
decode_response_with_success("[null]", result);
}
TEST(FlJsonMethodCodecTest, DecodeResponseSuccessString) {
g_autoptr(FlValue) result = fl_value_new_string("hello");
decode_response_with_success("[\"hello\"]", result);
}
TEST(FlJsonMethodCodecTest, DecodeResponseSuccessList) {
g_autoptr(FlValue) result = fl_value_new_list();
fl_value_append_take(result, fl_value_new_string("count"));
fl_value_append_take(result, fl_value_new_int(42));
decode_response_with_success("[[\"count\",42]]", result);
}
TEST(FlJsonMethodCodecTest, DecodeResponseErrorEmptyCode) {
decode_response_with_error("[\"\",null,null]", "", nullptr, nullptr);
}
TEST(FlJsonMethodCodecTest, DecodeResponseErrorNoMessageOrDetails) {
decode_response_with_error("[\"error\",null,null]", "error", nullptr,
nullptr);
}
TEST(FlJsonMethodCodecTest, DecodeResponseErrorMessage) {
decode_response_with_error("[\"error\",\"message\",null]", "error", "message",
nullptr);
}
TEST(FlJsonMethodCodecTest, DecodeResponseErrorDetails) {
g_autoptr(FlValue) details = fl_value_new_list();
fl_value_append_take(details, fl_value_new_string("count"));
fl_value_append_take(details, fl_value_new_int(42));
decode_response_with_error("[\"error\",null,[\"count\",42]]", "error",
nullptr, details);
}
TEST(FlJsonMethodCodecTest, DecodeResponseErrorMessageAndDetails) {
g_autoptr(FlValue) details = fl_value_new_list();
fl_value_append_take(details, fl_value_new_string("count"));
fl_value_append_take(details, fl_value_new_int(42));
decode_response_with_error("[\"error\",\"message\",[\"count\",42]]", "error",
"message", details);
}
TEST(FlJsonMethodCodecTest, DecodeResponseNotImplemented) {
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
g_autoptr(GBytes) message = g_bytes_new(nullptr, 0);
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
ASSERT_NE(response, nullptr);
EXPECT_EQ(error, nullptr);
EXPECT_TRUE(FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(response));
}
TEST(FlJsonMethodCodecTest, DecodeResponseNoTerminator) {
decode_error_response("[42", FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON);
}
TEST(FlJsonMethodCodecTest, DecodeResponseInvalidJson) {
decode_error_response("X", FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON);
}
TEST(FlJsonMethodCodecTest, DecodeResponseMissingDetails) {
decode_error_response("[\"error\",\"message\"]", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED);
}
TEST(FlJsonMethodCodecTest, DecodeResponseExtraDetails) {
decode_error_response("[\"error\",\"message\",true,42]",
FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED);
}
TEST(FlJsonMethodCodecTest, DecodeResponseSuccessExtraData) {
decode_error_response("[null]X", FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON);
}
TEST(FlJsonMethodCodecTest, DecodeResponseErrorExtraData) {
decode_error_response("[\"error\",null,null]X", FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON);
}
| engine/shell/platform/linux/fl_json_method_codec_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_json_method_codec_test.cc",
"repo_id": "engine",
"token_count": 6917
} | 360 |
// 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_LINUX_FL_KEYBOARD_VIEW_DELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_KEYBOARD_VIEW_DELEGATE_H_
#include <gdk/gdk.h>
#include <cinttypes>
#include <functional>
#include <memory>
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/linux/fl_key_event.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h"
typedef std::function<void()> KeyboardLayoutNotifier;
G_BEGIN_DECLS
G_DECLARE_INTERFACE(FlKeyboardViewDelegate,
fl_keyboard_view_delegate,
FL,
KEYBOARD_VIEW_DELEGATE,
GObject);
/**
* FlKeyboardViewDelegate:
*
* An interface for a class that provides `FlKeyboardManager` with
* platform-related features.
*
* This interface is typically implemented by `FlView`.
*/
struct _FlKeyboardViewDelegateInterface {
GTypeInterface g_iface;
void (*send_key_event)(FlKeyboardViewDelegate* delegate,
const FlutterKeyEvent* event,
FlutterKeyEventCallback callback,
void* user_data);
gboolean (*text_filter_key_press)(FlKeyboardViewDelegate* delegate,
FlKeyEvent* event);
FlBinaryMessenger* (*get_messenger)(FlKeyboardViewDelegate* delegate);
void (*redispatch_event)(FlKeyboardViewDelegate* delegate,
std::unique_ptr<FlKeyEvent> event);
void (*subscribe_to_layout_change)(FlKeyboardViewDelegate* delegate,
KeyboardLayoutNotifier notifier);
guint (*lookup_key)(FlKeyboardViewDelegate* view_delegate,
const GdkKeymapKey* key);
GHashTable* (*get_keyboard_state)(FlKeyboardViewDelegate* delegate);
};
/**
* fl_keyboard_view_delegate_send_key_event:
*
* Handles `FlKeyboardManager`'s request to send a `FlutterKeyEvent` through the
* embedder API to the framework.
*
* The ownership of the `event` is kept by the keyboard manager, and the `event`
* might be immediately destroyed after this function returns.
*
* The `callback` must eventually be called exactly once with the event result
* and the `user_data`.
*/
void fl_keyboard_view_delegate_send_key_event(FlKeyboardViewDelegate* delegate,
const FlutterKeyEvent* event,
FlutterKeyEventCallback callback,
void* user_data);
/**
* fl_keyboard_view_delegate_text_filter_key_press:
*
* Handles `FlKeyboardManager`'s request to check if the GTK text input IM
* filter would like to handle a GDK event.
*
* The ownership of the `event` is kept by the keyboard manager.
*/
gboolean fl_keyboard_view_delegate_text_filter_key_press(
FlKeyboardViewDelegate* delegate,
FlKeyEvent* event);
/**
* fl_keyboard_view_delegate_get_messenger:
*
* Returns a binary messenger that can be used to send messages to the
* framework.
*
* The ownership of messenger is kept by the view delegate.
*/
FlBinaryMessenger* fl_keyboard_view_delegate_get_messenger(
FlKeyboardViewDelegate* delegate);
/**
* fl_keyboard_view_delegate_redispatch_event:
*
* Handles `FlKeyboardManager`'s request to insert a GDK event to the system for
* redispatching.
*
* The ownership of event will be transferred to the view delegate. The view
* delegate is responsible to call fl_key_event_dispose.
*/
void fl_keyboard_view_delegate_redispatch_event(
FlKeyboardViewDelegate* delegate,
std::unique_ptr<FlKeyEvent> event);
void fl_keyboard_view_delegate_subscribe_to_layout_change(
FlKeyboardViewDelegate* delegate,
KeyboardLayoutNotifier notifier);
guint fl_keyboard_view_delegate_lookup_key(FlKeyboardViewDelegate* delegate,
const GdkKeymapKey* key);
/**
* fl_keyboard_view_delegate_get_keyboard_state:
*
* Returns the keyboard pressed state. The hash table contains one entry per
* pressed keys, mapping from the logical key to the physical key.*
*
*/
GHashTable* fl_keyboard_view_delegate_get_keyboard_state(
FlKeyboardViewDelegate* delegate);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_KEYBOARD_VIEW_DELEGATE_H_
| engine/shell/platform/linux/fl_keyboard_view_delegate.h/0 | {
"file_path": "engine/shell/platform/linux/fl_keyboard_view_delegate.h",
"repo_id": "engine",
"token_count": 1760
} | 361 |
// 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_LINUX_FL_PIXEL_BUFFER_TEXTURE_PRIVATE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_PIXEL_BUFFER_TEXTURE_PRIVATE_H_
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_pixel_buffer_texture.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h"
G_BEGIN_DECLS
/**
* fl_pixel_buffer_texture_populate:
* @texture: an #FlPixelBufferTexture.
* @width: width of the texture.
* @height: height of the texture.
* @opengl_texture: (out): return an #FlutterOpenGLTexture.
* @error: (allow-none): #GError location to store the error occurring, or
* %NULL to ignore.
*
* Attempts to populate the specified @opengl_texture with texture details
* such as the name, width, height and the pixel format.
*
* Returns: %TRUE on success.
*/
gboolean fl_pixel_buffer_texture_populate(FlPixelBufferTexture* texture,
uint32_t width,
uint32_t height,
FlutterOpenGLTexture* opengl_texture,
GError** error);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_PIXEL_BUFFER_TEXTURE_PRIVATE_H_
| engine/shell/platform/linux/fl_pixel_buffer_texture_private.h/0 | {
"file_path": "engine/shell/platform/linux/fl_pixel_buffer_texture_private.h",
"repo_id": "engine",
"token_count": 610
} | 362 |
// 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_LINUX_FL_SCROLLING_MANAGER_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_SCROLLING_MANAGER_H_
#include <gdk/gdk.h>
#include "flutter/shell/platform/linux/fl_scrolling_view_delegate.h"
G_BEGIN_DECLS
#define FL_TYPE_SCROLLING_MANAGER fl_scrolling_manager_get_type()
G_DECLARE_FINAL_TYPE(FlScrollingManager,
fl_scrolling_manager,
FL,
SCROLLING_MANAGER,
GObject);
/**
* fl_scrolling_manager_new:
* @view_delegate: An interface that the manager requires to communicate with
* the platform. Usually implemented by FlView.
*
* Create a new #FlScrollingManager.
*
* Returns: a new #FlScrollingManager.
*/
FlScrollingManager* fl_scrolling_manager_new(
FlScrollingViewDelegate* view_delegate);
/**
* fl_scrolling_manager_set_last_mouse_position:
* @manager: an #FlScrollingManager.
* @x: the mouse x-position, in window coordinates.
* @y: the mouse y-position, in window coordinates.
*
* Inform the scrolling manager of the mouse position.
* This position will be used when sending scroll pointer events.
*/
void fl_scrolling_manager_set_last_mouse_position(FlScrollingManager* manager,
gdouble x,
gdouble y);
/**
* fl_scrolling_manager_handle_scroll_event:
* @manager: an #FlScrollingManager.
* @event: the scroll event.
* @scale_factor: the GTK scaling factor of the window.
*
* Inform the scrolling manager of a scroll event.
*/
void fl_scrolling_manager_handle_scroll_event(FlScrollingManager* manager,
GdkEventScroll* event,
gint scale_factor);
/**
* fl_scrolling_manager_handle_rotation_begin:
* @manager: an #FlScrollingManager.
*
* Inform the scrolling manager that a rotation gesture has begun.
*/
void fl_scrolling_manager_handle_rotation_begin(FlScrollingManager* manager);
/**
* fl_scrolling_manager_handle_rotation_update:
* @manager: an #FlScrollingManager.
* @rotation: the rotation angle, in radians.
*
* Inform the scrolling manager that a rotation gesture has updated.
*/
void fl_scrolling_manager_handle_rotation_update(FlScrollingManager* manager,
gdouble rotation);
/**
* fl_scrolling_manager_handle_rotation_end:
* @manager: an #FlScrollingManager.
*
* Inform the scrolling manager that a rotation gesture has ended.
*/
void fl_scrolling_manager_handle_rotation_end(FlScrollingManager* manager);
/**
* fl_scrolling_manager_handle_zoom_begin:
* @manager: an #FlScrollingManager.
*
* Inform the scrolling manager that a zoom gesture has begun.
*/
void fl_scrolling_manager_handle_zoom_begin(FlScrollingManager* manager);
/**
* fl_scrolling_manager_handle_zoom_update:
* @manager: an #FlScrollingManager.
* @scale: the zoom scale.
*
* Inform the scrolling manager that a zoom gesture has updated.
*/
void fl_scrolling_manager_handle_zoom_update(FlScrollingManager* manager,
gdouble scale);
/**
* fl_scrolling_manager_handle_zoom_end:
* @manager: an #FlScrollingManager.
*
* Inform the scrolling manager that a zoom gesture has ended.
*/
void fl_scrolling_manager_handle_zoom_end(FlScrollingManager* manager);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_SCROLLING_MANAGER_H_
| engine/shell/platform/linux/fl_scrolling_manager.h/0 | {
"file_path": "engine/shell/platform/linux/fl_scrolling_manager.h",
"repo_id": "engine",
"token_count": 1414
} | 363 |
// 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/linux/public/flutter_linux/fl_string_codec.h"
#include <gmodule.h>
#include <cstring>
G_DEFINE_QUARK(fl_string_codec_error_quark, fl_string_codec_error)
struct _FlStringCodec {
FlMessageCodec parent_instance;
};
G_DEFINE_TYPE(FlStringCodec, fl_string_codec, fl_message_codec_get_type())
// Implements FlMessageCodec::encode_message.
static GBytes* fl_string_codec_encode_message(FlMessageCodec* codec,
FlValue* value,
GError** error) {
if (fl_value_get_type(value) != FL_VALUE_TYPE_STRING) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE,
"Only string values supported");
return nullptr;
}
const gchar* text = fl_value_get_string(value);
return g_bytes_new(text, strlen(text));
}
// Implements FlMessageCodec::decode_message.
static FlValue* fl_string_codec_decode_message(FlMessageCodec* codec,
GBytes* message,
GError** error) {
gsize data_length;
const gchar* data =
static_cast<const gchar*>(g_bytes_get_data(message, &data_length));
return fl_value_new_string_sized(data, data_length);
}
static void fl_string_codec_class_init(FlStringCodecClass* klass) {
FL_MESSAGE_CODEC_CLASS(klass)->encode_message =
fl_string_codec_encode_message;
FL_MESSAGE_CODEC_CLASS(klass)->decode_message =
fl_string_codec_decode_message;
}
static void fl_string_codec_init(FlStringCodec* self) {}
G_MODULE_EXPORT FlStringCodec* fl_string_codec_new() {
return static_cast<FlStringCodec*>(
g_object_new(fl_string_codec_get_type(), nullptr));
}
| engine/shell/platform/linux/fl_string_codec.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_string_codec.cc",
"repo_id": "engine",
"token_count": 880
} | 364 |
// 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/linux/public/flutter_linux/fl_texture_registrar.h"
#include "flutter/shell/platform/linux/fl_texture_registrar_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_pixel_buffer_texture.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_gl.h"
#include "flutter/shell/platform/linux/testing/fl_test.h"
#include "flutter/shell/platform/linux/testing/mock_texture_registrar.h"
#include "gtest/gtest.h"
#include <epoxy/gl.h>
#include <gmodule.h>
#include <pthread.h>
static constexpr uint32_t kBufferWidth = 4u;
static constexpr uint32_t kBufferHeight = 4u;
static constexpr uint32_t kRealBufferWidth = 2u;
static constexpr uint32_t kRealBufferHeight = 2u;
static constexpr uint64_t kThreadCount = 16u;
G_DECLARE_FINAL_TYPE(FlTestRegistrarTexture,
fl_test_registrar_texture,
FL,
TEST_REGISTRAR_TEXTURE,
FlTextureGL)
/// A simple texture.
struct _FlTestRegistrarTexture {
FlTextureGL parent_instance;
};
G_DEFINE_TYPE(FlTestRegistrarTexture,
fl_test_registrar_texture,
fl_texture_gl_get_type())
static gboolean fl_test_registrar_texture_populate(FlTextureGL* texture,
uint32_t* target,
uint32_t* format,
uint32_t* width,
uint32_t* height,
GError** error) {
EXPECT_TRUE(FL_IS_TEST_REGISTRAR_TEXTURE(texture));
EXPECT_EQ(*width, kBufferWidth);
EXPECT_EQ(*height, kBufferHeight);
*target = GL_TEXTURE_2D;
*format = GL_R8;
*width = kRealBufferWidth;
*height = kRealBufferHeight;
return TRUE;
}
static void fl_test_registrar_texture_class_init(
FlTestRegistrarTextureClass* klass) {
FL_TEXTURE_GL_CLASS(klass)->populate = fl_test_registrar_texture_populate;
}
static void fl_test_registrar_texture_init(FlTestRegistrarTexture* self) {}
static FlTestRegistrarTexture* fl_test_registrar_texture_new() {
return FL_TEST_REGISTRAR_TEXTURE(
g_object_new(fl_test_registrar_texture_get_type(), nullptr));
}
static void* add_mock_texture_to_registrar(void* pointer) {
g_return_val_if_fail(FL_TEXTURE_REGISTRAR(pointer), ((void*)NULL));
FlTextureRegistrar* registrar = FL_TEXTURE_REGISTRAR(pointer);
g_autoptr(FlTexture) texture = FL_TEXTURE(fl_test_registrar_texture_new());
fl_texture_registrar_register_texture(registrar, texture);
int64_t* id = static_cast<int64_t*>(malloc(sizeof(int64_t)));
id[0] = fl_texture_get_id(texture);
pthread_exit(id);
}
// Checks can make a mock registrar.
TEST(FlTextureRegistrarTest, MockRegistrar) {
g_autoptr(FlTexture) texture = FL_TEXTURE(fl_test_registrar_texture_new());
g_autoptr(FlMockTextureRegistrar) registrar = fl_mock_texture_registrar_new();
EXPECT_TRUE(FL_IS_MOCK_TEXTURE_REGISTRAR(registrar));
EXPECT_TRUE(fl_texture_registrar_register_texture(
FL_TEXTURE_REGISTRAR(registrar), texture));
EXPECT_EQ(fl_mock_texture_registrar_get_texture(registrar), texture);
EXPECT_TRUE(fl_texture_registrar_mark_texture_frame_available(
FL_TEXTURE_REGISTRAR(registrar), texture));
EXPECT_TRUE(fl_mock_texture_registrar_get_frame_available(registrar));
EXPECT_TRUE(fl_texture_registrar_unregister_texture(
FL_TEXTURE_REGISTRAR(registrar), texture));
EXPECT_EQ(fl_mock_texture_registrar_get_texture(registrar), nullptr);
}
// Test that registering a texture works.
TEST(FlTextureRegistrarTest, RegisterTexture) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlTextureRegistrar) registrar = fl_texture_registrar_new(engine);
g_autoptr(FlTexture) texture = FL_TEXTURE(fl_test_registrar_texture_new());
EXPECT_FALSE(fl_texture_registrar_unregister_texture(registrar, texture));
EXPECT_TRUE(fl_texture_registrar_register_texture(registrar, texture));
EXPECT_TRUE(fl_texture_registrar_unregister_texture(registrar, texture));
}
// Test that marking a texture frame available works.
TEST(FlTextureRegistrarTest, MarkTextureFrameAvailable) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlTextureRegistrar) registrar = fl_texture_registrar_new(engine);
g_autoptr(FlTexture) texture = FL_TEXTURE(fl_test_registrar_texture_new());
EXPECT_FALSE(
fl_texture_registrar_mark_texture_frame_available(registrar, texture));
EXPECT_TRUE(fl_texture_registrar_register_texture(registrar, texture));
EXPECT_TRUE(
fl_texture_registrar_mark_texture_frame_available(registrar, texture));
}
// Test the textures can be accessed via multiple threads without
// synchronization issues.
// TODO(robert-ancell): Re-enable when no longer flaky
// https://github.com/flutter/flutter/issues/138197
TEST(FlTextureRegistrarTest,
DISABLED_RegistrarRegisterTextureInMultipleThreads) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlTextureRegistrar) registrar = fl_texture_registrar_new(engine);
pthread_t threads[kThreadCount];
int64_t ids[kThreadCount];
for (uint64_t t = 0; t < kThreadCount; t++) {
EXPECT_EQ(pthread_create(&threads[t], NULL, add_mock_texture_to_registrar,
(void*)registrar),
0);
}
for (uint64_t t = 0; t < kThreadCount; t++) {
void* id;
pthread_join(threads[t], &id);
ids[t] = static_cast<int64_t*>(id)[0];
free(id);
};
// Check all the textures were created.
for (uint64_t t = 0; t < kThreadCount; t++) {
EXPECT_TRUE(fl_texture_registrar_lookup_texture(registrar, ids[t]) != NULL);
};
}
| engine/shell/platform/linux/fl_texture_registrar_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_texture_registrar_test.cc",
"repo_id": "engine",
"token_count": 2449
} | 365 |
// 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_LINUX_PUBLIC_FLUTTER_LINUX_FL_ENGINE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_ENGINE_H_
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
#include <glib-object.h>
#include <gmodule.h>
#include "fl_binary_messenger.h"
#include "fl_dart_project.h"
#include "fl_texture_registrar.h"
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_FINAL_TYPE(FlEngine, fl_engine, FL, ENGINE, GObject)
/**
* FlEngine:
*
* #FlEngine is an object that contains a running Flutter engine.
*/
/**
* fl_engine_new_headless:
* @project: an #FlDartProject.
*
* Creates new Flutter engine running in headless mode.
*
* Returns: a new #FlEngine.
*/
FlEngine* fl_engine_new_headless(FlDartProject* project);
/**
* fl_engine_get_binary_messenger:
* @engine: an #FlEngine.
*
* Gets the messenger to communicate with this engine.
*
* Returns: an #FlBinaryMessenger.
*/
FlBinaryMessenger* fl_engine_get_binary_messenger(FlEngine* engine);
/**
* fl_engine_get_texture_registrar:
* @engine: an #FlEngine.
*
* Gets the texture registrar for registering textures.
*
* Returns: an #FlTextureRegistrar.
*/
FlTextureRegistrar* fl_engine_get_texture_registrar(FlEngine* engine);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_ENGINE_H_
| engine/shell/platform/linux/public/flutter_linux/fl_engine.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_engine.h",
"repo_id": "engine",
"token_count": 587
} | 366 |
// 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_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_GL_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_GL_H_
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
#include <glib-object.h>
#include <gmodule.h>
#include <stdint.h>
#include "fl_texture.h"
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_DERIVABLE_TYPE(FlTextureGL, fl_texture_gl, FL, TEXTURE_GL, GObject)
/**
* FlTextureGL:
*
* #FlTextureGL is an abstract class that represents an OpenGL texture.
*
* If you want to render textures in other OpenGL context, create and use the
* #GdkGLContext by calling gdk_window_create_gl_context () with the #GdkWindow
* of #FlView. The context will be shared with the one used by Flutter.
*
* The following example shows how to implement an #FlTextureGL.
* ![<!-- language="C" -->
* #include <epoxy/gl.h>
*
* struct _MyTextureGL {
* FlTextureGL parent_instance;
*
* GLuint texture_id;
* };
*
* G_DEFINE_TYPE(MyTextureGL,
* my_texture_gl,
* fl_texture_gl_get_type ())
*
* static gboolean
* my_texture_gl_populate (FlTextureGL *texture,
* uint32_t *target,
* uint32_t *name,
* uint32_t *width,
* uint32_t *height,
* GError **error) {
* MyTextureGL *self = MY_TEXTURE_GL (texture);
* if (self->texture_id == 0) {
* glGenTextures (1, &self->texture_id);
* glBindTexture (GL_TEXTURE_2D, self->texture_id);
* // further configuration here.
* } else {
* glBindTexture (GL_TEXTURE_2D, self->texture_id);
* }
*
* // For example, we render pixel buffer here.
* // Note that Flutter only accepts textures in GL_RGBA8 format.
* static char buffer[] = { 0x1f, 0x2f, 0x3f, 0x4f }; // 1x1 pixel.
* glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA,
* GL_UNSIGNED_BYTE, buffer);
*
* *target = GL_TEXTURE_2D;
* *name = self->texture_id;
* *width = 1;
* *height = 1;
*
* return TRUE;
* }
*
* static void my_texture_class_init(MyTextureClass* klass) {
* FL_TEXTURE_GL_CLASS(klass)->populate = my_texture_gl_populate;
* }
*
* static void my_texture_init(MyTexture* self) {}
* ]|
*/
struct _FlTextureGLClass {
GObjectClass parent_class;
/**
* Virtual method called when Flutter populates this texture. The OpenGL
* context used by Flutter has been already set.
* @texture: an #FlTexture.
* @target: texture target (example GL_TEXTURE_2D or GL_TEXTURE_RECTANGLE).
* @name: (out): name of texture.
* @width: (inout): width of the texture in pixels.
* @height: (inout): height of the texture in pixels.
* @error: (allow-none): #GError location to store the error occurring, or
* %NULL to ignore.
*
* Returns: %TRUE on success.
*/
gboolean (*populate)(FlTextureGL* texture,
uint32_t* target,
uint32_t* name,
uint32_t* width,
uint32_t* height,
GError** error);
};
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_GL_H_
| engine/shell/platform/linux/public/flutter_linux/fl_texture_gl.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_texture_gl.h",
"repo_id": "engine",
"token_count": 1561
} | 367 |
// 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 <epoxy/egl.h>
#include <epoxy/gl.h>
typedef struct {
EGLint config_id;
EGLint buffer_size;
EGLint color_buffer_type;
EGLint transparent_type;
EGLint level;
EGLint red_size;
EGLint green_size;
EGLint blue_size;
EGLint alpha_size;
EGLint depth_size;
EGLint stencil_size;
EGLint samples;
EGLint sample_buffers;
EGLint native_visual_id;
EGLint native_visual_type;
EGLint native_renderable;
EGLint config_caveat;
EGLint bind_to_texture_rgb;
EGLint bind_to_texture_rgba;
EGLint renderable_type;
EGLint conformant;
EGLint surface_type;
EGLint max_pbuffer_width;
EGLint max_pbuffer_height;
EGLint max_pbuffer_pixels;
EGLint min_swap_interval;
EGLint max_swap_interval;
} MockConfig;
typedef struct {
} MockDisplay;
typedef struct {
} MockContext;
typedef struct {
} MockSurface;
static bool display_initialized = false;
static MockDisplay mock_display;
static MockConfig mock_config;
static MockContext mock_context;
static MockSurface mock_surface;
static EGLint mock_error = EGL_SUCCESS;
static bool check_display(EGLDisplay dpy) {
if (dpy == nullptr) {
mock_error = EGL_BAD_DISPLAY;
return false;
}
return true;
}
static bool check_initialized(EGLDisplay dpy) {
if (!display_initialized) {
mock_error = EGL_NOT_INITIALIZED;
return false;
}
return true;
}
static bool check_config(EGLConfig config) {
if (config == nullptr) {
mock_error = EGL_BAD_CONFIG;
return false;
}
return true;
}
static EGLBoolean bool_success() {
mock_error = EGL_SUCCESS;
return EGL_TRUE;
}
static EGLBoolean bool_failure(EGLint error) {
mock_error = error;
return EGL_FALSE;
}
EGLBoolean _eglBindAPI(EGLenum api) {
return bool_success();
}
EGLBoolean _eglChooseConfig(EGLDisplay dpy,
const EGLint* attrib_list,
EGLConfig* configs,
EGLint config_size,
EGLint* num_config) {
if (!check_display(dpy) || !check_initialized(dpy)) {
return EGL_FALSE;
}
if (configs == nullptr) {
if (num_config != nullptr) {
*num_config = 1;
}
return bool_success();
}
EGLint n_returned = 0;
if (config_size >= 1) {
configs[0] = &mock_config;
n_returned++;
}
if (num_config != nullptr) {
*num_config = n_returned;
}
return bool_success();
}
EGLContext _eglCreateContext(EGLDisplay dpy,
EGLConfig config,
EGLContext share_context,
const EGLint* attrib_list) {
if (!check_display(dpy) || !check_initialized(dpy) || !check_config(config)) {
return EGL_NO_CONTEXT;
}
mock_error = EGL_SUCCESS;
return &mock_context;
}
EGLSurface _eglCreatePbufferSurface(EGLDisplay dpy,
EGLConfig config,
const EGLint* attrib_list) {
if (!check_display(dpy) || !check_initialized(dpy) || !check_config(config)) {
return EGL_NO_SURFACE;
}
mock_error = EGL_SUCCESS;
return &mock_surface;
}
EGLSurface _eglCreateWindowSurface(EGLDisplay dpy,
EGLConfig config,
EGLNativeWindowType win,
const EGLint* attrib_list) {
if (!check_display(dpy) || !check_initialized(dpy) || !check_config(config)) {
return EGL_NO_SURFACE;
}
mock_error = EGL_SUCCESS;
return &mock_surface;
}
EGLBoolean _eglGetConfigAttrib(EGLDisplay dpy,
EGLConfig config,
EGLint attribute,
EGLint* value) {
if (!check_display(dpy) || !check_initialized(dpy) || !check_config(config)) {
return EGL_FALSE;
}
MockConfig* c = static_cast<MockConfig*>(config);
switch (attribute) {
case EGL_CONFIG_ID:
*value = c->config_id;
return bool_success();
case EGL_BUFFER_SIZE:
*value = c->buffer_size;
return bool_success();
case EGL_COLOR_BUFFER_TYPE:
*value = c->color_buffer_type;
return bool_success();
case EGL_TRANSPARENT_TYPE:
*value = c->transparent_type;
return bool_success();
case EGL_LEVEL:
*value = c->level;
return bool_success();
case EGL_RED_SIZE:
*value = c->red_size;
return bool_success();
case EGL_GREEN_SIZE:
*value = c->green_size;
return bool_success();
case EGL_BLUE_SIZE:
*value = c->blue_size;
return bool_success();
case EGL_ALPHA_SIZE:
*value = c->alpha_size;
return bool_success();
case EGL_DEPTH_SIZE:
*value = c->depth_size;
return bool_success();
case EGL_STENCIL_SIZE:
*value = c->stencil_size;
return bool_success();
case EGL_SAMPLES:
*value = c->samples;
return bool_success();
case EGL_SAMPLE_BUFFERS:
*value = c->sample_buffers;
return bool_success();
case EGL_NATIVE_VISUAL_ID:
*value = c->native_visual_id;
return bool_success();
case EGL_NATIVE_VISUAL_TYPE:
*value = c->native_visual_type;
return bool_success();
case EGL_NATIVE_RENDERABLE:
*value = c->native_renderable;
return bool_success();
case EGL_CONFIG_CAVEAT:
*value = c->config_caveat;
return bool_success();
case EGL_BIND_TO_TEXTURE_RGB:
*value = c->bind_to_texture_rgb;
return bool_success();
case EGL_BIND_TO_TEXTURE_RGBA:
*value = c->bind_to_texture_rgba;
return bool_success();
case EGL_RENDERABLE_TYPE:
*value = c->renderable_type;
return bool_success();
case EGL_CONFORMANT:
*value = c->conformant;
return bool_success();
case EGL_SURFACE_TYPE:
*value = c->surface_type;
return bool_success();
case EGL_MAX_PBUFFER_WIDTH:
*value = c->max_pbuffer_width;
return bool_success();
case EGL_MAX_PBUFFER_HEIGHT:
*value = c->max_pbuffer_height;
return bool_success();
case EGL_MAX_PBUFFER_PIXELS:
*value = c->max_pbuffer_pixels;
return bool_success();
case EGL_MIN_SWAP_INTERVAL:
*value = c->min_swap_interval;
return bool_success();
case EGL_MAX_SWAP_INTERVAL:
*value = c->max_swap_interval;
return bool_success();
default:
return bool_failure(EGL_BAD_ATTRIBUTE);
}
}
EGLDisplay _eglGetDisplay(EGLNativeDisplayType display_id) {
return &mock_display;
}
EGLint _eglGetError() {
EGLint error = mock_error;
mock_error = EGL_SUCCESS;
return error;
}
void (*_eglGetProcAddress(const char* procname))(void) {
mock_error = EGL_SUCCESS;
return nullptr;
}
EGLBoolean _eglInitialize(EGLDisplay dpy, EGLint* major, EGLint* minor) {
if (!check_display(dpy)) {
return EGL_FALSE;
}
if (!display_initialized) {
mock_config.config_id = 1;
mock_config.buffer_size = 32;
mock_config.color_buffer_type = EGL_RGB_BUFFER;
mock_config.transparent_type = EGL_NONE;
mock_config.level = 1;
mock_config.red_size = 8;
mock_config.green_size = 8;
mock_config.blue_size = 8;
mock_config.alpha_size = 0;
mock_config.depth_size = 0;
mock_config.stencil_size = 0;
mock_config.samples = 0;
mock_config.sample_buffers = 0;
mock_config.native_visual_id = 1;
mock_config.native_visual_type = 0;
mock_config.native_renderable = EGL_TRUE;
mock_config.config_caveat = EGL_NONE;
mock_config.bind_to_texture_rgb = EGL_TRUE;
mock_config.bind_to_texture_rgba = EGL_FALSE;
mock_config.renderable_type = EGL_OPENGL_ES2_BIT;
mock_config.conformant = EGL_OPENGL_ES2_BIT;
mock_config.surface_type = EGL_WINDOW_BIT | EGL_PBUFFER_BIT;
mock_config.max_pbuffer_width = 1024;
mock_config.max_pbuffer_height = 1024;
mock_config.max_pbuffer_pixels = 1024 * 1024;
mock_config.min_swap_interval = 0;
mock_config.max_swap_interval = 1000;
display_initialized = true;
}
if (major != nullptr) {
*major = 1;
}
if (minor != nullptr) {
*minor = 5;
}
return bool_success();
}
EGLBoolean _eglMakeCurrent(EGLDisplay dpy,
EGLSurface draw,
EGLSurface read,
EGLContext ctx) {
if (!check_display(dpy) || !check_initialized(dpy)) {
return EGL_FALSE;
}
return bool_success();
}
EGLBoolean _eglSwapBuffers(EGLDisplay dpy, EGLSurface surface) {
if (!check_display(dpy) || !check_initialized(dpy)) {
return EGL_FALSE;
}
return bool_success();
}
static void _glBindFramebuffer(GLenum target, GLuint framebuffer) {}
static void _glBindTexture(GLenum target, GLuint texture) {}
void _glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers) {}
void _glDeleteTextures(GLsizei n, const GLuint* textures) {}
static void _glFramebufferTexture2D(GLenum target,
GLenum attachment,
GLenum textarget,
GLuint texture,
GLint level) {}
static void _glGenTextures(GLsizei n, GLuint* textures) {
for (GLsizei i = 0; i < n; i++) {
textures[i] = 0;
}
}
static void _glGenFramebuffers(GLsizei n, GLuint* framebuffers) {
for (GLsizei i = 0; i < n; i++) {
framebuffers[i] = 0;
}
}
static void _glTexParameterf(GLenum target, GLenum pname, GLfloat param) {}
static void _glTexParameteri(GLenum target, GLenum pname, GLint param) {}
static void _glTexImage2D(GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLint border,
GLenum format,
GLenum type,
const void* pixels) {}
static GLenum _glGetError() {
return GL_NO_ERROR;
}
bool epoxy_has_gl_extension(const char* extension) {
return false;
}
bool epoxy_is_desktop_gl(void) {
return false;
}
int epoxy_gl_version(void) {
return 0;
}
#ifdef __GNUC__
#define CONSTRUCT(_func) static void _func(void) __attribute__((constructor));
#define DESTRUCT(_func) static void _func(void) __attribute__((destructor));
#elif defined(_MSC_VER) && (_MSC_VER >= 1500)
#define CONSTRUCT(_func) \
static void _func(void); \
static int _func##_wrapper(void) { \
_func(); \
return 0; \
} \
__pragma(section(".CRT$XCU", read)) \
__declspec(allocate(".CRT$XCU")) static int (*_array##_func)(void) = \
_func##_wrapper;
#else
#error "You will need constructor support for your compiler"
#endif
CONSTRUCT(library_init)
EGLBoolean (*epoxy_eglBindAPI)(EGLenum api);
EGLBoolean (*epoxy_eglChooseConfig)(EGLDisplay dpy,
const EGLint* attrib_list,
EGLConfig* configs,
EGLint config_size,
EGLint* num_config);
EGLContext (*epoxy_eglCreateContext)(EGLDisplay dpy,
EGLConfig config,
EGLContext share_context,
const EGLint* attrib_list);
EGLSurface (*epoxy_eglCreatePbufferSurface)(EGLDisplay dpy,
EGLConfig config,
const EGLint* attrib_list);
EGLSurface (*epoxy_eglCreateWindowSurface)(EGLDisplay dpy,
EGLConfig config,
EGLNativeWindowType win,
const EGLint* attrib_list);
EGLBoolean (*epoxy_eglGetConfigAttrib)(EGLDisplay dpy,
EGLConfig config,
EGLint attribute,
EGLint* value);
EGLDisplay (*epoxy_eglGetDisplay)(EGLNativeDisplayType display_id);
EGLint (*epoxy_eglGetError)();
void (*(*epoxy_eglGetProcAddress)(const char* procname))(void);
EGLBoolean (*epoxy_eglInitialize)(EGLDisplay dpy, EGLint* major, EGLint* minor);
EGLBoolean (*epoxy_eglMakeCurrent)(EGLDisplay dpy,
EGLSurface draw,
EGLSurface read,
EGLContext ctx);
EGLBoolean (*epoxy_eglSwapBuffers)(EGLDisplay dpy, EGLSurface surface);
void (*epoxy_glBindFramebuffer)(GLenum target, GLuint framebuffer);
void (*epoxy_glBindTexture)(GLenum target, GLuint texture);
void (*epoxy_glDeleteFramebuffers)(GLsizei n, const GLuint* framebuffers);
void (*epoxy_glDeleteTextures)(GLsizei n, const GLuint* textures);
void (*epoxy_glFramebufferTexture2D)(GLenum target,
GLenum attachment,
GLenum textarget,
GLuint texture,
GLint level);
void (*epoxy_glGenFramebuffers)(GLsizei n, GLuint* framebuffers);
void (*epoxy_glGenTextures)(GLsizei n, GLuint* textures);
void (*epoxy_glTexParameterf)(GLenum target, GLenum pname, GLfloat param);
void (*epoxy_glTexParameteri)(GLenum target, GLenum pname, GLint param);
void (*epoxy_glTexImage2D)(GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLint border,
GLenum format,
GLenum type,
const void* pixels);
GLenum (*epoxy_glGetError)();
static void library_init() {
epoxy_eglBindAPI = _eglBindAPI;
epoxy_eglChooseConfig = _eglChooseConfig;
epoxy_eglCreateContext = _eglCreateContext;
epoxy_eglCreatePbufferSurface = _eglCreatePbufferSurface;
epoxy_eglCreateWindowSurface = _eglCreateWindowSurface;
epoxy_eglGetConfigAttrib = _eglGetConfigAttrib;
epoxy_eglGetDisplay = _eglGetDisplay;
epoxy_eglGetError = _eglGetError;
epoxy_eglGetProcAddress = _eglGetProcAddress;
epoxy_eglInitialize = _eglInitialize;
epoxy_eglMakeCurrent = _eglMakeCurrent;
epoxy_eglSwapBuffers = _eglSwapBuffers;
epoxy_glBindFramebuffer = _glBindFramebuffer;
epoxy_glBindTexture = _glBindTexture;
epoxy_glDeleteFramebuffers = _glDeleteFramebuffers;
epoxy_glDeleteTextures = _glDeleteTextures;
epoxy_glFramebufferTexture2D = _glFramebufferTexture2D;
epoxy_glGenFramebuffers = _glGenFramebuffers;
epoxy_glGenTextures = _glGenTextures;
epoxy_glTexParameterf = _glTexParameterf;
epoxy_glTexParameteri = _glTexParameteri;
epoxy_glTexImage2D = _glTexImage2D;
epoxy_glGetError = _glGetError;
}
| engine/shell/platform/linux/testing/mock_epoxy.cc/0 | {
"file_path": "engine/shell/platform/linux/testing/mock_epoxy.cc",
"repo_id": "engine",
"token_count": 7488
} | 368 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.