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.
@TestOn('browser')
library;
import 'dart:js_util';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
int callOrder = 1;
int initCalled = 0;
int runCalled = 0;
setUp(() {
callOrder = 1;
initCalled = 0;
runCalled = 0;
});
Future<void> mockInit ([JsFlutterConfiguration? configuration]) async {
debugOverrideJsConfiguration(configuration);
addTearDown(() => debugOverrideJsConfiguration(null));
initCalled = callOrder++;
await Future<void>.delayed(const Duration(milliseconds: 1));
}
void mockRunApp () {
runCalled = callOrder++;
}
test('autoStart() immediately calls init and run', () async {
final AppBootstrap bootstrap = AppBootstrap(
initializeEngine: mockInit,
runApp: mockRunApp,
);
await bootstrap.autoStart();
expect(initCalled, 1, reason: 'initEngine should be called first.');
expect(runCalled, 2, reason: 'runApp should be called after init.');
});
test('engineInitializer autoStart() does the same as Dart autoStart()', () async {
final AppBootstrap bootstrap = AppBootstrap(
initializeEngine: mockInit,
runApp: mockRunApp,
);
final FlutterEngineInitializer engineInitializer = bootstrap.prepareEngineInitializer();
expect(engineInitializer, isNotNull);
final Object maybeApp = await promiseToFuture<Object>(callMethod<Object>(engineInitializer, 'autoStart', <Object?>[]));
expect(maybeApp, isA<FlutterApp>());
expect(initCalled, 1, reason: 'initEngine should be called first.');
expect(runCalled, 2, reason: 'runApp should be called after init.');
});
test('engineInitializer initEngine() calls init and returns an appRunner', () async {
final AppBootstrap bootstrap = AppBootstrap(
initializeEngine: mockInit,
runApp: mockRunApp,
);
final FlutterEngineInitializer engineInitializer = bootstrap.prepareEngineInitializer();
final Object maybeAppInitializer = await promiseToFuture<Object>(callMethod<Object>(engineInitializer, 'initializeEngine', <Object?>[]));
expect(maybeAppInitializer, isA<FlutterAppRunner>());
expect(initCalled, 1, reason: 'initEngine should have been called.');
expect(runCalled, 0, reason: 'runApp should not have been called.');
});
test('appRunner runApp() calls run and returns a FlutterApp', () async {
final AppBootstrap bootstrap = AppBootstrap(
initializeEngine: mockInit,
runApp: mockRunApp,
);
final FlutterEngineInitializer engineInitializer = bootstrap.prepareEngineInitializer();
final Object appInitializer = await promiseToFuture<Object>(callMethod<Object>(
engineInitializer,
'initializeEngine',
<Object?>[]
));
expect(appInitializer, isA<FlutterAppRunner>());
final Object maybeApp = await promiseToFuture<Object>(callMethod<Object>(
appInitializer,
'runApp',
<Object?>[]
));
expect(maybeApp, isA<FlutterApp>());
expect(initCalled, 1, reason: 'initEngine should have been called.');
expect(runCalled, 2, reason: 'runApp should have been called.');
});
group('FlutterApp', () {
test('has addView/removeView methods', () async {
final AppBootstrap bootstrap = AppBootstrap(
initializeEngine: mockInit,
runApp: mockRunApp,
);
final FlutterEngineInitializer engineInitializer = bootstrap.prepareEngineInitializer();
final Object appInitializer = await promiseToFuture<Object>(callMethod<Object>(
engineInitializer,
'initializeEngine',
<Object?>[]
));
final Object maybeApp = await promiseToFuture<Object>(callMethod<Object>(
appInitializer,
'runApp',
<Object?>[]
));
expect(maybeApp, isA<FlutterApp>());
expect(getJsProperty<dynamic>(maybeApp, 'addView'), isA<Function>());
expect(getJsProperty<dynamic>(maybeApp, 'removeView'), isA<Function>());
});
test('addView/removeView respectively adds/removes view', () async {
final AppBootstrap bootstrap = AppBootstrap(
initializeEngine: mockInit,
runApp: mockRunApp,
);
final FlutterEngineInitializer engineInitializer = bootstrap.prepareEngineInitializer();
final Object appInitializer = await promiseToFuture<Object>(callMethod<Object>(
engineInitializer,
'initializeEngine',
<dynamic>[jsify(<String, Object?>{
'multiViewEnabled': true,
})]
));
final Object maybeApp = await promiseToFuture<Object>(callMethod<Object>(
appInitializer,
'runApp',
<Object?>[]
));
final int viewId = callMethod<num>(
maybeApp,
'addView',
<dynamic>[jsify(<String, Object?>{
'hostElement': createDomElement('div'),
})]
).toInt();
expect(bootstrap.viewManager[viewId], isNotNull);
callMethod<Object>(
maybeApp,
'removeView',
<Object>[viewId]
);
expect(bootstrap.viewManager[viewId], isNull);
});
});
}
| engine/lib/web_ui/test/engine/app_bootstrap_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/app_bootstrap_test.dart",
"repo_id": "engine",
"token_count": 1917
} | 322 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine/html_image_codec.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests();
group('HtmCodec', () {
test('supports raw images - RGBA8888', () async {
final Completer<ui.Image> completer = Completer<ui.Image>();
const int width = 200;
const int height = 300;
final Uint32List list = Uint32List(width * height);
for (int index = 0; index < list.length; index += 1) {
list[index] = 0xFF0000FF;
}
ui.decodeImageFromPixels(
list.buffer.asUint8List(),
width,
height,
ui.PixelFormat.rgba8888,
(ui.Image image) => completer.complete(image),
);
final ui.Image image = await completer.future;
expect(image.width, width);
expect(image.height, height);
});
test('supports raw images - BGRA8888', () async {
final Completer<ui.Image> completer = Completer<ui.Image>();
const int width = 200;
const int height = 300;
final Uint32List list = Uint32List(width * height);
for (int index = 0; index < list.length; index += 1) {
list[index] = 0xFF0000FF;
}
ui.decodeImageFromPixels(
list.buffer.asUint8List(),
width,
height,
ui.PixelFormat.bgra8888,
(ui.Image image) => completer.complete(image),
);
final ui.Image image = await completer.future;
expect(image.width, width);
expect(image.height, height);
});
test('loads sample image', () async {
final HtmlCodec codec = HtmlCodec('sample_image1.png');
final ui.FrameInfo frameInfo = await codec.getNextFrame();
expect(frameInfo.image, isNotNull);
expect(frameInfo.image.width, 100);
expect(frameInfo.image.toString(), '[100×100]');
});
test('dispose image image', () async {
final HtmlCodec codec = HtmlCodec('sample_image1.png');
final ui.FrameInfo frameInfo = await codec.getNextFrame();
expect(frameInfo.image, isNotNull);
expect(frameInfo.image.debugDisposed, isFalse);
frameInfo.image.dispose();
expect(frameInfo.image.debugDisposed, isTrue);
});
test('provides image loading progress', () async {
final StringBuffer buffer = StringBuffer();
final HtmlCodec codec = HtmlCodec('sample_image1.png',
chunkCallback: (int loaded, int total) {
buffer.write('$loaded/$total,');
});
await codec.getNextFrame();
expect(buffer.toString(), '0/100,100/100,');
});
/// Regression test for Firefox
/// https://github.com/flutter/flutter/issues/66412
test('Returns nonzero natural width/height', () async {
final HtmlCodec codec = HtmlCodec(
'data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHZpZXdCb3g9I'
'jAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dG'
'l0bGU+QWJzdHJhY3QgaWNvbjwvdGl0bGU+PHBhdGggZD0iTTEyIDBjOS42MDEgMCAx'
'MiAyLjM5OSAxMiAxMiAwIDkuNjAxLTIuMzk5IDEyLTEyIDEyLTkuNjAxIDAtMTItMi'
'4zOTktMTItMTJDMCAyLjM5OSAyLjM5OSAwIDEyIDB6bS0xLjk2OSAxOC41NjRjMi41'
'MjQuMDAzIDQuNjA0LTIuMDcgNC42MDktNC41OTUgMC0yLjUyMS0yLjA3NC00LjU5NS'
'00LjU5NS00LjU5NVM1LjQ1IDExLjQ0OSA1LjQ1IDEzLjk2OWMwIDIuNTE2IDIuMDY1'
'IDQuNTg4IDQuNTgxIDQuNTk1em04LjM0NC0uMTg5VjUuNjI1SDUuNjI1djIuMjQ3aD'
'EwLjQ5OHYxMC41MDNoMi4yNTJ6bS04LjM0NC02Ljc0OGEyLjM0MyAyLjM0MyAwIDEx'
'LS4wMDIgNC42ODYgMi4zNDMgMi4zNDMgMCAwMS4wMDItNC42ODZ6Ii8+PC9zdmc+');
final ui.FrameInfo frameInfo = await codec.getNextFrame();
expect(frameInfo.image.width, isNot(0));
});
});
group('ImageCodecUrl', () {
test('loads sample image from web', () async {
final Uri uri = Uri.base.resolve('sample_image1.png');
final HtmlCodec codec = await ui_web.createImageCodecFromUrl(uri) as HtmlCodec;
final ui.FrameInfo frameInfo = await codec.getNextFrame();
expect(frameInfo.image, isNotNull);
expect(frameInfo.image.width, 100);
});
test('provides image loading progress from web', () async {
final Uri uri = Uri.base.resolve('sample_image1.png');
final StringBuffer buffer = StringBuffer();
final HtmlCodec codec = await ui_web.createImageCodecFromUrl(uri,
chunkCallback: (int loaded, int total) {
buffer.write('$loaded/$total,');
}) as HtmlCodec;
await codec.getNextFrame();
expect(buffer.toString(), '0/100,100/100,');
});
});
}
| engine/lib/web_ui/test/engine/image/html_image_codec_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/image/html_image_codec_test.dart",
"repo_id": "engine",
"token_count": 2244
} | 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 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
setUpAll(() async {
await bootstrapAndRunApp();
});
group('PlatformViewManager', () {
const String viewType = 'forTest';
const int viewId = 6;
late PlatformViewManager contentManager;
setUp(() {
contentManager = PlatformViewManager();
});
group('knowsViewType', () {
test('recognizes viewTypes after registering them', () async {
expect(contentManager.knowsViewType(viewType), isFalse);
contentManager.registerFactory(viewType, (int id) => createDomHTMLDivElement());
expect(contentManager.knowsViewType(viewType), isTrue);
});
});
group('knowsViewId', () {
test('recognizes viewIds after *rendering* them', () async {
expect(contentManager.knowsViewId(viewId), isFalse);
contentManager.registerFactory(viewType, (int id) => createDomHTMLDivElement());
expect(contentManager.knowsViewId(viewId), isFalse);
contentManager.renderContent(viewType, viewId, null);
expect(contentManager.knowsViewId(viewId), isTrue);
});
test('forgets viewIds after clearing them', () {
contentManager.registerFactory(viewType, (int id) => createDomHTMLDivElement());
final DomElement view = contentManager.renderContent(viewType, viewId, null);
expect(contentManager.knowsViewId(viewId), isTrue);
contentManager.clearPlatformView(viewId);
expect(contentManager.knowsViewId(viewId), isFalse);
expect(view.parentNode, isNull);
});
});
group('registerFactory', () {
test('does NOT re-register factories', () async {
contentManager.registerFactory(
viewType, (int id) => createDomHTMLDivElement()..id = 'pass');
// this should be rejected
contentManager.registerFactory(
viewType, (int id) => createDomHTMLSpanElement()..id = 'fail');
final DomElement contents =
contentManager.renderContent(viewType, viewId, null);
expect(contents.querySelector('#pass'), isNotNull);
expect(contents.querySelector('#fail'), isNull,
reason: 'Factories cannot be overridden once registered');
});
});
group('renderContent', () {
const String unregisteredViewType = 'unregisteredForTest';
const String anotherViewType = 'anotherViewType';
setUp(() {
contentManager.registerFactory(viewType, (int id) {
return createDomHTMLDivElement()..setAttribute('data-viewId', '$id');
});
contentManager.registerFactory(anotherViewType, (int id) {
return createDomHTMLDivElement()
..setAttribute('data-viewId', '$id')
..style.height = 'auto'
..style.width = '55%';
});
});
test('refuse to render views for unregistered factories', () async {
expect(
() => contentManager.renderContent(unregisteredViewType, viewId, null),
throwsA(const TypeMatcher<AssertionError>().having(
(AssertionError error) => error.message,
'assertion message',
contains(unregisteredViewType),
)),
);
});
test('rendered markup contains required attributes', () async {
final DomElement content =
contentManager.renderContent(viewType, viewId, null);
expect(content.getAttribute('slot'), getPlatformViewSlotName(viewId));
expect(content.getAttribute('id'), getPlatformViewDomId(viewId));
final DomElement userContent = content.querySelector('div')!;
expect(userContent.style.height, '100%');
expect(userContent.style.width, '100%');
});
test('slot property has the same value as createPlatformViewSlot', () async {
final DomElement content =
contentManager.renderContent(viewType, viewId, null);
final DomElement slot = createPlatformViewSlot(viewId);
final DomElement innerSlot = slot.querySelector('slot')!;
expect(content.getAttribute('slot'), innerSlot.getAttribute('name'),
reason:
'The slot attribute of the rendered content must match the name attribute of the SLOT of a given viewId');
});
test('do not modify style.height / style.width if passed by the user (anotherViewType)',
() async {
final DomElement content =
contentManager.renderContent(anotherViewType, viewId, null);
final DomElement userContent = content.querySelector('div')!;
expect(userContent.style.height, 'auto');
expect(userContent.style.width, '55%');
});
test('returns cached instances of already-rendered content', () async {
final DomElement firstRender =
contentManager.renderContent(viewType, viewId, null);
final DomElement anotherRender =
contentManager.renderContent(viewType, viewId, null);
expect(firstRender, same(anotherRender));
});
});
group('getViewById', () {
test('finds created views', () async {
final Map<int, DomElement> views1 = <int, DomElement>{
1: createDomHTMLDivElement(),
2: createDomHTMLDivElement(),
5: createDomHTMLDivElement(),
};
final Map<int, DomElement> views2 = <int, DomElement>{
3: createDomHTMLDivElement(),
4: createDomHTMLDivElement(),
};
contentManager.registerFactory('forTest1', (int id) => views1[id]!);
contentManager.registerFactory('forTest2', (int id) => views2[id]!);
// Render all 5 views.
for (final int id in views1.keys) {
contentManager.renderContent('forTest1', id, null);
}
for (final int id in views2.keys) {
contentManager.renderContent('forTest2', id, null);
}
// Check all 5 views.
for (final int id in views1.keys) {
expect(contentManager.getViewById(id), views1[id]);
}
for (final int id in views2.keys) {
expect(contentManager.getViewById(id), views2[id]);
}
// Throws for unknown viewId.
expect(() {
contentManager.getViewById(99);
}, throwsA(isA<AssertionError>()));
});
test('throws if view has been cleared', () {
final DomHTMLDivElement view = createDomHTMLDivElement();
contentManager.registerFactory(viewType, (int id) => view);
// Throws before viewId is rendered.
expect(() {
contentManager.getViewById(viewId);
}, throwsA(isA<AssertionError>()));
contentManager.renderContent(viewType, viewId, null);
// Succeeds after viewId is rendered.
expect(contentManager.getViewById(viewId), view);
contentManager.clearPlatformView(viewId);
// Throws after viewId is cleared.
expect(() {
contentManager.getViewById(viewId);
}, throwsA(isA<AssertionError>()));
});
});
test('default factories', () {
final DomElement content0 = contentManager.renderContent(
ui_web.PlatformViewRegistry.defaultVisibleViewType,
viewId,
<dynamic, dynamic>{'tagName': 'table'},
);
expect(
contentManager.getViewById(viewId),
content0.querySelector('table'),
);
expect(contentManager.isVisible(viewId), isTrue);
expect(contentManager.isInvisible(viewId), isFalse);
final DomElement content1 = contentManager.renderContent(
ui_web.PlatformViewRegistry.defaultInvisibleViewType,
viewId + 1,
<dynamic, dynamic>{'tagName': 'script'},
);
expect(
contentManager.getViewById(viewId + 1),
content1.querySelector('script'),
);
expect(contentManager.isVisible(viewId + 1), isFalse);
expect(contentManager.isInvisible(viewId + 1), isTrue);
final DomElement content2 = contentManager.renderContent(
ui_web.PlatformViewRegistry.defaultVisibleViewType,
viewId + 2,
<dynamic, dynamic>{'tagName': 'p'},
);
expect(
contentManager.getViewById(viewId + 2),
content2.querySelector('p'),
);
expect(contentManager.isVisible(viewId + 2), isTrue);
expect(contentManager.isInvisible(viewId + 2), isFalse);
});
});
}
| engine/lib/web_ui/test/engine/platform_views/content_manager_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/platform_views/content_manager_test.dart",
"repo_id": "engine",
"token_count": 3459
} | 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.
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/semantics.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('$DesktopSemanticsEnabler', () {
late DesktopSemanticsEnabler desktopSemanticsEnabler;
late DomElement? placeholder;
setUp(() {
EngineSemantics.instance.semanticsEnabled = false;
desktopSemanticsEnabler = DesktopSemanticsEnabler();
placeholder = desktopSemanticsEnabler.prepareAccessibilityPlaceholder();
domDocument.body!.append(placeholder!);
});
tearDown(() {
expect(placeholder, isNotNull,
reason: 'Expected the test to create a placeholder');
placeholder!.remove();
EngineSemantics.instance.semanticsEnabled = false;
});
test('prepare accessibility placeholder', () async {
expect(placeholder!.getAttribute('role'), 'button');
expect(placeholder!.getAttribute('aria-live'), 'polite');
expect(placeholder!.getAttribute('tabindex'), '0');
domDocument.body!.append(placeholder!);
expect(domDocument.getElementsByTagName('flt-semantics-placeholder'),
isNotEmpty);
expect(placeholder!.getBoundingClientRect().height, 1);
expect(placeholder!.getBoundingClientRect().width, 1);
expect(placeholder!.getBoundingClientRect().top, -1);
expect(placeholder!.getBoundingClientRect().left, -1);
});
test('Not relevant events should be forwarded to the framework', () async {
// Attach the placeholder to dom.
domDocument.body!.append(placeholder!);
DomEvent event = createDomEvent('Event', 'mousemove');
bool shouldForwardToFramework =
desktopSemanticsEnabler.tryEnableSemantics(event);
expect(shouldForwardToFramework, isTrue);
// Pointer events are not defined in webkit.
if (browserEngine != BrowserEngine.webkit) {
event = createDomEvent('Event', 'pointermove');
shouldForwardToFramework =
desktopSemanticsEnabler.tryEnableSemantics(event);
expect(shouldForwardToFramework, isTrue);
}
});
test(
'Relevant events targeting placeholder should not be forwarded to the framework',
() async {
final DomEvent event = createDomEvent('Event', 'mousedown');
placeholder!.dispatchEvent(event);
final bool shouldForwardToFramework =
desktopSemanticsEnabler.tryEnableSemantics(event);
expect(shouldForwardToFramework, isFalse);
});
test('disposes of the placeholder', () {
domDocument.body!.append(placeholder!);
expect(placeholder!.isConnected, isTrue);
desktopSemanticsEnabler.dispose();
expect(placeholder!.isConnected, isFalse);
});
}, skip: isMobile);
group(
'$MobileSemanticsEnabler',
() {
late MobileSemanticsEnabler mobileSemanticsEnabler;
DomElement? placeholder;
setUp(() {
EngineSemantics.instance.semanticsEnabled = false;
mobileSemanticsEnabler = MobileSemanticsEnabler();
placeholder = mobileSemanticsEnabler.prepareAccessibilityPlaceholder();
domDocument.body!.append(placeholder!);
});
tearDown(() {
placeholder!.remove();
EngineSemantics.instance.semanticsEnabled = false;
});
test('prepare accessibility placeholder', () async {
expect(placeholder!.getAttribute('role'), 'button');
// Placeholder should cover all the screen on a mobile device.
final num bodyHeight = domWindow.innerHeight!;
final num bodyWidth = domWindow.innerWidth!;
expect(placeholder!.getBoundingClientRect().height, bodyHeight);
expect(placeholder!.getBoundingClientRect().width, bodyWidth);
});
test('Non-relevant events should be forwarded to the framework',
() async {
final DomEvent event = createDomPointerEvent('pointermove');
final bool shouldForwardToFramework =
mobileSemanticsEnabler.tryEnableSemantics(event);
expect(shouldForwardToFramework, isTrue);
});
test('Enables semantics when receiving a relevant event', () {
expect(mobileSemanticsEnabler.semanticsActivationTimer, isNull);
// Send a click off center
placeholder!.dispatchEvent(createDomMouseEvent(
'click',
<Object?, Object?>{
'clientX': 0,
'clientY': 0,
}
));
expect(mobileSemanticsEnabler.semanticsActivationTimer, isNull);
// Send a click at center
final DomRect activatingElementRect =
placeholder!.getBoundingClientRect();
final int midX = (activatingElementRect.left +
(activatingElementRect.right - activatingElementRect.left) / 2)
.toInt();
final int midY = (activatingElementRect.top +
(activatingElementRect.bottom - activatingElementRect.top) / 2)
.toInt();
placeholder!.dispatchEvent(createDomMouseEvent(
'click',
<Object?, Object?>{
'clientX': midX,
'clientY': midY,
}
));
expect(mobileSemanticsEnabler.semanticsActivationTimer, isNotNull);
});
},
// We can run `MobileSemanticsEnabler` tests in mobile browsers and in desktop Chrome.
skip: isDesktop && browserEngine != BrowserEngine.blink,
);
}
| engine/lib/web_ui/test/engine/semantics/semantics_helper_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/semantics/semantics_helper_test.dart",
"repo_id": "engine",
"token_count": 2120
} | 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 'dart:async';
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
final Float32List identityTransform = Matrix4.identity().storage;
final Float32List xTranslation = (Matrix4.identity()..translate(10)).storage;
final Float32List yTranslation = (Matrix4.identity()..translate(0, 10)).storage;
final Float32List zTranslation = (Matrix4.identity()..translate(0, 0, 10)).storage;
final Float32List scaleAndTranslate2d = (Matrix4.identity()..scale(2, 3, 1)..translate(4, 5)).storage;
final Float32List rotation2d = (Matrix4.identity()..rotateZ(0.2)).storage;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
test('transformKindOf and isIdentityFloat32ListTransform identify matrix kind', () {
expect(transformKindOf(identityTransform), TransformKind.identity);
expect(isIdentityFloat32ListTransform(identityTransform), isTrue);
expect(transformKindOf(zTranslation), TransformKind.complex);
expect(isIdentityFloat32ListTransform(zTranslation), isFalse);
expect(transformKindOf(xTranslation), TransformKind.transform2d);
expect(isIdentityFloat32ListTransform(xTranslation), isFalse);
expect(transformKindOf(yTranslation), TransformKind.transform2d);
expect(isIdentityFloat32ListTransform(yTranslation), isFalse);
expect(transformKindOf(scaleAndTranslate2d), TransformKind.transform2d);
expect(isIdentityFloat32ListTransform(scaleAndTranslate2d), isFalse);
expect(transformKindOf(rotation2d), TransformKind.transform2d);
expect(isIdentityFloat32ListTransform(rotation2d), isFalse);
});
test('canonicalizes font families correctly on iOS (not 15)', () {
debugOperatingSystemOverride = OperatingSystem.iOs;
debugIsIOS15 = false;
expect(
canonicalizeFontFamily('sans-serif'),
'sans-serif',
);
expect(
canonicalizeFontFamily('foo'),
'"foo", -apple-system, BlinkMacSystemFont, sans-serif',
);
expect(
canonicalizeFontFamily('.SF Pro Text'),
'-apple-system, BlinkMacSystemFont',
);
debugOperatingSystemOverride = null;
debugIsIOS15 = null;
});
test('does not use -apple-system on iOS 15', () {
debugOperatingSystemOverride = OperatingSystem.iOs;
debugIsIOS15 = true;
expect(
canonicalizeFontFamily('sans-serif'),
'sans-serif',
);
expect(
canonicalizeFontFamily('foo'),
'"foo", BlinkMacSystemFont, sans-serif',
);
expect(
canonicalizeFontFamily('.SF Pro Text'),
'BlinkMacSystemFont',
);
debugOperatingSystemOverride = null;
debugIsIOS15 = null;
});
test('parseFloat basic tests', () {
// Simple integers and doubles.
expect(parseFloat('108'), 108.0);
expect(parseFloat('.34'), 0.34);
expect(parseFloat('108.34'), 108.34);
// Number followed by text.
expect(parseFloat('108.34px'), 108.34);
expect(parseFloat('108.34px29'), 108.34);
expect(parseFloat('108.34px 29'), 108.34);
// Number followed by space and text.
expect(parseFloat('108.34 px29'), 108.34);
expect(parseFloat('108.34 px 29'), 108.34);
// Invalid numbers.
expect(parseFloat('text'), isNull);
expect(parseFloat('text108'), isNull);
expect(parseFloat('text 108'), isNull);
expect(parseFloat('another text 108'), isNull);
});
test('can set style properties on elements', () {
final DomElement element = domDocument.createElement('div');
setElementStyle(element, 'color', 'red');
expect(element.style.color, 'red');
});
test('can remove style properties from elements', () {
final DomElement element = domDocument.createElement('div');
setElementStyle(element, 'color', 'blue');
expect(element.style.color, 'blue');
setElementStyle(element, 'color', null);
expect(element.style.color, '');
});
test('futurize turns a Callbacker into a Future', () async {
final Future<String> stringFuture = futurize((Callback<String> callback) {
scheduleMicrotask(() {
callback('hello');
});
return null;
});
expect(await stringFuture, 'hello');
});
test('futurize converts error string to exception', () async {
try {
await futurize((Callback<String> callback) {
return 'this is an error';
});
fail('Expected it to throw');
} on Exception catch(exception) {
expect('$exception', contains('this is an error'));
}
});
test('futurize converts async null into an async operation failure', () async {
final Future<String?> stringFuture = futurize((Callback<String?> callback) {
scheduleMicrotask(() {
callback(null);
});
return null;
});
try {
await stringFuture;
fail('Expected it to throw');
} on Exception catch(exception) {
expect('$exception', contains('operation failed'));
}
});
test('futurize converts sync null into a sync operation failure', () async {
try {
await futurize((Callback<String?> callback) {
callback(null);
return null;
});
fail('Expected it to throw');
} on Exception catch(exception) {
expect('$exception', contains('operation failed'));
}
});
}
| engine/lib/web_ui/test/engine/util_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/util_test.dart",
"repo_id": "engine",
"token_count": 1895
} | 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 'dart:async';
import 'dart:js_interop';
import 'dart:js_util' as js_util;
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import '../common/matchers.dart';
const int kPhysicalKeyA = 0x00070004;
const int kLogicalKeyA = 0x00000000061;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
late EngineFlutterWindow myWindow;
final EnginePlatformDispatcher dispatcher = EnginePlatformDispatcher.instance;
setUp(() {
myWindow = EngineFlutterView.implicit(dispatcher, createDomHTMLDivElement());
dispatcher.viewManager.registerView(myWindow);
});
tearDown(() async {
dispatcher.viewManager.unregisterView(myWindow.viewId);
await myWindow.resetHistory();
myWindow.dispose();
});
test('onTextScaleFactorChanged preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback() {
expect(Zone.current, innerZone);
}
myWindow.onTextScaleFactorChanged = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onTextScaleFactorChanged, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnTextScaleFactorChanged();
});
test('onPlatformBrightnessChanged preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback() {
expect(Zone.current, innerZone);
}
myWindow.onPlatformBrightnessChanged = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onPlatformBrightnessChanged, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnPlatformBrightnessChanged();
});
test('onMetricsChanged preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback() {
expect(Zone.current, innerZone);
}
myWindow.onMetricsChanged = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onMetricsChanged, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnMetricsChanged();
});
test('onLocaleChanged preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback() {
expect(Zone.current, innerZone);
}
myWindow.onLocaleChanged = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onLocaleChanged, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnLocaleChanged();
});
test('onBeginFrame preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback(Duration _) {
expect(Zone.current, innerZone);
}
myWindow.onBeginFrame = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onBeginFrame, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnBeginFrame(Duration.zero);
});
test('onReportTimings preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback(List<dynamic> _) {
expect(Zone.current, innerZone);
}
myWindow.onReportTimings = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onReportTimings, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnReportTimings(<ui.FrameTiming>[]);
});
test('onDrawFrame preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback() {
expect(Zone.current, innerZone);
}
myWindow.onDrawFrame = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onDrawFrame, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnDrawFrame();
});
test('onPointerDataPacket preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback(ui.PointerDataPacket _) {
expect(Zone.current, innerZone);
}
myWindow.onPointerDataPacket = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onPointerDataPacket, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnPointerDataPacket(const ui.PointerDataPacket());
});
test('invokeOnKeyData returns normally when onKeyData is null', () {
const ui.KeyData keyData = ui.KeyData(
timeStamp: Duration(milliseconds: 1),
type: ui.KeyEventType.repeat,
physical: kPhysicalKeyA,
logical: kLogicalKeyA,
character: 'a',
synthesized: true,
);
expect(() {
EnginePlatformDispatcher.instance.invokeOnKeyData(keyData, (bool result) {
expect(result, isFalse);
});
}, returnsNormally);
});
test('onKeyData preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
bool onKeyData(ui.KeyData _) {
expect(Zone.current, innerZone);
return false;
}
myWindow.onKeyData = onKeyData;
// Test that the getter returns the exact same onKeyData, e.g. it doesn't
// wrap it.
expect(myWindow.onKeyData, same(onKeyData));
});
const ui.KeyData keyData = ui.KeyData(
timeStamp: Duration(milliseconds: 1),
type: ui.KeyEventType.repeat,
physical: kPhysicalKeyA,
logical: kLogicalKeyA,
character: 'a',
synthesized: true,
);
EnginePlatformDispatcher.instance.invokeOnKeyData(keyData, (bool result) {
expect(result, isFalse);
});
myWindow.onKeyData = null;
});
test('onSemanticsEnabledChanged preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback() {
expect(Zone.current, innerZone);
}
myWindow.onSemanticsEnabledChanged = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onSemanticsEnabledChanged, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnSemanticsEnabledChanged();
});
test('onSemanticsActionEvent preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback(ui.SemanticsActionEvent _) {
expect(Zone.current, innerZone);
}
ui.PlatformDispatcher.instance.onSemanticsActionEvent = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(ui.PlatformDispatcher.instance.onSemanticsActionEvent, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnSemanticsAction(0, ui.SemanticsAction.tap, null);
});
test('onAccessibilityFeaturesChanged preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback() {
expect(Zone.current, innerZone);
}
myWindow.onAccessibilityFeaturesChanged = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onAccessibilityFeaturesChanged, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnAccessibilityFeaturesChanged();
});
test('onPlatformMessage preserves the zone', () {
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
void callback(String _, ByteData? __, void Function(ByteData?)? ___) {
expect(Zone.current, innerZone);
}
myWindow.onPlatformMessage = callback;
// Test that the getter returns the exact same callback, e.g. it doesn't wrap it.
expect(myWindow.onPlatformMessage, same(callback));
});
EnginePlatformDispatcher.instance.invokeOnPlatformMessage('foo', null, (ByteData? data) {
// Not testing anything here.
});
});
test('sendPlatformMessage preserves the zone', () async {
final Completer<void> completer = Completer<void>();
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
final ByteData inputData = ByteData(4);
inputData.setUint32(0, 42);
myWindow.sendPlatformMessage(
'flutter/debug-echo',
inputData,
(ByteData? outputData) {
expect(Zone.current, innerZone);
completer.complete();
},
);
});
await completer.future;
});
test('sendPlatformMessage responds even when channel is unknown', () async {
bool responded = false;
final ByteData inputData = ByteData(4);
inputData.setUint32(0, 42);
myWindow.sendPlatformMessage(
'flutter/__unknown__channel__',
null,
(ByteData? outputData) {
responded = true;
expect(outputData, isNull);
},
);
await Future<void>.delayed(const Duration(milliseconds: 1));
expect(responded, isTrue);
});
// Emulates the framework sending a request for screen orientation lock.
Future<bool> sendSetPreferredOrientations(List<dynamic> orientations) {
final Completer<bool> completer = Completer<bool>();
final ByteData? inputData = const JSONMethodCodec().encodeMethodCall(MethodCall(
'SystemChrome.setPreferredOrientations',
orientations,
));
myWindow.sendPlatformMessage(
'flutter/platform',
inputData,
(ByteData? outputData) {
const MethodCodec codec = JSONMethodCodec();
completer.complete(codec.decodeEnvelope(outputData!) as bool);
},
);
return completer.future;
}
// Regression test for https://github.com/flutter/flutter/issues/88269
test('sets preferred screen orientation', () async {
final DomScreen? original = domWindow.screen;
final List<String> lockCalls = <String>[];
int unlockCount = 0;
bool simulateError = false;
// The `orientation` property cannot be overridden, so this test overrides the entire `screen`.
js_util.setProperty(domWindow, 'screen', js_util.jsify(<Object?, Object?>{
'orientation': <Object?, Object?>{
'lock': (String lockType) {
lockCalls.add(lockType);
return futureToPromise(() async {
if (simulateError) {
throw Error();
}
return 0.toJS;
}());
}.toJS,
'unlock': () {
unlockCount += 1;
}.toJS,
},
}));
// Sanity-check the test setup.
expect(lockCalls, <String>[]);
expect(unlockCount, 0);
await domWindow.screen!.orientation!.lock('hi');
domWindow.screen!.orientation!.unlock();
expect(lockCalls, <String>['hi']);
expect(unlockCount, 1);
lockCalls.clear();
unlockCount = 0;
expect(await sendSetPreferredOrientations(<dynamic>['DeviceOrientation.portraitUp']), isTrue);
expect(lockCalls, <String>[ScreenOrientation.lockTypePortraitPrimary]);
expect(unlockCount, 0);
lockCalls.clear();
unlockCount = 0;
expect(await sendSetPreferredOrientations(<dynamic>['DeviceOrientation.portraitDown']), isTrue);
expect(lockCalls, <String>[ScreenOrientation.lockTypePortraitSecondary]);
expect(unlockCount, 0);
lockCalls.clear();
unlockCount = 0;
expect(await sendSetPreferredOrientations(<dynamic>['DeviceOrientation.landscapeLeft']), isTrue);
expect(lockCalls, <String>[ScreenOrientation.lockTypeLandscapePrimary]);
expect(unlockCount, 0);
lockCalls.clear();
unlockCount = 0;
expect(await sendSetPreferredOrientations(<dynamic>['DeviceOrientation.landscapeRight']), isTrue);
expect(lockCalls, <String>[ScreenOrientation.lockTypeLandscapeSecondary]);
expect(unlockCount, 0);
lockCalls.clear();
unlockCount = 0;
expect(await sendSetPreferredOrientations(<dynamic>[]), isTrue);
expect(lockCalls, <String>[]);
expect(unlockCount, 1);
lockCalls.clear();
unlockCount = 0;
simulateError = true;
expect(await sendSetPreferredOrientations(<dynamic>['DeviceOrientation.portraitDown']), isFalse);
expect(lockCalls, <String>[ScreenOrientation.lockTypePortraitSecondary]);
expect(unlockCount, 0);
js_util.setProperty(domWindow, 'screen', original);
});
/// Regression test for https://github.com/flutter/flutter/issues/66128.
test("setPreferredOrientation responds even if browser doesn't support api", () async {
final DomScreen? original = domWindow.screen;
// The `orientation` property cannot be overridden, so this test overrides the entire `screen`.
js_util.setProperty(domWindow, 'screen', js_util.jsify(<Object?, Object?>{
'orientation': null,
}));
expect(domWindow.screen!.orientation, isNull);
expect(await sendSetPreferredOrientations(<dynamic>[]), isFalse);
js_util.setProperty(domWindow, 'screen', original);
});
test('SingletonFlutterWindow implements locale, locales, and locale change notifications', () async {
// This will count how many times we notified about locale changes.
int localeChangedCount = 0;
myWindow.onLocaleChanged = () {
localeChangedCount += 1;
};
// We populate the initial list of locales automatically (only test that we
// got some locales; some contributors may be in different locales, so we
// can't test the exact contents).
expect(myWindow.locale, isA<ui.Locale>());
expect(myWindow.locales, isNotEmpty);
// Trigger a change notification (reset locales because the notification
// doesn't actually change the list of languages; the test only observes
// that the list is populated again).
EnginePlatformDispatcher.instance.debugResetLocales();
expect(myWindow.locales, isEmpty);
expect(myWindow.locale, equals(const ui.Locale.fromSubtags()));
expect(localeChangedCount, 0);
domWindow.dispatchEvent(createDomEvent('Event', 'languagechange'));
expect(myWindow.locales, isNotEmpty);
expect(localeChangedCount, 1);
});
test('dispatches browser event on flutter/service_worker channel', () async {
final Completer<void> completer = Completer<void>();
domWindow.addEventListener('flutter-first-frame',
createDomEventListener((DomEvent e) => completer.complete()));
final Zone innerZone = Zone.current.fork();
innerZone.runGuarded(() {
myWindow.sendPlatformMessage(
'flutter/service_worker',
ByteData(0),
(ByteData? outputData) { },
);
});
await expectLater(completer.future, completes);
});
test('sets global html attributes', () {
final DomElement host = createDomHTMLDivElement();
final EngineFlutterView view = EngineFlutterView(dispatcher, host);
expect(host.getAttribute('flt-renderer'), 'html (requested explicitly)');
expect(host.getAttribute('flt-build-mode'), 'debug');
view.dispose();
});
test('in full-page mode, Flutter window replaces viewport meta tags', () {
final DomHTMLMetaElement existingMeta = createDomHTMLMetaElement()
..name = 'viewport'
..content = 'foo=bar';
domDocument.head!.append(existingMeta);
expect(existingMeta.isConnected, isTrue);
final EngineFlutterWindow implicitView = EngineFlutterView.implicit(dispatcher, null);
// The existing viewport meta tag should've been removed.
expect(existingMeta.isConnected, isFalse);
// And a new one should've been added.
final DomHTMLMetaElement? newMeta = domDocument.head!.querySelector('meta[name="viewport"]') as DomHTMLMetaElement?;
expect(newMeta, isNotNull);
newMeta!;
expect(newMeta.getAttribute('flt-viewport'), isNotNull);
expect(newMeta.name, 'viewport');
expect(newMeta.content, contains('width=device-width'));
expect(newMeta.content, contains('initial-scale=1.0'));
expect(newMeta.content, contains('maximum-scale=1.0'));
expect(newMeta.content, contains('user-scalable=no'));
implicitView.dispose();
});
test('auto-view-id', () {
final DomElement host = createDomHTMLDivElement();
final EngineFlutterView implicit1 = EngineFlutterView.implicit(dispatcher, host);
final EngineFlutterView implicit2 = EngineFlutterView.implicit(dispatcher, host);
expect(implicit1.viewId, kImplicitViewId);
expect(implicit2.viewId, kImplicitViewId);
final EngineFlutterView view1 = EngineFlutterView(dispatcher, host);
final EngineFlutterView view2 = EngineFlutterView(dispatcher, host);
final EngineFlutterView view3 = EngineFlutterView(dispatcher, host);
expect(view1.viewId, isNot(kImplicitViewId));
expect(view2.viewId, isNot(kImplicitViewId));
expect(view3.viewId, isNot(kImplicitViewId));
expect(view1.viewId, isNot(view2.viewId));
expect(view2.viewId, isNot(view3.viewId));
expect(view3.viewId, isNot(view1.viewId));
implicit1.dispose();
implicit2.dispose();
view1.dispose();
view2.dispose();
view3.dispose();
});
test('registration', () {
final DomHTMLDivElement host = createDomHTMLDivElement();
final EnginePlatformDispatcher dispatcher = EnginePlatformDispatcher();
expect(dispatcher.viewManager.views, isEmpty);
// Creating the view shouldn't register it.
final EngineFlutterView view = EngineFlutterView(dispatcher, host);
expect(dispatcher.viewManager.views, isEmpty);
dispatcher.viewManager.registerView(view);
expect(dispatcher.viewManager.views, <EngineFlutterView>[view]);
// Disposing the view shouldn't unregister it.
view.dispose();
expect(dispatcher.viewManager.views, <EngineFlutterView>[view]);
dispatcher.dispose();
});
test('dispose', () {
final DomHTMLDivElement host = createDomHTMLDivElement();
final EngineFlutterView view =
EngineFlutterView(EnginePlatformDispatcher.instance, host);
// First, let's make sure the view's root element was inserted into the
// host, and the dimensions provider is active.
expect(view.dom.rootElement.parentElement, host);
expect(view.dimensionsProvider.isClosed, isFalse);
// Now, let's dispose the view and make sure its root element was removed,
// and the dimensions provider is closed.
view.dispose();
expect(view.dom.rootElement.parentElement, isNull);
expect(view.dimensionsProvider.isClosed, isTrue);
// Can't render into a disposed view.
expect(
() => view.render(ui.SceneBuilder().build()),
throwsAssertionError,
);
// Can't update semantics on a disposed view.
expect(
() => view.updateSemantics(ui.SemanticsUpdateBuilder().build()),
throwsAssertionError,
);
});
group('resizing', () {
late DomHTMLDivElement host;
late EngineFlutterView view;
late int metricsChangedCount;
setUp(() async {
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(2.5);
host = createDomHTMLDivElement();
view = EngineFlutterView(EnginePlatformDispatcher.instance, host);
host.style
..width = '10px'
..height = '10px';
domDocument.body!.append(host);
// Let the DOM settle before starting the test, so we don't get the first
// 10,10 Size in the test. Otherwise, the ResizeObserver may trigger
// unexpectedly after the test has started, and break our "first" result.
await view.onResize.first;
metricsChangedCount = 0;
view.platformDispatcher.onMetricsChanged = () {
metricsChangedCount++;
};
});
tearDown(() {
view.dispose();
host.remove();
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(null);
view.platformDispatcher.onMetricsChanged = null;
});
test('listens to resize', () async {
// Initial size is 10x10, with a 2.5 dpr, is equal to 25x25 physical pixels.
expect(view.physicalSize, const ui.Size(25.0, 25.0));
expect(metricsChangedCount, 0);
// Simulate the browser resizing the host to 20x20.
host.style
..width = '20px'
..height = '20px';
await view.onResize.first;
expect(view.physicalSize, const ui.Size(50.0, 50.0));
expect(metricsChangedCount, 1);
});
test('maintains debugPhysicalSizeOverride', () async {
// Initial size is 10x10, with a 2.5 dpr, is equal to 25x25 physical pixels.
expect(view.physicalSize, const ui.Size(25.0, 25.0));
view.debugPhysicalSizeOverride = const ui.Size(100.0, 100.0);
view.debugForceResize();
expect(view.physicalSize, const ui.Size(100.0, 100.0));
// Resize the host to 20x20.
host.style
..width = '20px'
..height = '20px';
await view.onResize.first;
// The view should maintain the debugPhysicalSizeOverride.
expect(view.physicalSize, const ui.Size(100.0, 100.0));
});
test('can resize host', () async {
// Reset host style, so it tightly wraps the rootElement of the view.
// This style change will trigger a "onResize" event when all the DOM
// operations settle that we must await before taking measurements.
host.style
..display = 'inline-block'
..width = 'auto'
..height = 'auto';
// Resize the host to 20x20 (physical pixels).
view.resize(const ui.Size.square(50));
await view.onResize.first;
// The host tightly wraps the rootElement:
expect(view.physicalSize, const ui.Size(50.0, 50.0));
// Inspect the rootElement directly:
expect(view.dom.rootElement.clientWidth, 50 / view.devicePixelRatio);
expect(view.dom.rootElement.clientHeight, 50 / view.devicePixelRatio);
});
});
group('physicalConstraints', () {
const double dpr = 2.5;
late DomHTMLDivElement host;
late EngineFlutterView view;
setUp(() async {
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(dpr);
host = createDomHTMLDivElement()
..style.width = '640px'
..style.height = '480px';
domDocument.body!.append(host);
});
tearDown(() {
host.remove();
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(null);
});
test('JsViewConstraints are passed and used to compute physicalConstraints', () async {
view = EngineFlutterView(
EnginePlatformDispatcher.instance,
host,
viewConstraints: JsViewConstraints(
minHeight: 320,
maxHeight: double.infinity,
));
// All the metrics until now have been expressed in logical pixels, because
// they're coming from CSS/the browser, which works in logical pixels.
expect(view.physicalConstraints, const ViewConstraints(
minHeight: 320,
// ignore: avoid_redundant_argument_values
maxHeight: double.infinity,
minWidth: 640,
maxWidth: 640,
// However the framework expects physical pixels, so we multiply our expectations
// by the current DPR (2.5)
) * dpr);
});
});
}
| engine/lib/web_ui/test/engine/window_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/window_test.dart",
"repo_id": "engine",
"token_count": 8454
} | 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 '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,
);
test('Should blur rectangles based on sigma.', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500));
for (int blurSigma = 1; blurSigma < 10; blurSigma += 2) {
final SurfacePaint paint = SurfacePaint()
..color = const Color(0xFF2fdfd2)
..maskFilter = MaskFilter.blur(BlurStyle.normal, blurSigma.toDouble());
rc.drawRect(Rect.fromLTWH(15.0, 15.0 + blurSigma * 40, 200, 20), paint);
}
await canvasScreenshot(rc, 'dom_mask_filter_blur');
});
}
| engine/lib/web_ui/test/html/compositing/dom_mask_filter_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/compositing/dom_mask_filter_golden_test.dart",
"repo_id": "engine",
"token_count": 398
} | 328 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide window;
import '../../common/test_initialization.dart';
import 'helper.dart';
const Rect bounds = Rect.fromLTWH(0, 0, 800, 600);
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
test('paints spans and lines correctly', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
Offset offset = Offset.zero;
CanvasParagraph paragraph;
// Single-line multi-span.
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(
color: green,
background: Paint()..color = red,
));
builder.addText('ipsum ');
builder.pop();
builder.addText('.');
})
..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
// Multi-line single-span.
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (CanvasParagraphBuilder builder) {
builder.addText('Lorem ipsum dolor sit');
})
..layout(constrain(90.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
// Multi-line multi-span.
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ipsum ');
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = red));
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pop();
builder.addText('sit');
})
..layout(constrain(90.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_general');
});
test('respects alignment', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
Offset offset = Offset.zero;
CanvasParagraph paragraph;
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('sit');
}
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.left),
build,
)..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.center),
build,
)..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.right),
build,
)..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_align');
});
test('respects alignment in DOM mode', () {
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
Offset offset = Offset.zero;
CanvasParagraph paragraph;
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('sit');
}
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.left),
build,
)..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.center),
build,
)..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.right),
build,
)..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_align_dom');
});
void testAlignAndTransform(EngineCanvas canvas) {
CanvasParagraph paragraph;
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: white));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('ipsum\n');
builder.pushStyle(EngineTextStyle.only(color: yellow));
builder.addText('dolor');
}
void drawParagraphAt(Offset offset, TextAlign align) {
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 20.0, textAlign: align),
build,
)..layout(constrain(150.0));
canvas.save();
canvas.translate(offset.dx, offset.dy);
canvas.rotate(math.pi / 4);
final Rect rect = Rect.fromLTRB(0.0, 0.0, 150.0, paragraph.height);
canvas.drawRect(rect, SurfacePaintData()..color = black.value);
canvas.drawParagraph(paragraph, Offset.zero);
canvas.restore();
}
drawParagraphAt(const Offset(50.0, 0.0), TextAlign.left);
drawParagraphAt(const Offset(150.0, 0.0), TextAlign.center);
drawParagraphAt(const Offset(250.0, 0.0), TextAlign.right);
}
test('alignment and transform', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testAlignAndTransform(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_align_transform');
});
test('alignment and transform (DOM)', () {
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testAlignAndTransform(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_align_transform_dom');
});
void testGiantParagraphStyles(EngineCanvas canvas) {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 80.0),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: yellow, fontSize: 24.0));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: red, fontSize: 32.0));
builder.addText('ipsum');
},
)..layout(constrain(double.infinity));
final Rect rect = Rect.fromLTRB(0.0, 0.0, paragraph.maxIntrinsicWidth, paragraph.height);
canvas.drawRect(rect, SurfacePaintData()..color = black.value);
canvas.drawParagraph(paragraph, Offset.zero);
}
test('giant paragraph style', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testGiantParagraphStyles(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_giant_paragraph_style');
});
test('giant paragraph style (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testGiantParagraphStyles(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_giant_paragraph_style_dom');
});
test('giant font size on the body tag (DOM)', () async {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 200);
// Store the old font size value on the body, and set a gaint font size.
final String oldBodyFontSize = domDocument.body!.style.fontSize;
domDocument.body!.style.fontSize = '100px';
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
Offset offset = const Offset(10.0, 10.0);
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto'),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: yellow, fontSize: 24.0));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: red, fontSize: 48.0));
builder.addText('ipsum');
},
)..layout(constrain(double.infinity));
final Rect rect = Rect.fromLTWH(offset.dx, offset.dy, paragraph.maxIntrinsicWidth, paragraph.height);
canvas.drawRect(rect, SurfacePaintData()..color = black.value);
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(paragraph.maxIntrinsicWidth, 0.0);
// Add some extra padding between the two paragraphs.
offset = offset.translate(20.0, 0.0);
// Use the same height as the previous paragraph so that the 2 paragraphs
// look nice in the screenshot.
final double placeholderHeight = paragraph.height;
final double placeholderWidth = paragraph.height * 2;
final CanvasParagraph paragraph2 = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {
builder.addPlaceholder(placeholderWidth, placeholderHeight, PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic);
},
)..layout(constrain(double.infinity));
final Rect rect2 = Rect.fromLTWH(offset.dx, offset.dy, paragraph2.maxIntrinsicWidth, paragraph2.height);
canvas.drawRect(rect2, SurfacePaintData()..color = black.value);
canvas.drawParagraph(paragraph2, offset);
// Draw a rect in the placeholder.
// Leave some padding around the placeholder to make the black paragraph
// background visible.
const double padding = 5;
final TextBox placeholderBox = paragraph2.getBoxesForPlaceholders().single;
canvas.drawRect(
placeholderBox.toRect().shift(offset).deflate(padding),
SurfacePaintData()..color = red.value,
);
await takeScreenshot(canvas, bounds, 'canvas_paragraph_giant_body_font_size_dom');
// Restore the old font size value.
domDocument.body!.style.fontSize = oldBodyFontSize;
});
test('paints spans with varying heights/baselines', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto'),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(fontSize: 20.0));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(
fontSize: 40.0,
background: Paint()..color = green,
));
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(
fontSize: 10.0,
color: white,
background: Paint()..color = black,
));
builder.addText('dolor ');
builder.pushStyle(EngineTextStyle.only(fontSize: 30.0));
builder.addText('sit ');
builder.pop();
builder.pop();
builder.pushStyle(EngineTextStyle.only(
fontSize: 20.0,
background: Paint()..color = blue,
));
builder.addText('amet');
},
)..layout(constrain(220.0));
canvas.drawParagraph(paragraph, Offset.zero);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_varying_heights');
});
test('respects letter-spacing', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto'),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green, letterSpacing: 1));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: red, letterSpacing: 3));
builder.addText('Lorem');
},
)..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_letter_spacing');
});
test('letter-spacing Thai', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const String yes = '\u0e43\u0e0a\u0e48';
const String no = '\u0e44\u0e21\u0e48';
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 36),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('$yes $no ');
builder.pushStyle(EngineTextStyle.only(color: green, letterSpacing: 1));
builder.addText('$yes $no ');
builder.pushStyle(EngineTextStyle.only(color: red, letterSpacing: 3));
builder.addText('$yes $no');
},
)..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, const Offset(20, 20));
return takeScreenshot(canvas, bounds, 'canvas_paragraph_letter_spacing_thai');
});
test('draws text decorations', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
final List<TextDecorationStyle> decorationStyles = <TextDecorationStyle>[
TextDecorationStyle.solid,
TextDecorationStyle.double,
TextDecorationStyle.dotted,
TextDecorationStyle.dashed,
TextDecorationStyle.wavy,
];
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto'),
(CanvasParagraphBuilder builder) {
for (final TextDecorationStyle decorationStyle in decorationStyles) {
builder.pushStyle(EngineTextStyle.only(
color: const Color.fromRGBO(50, 50, 255, 1.0),
decoration: TextDecoration.underline,
decorationStyle: decorationStyle,
decorationColor: red,
fontFamily: 'Roboto',
fontSize: 30,
));
builder.addText('Hello World');
builder.pop();
builder.addText(' ');
}
},
)..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_decoration');
});
void testFontFeatures(EngineCanvas canvas) {
const String text = 'Bb Difficult ';
const FontFeature enableSmallCaps = FontFeature('smcp');
const FontFeature disableSmallCaps = FontFeature('smcp', 0);
const String numeric = '123.4560';
const FontFeature enableOnum = FontFeature('onum');
const FontFeature disableLigatures = FontFeature('liga', 0);
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto'),
(CanvasParagraphBuilder builder) {
// Small Caps
builder.pushStyle(EngineTextStyle.only(
height: 1.5,
color: black,
fontSize: 32.0,
));
builder.pushStyle(EngineTextStyle.only(
color: blue,
fontFeatures: <FontFeature>[enableSmallCaps],
));
builder.addText(text);
// Make sure disabling a font feature also works.
builder.pushStyle(EngineTextStyle.only(
color: black,
fontFeatures: <FontFeature>[disableSmallCaps],
));
builder.addText(' (smcp)\n');
builder.pop(); // disableSmallCaps
builder.pop(); // enableSmallCaps
// No ligatures
builder.pushStyle(EngineTextStyle.only(
color: blue,
fontFeatures: <FontFeature>[disableLigatures],
));
builder.addText(text);
builder.pop(); // disableLigatures
builder.addText(' (no liga)\n');
// No font features
builder.pushStyle(EngineTextStyle.only(
color: blue,
));
builder.addText(text);
builder.pop(); // color: blue
builder.addText(' (none)\n');
// Onum
builder.pushStyle(EngineTextStyle.only(
color: blue,
fontFeatures: <FontFeature>[enableOnum],
));
builder.addText(numeric);
builder.pop(); // enableOnum
builder.addText(' (onum)\n');
// No font features
builder.pushStyle(EngineTextStyle.only(
color: blue,
));
builder.addText(numeric);
builder.pop(); // color: blue
builder.addText(' (none)\n\n');
// Multiple font features
builder.addText('Combined (smcp, onum):\n');
builder.pushStyle(EngineTextStyle.only(
color: blue,
fontFeatures: <FontFeature>[
enableSmallCaps,
enableOnum,
],
));
builder.addText('$text $numeric');
builder.pop(); // enableSmallCaps, enableOnum
},
)..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('font features', () {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 500);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testFontFeatures(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_font_features');
});
test('font features (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 500);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testFontFeatures(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_font_features_dom');
});
void testFontVariations(EngineCanvas canvas) {
const String text = 'ABCDE 12345\n';
FontVariation weight(double w) => FontVariation('wght', w);
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'RobotoVariable'),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(
fontSize: 48.0,
));
builder.addText(text);
builder.pushStyle(EngineTextStyle.only(
fontSize: 48.0,
fontVariations: <FontVariation>[weight(900)],
));
builder.addText(text);
builder.pushStyle(EngineTextStyle.only(
fontSize: 48.0,
fontVariations: <FontVariation>[weight(200)],
));
builder.addText(text);
builder.pop();
builder.pop();
builder.pop();
},
)..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('font variations', () {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 500);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testFontVariations(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_font_variations');
});
test('font variations (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 500);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testFontVariations(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_font_variations_dom');
});
void testBackgroundStyle(EngineCanvas canvas) {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 40.0),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = blue));
builder.addText('Lor');
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = black, color: white));
builder.addText('em ');
builder.pop();
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = green));
builder.addText('ipsu');
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = yellow));
builder.addText('m\ndo');
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = red));
builder.addText('lor sit');
},
);
paragraph.layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('background style', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testBackgroundStyle(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_background_style');
});
test('background style (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testBackgroundStyle(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_background_style_dom');
});
void testForegroundStyle(EngineCanvas canvas) {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 40.0),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem');
builder.pop();
builder.pushStyle(EngineTextStyle.only(foreground: Paint()..color = red..style = PaintingStyle.stroke));
builder.addText('ipsum\n');
builder.pop();
builder.pushStyle(EngineTextStyle.only(foreground: Paint()..color = blue..style = PaintingStyle.stroke..strokeWidth = 0.0));
builder.addText('dolor');
builder.pop();
builder.pushStyle(EngineTextStyle.only(foreground: Paint()..color = green..style = PaintingStyle.stroke..strokeWidth = 2.0));
builder.addText('sit\n');
builder.pop();
builder.pushStyle(EngineTextStyle.only(foreground: Paint()..color = yellow..style = PaintingStyle.stroke..strokeWidth = 4.0));
builder.addText('amet');
},
);
paragraph.layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('foreground style', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testForegroundStyle(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_foreground_style');
});
test('foreground style (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testForegroundStyle(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_foreground_style_dom');
});
test('paragraph bounds hug the text inside the paragraph', () async {
const Rect bounds = Rect.fromLTWH(0, 0, 150, 100);
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 20,
textAlign: TextAlign.center,
));
// Expected layout with center-alignment is something like this:
//
// _________________
// | A |
// | |AAAAA| |
// | | AAA | |
// |----|-----|----|
// | |<--->| |
// | 100 |
// | |
// |<------------->|
// 110
//
// The width of the paragraph is bigger than the actual content because the
// longest line "AAAAA" is 100px, which is smaller than 110px specified in
// the constraint. After the layout and centering the paint bounds would
// "hug" the text inside the paragraph more tightly than the box allocated
// for the paragraph.
builder.addText('A AAAAA AAA');
final CanvasParagraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 110));
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
canvas.translate(20, 20);
canvas.drawParagraph(paragraph, Offset.zero);
canvas.drawRect(
Rect.fromLTRB(
0,
0,
paragraph.width,
paragraph.height,
),
SurfacePaintData()
..style = PaintingStyle.stroke
..strokeWidth = 1,
);
canvas.drawRect(
paragraph.paintBounds,
SurfacePaintData()
..color = 0xFF00FF00
..style = PaintingStyle.stroke
..strokeWidth = 1,
);
await takeScreenshot(canvas, bounds, 'canvas_paragraph_bounds');
});
}
| engine/lib/web_ui/test/html/paragraph/general_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/paragraph/general_golden_test.dart",
"repo_id": "engine",
"token_count": 9357
} | 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.
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart' hide ColorSpace;
import 'package:ui/ui.dart' hide TextStyle;
import 'package:web_engine_tester/golden_tester.dart';
import '../common/matchers.dart';
import '../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
setUpTestViewDimensions: false,
);
const double screenWidth = 600.0;
const double screenHeight = 800.0;
const Rect screenRect = Rect.fromLTWH(0, 0, screenWidth, screenHeight);
final SurfacePaint testPaint = SurfacePaint()..color = const Color(0xFFFF0000);
// Commit a recording canvas to a bitmap, and compare with the expected
Future<void> checkScreenshot(RecordingCanvas rc, String fileName,
{ Rect region = const Rect.fromLTWH(0, 0, 500, 500) }) async {
final EngineCanvas engineCanvas = BitmapCanvas(screenRect,
RenderStrategy());
// Draws the estimated bounds so we can spot the bug in Gold.
engineCanvas
..save()
..drawRect(
rc.pictureBounds!,
SurfacePaintData()
..color = const Color.fromRGBO(0, 0, 255, 1.0).value
..style = PaintingStyle.stroke
..strokeWidth = 1.0,
)
..restore();
rc.apply(engineCanvas, screenRect);
// 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(engineCanvas.rootElement);
domDocument.body!.append(sceneElement);
await matchGoldenFile('paint_bounds_for_$fileName.png', region: region);
} finally {
// The page is reused across tests, so remove the element after taking the
// screenshot.
sceneElement.remove();
}
}
test('Empty canvas reports correct paint bounds', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTWH(1, 2, 300, 400));
rc.endRecording();
expect(rc.pictureBounds, Rect.zero);
await checkScreenshot(rc, 'empty_canvas');
});
test('Computes paint bounds for draw line', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawLine(const Offset(50, 100), const Offset(120, 140), testPaint);
rc.endRecording();
// The off by one is due to the minimum stroke width of 1.
expect(rc.pictureBounds, const Rect.fromLTRB(49, 99, 121, 141));
await checkScreenshot(rc, 'draw_line');
});
test('Computes paint bounds for draw line when line exceeds limits',
() async {
// Uses max bounds when computing paint bounds
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawLine(const Offset(50, 100), const Offset(screenWidth + 100.0, 140),
testPaint);
rc.endRecording();
// The off by one is due to the minimum stroke width of 1.
expect(
rc.pictureBounds, const Rect.fromLTRB(49.0, 99.0, screenWidth, 141.0));
await checkScreenshot(rc, 'draw_line_exceeding_limits');
});
test('Computes paint bounds for draw rect', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawRect(const Rect.fromLTRB(10, 20, 30, 40), testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(10, 20, 30, 40));
await checkScreenshot(rc, 'draw_rect');
});
test('Computes paint bounds for draw rect when exceeds limits', () async {
// Uses max bounds when computing paint bounds
RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawRect(
const Rect.fromLTRB(10, 20, 30 + screenWidth, 40 + screenHeight),
testPaint);
rc.endRecording();
expect(rc.pictureBounds,
const Rect.fromLTRB(10, 20, screenWidth, screenHeight));
rc = RecordingCanvas(screenRect);
rc.drawRect(const Rect.fromLTRB(-200, -100, 30, 40), testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(0, 0, 30, 40));
await checkScreenshot(rc, 'draw_rect_exceeding_limits');
});
test('Computes paint bounds for translate', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.translate(5, 7);
rc.drawRect(const Rect.fromLTRB(10, 20, 30, 40), testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(15, 27, 35, 47));
await checkScreenshot(rc, 'translate');
});
test('Computes paint bounds for scale', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.scale(2, 2);
rc.drawRect(const Rect.fromLTRB(10, 20, 30, 40), testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(20, 40, 60, 80));
await checkScreenshot(rc, 'scale');
});
test('Computes paint bounds for rotate', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.rotate(math.pi / 4.0);
rc.drawLine(
const Offset(1, 0), Offset(50 * math.sqrt(2) - 1, 0), testPaint);
rc.endRecording();
// The extra 0.7 is due to stroke width of 1 rotated by 45 degrees.
expect(rc.pictureBounds,
within(distance: 0.1, from: const Rect.fromLTRB(0, 0, 50.7, 50.7)));
await checkScreenshot(rc, 'rotate');
});
test('Computes paint bounds for horizontal skew', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.skew(1.0, 0.0);
rc.drawRect(const Rect.fromLTRB(20, 20, 40, 40), testPaint);
rc.endRecording();
expect(
rc.pictureBounds,
within(
distance: 0.1, from: const Rect.fromLTRB(40.0, 20.0, 80.0, 40.0)));
await checkScreenshot(rc, 'skew_horizontally');
});
test('Computes paint bounds for vertical skew', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.skew(0.0, 1.0);
rc.drawRect(const Rect.fromLTRB(20, 20, 40, 40), testPaint);
rc.endRecording();
expect(
rc.pictureBounds,
within(
distance: 0.1, from: const Rect.fromLTRB(20.0, 40.0, 40.0, 80.0)));
await checkScreenshot(rc, 'skew_vertically');
});
test('Computes paint bounds for a complex transform', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
final Float32List matrix = Float32List(16);
// translate(210, 220) , scale(2, 3), rotate(math.pi / 4.0)
matrix[0] = 1.4;
matrix[1] = 2.12;
matrix[2] = 0.0;
matrix[3] = 0.0;
matrix[4] = -1.4;
matrix[5] = 2.12;
matrix[6] = 0.0;
matrix[7] = 0.0;
matrix[8] = 0.0;
matrix[9] = 0.0;
matrix[10] = 2.0;
matrix[11] = 0.0;
matrix[12] = 210.0;
matrix[13] = 220.0;
matrix[14] = 0.0;
matrix[15] = 1.0;
rc.transform(matrix);
rc.drawRect(const Rect.fromLTRB(10, 20, 30, 40), testPaint);
rc.endRecording();
expect(
rc.pictureBounds,
within(
distance: 0.001,
from: const Rect.fromLTRB(168.0, 283.6, 224.0, 368.4)));
await checkScreenshot(rc, 'complex_transform');
});
test('drawPaint should cover full size', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawPaint(testPaint);
rc.drawRect(const Rect.fromLTRB(10, 20, 30, 40), testPaint);
rc.endRecording();
expect(rc.pictureBounds, screenRect);
await checkScreenshot(rc, 'draw_paint');
});
test('drawColor should cover full size', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
final SurfacePaint testPaint = SurfacePaint()..color = const Color(0xFF80FF00);
rc.drawRect(const Rect.fromLTRB(10, 20, 30, 40), testPaint);
rc.drawColor(const Color(0xFFFF0000), BlendMode.multiply);
rc.drawRect(const Rect.fromLTRB(10, 60, 30, 80), testPaint);
rc.endRecording();
expect(rc.pictureBounds, screenRect);
await checkScreenshot(rc, 'draw_color');
});
test('Computes paint bounds for draw oval', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawOval(const Rect.fromLTRB(10, 20, 30, 40), testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(10, 20, 30, 40));
await checkScreenshot(rc, 'draw_oval');
});
test('Computes paint bounds for draw round rect', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawRRect(
RRect.fromRectAndRadius(
const Rect.fromLTRB(10, 20, 30, 40), const Radius.circular(5.0)),
testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(10, 20, 30, 40));
await checkScreenshot(rc, 'draw_round_rect');
});
test(
'Computes empty paint bounds when inner rect outside of outer rect for '
'drawDRRect', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawDRRect(RRect.fromRectAndCorners(const Rect.fromLTRB(10, 20, 30, 40)),
RRect.fromRectAndCorners(const Rect.fromLTRB(1, 2, 3, 4)), testPaint);
rc.endRecording();
expect(rc.pictureBounds, Rect.zero);
await checkScreenshot(rc, 'draw_drrect_empty');
});
test('Computes paint bounds using outer rect for drawDRRect', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawDRRect(
RRect.fromRectAndCorners(const Rect.fromLTRB(10, 20, 30, 40)),
RRect.fromRectAndCorners(const Rect.fromLTRB(12, 22, 28, 38)),
testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(10, 20, 30, 40));
await checkScreenshot(rc, 'draw_drrect');
});
test('Computes paint bounds for draw circle', () async {
// Paint bounds of one circle.
RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawCircle(const Offset(20, 20), 10.0, testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(10.0, 10.0, 30.0, 30.0));
// Paint bounds of a union of two circles.
rc = RecordingCanvas(screenRect);
rc.drawCircle(const Offset(20, 20), 10.0, testPaint);
rc.drawCircle(const Offset(200, 300), 100.0, testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(10.0, 10.0, 300.0, 400.0));
await checkScreenshot(rc, 'draw_circle');
});
test('Computes paint bounds for draw image', () {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawImage(TestImage(), const Offset(50, 100), SurfacePaint());
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(50.0, 100.0, 70.0, 110.0));
});
test('Computes paint bounds for draw image rect', () {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.drawImageRect(TestImage(), const Rect.fromLTRB(1, 1, 20, 10),
const Rect.fromLTRB(5, 6, 400, 500), SurfacePaint());
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(5.0, 6.0, 400.0, 500.0));
});
test('Computes paint bounds for single-line draw paragraph', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
final Paragraph paragraph = createTestParagraph();
const double textLeft = 5.0;
const double textTop = 7.0;
const double widthConstraint = 300.0;
paragraph.layout(const ParagraphConstraints(width: widthConstraint));
rc.drawParagraph(paragraph, const Offset(textLeft, textTop));
rc.endRecording();
expect(
rc.pictureBounds!.width,
lessThan(widthConstraint),
reason: 'The given width constraint $widthConstraint is more than the '
'test string needs, so the width of the visible text is actually '
'smaller than the given width.',
);
expect(
rc.pictureBounds,
Rect.fromLTRB(textLeft, textTop, textLeft + paragraph.maxIntrinsicWidth, 21.0),
);
await checkScreenshot(rc, 'draw_paragraph');
}, // TODO(mdebbar): https://github.com/flutter/flutter/issues/65789
skip: browserEngine == BrowserEngine.webkit &&
operatingSystem == OperatingSystem.iOs);
test('Computes paint bounds for multi-line draw paragraph', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
final Paragraph paragraph = createTestParagraph();
const double textLeft = 5.0;
const double textTop = 7.0;
// Do not go lower than the shortest word.
const double widthConstraint = 130.0;
paragraph.layout(const ParagraphConstraints(width: widthConstraint));
rc.drawParagraph(paragraph, const Offset(textLeft, textTop));
rc.endRecording();
const double fontWidth = 14;
const int lettersInLongestWord = 9;
const double longestLineWidth = lettersInLongestWord * fontWidth;
expect(
rc.pictureBounds!.width,
lessThan(widthConstraint),
reason: 'The test string "A short sentence." is broken up into two lines, '
'"A short" and "sentence.". The longest line contains '
'$lettersInLongestWord characters, each ${fontWidth}px wide. '
'That line is ${longestLineWidth}px wide, which is less than '
'$widthConstraint.',
);
expect(
rc.pictureBounds,
const Rect.fromLTRB(textLeft, textTop, textLeft + longestLineWidth, 35.0),
);
await checkScreenshot(rc, 'draw_paragraph_multi_line');
}, // TODO(mdebbar): https://github.com/flutter/flutter/issues/65789
skip: browserEngine == BrowserEngine.webkit &&
operatingSystem == OperatingSystem.iOs);
test('Should exclude painting outside simple clipRect', () async {
// One clipped line.
RecordingCanvas rc = RecordingCanvas(screenRect);
rc.clipRect(const Rect.fromLTRB(50, 50, 100, 100), ClipOp.intersect);
rc.drawLine(const Offset(10, 11), const Offset(20, 21), testPaint);
rc.endRecording();
expect(rc.pictureBounds, Rect.zero);
// Two clipped lines.
rc = RecordingCanvas(screenRect);
rc.clipRect(const Rect.fromLTRB(50, 50, 100, 100), ClipOp.intersect);
rc.drawLine(const Offset(10, 11), const Offset(20, 21), testPaint);
rc.drawLine(const Offset(52, 53), const Offset(55, 56), testPaint);
rc.endRecording();
// Extra pixel due to default line length
expect(rc.pictureBounds, const Rect.fromLTRB(51, 52, 56, 57));
await checkScreenshot(rc, 'clip_rect_simple');
});
test('Should include intersection of clipRect and painting', () async {
RecordingCanvas rc = RecordingCanvas(screenRect);
rc.clipRect(const Rect.fromLTRB(50, 50, 100, 100), ClipOp.intersect);
rc.drawRect(const Rect.fromLTRB(20, 60, 120, 70), testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(50, 60, 100, 70));
await checkScreenshot(rc, 'clip_rect_intersects_paint_left_to_right');
rc = RecordingCanvas(screenRect);
rc.clipRect(const Rect.fromLTRB(50, 50, 100, 100), ClipOp.intersect);
rc.drawRect(const Rect.fromLTRB(60, 20, 70, 200), testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(60, 50, 70, 100));
await checkScreenshot(rc, 'clip_rect_intersects_paint_top_to_bottom');
});
test('Should intersect rects for multiple clipRect calls', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
rc.clipRect(const Rect.fromLTRB(50, 50, 100, 100), ClipOp.intersect);
rc.scale(2.0, 2.0);
rc.clipRect(const Rect.fromLTRB(30, 30, 45, 45), ClipOp.intersect);
rc.drawRect(const Rect.fromLTRB(10, 30, 60, 35), testPaint);
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(60, 60, 90, 70));
await checkScreenshot(rc, 'clip_rects_intersect');
});
// drawShadow
test('Computes paint bounds for drawShadow', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
final Path path = Path();
path.addRect(const Rect.fromLTRB(20, 30, 100, 110));
rc.drawShadow(path, const Color(0xFFFF0000), 2.0, true);
rc.endRecording();
expect(
rc.pictureBounds,
within(
distance: 0.05, from: const Rect.fromLTRB(0.0, 8.5, 123.5, 134.1)),
);
await checkScreenshot(rc, 'path_with_shadow');
});
test('Clip with negative scale reports correct paint bounds', () async {
// The following draws a filled rectangle that occupies the bottom half of
// the canvas. Notice that both the clip and the rectangle are drawn
// forward. What makes them appear at the bottom is the translation and a
// vertical flip via a negative scale. This replicates the Material
// overscroll glow effect at the bottom of a list, where it is drawn upside
// down.
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 100, 100));
rc
..translate(0, 100)
..scale(1, -1)
..clipRect(const Rect.fromLTRB(0, 0, 100, 50), ClipOp.intersect)
..drawRect(const Rect.fromLTRB(0, 0, 100, 100), SurfacePaint());
rc.endRecording();
expect(rc.pictureBounds, const Rect.fromLTRB(0.0, 50.0, 100.0, 100.0));
await checkScreenshot(rc, 'scale_negative');
});
test('Clip with a rotation reports correct paint bounds', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 100, 100));
rc
..translate(50, 50)
..rotate(math.pi / 4.0)
..clipRect(const Rect.fromLTWH(-20, -20, 40, 40), ClipOp.intersect)
..drawRect(const Rect.fromLTWH(-80, -80, 160, 160), SurfacePaint());
rc.endRecording();
expect(
rc.pictureBounds,
within(
distance: 0.001,
from: Rect.fromCircle(
center: const Offset(50, 50), radius: 20 * math.sqrt(2))),
);
await checkScreenshot(rc, 'clip_rect_rotated');
});
test('Rotated line reports correct paint bounds', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 100, 100));
rc
..translate(50, 50)
..rotate(math.pi / 4.0)
..drawLine(Offset.zero, const Offset(20, 20), SurfacePaint());
rc.endRecording();
expect(
rc.pictureBounds,
within(distance: 0.1, from: const Rect.fromLTRB(34.4, 48.6, 65.6, 79.7)),
);
await checkScreenshot(rc, 'line_rotated');
});
// Regression test for https://github.com/flutter/flutter/issues/46339.
test('Should draw a Rect for straight line when strokeWidth is zero.', () async {
final RecordingCanvas rc = RecordingCanvas(screenRect);
final Path path = Path();
final SurfacePaint paint = SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 0.0
..color = const Color(0xFFFF0000);
path.moveTo(10, 10);
path.lineTo(90, 10);
rc.drawPath(path, paint);
rc.endRecording();
// Should draw a Rect
final List<PaintCommand> commands = rc.debugPaintCommands;
expect(commands.length, 1);
expect(commands.first, isA<PaintDrawRect>());
// Should inflate picture bounds
expect(
rc.pictureBounds,
within(distance: 0.1, from: const Rect.fromLTRB(10, 10, 90, 11)),
);
await checkScreenshot(rc, 'path_straight_line_with_zero_stroke_width');
});
test('Should support reusing path and reset when drawing into canvas.',
() async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 100, 100));
final Path path = Path();
path.moveTo(3, 0);
path.lineTo(100, 97);
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFFFF0000));
path.reset();
path.moveTo(0, 3);
path.lineTo(97, 100);
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFF00FF00));
rc.endRecording();
await checkScreenshot(rc, 'reuse_path');
});
test('Should draw RRect after line when beginning new path.', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 200, 400));
rc.save();
rc.translate(50.0, 100.0);
final Path path = Path();
// Draw a vertical small line (caret).
path.moveTo(8, 4);
path.lineTo(8, 24);
// Draw round rect below caret.
path.addRRect(
RRect.fromLTRBR(0.5, 100.5, 80.7, 150.7, const Radius.circular(10)));
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFF404000));
rc.restore();
rc.endRecording();
await checkScreenshot(rc, 'path_with_line_and_roundrect');
});
// Regression test for https://github.com/flutter/flutter/issues/64371.
test('Should draw line following a polygon without closing path.', () async {
final RecordingCanvas rc =
RecordingCanvas(const Rect.fromLTRB(0, 0, 200, 400));
rc.save();
rc.translate(50.0, 100.0);
final Path path = Path();
// Draw a vertical small line (caret).
path.addPolygon(const <Offset>[Offset(0, 10), Offset(20,5), Offset(50,10)],
false);
path.lineTo(60, 80);
path.lineTo(0, 80);
path.close();
rc.drawPath(
path,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = const Color(0xFF404000));
rc.restore();
rc.endRecording();
await checkScreenshot(rc, 'path_with_addpolygon');
});
test('should include paint spread in bounds estimates', () async {
final SurfaceSceneBuilder sb = SurfaceSceneBuilder();
final List<PaintSpreadPainter> painters = <PaintSpreadPainter>[
(RecordingCanvas canvas, SurfacePaint paint) {
canvas.drawLine(
Offset.zero,
const Offset(20.0, 20.0),
paint,
);
},
(RecordingCanvas canvas, SurfacePaint paint) {
canvas.drawRect(
const Rect.fromLTRB(0.0, 0.0, 20.0, 20.0),
paint,
);
},
(RecordingCanvas canvas, SurfacePaint paint) {
canvas.drawRRect(
RRect.fromLTRBR(0.0, 0.0, 20.0, 20.0, const Radius.circular(7.0)),
paint,
);
},
(RecordingCanvas canvas, SurfacePaint paint) {
canvas.drawDRRect(
RRect.fromLTRBR(0.0, 0.0, 20.0, 20.0, const Radius.circular(5.0)),
RRect.fromLTRBR(4.0, 4.0, 16.0, 16.0, const Radius.circular(5.0)),
paint,
);
},
(RecordingCanvas canvas, SurfacePaint paint) {
canvas.drawOval(
const Rect.fromLTRB(0.0, 5.0, 20.0, 15.0),
paint,
);
},
(RecordingCanvas canvas, SurfacePaint paint) {
canvas.drawCircle(
const Offset(10.0, 10.0),
10.0,
paint,
);
},
(RecordingCanvas canvas, SurfacePaint paint) {
final SurfacePath path = SurfacePath()
..moveTo(10, 0)
..lineTo(20, 10)
..lineTo(10, 20)
..lineTo(0, 10)
..close();
canvas.drawPath(path, paint);
},
// Images are not affected by mask filter or stroke width. They use image
// filter instead.
(RecordingCanvas canvas, SurfacePaint paint) {
canvas.drawImage(_createRealTestImage(), Offset.zero, paint);
},
(RecordingCanvas canvas, SurfacePaint paint) {
canvas.drawImageRect(
_createRealTestImage(),
const Rect.fromLTRB(0, 0, 20, 20),
const Rect.fromLTRB(5, 5, 15, 15),
paint,
);
},
];
Picture drawBounds(Rect bounds) {
final EnginePictureRecorder recorder = EnginePictureRecorder();
final RecordingCanvas canvas = recorder.beginRecording(Rect.largest);
canvas.drawRect(
bounds,
SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 1.0
..color = const Color.fromARGB(255, 0, 255, 0),
);
return recorder.endRecording();
}
for (int i = 0; i < painters.length; i++) {
sb.pushOffset(0.0, 20.0 + 60.0 * i);
final PaintSpreadPainter painter = painters[i];
// Paint with zero paint spread.
{
sb.pushOffset(20.0, 0.0);
final EnginePictureRecorder recorder = EnginePictureRecorder();
final RecordingCanvas canvas = recorder.beginRecording(Rect.largest);
final SurfacePaint zeroSpreadPaint = SurfacePaint();
painter(canvas, zeroSpreadPaint);
sb.addPicture(Offset.zero, recorder.endRecording());
sb.addPicture(Offset.zero, drawBounds(canvas.pictureBounds!));
sb.pop();
}
// Paint with a thick stroke paint.
{
sb.pushOffset(80.0, 0.0);
final EnginePictureRecorder recorder = EnginePictureRecorder();
final RecordingCanvas canvas = recorder.beginRecording(Rect.largest);
final SurfacePaint thickStrokePaint = SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 5.0;
painter(canvas, thickStrokePaint);
sb.addPicture(Offset.zero, recorder.endRecording());
sb.addPicture(Offset.zero, drawBounds(canvas.pictureBounds!));
sb.pop();
}
// Paint with a mask filter blur.
{
sb.pushOffset(140.0, 0.0);
final EnginePictureRecorder recorder = EnginePictureRecorder();
final RecordingCanvas canvas = recorder.beginRecording(Rect.largest);
final SurfacePaint maskFilterBlurPaint = SurfacePaint()
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 5.0);
painter(canvas, maskFilterBlurPaint);
sb.addPicture(Offset.zero, recorder.endRecording());
sb.addPicture(Offset.zero, drawBounds(canvas.pictureBounds!));
sb.pop();
}
// Paint with a thick stroke paint and a mask filter blur.
{
sb.pushOffset(200.0, 0.0);
final EnginePictureRecorder recorder = EnginePictureRecorder();
final RecordingCanvas canvas = recorder.beginRecording(Rect.largest);
final SurfacePaint thickStrokeAndBlurPaint = SurfacePaint()
..style = PaintingStyle.stroke
..strokeWidth = 5.0
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 5.0);
painter(canvas, thickStrokeAndBlurPaint);
sb.addPicture(Offset.zero, recorder.endRecording());
sb.addPicture(Offset.zero, drawBounds(canvas.pictureBounds!));
sb.pop();
}
sb.pop();
}
final DomElement sceneElement = sb.build().webOnlyRootElement!;
domDocument.body!.append(sceneElement);
try {
await matchGoldenFile(
'paint_spread_bounds.png',
region: const Rect.fromLTRB(0, 0, 250, 600),
);
} finally {
sceneElement.remove();
}
});
}
typedef PaintSpreadPainter = void Function(
RecordingCanvas canvas, SurfacePaint paint);
const String _base64Encoded20x20TestImage = 'iVBORw0KGgoAAAANSUhEUgAAABQAAAAUC'
'AIAAAAC64paAAAACXBIWXMAAC4jAAAuIwF4pT92AAAA'
'B3RJTUUH5AMFFBksg4i3gQAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAAj'
'SURBVDjLY2TAC/7jlWVioACMah4ZmhnxpyHG0QAb1UyZZgBjWAIm/clP0AAAAABJRU5ErkJggg==';
HtmlImage _createRealTestImage() {
return HtmlImage(
createDomHTMLImageElement()
..src = 'data:text/plain;base64,$_base64Encoded20x20TestImage',
20,
20,
);
}
class TestImage implements Image {
@override
int get width => 20;
@override
int get height => 10;
@override
Future<ByteData> toByteData(
{ImageByteFormat format = ImageByteFormat.rawRgba}) async {
throw UnsupportedError('Cannot encode test image');
}
@override
String toString() => '[$width\u00D7$height]';
@override
void dispose() {}
@override
bool get debugDisposed => false;
@override
Image clone() => this;
@override
bool isCloneOf(Image other) => other == this;
@override
List<StackTrace>/*?*/ debugGetOpenHandleStackTraces() => <StackTrace>[];
@override
ColorSpace get colorSpace => ColorSpace.sRGB;
}
Paragraph createTestParagraph() {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'Ahem',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: 14.0,
));
builder.addText('A short sentence.');
return builder.build();
}
| engine/lib/web_ui/test/html/recording_canvas_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/recording_canvas_golden_test.dart",
"repo_id": "engine",
"token_count": 11399
} | 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.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../common/test_initialization.dart';
import '../paragraph/helper.dart';
import 'layout_service_helper.dart';
const bool skipWordSpacing = true;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(withImplicitView: true);
test('no text', () {
final CanvasParagraph paragraph = CanvasParagraphBuilder(ahemStyle).build();
paragraph.layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 0);
expect(paragraph.minIntrinsicWidth, 0);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l('', 0, 0, width: 0.0, height: 10.0, baseline: 8.0),
]);
});
test('preserves whitespace when measuring', () {
CanvasParagraph paragraph;
// leading whitespaces
paragraph = plain(ahemStyle, ' abc')..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 60);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l(' abc', 0, 6, hardBreak: true, width: 60.0),
]);
// trailing whitespaces
paragraph = plain(ahemStyle, 'abc ')..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 60);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 6, hardBreak: true, width: 30.0),
]);
// mixed whitespaces
paragraph = plain(ahemStyle, ' ab c ')
..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 100);
expect(paragraph.minIntrinsicWidth, 20);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l(' ab c ', 0, 10, hardBreak: true, width: 80.0, left: 0.0),
]);
// single whitespace
paragraph = plain(ahemStyle, ' ')..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 10);
expect(paragraph.minIntrinsicWidth, 0);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l(' ', 0, 1, hardBreak: true, width: 0.0, left: 0.0),
]);
// whitespace only
paragraph = plain(ahemStyle, ' ')..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 50);
expect(paragraph.minIntrinsicWidth, 0);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l(' ', 0, 5, hardBreak: true, width: 0.0, left: 0.0),
]);
});
test('uses single-line when text can fit without wrapping', () {
final CanvasParagraph paragraph = plain(ahemStyle, '12345')
..layout(constrain(50.0));
// Should fit on a single line.
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 50);
expect(paragraph.minIntrinsicWidth, 50);
expect(paragraph.width, 50);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l('12345', 0, 5, hardBreak: true, width: 50.0, left: 0.0, height: 10.0, baseline: 8.0),
]);
});
test('simple multi-line text', () {
final CanvasParagraph paragraph = plain(ahemStyle, 'foo bar baz')
..layout(constrain(70.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 110);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.width, 70);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('foo bar ', 0, 8, hardBreak: false, width: 70.0, left: 0.0, height: 10.0, baseline: 8.0),
l('baz', 8, 11, hardBreak: true, width: 30.0, left: 0.0, height: 10.0, baseline: 18.0),
]);
});
test('uses multi-line for long text', () {
CanvasParagraph paragraph;
// The long text doesn't fit in 50px of width, so it needs to wrap.
paragraph = plain(ahemStyle, '1234567890')..layout(constrain(50.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 100);
expect(paragraph.minIntrinsicWidth, 100);
expect(paragraph.width, 50);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('12345', 0, 5, hardBreak: false, width: 50.0, left: 0.0, height: 10.0, baseline: 8.0),
l('67890', 5, 10, hardBreak: true, width: 50.0, left: 0.0, height: 10.0, baseline: 18.0),
]);
// The first word is force-broken twice.
paragraph = plain(ahemStyle, 'abcdefghijk lm')..layout(constrain(50.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 140);
expect(paragraph.minIntrinsicWidth, 110);
expect(paragraph.width, 50);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('abcde', 0, 5, hardBreak: false, width: 50.0, left: 0.0, height: 10.0, baseline: 8.0),
l('fghij', 5, 10, hardBreak: false, width: 50.0, left: 0.0, height: 10.0, baseline: 18.0),
l('k lm', 10, 14, hardBreak: true, width: 40.0, left: 0.0, height: 10.0, baseline: 28.0),
]);
// Constraints enough only for "abcdef" but not for the trailing space.
paragraph = plain(ahemStyle, 'abcdef gh')..layout(constrain(60.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 90);
expect(paragraph.minIntrinsicWidth, 60);
expect(paragraph.width, 60);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcdef ', 0, 7, hardBreak: false, width: 60.0, left: 0.0, height: 10.0, baseline: 8.0),
l('gh', 7, 9, hardBreak: true, width: 20.0, left: 0.0, height: 10.0, baseline: 18.0),
]);
// Constraints aren't enough even for a single character. In this case,
// we show a minimum of one character per line.
paragraph = plain(ahemStyle, 'AA')..layout(constrain(8.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 20);
expect(paragraph.minIntrinsicWidth, 20);
expect(paragraph.width, 8);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('A', 0, 1, hardBreak: false, width: 10.0, left: 0.0, height: 10.0, baseline: 8.0),
l('A', 1, 2, hardBreak: true, width: 10.0, left: 0.0, height: 10.0, baseline: 18.0),
]);
// Extremely narrow constraints with new line in the middle.
paragraph = plain(ahemStyle, 'AA\nA')..layout(constrain(8.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 20);
expect(paragraph.minIntrinsicWidth, 20);
expect(paragraph.width, 8);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('A', 0, 1, hardBreak: false, width: 10.0, left: 0.0, height: 10.0, baseline: 8.0),
l('A', 1, 3, hardBreak: true, width: 10.0, left: 0.0, height: 10.0, baseline: 18.0),
l('A', 3, 4, hardBreak: true, width: 10.0, left: 0.0, height: 10.0, baseline: 28.0),
]);
// Extremely narrow constraints with new line in the end.
paragraph = plain(ahemStyle, 'AAA\n')..layout(constrain(8.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 30);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.width, 8);
expect(paragraph.height, 40);
expectLines(paragraph, <TestLine>[
l('A', 0, 1, hardBreak: false, width: 10.0, left: 0.0, height: 10.0, baseline: 8.0),
l('A', 1, 2, hardBreak: false, width: 10.0, left: 0.0, height: 10.0, baseline: 18.0),
l('A', 2, 4, hardBreak: true, width: 10.0, left: 0.0, height: 10.0, baseline: 28.0),
l('', 4, 4, hardBreak: true, width: 0.0, left: 0.0, height: 10.0, baseline: 38.0),
]);
});
test('uses multi-line for text that contains new-line', () {
final CanvasParagraph paragraph = plain(ahemStyle, '12\n34')
..layout(constrain(50.0));
// Text containing newlines should always be drawn in multi-line mode.
expect(paragraph.maxIntrinsicWidth, 20);
expect(paragraph.minIntrinsicWidth, 20);
expect(paragraph.width, 50);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('12', 0, 3, hardBreak: true, width: 20.0, left: 0.0),
l('34', 3, 5, hardBreak: true, width: 20.0, left: 0.0),
]);
});
test('empty lines', () {
CanvasParagraph paragraph;
// Empty lines in the beginning.
paragraph = plain(ahemStyle, '\n\n1234')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 40);
expect(paragraph.minIntrinsicWidth, 40);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('', 0, 1, hardBreak: true, width: 0.0, left: 0.0),
l('', 1, 2, hardBreak: true, width: 0.0, left: 0.0),
l('1234', 2, 6, hardBreak: true, width: 40.0, left: 0.0),
]);
// Empty lines in the middle.
paragraph = plain(ahemStyle, '12\n\n345')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 30);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('12', 0, 3, hardBreak: true, width: 20.0, left: 0.0),
l('', 3, 4, hardBreak: true, width: 0.0, left: 0.0),
l('345', 4, 7, hardBreak: true, width: 30.0, left: 0.0),
]);
// Empty lines in the end.
paragraph = plain(ahemStyle, '1234\n\n')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 40);
expect(paragraph.minIntrinsicWidth, 40);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('1234', 0, 5, hardBreak: true, width: 40.0, left: 0.0),
l('', 5, 6, hardBreak: true, width: 0.0, left: 0.0),
l('', 6, 6, hardBreak: true, width: 0.0, left: 0.0),
]);
});
test(
'wraps multi-line text correctly when constraint width is infinite',
() {
final CanvasParagraph paragraph = plain(ahemStyle, '123\n456 789')
..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 70);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.width, double.infinity);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('123', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('456 789', 4, 11, hardBreak: true, width: 70.0, left: 0.0),
]);
},
);
test('takes letter spacing into account', () {
final EngineTextStyle spacedTextStyle =
EngineTextStyle.only(letterSpacing: 3);
final CanvasParagraph spacedText =
plain(ahemStyle, 'abc', textStyle: spacedTextStyle)
..layout(constrain(100.0));
expect(spacedText.minIntrinsicWidth, 39);
expect(spacedText.maxIntrinsicWidth, 39);
});
test('takes word spacing into account', () {
final CanvasParagraph normalText = plain(ahemStyle, 'a b c')
..layout(constrain(100.0));
final CanvasParagraph spacedText = plain(ahemStyle, 'a b c',
textStyle: EngineTextStyle.only(wordSpacing: 1.5))
..layout(constrain(100.0));
expect(
normalText.maxIntrinsicWidth < spacedText.maxIntrinsicWidth,
isTrue,
);
}, skip: skipWordSpacing);
test('minIntrinsicWidth', () {
CanvasParagraph paragraph;
// Simple case.
paragraph = plain(ahemStyle, 'abc de fghi')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 4, hardBreak: false, width: 30.0, left: 0.0),
l('de ', 4, 7, hardBreak: false, width: 20.0, left: 0.0),
l('fghi', 7, 11, hardBreak: true, width: 40.0, left: 0.0),
]);
// With new lines.
paragraph = plain(ahemStyle, 'abcd\nef\nghi')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abcd', 0, 5, hardBreak: true, width: 40.0, left: 0.0),
l('ef', 5, 8, hardBreak: true, width: 20.0, left: 0.0),
l('ghi', 8, 11, hardBreak: true, width: 30.0, left: 0.0),
]);
// With trailing whitespace.
paragraph = plain(ahemStyle, 'abcd efg')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abcd ', 0, 10, hardBreak: false, width: 40.0, left: 0.0),
l('efg', 10, 13, hardBreak: true, width: 30.0, left: 0.0),
]);
// With trailing whitespace and new lines.
paragraph = plain(ahemStyle, 'abc \ndefg')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 8, hardBreak: true, width: 30.0, left: 0.0),
l('defg', 8, 12, hardBreak: true, width: 40.0, left: 0.0),
]);
// Very long text.
paragraph = plain(ahemStyle, 'AAAAAAAAAAAA')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 120);
expectLines(paragraph, <TestLine>[
l('AAAAA', 0, 5, hardBreak: false, width: 50.0, left: 0.0),
l('AAAAA', 5, 10, hardBreak: false, width: 50.0, left: 0.0),
l('AA', 10, 12, hardBreak: true, width: 20.0, left: 0.0),
]);
});
test('maxIntrinsicWidth', () {
CanvasParagraph paragraph;
// Simple case.
paragraph = plain(ahemStyle, 'abc de fghi')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 110);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 4, hardBreak: false, width: 30.0, left: 0.0),
l('de ', 4, 7, hardBreak: false, width: 20.0, left: 0.0),
l('fghi', 7, 11, hardBreak: true, width: 40.0, left: 0.0),
]);
// With new lines.
paragraph = plain(ahemStyle, 'abcd\nef\nghi')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abcd', 0, 5, hardBreak: true, width: 40.0, left: 0.0),
l('ef', 5, 8, hardBreak: true, width: 20.0, left: 0.0),
l('ghi', 8, 11, hardBreak: true, width: 30.0, left: 0.0),
]);
// With long whitespace.
paragraph = plain(ahemStyle, 'abcd efg')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 100);
expectLines(paragraph, <TestLine>[
l('abcd ', 0, 7, hardBreak: false, width: 40.0, left: 0.0),
l('efg', 7, 10, hardBreak: true, width: 30.0, left: 0.0),
]);
// With trailing whitespace.
paragraph = plain(ahemStyle, 'abc def ')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 100);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 4, hardBreak: false, width: 30.0, left: 0.0),
l('def ', 4, 10, hardBreak: true, width: 30.0, left: 0.0),
]);
// With trailing whitespace and new lines.
paragraph = plain(ahemStyle, 'abc \ndef ')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 60);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 5, hardBreak: true, width: 30.0, left: 0.0),
l('def ', 5, 11, hardBreak: true, width: 30.0, left: 0.0),
]);
// Very long text.
paragraph = plain(ahemStyle, 'AAAAAAAAAAAA')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 120);
expectLines(paragraph, <TestLine>[
l('AAAAA', 0, 5, hardBreak: false, width: 50.0, left: 0.0),
l('AAAAA', 5, 10, hardBreak: false, width: 50.0, left: 0.0),
l('AA', 10, 12, hardBreak: true, width: 20.0, left: 0.0),
]);
});
test('respects text overflow', () {
final EngineParagraphStyle overflowStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
ellipsis: '...',
);
// The text shouldn't be broken into multiple lines, so the height should
// be equal to a height of a single line.
final CanvasParagraph longText = plain(
overflowStyle,
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
)..layout(constrain(50.0));
expect(longText.minIntrinsicWidth, 480);
expect(longText.maxIntrinsicWidth, 480);
expect(longText.height, 10);
expectLines(longText, <TestLine>[
l('AA...', 0, 2, hardBreak: true, width: 50.0, left: 0.0),
]);
// The short prefix should make the text break into two lines, but the
// second line should remain unbroken.
final CanvasParagraph longTextShortPrefix = plain(
overflowStyle,
'AAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
)..layout(constrain(50.0));
expect(longTextShortPrefix.minIntrinsicWidth, 450);
expect(longTextShortPrefix.maxIntrinsicWidth, 450);
expect(longTextShortPrefix.height, 20);
expectLines(longTextShortPrefix, <TestLine>[
l('AAA', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('AA...', 4, 6, hardBreak: true, width: 50.0, left: 0.0),
]);
// Constraints only enough to fit "AA" with the ellipsis, but not the
// trailing white space.
final CanvasParagraph trailingSpace = plain(overflowStyle, 'AA AAA')
..layout(constrain(50.0));
expect(trailingSpace.minIntrinsicWidth, 30);
expect(trailingSpace.maxIntrinsicWidth, 60);
expect(trailingSpace.height, 10);
expectLines(trailingSpace, <TestLine>[
l('AA...', 0, 2, hardBreak: true, width: 50.0, left: 0.0),
]);
// Tiny constraints.
final CanvasParagraph paragraph = plain(overflowStyle, 'AAAA')
..layout(constrain(30.0));
expect(paragraph.minIntrinsicWidth, 40);
expect(paragraph.maxIntrinsicWidth, 40);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l('...', 0, 0, hardBreak: true, width: 30.0, left: 0.0),
]);
// Tinier constraints (not enough for the ellipsis).
paragraph.layout(constrain(10.0));
expect(paragraph.minIntrinsicWidth, 40);
expect(paragraph.maxIntrinsicWidth, 40);
expect(paragraph.height, 10);
// TODO(mdebbar): https://github.com/flutter/flutter/issues/34346
// expectLines(paragraph, <TestLine>[
// l('.', 0, 0, hardBreak: false, width: 10.0, left: 0.0),
// ]);
expectLines(paragraph, <TestLine>[
l('...', 0, 0, hardBreak: true, width: 30.0, left: 0.0),
]);
});
test('respects max lines', () {
final EngineParagraphStyle maxlinesStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
maxLines: 2,
);
// The height should be that of a single line.
final CanvasParagraph oneline = plain(maxlinesStyle, 'One line')
..layout(constrain(double.infinity));
expect(oneline.height, 10);
expectLines(oneline, <TestLine>[
l('One line', 0, 8, hardBreak: true, width: 80.0, left: 0.0),
]);
// The height should respect max lines and be limited to two lines here.
final CanvasParagraph threelines =
plain(maxlinesStyle, 'First\nSecond\nThird')
..layout(constrain(double.infinity));
expect(threelines.height, 20);
expectLines(threelines, <TestLine>[
l('First', 0, 6, hardBreak: true, width: 50.0, left: 0.0),
l('Second', 6, 13, hardBreak: true, width: 60.0, left: 0.0),
]);
// The height should respect max lines and be limited to two lines here.
final CanvasParagraph veryLong = plain(
maxlinesStyle,
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
)..layout(constrain(50.0));
expect(veryLong.height, 20);
expectLines(veryLong, <TestLine>[
l('Lorem ', 0, 6, hardBreak: false, width: 50.0, left: 0.0),
l('ipsum ', 6, 12, hardBreak: false, width: 50.0, left: 0.0),
]);
// Case when last line is a long unbreakable word.
final CanvasParagraph veryLongLastLine = plain(
maxlinesStyle,
'AAA AAAAAAAAAAAAAAAAAAA',
)..layout(constrain(50.0));
expect(veryLongLastLine.height, 20);
expectLines(veryLongLastLine, <TestLine>[
l('AAA ', 0, 4, hardBreak: false, width: 30.0, left: 0.0),
l('AAAAA', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
]);
});
test('respects text overflow and max lines combined', () {
final EngineParagraphStyle onelineStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
maxLines: 1,
ellipsis: '...',
);
final EngineParagraphStyle multilineStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
maxLines: 2,
ellipsis: '...',
);
CanvasParagraph paragraph;
// Simple no overflow case.
paragraph = plain(onelineStyle, 'abcdef')..layout(constrain(60.0));
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l('abcdef', 0, 6, hardBreak: true, width: 60.0, left: 0.0),
]);
// Simple overflow case.
paragraph = plain(onelineStyle, 'abcd efg')..layout(constrain(60.0));
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l('abc...', 0, 3, hardBreak: true, width: 60.0, left: 0.0),
]);
// Another simple overflow case.
paragraph = plain(onelineStyle, 'a bcde fgh')..layout(constrain(60.0));
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l('a b...', 0, 3, hardBreak: true, width: 60.0, left: 0.0),
]);
// The ellipsis is supposed to go on the second line, but because the
// 2nd line doesn't overflow, no ellipsis is shown.
paragraph = plain(multilineStyle, 'abcdef ghijkl')..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcdef ', 0, 7, hardBreak: false, width: 60.0, left: 0.0),
l('ghijkl', 7, 13, hardBreak: true, width: 60.0, left: 0.0),
]);
// But when the 2nd line is long enough, the ellipsis is shown.
paragraph = plain(multilineStyle, 'abcd efghijkl')..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcd ', 0, 5, hardBreak: false, width: 40.0, left: 0.0),
l('efg...', 5, 8, hardBreak: true, width: 60.0, left: 0.0),
]);
// Even if the second line can be broken, we don't break it, we just
// insert the ellipsis.
paragraph = plain(multilineStyle, 'abcde f gh ijk')
..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcde ', 0, 6, hardBreak: false, width: 50.0, left: 0.0),
l('f g...', 6, 9, hardBreak: true, width: 60.0, left: 0.0),
]);
// First line overflows but second line doesn't.
paragraph = plain(multilineStyle, 'abcdefg hijk')..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcdef', 0, 6, hardBreak: false, width: 60.0, left: 0.0),
l('g hijk', 6, 12, hardBreak: true, width: 60.0, left: 0.0),
]);
// Both first and second lines overflow.
paragraph = plain(multilineStyle, 'abcdefg hijklmnop')
..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcdef', 0, 6, hardBreak: false, width: 60.0, left: 0.0),
l('g h...', 6, 9, hardBreak: true, width: 60.0, left: 0.0),
]);
});
test('handles textAlign', () {
CanvasParagraph paragraph;
EngineParagraphStyle createStyle(ui.TextAlign textAlign) {
return EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
textAlign: textAlign,
textDirection: ui.TextDirection.ltr,
);
}
paragraph = plain(createStyle(ui.TextAlign.start), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 0.0),
]);
paragraph = plain(createStyle(ui.TextAlign.end), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 20.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0),
]);
paragraph = plain(createStyle(ui.TextAlign.center), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 10.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 20.0),
]);
paragraph = plain(createStyle(ui.TextAlign.left), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 0.0),
]);
paragraph = plain(createStyle(ui.TextAlign.right), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 20.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0),
]);
});
test('handles rtl with textAlign', () {
CanvasParagraph paragraph;
EngineParagraphStyle createStyle(ui.TextAlign textAlign) {
return EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
textAlign: textAlign,
textDirection: ui.TextDirection.rtl,
);
}
paragraph = plain(createStyle(ui.TextAlign.start), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 20.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0),
]);
paragraph = plain(createStyle(ui.TextAlign.end), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 0.0),
]);
paragraph = plain(createStyle(ui.TextAlign.center), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 10.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 20.0),
]);
paragraph = plain(createStyle(ui.TextAlign.left), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 0.0),
]);
paragraph = plain(createStyle(ui.TextAlign.right), 'abc\ndefghi')
..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 20.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0),
]);
});
test('uses a single minimal canvas', () {
debugResetCanvasCount();
plain(ahemStyle, 'Lorem').layout(constrain(double.infinity));
plain(ahemStyle, 'ipsum dolor').layout(constrain(150.0));
// Try different styles too.
plain(EngineParagraphStyle(fontWeight: ui.FontWeight.bold), 'sit amet').layout(constrain(300.0));
expect(textContext.canvas!.width, isZero);
expect(textContext.canvas!.height, isZero);
// This number is 0 instead of 1 because the canvas is created at the top
// level as a global variable. So by the time this test runs, the canvas
// would have been created already.
//
// So we just make sure that no new canvas is created after the above layout
// calls.
expect(debugCanvasCount, 0);
});
test('does not leak styles across spanometers', () {
// This prevents the Ahem font from being forced in all paragraphs.
ui_web.debugEmulateFlutterTesterEnvironment = false;
final CanvasParagraph p1 = plain(
EngineParagraphStyle(
fontSize: 20.0,
fontFamily: 'FontFamily1',
),
'Lorem',
)..layout(constrain(double.infinity));
// After the layout, the canvas should have the above style applied.
expect(textContext.font, contains('20px'));
expect(textContext.font, contains('FontFamily1'));
final CanvasParagraph p2 = plain(
EngineParagraphStyle(
fontSize: 40.0,
fontFamily: 'FontFamily2',
),
'ipsum dolor',
)..layout(constrain(double.infinity));
// After the layout, the canvas should have the above style applied.
expect(textContext.font, contains('40px'));
expect(textContext.font, contains('FontFamily2'));
p1.getBoxesForRange(0, 2);
// getBoxesForRange performs some text measurements. Let's make sure that it
// applied the correct style.
expect(textContext.font, contains('20px'));
expect(textContext.font, contains('FontFamily1'));
p2.getBoxesForRange(0, 4);
// getBoxesForRange performs some text measurements. Let's make sure that it
// applied the correct style.
expect(textContext.font, contains('40px'));
expect(textContext.font, contains('FontFamily2'));
ui_web.debugEmulateFlutterTesterEnvironment = true;
});
}
| engine/lib/web_ui/test/html/text/layout_service_plain_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/html/text/layout_service_plain_test.dart",
"repo_id": "engine",
"token_count": 11973
} | 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 'dart:async';
import 'dart:math' as math;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
import '../common/test_initialization.dart';
import 'utils.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
setUpTestViewDimensions: false,
);
const ui.Rect region = ui.Rect.fromLTWH(0, 0, 128, 128);
Future<void> drawTestImageWithPaint(ui.Paint paint) async {
final ui.Codec codec = await renderer.instantiateImageCodecFromUrl(
Uri(path: '/test_images/mandrill_128.png')
);
expect(codec.frameCount, 1);
final ui.FrameInfo info = await codec.getNextFrame();
final ui.Image image = info.image;
expect(image.width, 128);
expect(image.height, 128);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder, region);
canvas.drawImage(
image,
ui.Offset.zero,
paint,
);
await drawPictureUsingCurrentRenderer(recorder.endRecording());
}
test('blur filter', () async {
await drawTestImageWithPaint(ui.Paint()..imageFilter = ui.ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
));
await matchGoldenFile('ui_filter_blur_imagefilter.png', region: region);
});
test('dilate filter', () async {
await drawTestImageWithPaint(ui.Paint()..imageFilter = ui.ImageFilter.dilate(
radiusX: 5.0,
radiusY: 5.0,
));
await matchGoldenFile('ui_filter_dilate_imagefilter.png', region: region);
}, skip: !isSkwasm); // Only skwasm supports dilate filter right now
test('erode filter', () async {
await drawTestImageWithPaint(ui.Paint()..imageFilter = ui.ImageFilter.erode(
radiusX: 5.0,
radiusY: 5.0,
));
await matchGoldenFile('ui_filter_erode_imagefilter.png', region: region);
}, skip: !isSkwasm); // Only skwasm supports erode filter
test('matrix filter', () async {
await drawTestImageWithPaint(ui.Paint()..imageFilter = ui.ImageFilter.matrix(
Matrix4.rotationZ(math.pi / 6).toFloat64(),
filterQuality: ui.FilterQuality.high,
));
await matchGoldenFile('ui_filter_matrix_imagefilter.png', region: region);
});
test('resizing matrix filter', () async {
await drawTestImageWithPaint(ui.Paint()
..imageFilter = ui.ImageFilter.matrix(
Matrix4.diagonal3Values(0.5, 0.5, 1).toFloat64(),
filterQuality: ui.FilterQuality.high,
));
await matchGoldenFile('ui_filter_matrix_imagefilter_scaled.png',
region: region);
});
test('composed filters', () async {
final ui.ImageFilter filter = ui.ImageFilter.compose(
outer: ui.ImageFilter.matrix(
Matrix4.rotationZ(math.pi / 6).toFloat64(),
filterQuality: ui.FilterQuality.high,
),
inner: ui.ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
)
);
await drawTestImageWithPaint(ui.Paint()..imageFilter = filter);
await matchGoldenFile('ui_filter_composed_imagefilters.png', region: region);
}, skip: isHtml); // Only Skwasm and CanvasKit implement composable filters right now.
test('compose with colorfilter', () async {
final ui.ImageFilter filter = ui.ImageFilter.compose(
outer: const ui.ColorFilter.mode(
ui.Color.fromRGBO(0, 0, 255, 128),
ui.BlendMode.srcOver,
),
inner: ui.ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
)
);
await drawTestImageWithPaint(ui.Paint()..imageFilter = filter);
await matchGoldenFile('ui_filter_composed_colorfilter.png', region: region);
}, skip: isHtml); // Only Skwasm and CanvasKit implements composable filters right now.
test('color filter as image filter', () async {
const ui.ColorFilter colorFilter = ui.ColorFilter.mode(
ui.Color.fromRGBO(0, 0, 255, 128),
ui.BlendMode.srcOver,
);
await drawTestImageWithPaint(ui.Paint()..imageFilter = colorFilter);
await matchGoldenFile('ui_filter_colorfilter_as_imagefilter.png', region: region);
expect(colorFilter.toString(), 'ColorFilter.mode(Color(0x800000ff), BlendMode.srcOver)');
});
test('mode color filter', () async {
const ui.ColorFilter colorFilter = ui.ColorFilter.mode(
ui.Color.fromRGBO(0, 0, 255, 128),
ui.BlendMode.srcOver,
);
await drawTestImageWithPaint(ui.Paint()..colorFilter = colorFilter);
await matchGoldenFile('ui_filter_mode_colorfilter.png', region: region);
expect(colorFilter.toString(), 'ColorFilter.mode(Color(0x800000ff), BlendMode.srcOver)');
});
test('linearToSRGBGamma color filter', () async {
const ui.ColorFilter colorFilter = ui.ColorFilter.linearToSrgbGamma();
await drawTestImageWithPaint(ui.Paint()..colorFilter = colorFilter);
await matchGoldenFile('ui_filter_linear_to_srgb_colorfilter.png', region: region);
expect(colorFilter.toString(), 'ColorFilter.linearToSrgbGamma()');
}, skip: isHtml); // HTML renderer hasn't implemented this.
test('srgbToLinearGamma color filter', () async {
const ui.ColorFilter colorFilter = ui.ColorFilter.srgbToLinearGamma();
await drawTestImageWithPaint(ui.Paint()..colorFilter = colorFilter);
await matchGoldenFile('ui_filter_srgb_to_linear_colorfilter.png', region: region);
expect(colorFilter.toString(), 'ColorFilter.srgbToLinearGamma()');
}, skip: isHtml); // HTML renderer hasn't implemented this.
test('matrix color filter', () async {
const ui.ColorFilter sepia = ui.ColorFilter.matrix(<double>[
0.393, 0.769, 0.189, 0, 0,
0.349, 0.686, 0.168, 0, 0,
0.272, 0.534, 0.131, 0, 0,
0, 0, 0, 1, 0,
]);
await drawTestImageWithPaint(ui.Paint()..colorFilter = sepia);
await matchGoldenFile('ui_filter_matrix_colorfilter.png', region: region);
expect(sepia.toString(), startsWith('ColorFilter.matrix([0.393, 0.769, 0.189, '));
});
test('invert colors', () async {
await drawTestImageWithPaint(ui.Paint()..invertColors = true);
await matchGoldenFile('ui_filter_invert_colors.png', region: region);
});
test('invert colors with color filter', () async {
const ui.ColorFilter sepia = ui.ColorFilter.matrix(<double>[
0.393, 0.769, 0.189, 0, 0,
0.349, 0.686, 0.168, 0, 0,
0.272, 0.534, 0.131, 0, 0,
0, 0, 0, 1, 0,
]);
await drawTestImageWithPaint(ui.Paint()
..invertColors = true
..colorFilter = sepia);
await matchGoldenFile('ui_filter_invert_colors_with_colorfilter.png', region: region);
});
test('mask filter', () async {
const ui.MaskFilter maskFilter = ui.MaskFilter.blur(ui.BlurStyle.normal, 25.0);
await drawTestImageWithPaint(ui.Paint()..maskFilter = maskFilter);
await matchGoldenFile('ui_filter_blur_maskfilter.png', region: region);
});
}
| engine/lib/web_ui/test/ui/filters_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/ui/filters_test.dart",
"repo_id": "engine",
"token_count": 2802
} | 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.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
import 'package:ui/ui.dart';
import '../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests();
test('RRect.contains()', () {
final RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
topLeft: const Radius.circular(0.5),
topRight: const Radius.circular(0.25),
bottomRight: const Radius.elliptical(0.25, 0.75));
expect(rrect.contains(const Offset(1.0, 1.0)), isFalse);
expect(rrect.contains(const Offset(1.1, 1.1)), isFalse);
expect(rrect.contains(const Offset(1.15, 1.15)), isTrue);
expect(rrect.contains(const Offset(2.0, 1.0)), isFalse);
expect(rrect.contains(const Offset(1.93, 1.07)), isFalse);
expect(rrect.contains(const Offset(1.97, 1.7)), isFalse);
expect(rrect.contains(const Offset(1.7, 1.97)), isTrue);
expect(rrect.contains(const Offset(1.0, 1.99)), isTrue);
});
test('RRect.contains() large radii', () {
final RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
topLeft: const Radius.circular(5000.0),
topRight: const Radius.circular(2500.0),
bottomRight: const Radius.elliptical(2500.0, 7500.0));
expect(rrect.contains(const Offset(1.0, 1.0)), isFalse);
expect(rrect.contains(const Offset(1.1, 1.1)), isFalse);
expect(rrect.contains(const Offset(1.15, 1.15)), isTrue);
expect(rrect.contains(const Offset(2.0, 1.0)), isFalse);
expect(rrect.contains(const Offset(1.93, 1.07)), isFalse);
expect(rrect.contains(const Offset(1.97, 1.7)), isFalse);
expect(rrect.contains(const Offset(1.7, 1.97)), isTrue);
expect(rrect.contains(const Offset(1.0, 1.99)), isTrue);
});
test('RRect.webOnlyUniformRadii returns true when all corner radii are equal',
() {
final RRect rect1 = RRect.fromRectAndCorners(
const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0),
topLeft: const Radius.elliptical(5, 5),
topRight: const Radius.elliptical(5, 5),
bottomLeft: const Radius.elliptical(5, 5),
bottomRight: const Radius.elliptical(5, 5),
);
expect(rect1.webOnlyUniformRadii, isTrue);
final RRect rect2 = RRect.fromRectAndCorners(
const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0),
topLeft: const Radius.elliptical(1000, 5),
topRight: const Radius.elliptical(5, 5),
bottomLeft: const Radius.elliptical(5, 5),
bottomRight: const Radius.elliptical(5, 5),
);
expect(rect2.webOnlyUniformRadii, isFalse);
final RRect rect3 = RRect.fromRectAndCorners(
const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0),
topLeft: const Radius.elliptical(5, 1000),
topRight: const Radius.elliptical(5, 5),
bottomLeft: const Radius.elliptical(5, 5),
bottomRight: const Radius.elliptical(5, 5),
);
expect(rect3.webOnlyUniformRadii, isFalse);
final RRect rect4 = RRect.fromRectAndCorners(
const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0),
topLeft: const Radius.elliptical(5, 5),
topRight: const Radius.elliptical(1000, 5),
bottomLeft: const Radius.elliptical(5, 5),
bottomRight: const Radius.elliptical(5, 5),
);
expect(rect4.webOnlyUniformRadii, isFalse);
final RRect rect5 = RRect.fromRectAndCorners(
const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0),
topLeft: const Radius.elliptical(5, 5),
topRight: const Radius.elliptical(5, 1000),
bottomLeft: const Radius.elliptical(5, 5),
bottomRight: const Radius.elliptical(5, 5),
);
expect(rect5.webOnlyUniformRadii, isFalse);
final RRect rect6 = RRect.fromRectAndCorners(
const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0),
topLeft: const Radius.elliptical(5, 5),
topRight: const Radius.elliptical(5, 5),
bottomLeft: const Radius.elliptical(1000, 5),
bottomRight: const Radius.elliptical(5, 5),
);
expect(rect6.webOnlyUniformRadii, isFalse);
final RRect rect7 = RRect.fromRectAndCorners(
const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0),
topLeft: const Radius.elliptical(5, 5),
topRight: const Radius.elliptical(5, 5),
bottomLeft: const Radius.elliptical(5, 1000),
bottomRight: const Radius.elliptical(5, 5),
);
expect(rect7.webOnlyUniformRadii, isFalse);
final RRect rect8 = RRect.fromRectAndCorners(
const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0),
topLeft: const Radius.elliptical(5, 5),
topRight: const Radius.elliptical(5, 5),
bottomLeft: const Radius.elliptical(5, 5),
bottomRight: const Radius.elliptical(1000, 5),
);
expect(rect8.webOnlyUniformRadii, isFalse);
final RRect rect9 = RRect.fromRectAndCorners(
const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0),
topLeft: const Radius.elliptical(5, 5),
topRight: const Radius.elliptical(5, 5),
bottomLeft: const Radius.elliptical(5, 5),
bottomRight: const Radius.elliptical(5, 1000),
);
expect(rect9.webOnlyUniformRadii, isFalse);
});
}
| engine/lib/web_ui/test/ui/rrect_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/ui/rrect_test.dart",
"repo_id": "engine",
"token_count": 2265
} | 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.
#include "flutter/common/task_runners.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
#include "flutter/runtime/isolate_configuration.h"
#include "flutter/testing/fixture_test.h"
namespace flutter {
namespace testing {
using DartLifecycleTest = FixtureTest;
TEST_F(DartLifecycleTest, CanStartAndShutdownVM) {
auto settings = CreateSettingsForFixture();
settings.leak_vm = false;
settings.enable_vm_service = false;
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
{
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
}
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(DartLifecycleTest, CanStartAndShutdownVMOverAndOver) {
auto settings = CreateSettingsForFixture();
settings.leak_vm = false;
settings.enable_vm_service = false;
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto count = DartVM::GetVMLaunchCount();
for (size_t i = 0; i < 10; i++) {
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_EQ(DartVM::GetVMLaunchCount(), count + 1);
count = DartVM::GetVMLaunchCount();
}
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
static std::shared_ptr<DartIsolate> CreateAndRunRootIsolate(
const Settings& settings,
const DartVMData& vm,
const fml::RefPtr<fml::TaskRunner>& task_runner,
std::string entrypoint) {
FML_CHECK(!entrypoint.empty());
TaskRunners runners("io.flutter.test", task_runner, task_runner, task_runner,
task_runner);
auto isolate_configuration =
IsolateConfiguration::InferFromSettings(settings);
UIDartState::Context context(runners);
context.advisory_script_uri = "main.dart";
context.advisory_script_entrypoint = entrypoint.c_str();
auto isolate =
DartIsolate::CreateRunningRootIsolate(
vm.GetSettings(), // settings
vm.GetIsolateSnapshot(), // isolate_snapshot
{}, // platform configuration
DartIsolate::Flags{}, // flags
nullptr, // root isolate create callback
settings.isolate_create_callback, // isolate create callback
settings.isolate_shutdown_callback, // isolate shutdown callback,
entrypoint, // dart entrypoint
std::nullopt, // dart entrypoint library
{}, // dart entrypoint arguments
std::move(isolate_configuration), // isolate configuration
context // engine context
)
.lock();
if (!isolate) {
FML_LOG(ERROR) << "Could not launch the root isolate.";
return nullptr;
}
return isolate;
}
// TODO(chinmaygarde): This unit-test is flaky and indicates thread un-safety
// during shutdown. https://github.com/flutter/flutter/issues/36782
TEST_F(DartLifecycleTest, DISABLED_ShuttingDownTheVMShutsDownAllIsolates) {
auto settings = CreateSettingsForFixture();
settings.leak_vm = false;
// Make sure the service protocol launches
settings.enable_vm_service = true;
auto thread_task_runner = CreateNewThread();
for (size_t i = 0; i < 3; i++) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
const auto last_launch_count = DartVM::GetVMLaunchCount();
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_EQ(last_launch_count + 1, DartVM::GetVMLaunchCount());
const size_t isolate_count = 5;
fml::CountDownLatch latch(isolate_count);
auto vm_data = vm_ref.GetVMData();
for (size_t i = 0; i < isolate_count; ++i) {
thread_task_runner->PostTask(
[vm_data, &settings, &latch, thread_task_runner]() {
ASSERT_TRUE(CreateAndRunRootIsolate(settings, *vm_data.get(),
thread_task_runner,
"testIsolateShutdown"));
latch.CountDown();
});
}
latch.Wait();
}
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
} // namespace testing
} // namespace flutter
| engine/runtime/dart_lifecycle_unittests.cc/0 | {
"file_path": "engine/runtime/dart_lifecycle_unittests.cc",
"repo_id": "engine",
"token_count": 1891
} | 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.
#ifndef FLUTTER_RUNTIME_DART_VM_INITIALIZER_H_
#define FLUTTER_RUNTIME_DART_VM_INITIALIZER_H_
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/dart/runtime/include/dart_tools_api.h"
class DartVMInitializer {
public:
static void Initialize(Dart_InitializeParams* params,
bool enable_timeline_event_handler,
bool trace_systrace);
static void Cleanup();
private:
static void LogDartTimelineEvent(const char* label,
int64_t timestamp0,
int64_t timestamp1_or_async_id,
intptr_t flow_id_count,
const int64_t* flow_ids,
Dart_Timeline_Event_Type type,
intptr_t argument_count,
const char** argument_names,
const char** argument_values);
};
#endif // FLUTTER_RUNTIME_DART_VM_INITIALIZER_H_
| engine/runtime/dart_vm_initializer.h/0 | {
"file_path": "engine/runtime/dart_vm_initializer.h",
"repo_id": "engine",
"token_count": 642
} | 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_RUNTIME_PLATFORM_ISOLATE_MANAGER_H_
#define FLUTTER_RUNTIME_PLATFORM_ISOLATE_MANAGER_H_
#include <atomic>
#include <mutex>
#include <unordered_set>
#include "third_party/dart/runtime/include/dart_api.h"
namespace flutter {
/// Maintains a list of registered platform isolates, so that they can be
/// proactively shutdown as a group during shell shutdown.
class PlatformIsolateManager {
public:
/// Returns whether the PlatformIsolateManager is shutdown. New isolates
/// cannot be registered after the manager is shutdown. Must be called on the
/// platform thread.
bool HasShutdown();
/// Returns whether the PlatformIsolateManager is shutdown. New isolates
/// cannot be registered after the manager is shutdown. Callable from any
/// thread. The result may be obsolete immediately after the call.
bool HasShutdownMaybeFalseNegative();
/// Register an isolate in the list of platform isolates. Callable from any
/// thread.
bool RegisterPlatformIsolate(Dart_Isolate isolate);
/// Remove an isolate from the list of platform isolates. Must be called from
/// the platform thread.
void RemovePlatformIsolate(Dart_Isolate isolate);
/// Shuts down all registered isolates, and the manager itself. Must be called
/// from the platform thread.
void ShutdownPlatformIsolates();
/// Returns whether an isolate is registered. For testing only. Callable from
/// any thread.
bool IsRegisteredForTestingOnly(Dart_Isolate isolate);
private:
// This lock must be recursive because ShutdownPlatformIsolates indirectly
// calls RemovePlatformIsolate.
std::recursive_mutex lock_;
std::unordered_set<Dart_Isolate> platform_isolates_;
bool is_shutdown_ = false;
};
} // namespace flutter
#endif // FLUTTER_RUNTIME_PLATFORM_ISOLATE_MANAGER_H_
| engine/runtime/platform_isolate_manager.h/0 | {
"file_path": "engine/runtime/platform_isolate_manager.h",
"repo_id": "engine",
"token_count": 554
} | 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.
import("//flutter/common/config.gni")
import("//flutter/impeller/tools/impeller.gni")
import("//flutter/shell/gpu/gpu.gni")
import("//flutter/testing/testing.gni")
if (is_fuchsia) {
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
}
# Template to generate a dart embedder resource.cc file.
# Required invoker inputs:
# String output (name of output file)
# List inputs (list of input files to be included)
# String table_name (name of symbol for resource table)
# String root_prefix (base directory of resources)
# Optional invoker inputs:
# String input_directory (directory of resources that are recursively added)
# List deps
# List datadeps
template("dart_embedder_resources") {
action(target_name) {
script = "$dart_src/runtime/tools/create_resources.py"
deps = []
if (defined(invoker.deps)) {
deps += invoker.deps
}
datadeps = []
if (defined(invoker.datadeps)) {
datadeps = invoker.datadeps
}
output = invoker.output
outputs = [ output ]
inputs = [ script ] + invoker.inputs
root_prefix = rebase_path(invoker.root_prefix)
args = [
"--output",
rebase_path(output),
"--outer_namespace",
"flutter",
"--inner_namespace",
"runtime",
"--table_name",
invoker.table_name,
"--root_prefix",
root_prefix,
]
if (defined(invoker.input_directory)) {
args += [
"--client_root",
rebase_path(invoker.input_directory),
]
}
args += rebase_path(invoker.inputs)
}
}
source_set("platform_message_handler") {
sources = [ "platform_message_handler.h" ]
public_configs = [ "//flutter:config" ]
deps = [ "//flutter/fml:fml" ]
}
source_set("display") {
sources = [
"display.cc",
"display.h",
"variable_refresh_rate_display.cc",
"variable_refresh_rate_display.h",
"variable_refresh_rate_reporter.h",
]
public_configs = [ "//flutter:config" ]
deps = [ "//flutter/fml:fml" ]
}
source_set("common") {
sources = [
"animator.cc",
"animator.h",
"context_options.cc",
"context_options.h",
"display_manager.cc",
"display_manager.h",
"dl_op_spy.cc",
"dl_op_spy.h",
"engine.cc",
"engine.h",
"pipeline.cc",
"pipeline.h",
"platform_view.cc",
"platform_view.h",
"pointer_data_dispatcher.cc",
"pointer_data_dispatcher.h",
"rasterizer.cc",
"rasterizer.h",
"resource_cache_limit_calculator.cc",
"resource_cache_limit_calculator.h",
"run_configuration.cc",
"run_configuration.h",
"serialization_callbacks.cc",
"serialization_callbacks.h",
"shell.cc",
"shell.h",
"shell_io_manager.cc",
"shell_io_manager.h",
"skia_event_tracer_impl.cc",
"skia_event_tracer_impl.h",
"snapshot_controller.cc",
"snapshot_controller.h",
"snapshot_controller_skia.cc",
"snapshot_controller_skia.h",
"snapshot_surface_producer.h",
"switches.cc",
"switches.h",
"thread_host.cc",
"thread_host.h",
"vsync_waiter.cc",
"vsync_waiter.h",
"vsync_waiter_fallback.cc",
"vsync_waiter_fallback.h",
]
public_configs = [ "//flutter:config" ]
public_deps = [
":display",
":platform_message_handler",
"//flutter/shell/version",
"//flutter/third_party/rapidjson",
"//flutter/third_party/tonic",
"//flutter/third_party/txt",
]
deps = [
"$dart_src/runtime:dart_api",
"//flutter/assets",
"//flutter/common",
"//flutter/common/graphics",
"//flutter/flow",
"//flutter/fml",
"//flutter/lib/ui",
"//flutter/runtime",
"//flutter/shell/common:base64",
"//flutter/shell/profiling",
"//flutter/skia",
]
if (impeller_supports_rendering) {
sources += [
"snapshot_controller_impeller.cc",
"snapshot_controller_impeller.h",
]
deps += [ "//flutter/impeller" ]
}
}
# These are in their own source_set to avoid a dependency cycle with //common/graphics
source_set("base64") {
sources = [
"base64.cc",
"base64.h",
]
deps = [ "//flutter/fml" ]
}
template("shell_host_executable") {
executable(target_name) {
testonly = true
deps = []
ldflags = []
forward_variables_from(invoker, "*")
deps += [
":common",
"//flutter/lib/snapshot",
"//flutter/runtime:libdart",
]
public_configs = [ "//flutter:export_dynamic_symbols" ]
}
}
if (enable_unittests) {
shell_gpu_configuration("shell_unittests_gpu_configuration") {
enable_software = test_enable_software
enable_vulkan = test_enable_vulkan
enable_gl = test_enable_gl
enable_metal = test_enable_metal
}
test_fixtures("shell_unittests_fixtures") {
dart_main = "fixtures/shell_test.dart"
fixtures = [
"fixtures/shelltest_screenshot.png",
"fixtures/hello_loop_2.gif",
"//flutter/third_party/txt/third_party/fonts/Roboto-Regular.ttf",
]
}
shell_host_executable("shell_benchmarks") {
sources = [
"dart_native_benchmarks.cc",
"shell_benchmarks.cc",
]
deps = [
":shell_unittests_fixtures",
"//flutter/benchmarking",
"//flutter/flow",
"//flutter/testing:dart",
"//flutter/testing:fixture_test",
"//flutter/testing:testing_lib",
]
}
config("shell_test_fixture_sources_config") {
defines = [
# Required for MSVC STL
"_ENABLE_ATOMIC_ALIGNMENT_FIX",
]
}
source_set("shell_test_fixture_sources") {
testonly = true
sources = [
"shell_test.cc",
"shell_test.h",
"shell_test_external_view_embedder.cc",
"shell_test_external_view_embedder.h",
"shell_test_platform_view.cc",
"shell_test_platform_view.h",
"vsync_waiters_test.cc",
"vsync_waiters_test.h",
]
public_deps = [
"//flutter/common/graphics",
"//flutter/flow",
"//flutter/runtime",
"//flutter/shell/common",
"//flutter/testing",
]
deps = [
":shell_unittests_gpu_configuration",
"//flutter/assets",
"//flutter/common",
"//flutter/lib/ui",
"//flutter/skia",
"//flutter/testing:dart",
"//flutter/testing:fixture_test",
"//flutter/third_party/rapidjson",
]
if (impeller_supports_rendering) {
deps += [ "//flutter/impeller" ]
}
public_configs = [
":shell_test_fixture_sources_config",
":shell_unittests_gpu_configuration_config",
]
if (test_enable_gl) {
sources += [
"shell_test_platform_view_gl.cc",
"shell_test_platform_view_gl.h",
]
public_deps += [ "//flutter/testing:opengl" ]
}
if (test_enable_vulkan) {
sources += [
"shell_test_platform_view_vulkan.cc",
"shell_test_platform_view_vulkan.h",
]
public_deps += [
"//flutter/flutter_vma:flutter_skia_vma",
"//flutter/vulkan",
]
}
if (test_enable_metal) {
sources += [
"shell_test_platform_view_metal.h",
"shell_test_platform_view_metal.mm",
]
public_deps += [ "//flutter/shell/platform/darwin/graphics" ]
}
}
shell_host_executable("shell_unittests") {
testonly = true
sources = [
"animator_unittests.cc",
"base64_unittests.cc",
"context_options_unittests.cc",
"dl_op_spy_unittests.cc",
"engine_animator_unittests.cc",
"engine_unittests.cc",
"input_events_unittests.cc",
"persistent_cache_unittests.cc",
"pipeline_unittests.cc",
"rasterizer_unittests.cc",
"resource_cache_limit_calculator_unittests.cc",
"shell_unittests.cc",
"switches_unittests.cc",
"variable_refresh_rate_display_unittests.cc",
"vsync_waiter_unittests.cc",
]
deps = [
":shell_test_fixture_sources",
":shell_unittests_fixtures",
"//flutter/assets",
"//flutter/common/graphics",
"//flutter/display_list/testing:display_list_testing",
"//flutter/shell/common:base64",
"//flutter/shell/profiling:profiling_unittests",
"//flutter/shell/version",
"//flutter/testing:fixture_test",
"//flutter/third_party/googletest:gmock",
]
if (is_fuchsia) {
sources += [ "shell_fuchsia_unittests.cc" ]
deps += [
"${fuchsia_sdk}/fidl/fuchsia.intl",
"${fuchsia_sdk}/fidl/fuchsia.settings",
"${fuchsia_sdk}/pkg/fidl_cpp",
"${fuchsia_sdk}/pkg/sys_cpp",
]
} else if (shell_enable_gl) {
# TODO(63837): This test is hard-coded to use a TestGLSurface so it cannot
# run on fuchsia or when GL is not enabled.
sources += [ "shell_io_manager_unittests.cc" ]
deps += [ "//flutter/third_party/swiftshader" ]
}
if (shell_enable_gl) {
deps += [
"//flutter/third_party/angle:libEGL_static",
"//flutter/third_party/angle:libGLESv2_static",
"//flutter/third_party/swiftshader",
]
}
}
}
| engine/shell/common/BUILD.gn/0 | {
"file_path": "engine/shell/common/BUILD.gn",
"repo_id": "engine",
"token_count": 4151
} | 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_COMMON_DL_OP_SPY_H_
#define FLUTTER_SHELL_COMMON_DL_OP_SPY_H_
#include "flutter/display_list/dl_op_receiver.h"
#include "flutter/display_list/utils/dl_receiver_utils.h"
namespace flutter {
//------------------------------------------------------------------------------
/// Receives to drawing commands of a DisplayListBuilder.
///
/// This is used to determine whether any non-transparent pixels will be drawn
/// on the canvas.
/// All the drawImage operations are considered drawing non-transparent pixels.
///
/// To use this class, dispatch the operations from DisplayList to a concrete
/// DlOpSpy object, and check the result of `did_draw` method.
///
/// ```
/// DlOpSpy dl_op_spy;
/// display_list.Dispatch(dl_op_spy);
/// bool did_draw = dl_op_spy.did_draw()
/// ```
///
class DlOpSpy final : public virtual DlOpReceiver,
private IgnoreAttributeDispatchHelper,
private IgnoreClipDispatchHelper,
private IgnoreTransformDispatchHelper {
public:
//----------------------------------------------------------------------------
/// @brief Returns true if any non transparent content has been drawn.
bool did_draw();
private:
void setColor(DlColor color) override;
void setColorSource(const DlColorSource* source) override;
void save() override;
void saveLayer(const SkRect& bounds,
const SaveLayerOptions options,
const DlImageFilter* backdrop) override;
void restore() override;
void drawColor(DlColor color, DlBlendMode mode) override;
void drawPaint() override;
void drawLine(const SkPoint& p0, const SkPoint& p1) override;
void drawRect(const SkRect& rect) override;
void drawOval(const SkRect& bounds) override;
void drawCircle(const SkPoint& center, SkScalar radius) override;
void drawRRect(const SkRRect& rrect) override;
void drawDRRect(const SkRRect& outer, const SkRRect& inner) override;
void drawPath(const SkPath& path) override;
void drawArc(const SkRect& oval_bounds,
SkScalar start_degrees,
SkScalar sweep_degrees,
bool use_center) override;
void drawPoints(PointMode mode,
uint32_t count,
const SkPoint points[]) override;
void drawVertices(const DlVertices* vertices, DlBlendMode mode) override;
void drawImage(const sk_sp<DlImage> image,
const SkPoint point,
DlImageSampling sampling,
bool render_with_attributes) override;
void drawImageRect(
const sk_sp<DlImage> image,
const SkRect& src,
const SkRect& dst,
DlImageSampling sampling,
bool render_with_attributes,
SrcRectConstraint constraint = SrcRectConstraint::kFast) override;
void drawImageNine(const sk_sp<DlImage> image,
const SkIRect& center,
const SkRect& dst,
DlFilterMode filter,
bool render_with_attributes) override;
void drawAtlas(const sk_sp<DlImage> atlas,
const SkRSXform xform[],
const SkRect tex[],
const DlColor colors[],
int count,
DlBlendMode mode,
DlImageSampling sampling,
const SkRect* cull_rect,
bool render_with_attributes) override;
void drawDisplayList(const sk_sp<DisplayList> display_list,
SkScalar opacity = SK_Scalar1) override;
void drawTextBlob(const sk_sp<SkTextBlob> blob,
SkScalar x,
SkScalar y) override;
void drawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame,
SkScalar x,
SkScalar y) override;
void drawShadow(const SkPath& path,
const DlColor color,
const SkScalar elevation,
bool transparent_occluder,
SkScalar dpr) override;
// Indicates if the attributes are set to values that will modify the
// destination. For now, the test only checks if there is a non-transparent
// color set.
bool will_draw_ = true;
bool did_draw_ = false;
};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_DL_OP_SPY_H_
| engine/shell/common/dl_op_spy.h/0 | {
"file_path": "engine/shell/common/dl_op_spy.h",
"repo_id": "engine",
"token_count": 1836
} | 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.
#ifndef FLUTTER_SHELL_COMMON_PLATFORM_VIEW_H_
#define FLUTTER_SHELL_COMMON_PLATFORM_VIEW_H_
#include <functional>
#include <memory>
#include "flutter/common/graphics/texture.h"
#include "flutter/common/task_runners.h"
#include "flutter/flow/embedded_views.h"
#include "flutter/flow/surface.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/lib/ui/semantics/custom_accessibility_action.h"
#include "flutter/lib/ui/semantics/semantics_node.h"
#include "flutter/lib/ui/window/key_data_packet.h"
#include "flutter/lib/ui/window/platform_message.h"
#include "flutter/lib/ui/window/pointer_data_packet.h"
#include "flutter/lib/ui/window/pointer_data_packet_converter.h"
#include "flutter/lib/ui/window/viewport_metrics.h"
#include "flutter/shell/common/platform_message_handler.h"
#include "flutter/shell/common/pointer_data_dispatcher.h"
#include "flutter/shell/common/vsync_waiter.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
namespace impeller {
class Context;
} // namespace impeller
namespace flutter {
//------------------------------------------------------------------------------
/// @brief Platform views are created by the shell on the platform task
/// runner. Unless explicitly specified, all platform view methods
/// are called on the platform task runner as well. Platform views
/// are usually sub-classed on a per platform basis and the bulk of
/// the window system integration happens using that subclass. Since
/// most platform window toolkits are usually only safe to access on
/// a single "main" thread, any interaction that requires access to
/// the underlying platform's window toolkit is routed through the
/// platform view associated with that shell. This involves
/// operations like settings up and tearing down the render surface,
/// platform messages, interacting with accessibility features on
/// the platform, input events, etc.
///
class PlatformView {
public:
//----------------------------------------------------------------------------
/// @brief Used to forward events from the platform view to interested
/// subsystems. This forwarding is done by the shell which sets
/// itself up as the delegate of the platform view.
///
class Delegate {
public:
using KeyDataResponse = std::function<void(bool)>;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the platform view was created
/// with the given render surface. This surface is platform
/// (iOS, Android) and client-rendering API (OpenGL, Software,
/// Metal, Vulkan) specific. This is usually a sign to the
/// rasterizer to set up and begin rendering to that surface.
///
/// @param[in] surface The surface
///
virtual void OnPlatformViewCreated(std::unique_ptr<Surface> surface) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the platform view was destroyed.
/// This is usually a sign to the rasterizer to suspend
/// rendering a previously configured surface and collect any
/// intermediate resources.
///
virtual void OnPlatformViewDestroyed() = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the platform needs to schedule a
/// frame to regenerate the layer tree and redraw the surface.
///
virtual void OnPlatformViewScheduleFrame() = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the specified callback needs to
/// be invoked after the rasterizer is done rendering the next
/// frame. This callback will be called on the render thread and
/// it is caller responsibility to perform any re-threading as
/// necessary. Due to the asynchronous nature of rendering in
/// Flutter, embedders usually add a placeholder over the
/// contents in which Flutter is going to render when Flutter is
/// first initialized. This callback may be used as a signal to
/// remove that placeholder.
///
/// @attention The callback will be invoked on the render thread and not
/// the calling thread.
///
/// @param[in] closure The callback to execute on the next frame.
///
virtual void OnPlatformViewSetNextFrameCallback(
const fml::closure& closure) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate the viewport metrics of a view have
/// been updated. The rasterizer will need to be reconfigured to
/// render the frame in the updated viewport metrics.
///
/// @param[in] view_id The ID for the view that `metrics` describes.
/// @param[in] metrics The updated viewport metrics.
///
virtual void OnPlatformViewSetViewportMetrics(
int64_t view_id,
const ViewportMetrics& metrics) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the platform has dispatched a
/// platform message from the embedder to the Flutter
/// application. This message must be forwarded to the running
/// isolate hosted by the engine on the UI thread.
///
/// @param[in] message The platform message to dispatch to the running
/// root isolate.
///
virtual void OnPlatformViewDispatchPlatformMessage(
std::unique_ptr<PlatformMessage> message) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the platform view has encountered
/// a pointer event. This pointer event needs to be forwarded to
/// the running root isolate hosted by the engine on the UI
/// thread.
///
/// @param[in] packet The pointer data packet containing multiple pointer
/// events.
///
virtual void OnPlatformViewDispatchPointerDataPacket(
std::unique_ptr<PointerDataPacket> packet) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the platform view has encountered
/// an accessibility related action on the specified node. This
/// event must be forwarded to the running root isolate hosted
/// by the engine on the UI thread.
///
/// @param[in] node_id The identifier of the accessibility node.
/// @param[in] action The accessibility related action performed on the
/// node of the specified ID.
/// @param[in] args An optional list of argument that apply to the
/// specified action.
///
virtual void OnPlatformViewDispatchSemanticsAction(
int32_t node_id,
SemanticsAction action,
fml::MallocMapping args) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the embedder has expressed an
/// opinion about whether the accessibility tree needs to be
/// enabled or disabled. This information needs to be forwarded
/// to the root isolate running on the UI thread.
///
/// @param[in] enabled Whether the accessibility tree is enabled or
/// disabled.
///
virtual void OnPlatformViewSetSemanticsEnabled(bool enabled) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the embedder has expressed an
/// opinion about the features to enable in the accessibility
/// tree.
///
/// The engine does not care about the accessibility feature
/// flags as all it does is forward this information from the
/// embedder to the framework. However, curious readers may
/// refer to `AccessibilityFeatures` in `window.dart` for
/// currently supported accessibility feature flags.
///
/// @param[in] flags The features to enable in the accessibility tree.
///
virtual void OnPlatformViewSetAccessibilityFeatures(int32_t flags) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the embedder has specified a
/// texture that it want the rasterizer to composite within the
/// Flutter layer tree. All textures must have a unique
/// identifier. When the rasterizer encounters an external
/// texture within its hierarchy, it gives the embedder a chance
/// to update that texture on the raster thread before it
/// composites the same on-screen.
///
/// @param[in] texture The texture that is being updated by the embedder
/// but composited by Flutter in its own hierarchy.
///
virtual void OnPlatformViewRegisterTexture(
std::shared_ptr<Texture> texture) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the embedder will no longer
/// attempt to composite the specified texture within the layer
/// tree. This allows the rasterizer to collect associated
/// resources.
///
/// @param[in] texture_id The identifier of the texture to unregister. If
/// the texture has not been previously registered,
/// this call does nothing.
///
virtual void OnPlatformViewUnregisterTexture(int64_t texture_id) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies the delegate that the embedder has updated the
/// contents of the texture with the specified identifier.
/// Typically, Flutter will only render a frame if there is an
/// updated layer tree. However, in cases where the layer tree
/// is static but one of the externally composited textures has
/// been updated by the embedder, the embedder needs to notify
/// the rasterizer to render a new frame. In such cases, the
/// existing layer tree may be reused with the frame composited
/// with all updated external textures.
///
/// @param[in] texture_id The identifier of the texture that has been
/// updated.
///
virtual void OnPlatformViewMarkTextureFrameAvailable(
int64_t texture_id) = 0;
//--------------------------------------------------------------------------
/// @brief Loads the dart shared library into the dart VM. When the
/// dart library is loaded successfully, the dart future
/// returned by the originating loadLibrary() call completes.
///
/// The Dart compiler may generate separate shared libraries
/// files called 'loading units' when libraries are imported
/// as deferred. Each of these shared libraries are identified
/// by a unique loading unit id. Callers should open and resolve
/// a SymbolMapping from the shared library. The Mappings should
/// be moved into this method, as ownership will be assumed by
/// the dart root isolate after successful loading and released
/// after shutdown of the root isolate. The loading unit may not
/// be used after isolate shutdown. If loading fails, the
/// mappings will be released.
///
/// This method is paired with a RequestDartDeferredLibrary
/// invocation that provides the embedder with the loading unit
/// id of the deferred library to load.
///
///
/// @param[in] loading_unit_id The unique id of the deferred library's
/// loading unit.
///
/// @param[in] snapshot_data Dart snapshot data of the loading unit's
/// shared library.
///
/// @param[in] snapshot_data Dart snapshot instructions of the loading
/// unit's shared library.
///
virtual void LoadDartDeferredLibrary(
intptr_t loading_unit_id,
std::unique_ptr<const fml::Mapping> snapshot_data,
std::unique_ptr<const fml::Mapping> snapshot_instructions) = 0;
//--------------------------------------------------------------------------
/// @brief Indicates to the dart VM that the request to load a deferred
/// library with the specified loading unit id has failed.
///
/// The dart future returned by the initiating loadLibrary()
/// call will complete with an error.
///
/// @param[in] loading_unit_id The unique id of the deferred library's
/// loading unit, as passed in by
/// RequestDartDeferredLibrary.
///
/// @param[in] error_message The error message that will appear in the
/// dart Future.
///
/// @param[in] transient A transient error is a failure due to
/// temporary conditions such as no network.
/// Transient errors allow the dart VM to
/// re-request the same deferred library and
/// loading_unit_id again. Non-transient
/// errors are permanent and attempts to
/// re-request the library will instantly
/// complete with an error.
virtual void LoadDartDeferredLibraryError(intptr_t loading_unit_id,
const std::string error_message,
bool transient) = 0;
//--------------------------------------------------------------------------
/// @brief Replaces the asset resolver handled by the engine's
/// AssetManager of the specified `type` with
/// `updated_asset_resolver`. The matching AssetResolver is
/// removed and replaced with `updated_asset_resolvers`.
///
/// AssetResolvers should be updated when the existing resolver
/// becomes obsolete and a newer one becomes available that
/// provides updated access to the same type of assets as the
/// existing one. This update process is meant to be performed
/// at runtime.
///
/// If a null resolver is provided, nothing will be done. If no
/// matching resolver is found, the provided resolver will be
/// added to the end of the AssetManager resolvers queue. The
/// replacement only occurs with the first matching resolver.
/// Any additional matching resolvers are untouched.
///
/// @param[in] updated_asset_resolver The asset resolver to replace the
/// resolver of matching type with.
///
/// @param[in] type The type of AssetResolver to update. Only resolvers of
/// the specified type will be replaced by the updated
/// resolver.
///
virtual void UpdateAssetResolverByType(
std::unique_ptr<AssetResolver> updated_asset_resolver,
AssetResolver::AssetResolverType type) = 0;
//--------------------------------------------------------------------------
/// @brief Called by the platform view on the platform thread to get
/// the settings object associated with the platform view
/// instance.
///
/// @return The settings.
///
virtual const Settings& OnPlatformViewGetSettings() const = 0;
};
//----------------------------------------------------------------------------
/// @brief Creates a platform view with the specified delegate and task
/// runner. The base class by itself does not do much but is
/// suitable for use in test environments where full platform
/// integration may not be necessary. The platform view may only
/// be created, accessed and destroyed on the platform task
/// runner.
///
/// @param delegate The delegate. This is typically the shell.
/// @param[in] task_runners The task runners used by this platform view.
///
explicit PlatformView(Delegate& delegate, const TaskRunners& task_runners);
//----------------------------------------------------------------------------
/// @brief Destroys the platform view. The platform view is owned by the
/// shell and will be destroyed by the same on the platform tasks
/// runner.
///
virtual ~PlatformView();
//----------------------------------------------------------------------------
/// @brief Invoked by the shell to obtain a platform specific vsync
/// waiter. It is optional for platforms to override this method
/// and provide a custom vsync waiter because a timer based
/// fall-back waiter is used by default. However, it is highly
/// recommended that platform provide their own Vsync waiter as
/// the timer based fall-back will not render frames aligned with
/// vsync boundaries.
///
/// @attention If a timer based fall-back is used, a warning is logged to the
/// console. In case this method is overridden in a subclass, it
/// must return a valid vsync waiter. Returning null will lead to
/// internal errors. If a valid vsync waiter cannot be returned,
/// subclasses should just call the based class method instead.
///
/// @return A vsync waiter. If is an internal error to return a null
/// waiter.
///
virtual std::unique_ptr<VsyncWaiter> CreateVSyncWaiter();
//----------------------------------------------------------------------------
/// @brief Used by embedders to dispatch a platform message to a
/// running root isolate hosted by the engine. If an isolate is
/// not running, the message is dropped. If there is no one on the
/// other side listening on the channel, the message is dropped.
/// When a platform message is dropped, any response handles
/// associated with that message will be dropped as well. All
/// users of platform messages must assume that message may not be
/// delivered and/or their response handles may not be invoked.
/// Platform messages are not buffered.
///
/// For embedders that wish to respond to platform message
/// directed from the framework to the embedder, the
/// `HandlePlatformMessage` method may be overridden.
///
/// @see HandlePlatformMessage()
///
/// @param[in] message The platform message to deliver to the root isolate.
///
void DispatchPlatformMessage(std::unique_ptr<PlatformMessage> message);
//----------------------------------------------------------------------------
/// @brief Overridden by embedders to perform actions in response to
/// platform messages sent from the framework to the embedder.
/// Default implementation of this method simply returns an empty
/// response.
///
/// Embedders that wish to send platform messages to the framework
/// may use the `DispatchPlatformMessage` method. This method is
/// for messages that go the other way.
///
/// @see DispatchPlatformMessage()
///
/// @param[in] message The message
///
virtual void HandlePlatformMessage(std::unique_ptr<PlatformMessage> message);
//----------------------------------------------------------------------------
/// @brief Used by embedders to dispatch an accessibility action to a
/// running isolate hosted by the engine.
///
/// @param[in] node_id The identifier of the accessibility node on which to
/// perform the action.
/// @param[in] action The action
/// @param[in] args The arguments
///
void DispatchSemanticsAction(int32_t node_id,
SemanticsAction action,
fml::MallocMapping args);
//----------------------------------------------------------------------------
/// @brief Used by embedder to notify the running isolate hosted by the
/// engine on the UI thread that the accessibility tree needs to
/// be generated.
///
/// @attention Subclasses may choose to override this method to perform
/// platform specific functions. However, they must call the base
/// class method at some point in their implementation.
///
/// @param[in] enabled Whether the accessibility tree needs to be generated.
///
virtual void SetSemanticsEnabled(bool enabled);
//----------------------------------------------------------------------------
/// @brief Used by the embedder to specify the features to enable in the
/// accessibility tree generated by the isolate. This information
/// is forwarded to the root isolate hosted by the engine on the
/// UI thread.
///
/// The engine does not care about the accessibility feature flags
/// as all it does is forward this information from the embedder
/// to the framework. However, curious readers may refer to
/// `AccessibilityFeatures` in `window.dart` for currently
/// supported accessibility feature flags.
///
/// @attention Subclasses may choose to override this method to perform
/// platform specific functions. However, they must call the base
/// class method at some point in their implementation.
///
/// @param[in] flags The features to enable in the accessibility tree.
///
virtual void SetAccessibilityFeatures(int32_t flags);
//----------------------------------------------------------------------------
/// @brief Used by the framework to tell the embedder to apply the
/// specified semantics node updates. The default implementation
/// of this method does nothing.
///
/// @see SemanticsNode, SemticsNodeUpdates,
/// CustomAccessibilityActionUpdates
///
/// @param[in] updates A map with the stable semantics node identifier as
/// key and the node properties as the value.
/// @param[in] actions A map with the stable semantics node identifier as
/// key and the custom node action as the value.
///
virtual void UpdateSemantics(SemanticsNodeUpdates updates,
CustomAccessibilityActionUpdates actions);
//----------------------------------------------------------------------------
/// @brief Used by the framework to tell the embedder that it has
/// registered a listener on a given channel.
///
/// @param[in] name The name of the channel on which the listener has
/// set or cleared a listener.
/// @param[in] listening True if a listener has been set, false if it has
/// been cleared.
///
virtual void SendChannelUpdate(const std::string& name, bool listening);
//----------------------------------------------------------------------------
/// @brief Used by embedders to specify the updated viewport metrics for
/// a view. In response to this call, on the raster thread, the
/// rasterizer may need to be reconfigured to the updated viewport
/// dimensions. On the UI thread, the framework may need to start
/// generating a new frame for the updated viewport metrics as
/// well.
///
/// @param[in] view_id The ID for the view that `metrics` describes.
/// @param[in] metrics The updated viewport metrics.
///
void SetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics);
//----------------------------------------------------------------------------
/// @brief Used by embedders to notify the shell that a platform view
/// has been created. This notification is used to create a
/// rendering surface and pick the client rendering API to use to
/// render into this surface. No frames will be scheduled or
/// rendered before this call. The surface must remain valid till
/// the corresponding call to NotifyDestroyed.
///
void NotifyCreated();
//----------------------------------------------------------------------------
/// @brief Used by embedders to notify the shell that the platform view
/// has been destroyed. This notification used to collect the
/// rendering surface and all associated resources. Frame
/// scheduling is also suspended.
///
/// @attention Subclasses may choose to override this method to perform
/// platform specific functions. However, they must call the base
/// class method at some point in their implementation.
///
virtual void NotifyDestroyed();
//----------------------------------------------------------------------------
/// @brief Used by embedders to schedule a frame. In response to this
/// call, the framework may need to start generating a new frame.
///
void ScheduleFrame();
//----------------------------------------------------------------------------
/// @brief Used by the shell to obtain a Skia GPU context that is capable
/// of operating on the IO thread. The context must be in the same
/// share-group as the Skia GPU context used on the render thread.
/// This context will always be used on the IO thread. Because it
/// is in the same share-group as the separate render thread
/// context, any GPU resources uploaded in this context will be
/// visible to the render thread context (synchronization of GPU
/// resources is managed by Skia).
///
/// If such context cannot be created on the IO thread, callers
/// may return `nullptr`. This will mean that all texture uploads
/// will be queued onto the render thread which will cause
/// performance issues. When this context is `nullptr`, an error
/// is logged to the console. It is highly recommended that all
/// platforms provide a resource context.
///
/// @attention Unlike all other methods on the platform view, this will be
/// called on IO task runner.
///
/// @return The Skia GPU context that is in the same share-group as the
/// main render thread GPU context. May be `nullptr` in case such
/// a context cannot be created.
///
virtual sk_sp<GrDirectContext> CreateResourceContext() const;
virtual std::shared_ptr<impeller::Context> GetImpellerContext() const;
//----------------------------------------------------------------------------
/// @brief Used by the shell to notify the embedder that the resource
/// context previously obtained via a call to
/// `CreateResourceContext()` is being collected. The embedder
/// is free to collect an platform specific resources
/// associated with this context.
///
/// @attention Unlike all other methods on the platform view, this will be
/// called on IO task runner.
///
virtual void ReleaseResourceContext() const;
//--------------------------------------------------------------------------
/// @brief Returns a platform-specific PointerDataDispatcherMaker so the
/// `Engine` can construct the PointerDataPacketDispatcher based
/// on platforms.
virtual PointerDataDispatcherMaker GetDispatcherMaker();
//----------------------------------------------------------------------------
/// @brief Returns a weak pointer to the platform view. Since the
/// platform view may only be created, accessed and destroyed
/// on the platform thread, any access to the platform view
/// from a non-platform task runner needs a weak pointer to
/// the platform view along with a reference to the platform
/// task runner. A task must be posted to the platform task
/// runner with the weak pointer captured in the same. The
/// platform view method may only be called in the posted task
/// once the weak pointer validity has been checked. This
/// method is used by callers to obtain that weak pointer.
///
/// @return The weak pointer to the platform view.
///
fml::WeakPtr<PlatformView> GetWeakPtr() const;
//----------------------------------------------------------------------------
/// @brief Gives embedders a chance to react to a "cold restart" of the
/// running isolate. The default implementation of this method
/// does nothing.
///
/// While a "hot restart" patches a running isolate, a "cold
/// restart" restarts the root isolate in a running shell.
///
virtual void OnPreEngineRestart() const;
//----------------------------------------------------------------------------
/// @brief Sets a callback that gets executed when the rasterizer renders
/// the next frame. Due to the asynchronous nature of
/// rendering in Flutter, embedders usually add a placeholder
/// over the contents in which Flutter is going to render when
/// Flutter is first initialized. This callback may be used as
/// a signal to remove that placeholder. The callback is
/// executed on the render task runner and not the platform
/// task runner. It is the embedder's responsibility to
/// re-thread as necessary.
///
/// @attention The callback is executed on the render task runner and not the
/// platform task runner. Embedders must re-thread as necessary.
///
/// @param[in] closure The callback to execute on the render thread when the
/// next frame gets rendered.
///
void SetNextFrameCallback(const fml::closure& closure);
//----------------------------------------------------------------------------
/// @brief Dispatches pointer events from the embedder to the
/// framework. Each pointer data packet may contain multiple
/// pointer input events. Each call to this method wakes up
/// the UI thread.
///
/// @param[in] packet The pointer data packet to dispatch to the framework.
///
void DispatchPointerDataPacket(std::unique_ptr<PointerDataPacket> packet);
//--------------------------------------------------------------------------
/// @brief Used by the embedder to specify a texture that it wants the
/// rasterizer to composite within the Flutter layer tree. All
/// textures must have a unique identifier. When the
/// rasterizer encounters an external texture within its
/// hierarchy, it gives the embedder a chance to update that
/// texture on the raster thread before it composites the same
/// on-screen.
///
/// @attention This method must only be called once per texture. When the
/// texture is updated, calling `MarkTextureFrameAvailable`
/// with the specified texture identifier is sufficient to
/// make Flutter re-render the frame with the updated texture
/// composited in-line.
///
/// @see UnregisterTexture, MarkTextureFrameAvailable
///
/// @param[in] texture The texture that is being updated by the embedder
/// but composited by Flutter in its own hierarchy.
///
void RegisterTexture(std::shared_ptr<flutter::Texture> texture);
//--------------------------------------------------------------------------
/// @brief Used by the embedder to notify the rasterizer that it will
/// no longer attempt to composite the specified texture within
/// the layer tree. This allows the rasterizer to collect
/// associated resources.
///
/// @attention This call must only be called once per texture identifier.
///
/// @see RegisterTexture, MarkTextureFrameAvailable
///
/// @param[in] texture_id The identifier of the texture to unregister. If
/// the texture has not been previously registered,
/// this call does nothing.
///
void UnregisterTexture(int64_t texture_id);
//--------------------------------------------------------------------------
/// @brief Used by the embedder to notify the rasterizer that the context
/// of the previously registered texture have been updated.
/// Typically, Flutter will only render a frame if there is an
/// updated layer tree. However, in cases where the layer tree
/// is static but one of the externally composited textures
/// has been updated by the embedder, the embedder needs to
/// notify the rasterizer to render a new frame. In such
/// cases, the existing layer tree may be reused with the
/// frame re-composited with all updated external textures.
/// Unlike the calls to register and unregister the texture,
/// this call must be made each time a new texture frame is
/// available.
///
/// @see RegisterTexture, UnregisterTexture
///
/// @param[in] texture_id The identifier of the texture that has been
/// updated.
///
void MarkTextureFrameAvailable(int64_t texture_id);
//--------------------------------------------------------------------------
/// @brief Directly invokes platform-specific APIs to compute the
/// locale the platform would have natively resolved to.
///
/// @param[in] supported_locale_data The vector of strings that represents
/// the locales supported by the app.
/// Each locale consists of three
/// strings: languageCode, countryCode,
/// and scriptCode in that order.
///
/// @return A vector of 3 strings languageCode, countryCode, and
/// scriptCode that represents the locale selected by the
/// platform. Empty strings mean the value was unassigned. Empty
/// vector represents a null locale.
///
virtual std::unique_ptr<std::vector<std::string>>
ComputePlatformResolvedLocales(
const std::vector<std::string>& supported_locale_data);
virtual std::shared_ptr<ExternalViewEmbedder> CreateExternalViewEmbedder();
//--------------------------------------------------------------------------
/// @brief Invoked when the dart VM requests that a deferred library
/// be loaded. Notifies the engine that the deferred library
/// identified by the specified loading unit id should be
/// downloaded and loaded into the Dart VM via
/// `LoadDartDeferredLibrary`
///
/// Upon encountering errors or otherwise failing to load a
/// loading unit with the specified id, the failure should be
/// directly reported to dart by calling
/// `LoadDartDeferredLibraryFailure` to ensure the waiting dart
/// future completes with an error.
///
/// @param[in] loading_unit_id The unique id of the deferred library's
/// loading unit. This id is to be passed
/// back into LoadDartDeferredLibrary
/// in order to identify which deferred
/// library to load.
///
virtual void RequestDartDeferredLibrary(intptr_t loading_unit_id);
//--------------------------------------------------------------------------
/// @brief Loads the Dart shared library into the Dart VM. When the
/// Dart library is loaded successfully, the Dart future
/// returned by the originating loadLibrary() call completes.
///
/// The Dart compiler may generate separate shared libraries
/// files called 'loading units' when libraries are imported
/// as deferred. Each of these shared libraries are identified
/// by a unique loading unit id. Callers should open and resolve
/// a SymbolMapping from the shared library. The Mappings should
/// be moved into this method, as ownership will be assumed by the
/// dart isolate after successful loading and released after
/// shutdown of the dart isolate. If loading fails, the mappings
/// will naturally go out of scope.
///
/// This method is paired with a RequestDartDeferredLibrary
/// invocation that provides the embedder with the loading unit id
/// of the deferred library to load.
///
///
/// @param[in] loading_unit_id The unique id of the deferred library's
/// loading unit, as passed in by
/// RequestDartDeferredLibrary.
///
/// @param[in] snapshot_data Dart snapshot data of the loading unit's
/// shared library.
///
/// @param[in] snapshot_data Dart snapshot instructions of the loading
/// unit's shared library.
///
virtual void LoadDartDeferredLibrary(
intptr_t loading_unit_id,
std::unique_ptr<const fml::Mapping> snapshot_data,
std::unique_ptr<const fml::Mapping> snapshot_instructions);
//--------------------------------------------------------------------------
/// @brief Indicates to the dart VM that the request to load a deferred
/// library with the specified loading unit id has failed.
///
/// The dart future returned by the initiating loadLibrary() call
/// will complete with an error.
///
/// @param[in] loading_unit_id The unique id of the deferred library's
/// loading unit, as passed in by
/// RequestDartDeferredLibrary.
///
/// @param[in] error_message The error message that will appear in the
/// dart Future.
///
/// @param[in] transient A transient error is a failure due to
/// temporary conditions such as no network.
/// Transient errors allow the dart VM to
/// re-request the same deferred library and
/// loading_unit_id again. Non-transient
/// errors are permanent and attempts to
/// re-request the library will instantly
/// complete with an error.
///
virtual void LoadDartDeferredLibraryError(intptr_t loading_unit_id,
const std::string error_message,
bool transient);
//--------------------------------------------------------------------------
/// @brief Replaces the asset resolver handled by the engine's
/// AssetManager of the specified `type` with
/// `updated_asset_resolver`. The matching AssetResolver is
/// removed and replaced with `updated_asset_resolvers`.
///
/// AssetResolvers should be updated when the existing resolver
/// becomes obsolete and a newer one becomes available that
/// provides updated access to the same type of assets as the
/// existing one. This update process is meant to be performed
/// at runtime.
///
/// If a null resolver is provided, nothing will be done. If no
/// matching resolver is found, the provided resolver will be
/// added to the end of the AssetManager resolvers queue. The
/// replacement only occurs with the first matching resolver.
/// Any additional matching resolvers are untouched.
///
/// @param[in] updated_asset_resolver The asset resolver to replace the
/// resolver of matching type with.
///
/// @param[in] type The type of AssetResolver to update. Only resolvers of
/// the specified type will be replaced by the updated
/// resolver.
///
virtual void UpdateAssetResolverByType(
std::unique_ptr<AssetResolver> updated_asset_resolver,
AssetResolver::AssetResolverType type);
//--------------------------------------------------------------------------
/// @brief Creates an object that produces surfaces suitable for raster
/// snapshotting. The rasterizer will request this surface if no
/// on screen surface is currently available when an application
/// requests a snapshot, e.g. if `Scene.toImage` or
/// `Picture.toImage` are called while the application is in the
/// background.
///
/// Not all backends support this kind of surface usage, and the
/// default implementation returns nullptr. Platforms should
/// override this if they can support GPU operations in the
/// background and support GPU resource context usage.
///
virtual std::unique_ptr<SnapshotSurfaceProducer>
CreateSnapshotSurfaceProducer();
//--------------------------------------------------------------------------
/// @brief Specifies a delegate that will receive PlatformMessages from
/// Flutter to the host platform.
///
/// @details If this returns `null` that means PlatformMessages should be sent
/// to the PlatformView. That is to protect legacy behavior, any embedder
/// that wants to support executing Platform Channel handlers on background
/// threads should be returning a thread-safe PlatformMessageHandler instead.
virtual std::shared_ptr<PlatformMessageHandler> GetPlatformMessageHandler()
const;
//----------------------------------------------------------------------------
/// @brief Get the settings for this platform view instance.
///
/// @return The settings.
///
const Settings& GetSettings() const;
//--------------------------------------------------------------------------
/// @brief Synchronously invokes platform-specific APIs to apply the
/// system text scaling on the given unscaled font size.
///
/// Platforms that support this feature (currently it's only
/// implemented for Android SDK level 34+) will send a valid
/// configuration_id to potential callers, before this method can
/// be called.
///
/// @param[in] unscaled_font_size The unscaled font size specified by the
/// app developer. The value is in logical
/// pixels, and is guaranteed to be finite and
/// non-negative.
/// @param[in] configuration_id The unique id of the configuration to use
/// for computing the scaled font size.
///
/// @return The scaled font size in logical pixels, or -1 if the given
/// configuration_id did not match a valid configuration.
///
virtual double GetScaledFontSize(double unscaled_font_size,
int configuration_id) const;
protected:
// This is the only method called on the raster task runner.
virtual std::unique_ptr<Surface> CreateRenderingSurface();
PlatformView::Delegate& delegate_;
const TaskRunners task_runners_;
PointerDataPacketConverter pointer_data_packet_converter_;
fml::WeakPtrFactory<PlatformView> weak_factory_; // Must be the last member.
private:
FML_DISALLOW_COPY_AND_ASSIGN(PlatformView);
};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_PLATFORM_VIEW_H_
| engine/shell/common/platform_view.h/0 | {
"file_path": "engine/shell/common/platform_view.h",
"repo_id": "engine",
"token_count": 16094
} | 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.
// A fuchsia-specific shell test.
//
// This test is only supposed to be ran on Fuchsia OS, as it exercises
// Fuchsia-specific functionality for which no equivalent exists elsewhere.
#define FML_USED_ON_EMBEDDER
#include <time.h>
#include <unistd.h>
#include <memory>
#include <fuchsia/intl/cpp/fidl.h>
#include <fuchsia/settings/cpp/fidl.h>
#include <lib/sys/cpp/component_context.h>
#include "flutter/fml/logging.h"
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/shell/common/shell_test.h"
namespace flutter {
namespace testing {
using fuchsia::intl::TimeZoneId;
using fuchsia::settings::Intl_Set_Result;
using fuchsia::settings::IntlSettings;
class FuchsiaShellTest : public ShellTest {
protected:
FuchsiaShellTest()
: ctx_(sys::ComponentContext::CreateAndServeOutgoingDirectory()),
intl_() {
ctx_->svc()->Connect(intl_.NewRequest());
}
~FuchsiaShellTest() {
// Restore the time zone that matches that of the test harness. This is
// the default.
// TODO(https://fxbug.dev/110019): This crashes right now.
// const std::string local_timezone = GetLocalTimezone();
// SetTimezone(local_timezone);
// AssertTimezone(local_timezone, GetSettings());
}
// Gets the international settings from this Fuchsia realm.
IntlSettings GetSettings() {
IntlSettings settings;
zx_status_t status = intl_->Watch(&settings);
EXPECT_EQ(status, ZX_OK);
return settings;
}
// Sets the timezone of this Fuchsia realm to `timezone_name`.
void SetTimezone(const std::string& timezone_name) {
fuchsia::settings::IntlSettings settings;
settings.set_time_zone_id(TimeZoneId{.id = timezone_name});
Intl_Set_Result result;
zx_status_t status = intl_->Set(std::move(settings), &result);
ASSERT_EQ(status, ZX_OK);
}
std::string GetLocalTimezone() {
const time_t timestamp = time(nullptr);
const struct tm* local_time = localtime(×tamp);
EXPECT_NE(local_time, nullptr)
<< "Could not get local time: errno=" << errno << ": "
<< strerror(errno);
return std::string(local_time->tm_zone);
}
std::string GetLocalTime() {
const time_t timestamp = time(nullptr);
const struct tm* local_time = localtime(×tamp);
EXPECT_NE(local_time, nullptr)
<< "Could not get local time: errno=" << errno << ": "
<< strerror(errno);
char buffer[sizeof("2020-08-26 14")];
const size_t written =
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H", local_time);
EXPECT_LT(0UL, written);
return std::string(buffer);
}
// Checks that the timezone name in the `settings` matches what is `expected`.
void AssertTimezone(const std::string& expected,
const IntlSettings& settings) {
ASSERT_EQ(expected, settings.time_zone_id().id);
}
std::unique_ptr<sys::ComponentContext> ctx_;
fuchsia::settings::IntlSyncPtr intl_;
fuchsia::settings::IntlSettings save_settings_;
};
// These functions are used by tests that are currently disabled.
#if false
static bool ValidateShell(Shell* shell) {
if (!shell) {
return false;
}
if (!shell->IsSetup()) {
return false;
}
ShellTest::PlatformViewNotifyCreated(shell);
{
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), [shell, &latch]() {
shell->GetPlatformView()->NotifyDestroyed();
latch.Signal();
});
latch.Wait();
}
return true;
}
// Runs the function `f` in lock-step with a Dart isolate until the function
// returns `true`, or until a certain fixed number of retries is exhausted.
// Events `tick` and `tock` are used to synchronize the lock-stepping. The
// event 'tick' is a signal to the dart isolate to advance a single iteration
// step. 'tock' is used by the dart isolate to signal that it has completed
// its step.
static void RunCoroutineWithRetry(int retries,
fml::AutoResetWaitableEvent* tick,
fml::AutoResetWaitableEvent* tock,
std::function<bool()> f) {
for (; retries > 0; retries--) {
// Do a single coroutine step.
tick->Signal();
tock->Wait();
if (f()) {
break;
}
FML_LOG(INFO) << "Retries left: " << retries;
sleep(1);
}
}
#endif // false
// Verifies that changing the Fuchsia settings timezone through the FIDL
// settings interface results in a change of the reported local time in the
// isolate.
//
// The test is as follows:
//
// - Set an initial timezone, then get a timestamp from the isolate rounded down
// to the nearest hour. The assumption is as long as this test doesn't run
// very near the whole hour, which should be very unlikely, the nearest hour
// will vary depending on the time zone.
// - Set a different timezone. Get a timestamp from the isolate again and
// confirm that this time around the timestamps are different.
// - Set the initial timezone again, and get the timestamp. This time, the
// timestamp rounded down to whole hour should match the timestamp we got
// in the initial step.
TEST_F(FuchsiaShellTest, LocaltimesVaryOnTimezoneChanges) {
#if defined(OS_FUCHSIA)
GTEST_SKIP()
<< "This test fails after the CF V2 migration. https://fxbug.dev/110019 ";
#else
// See fixtures/shell_test.dart, the callback NotifyLocalTime is declared
// there.
fml::AutoResetWaitableEvent latch;
std::string dart_isolate_time_str;
AddNativeCallback("NotifyLocalTime", CREATE_NATIVE_ENTRY([&](auto args) {
dart_isolate_time_str =
tonic::DartConverter<std::string>::FromDart(
Dart_GetNativeArgument(args, 0));
latch.Signal();
}));
// As long as this is set, the isolate will keep rerunning its only task.
bool continue_fixture = true;
fml::AutoResetWaitableEvent fixture_latch;
AddNativeCallback("WaitFixture", CREATE_NATIVE_ENTRY([&](auto args) {
// Wait for the test fixture to advance.
fixture_latch.Wait();
tonic::DartConverter<bool>::SetReturnValue(
args, continue_fixture);
}));
auto settings = CreateSettingsForFixture();
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("timezonesChange");
std::unique_ptr<Shell> shell = CreateShell(settings);
ASSERT_NE(shell.get(), nullptr);
ASSERT_TRUE(ValidateShell(shell.get()));
RunEngine(shell.get(), std::move(configuration));
latch.Wait(); // After this point, the fixture is at waitFixture().
// Start with the local timezone, ensure that the isolate and the test
// fixture are the same.
SetTimezone(GetLocalTimezone());
AssertTimezone(GetLocalTimezone(), GetSettings());
std::string expected = GetLocalTime();
std::string actual = "undefined";
RunCoroutineWithRetry(10, &fixture_latch, &latch, [&]() {
actual = dart_isolate_time_str;
FML_LOG(INFO) << "reference: " << expected << ", actual: " << actual;
return expected == actual;
});
ASSERT_EQ(expected, actual)
<< "The Dart isolate was expected to show the same time as the test "
<< "fixture eventually, but that didn't happen after multiple retries.";
// Set a new timezone, which is hopefully different from the local one.
SetTimezone("America/New_York");
AssertTimezone("America/New_York", GetSettings());
RunCoroutineWithRetry(10, &fixture_latch, &latch, [&]() {
actual = dart_isolate_time_str;
FML_LOG(INFO) << "reference: " << expected << ", actual: " << actual;
return expected != actual;
});
ASSERT_NE(expected, actual)
<< "The Dart isolate was expected to show a time different from the test "
<< "fixture eventually, but that didn't happen after multiple retries.";
// Set a new isolate timezone, and check that the reported time is eventually
// different from what it used to be prior to the change.
SetTimezone("Europe/Amsterdam");
AssertTimezone("Europe/Amsterdam", GetSettings());
RunCoroutineWithRetry(10, &fixture_latch, &latch, [&]() {
actual = dart_isolate_time_str;
FML_LOG(INFO) << "reference: " << expected << ", actual: " << actual;
return expected != actual;
});
ASSERT_NE(expected, actual)
<< "The Dart isolate was expected to show a time different from the "
<< "prior timezone eventually, but that didn't happen after multiple "
<< "retries.";
// Let's try to bring the timezone back to the old one.
expected = actual;
SetTimezone("America/New_York");
AssertTimezone("America/New_York", GetSettings());
RunCoroutineWithRetry(10, &fixture_latch, &latch, [&]() {
actual = dart_isolate_time_str;
FML_LOG(INFO) << "reference: " << expected << ", actual: " << actual;
return expected != actual;
});
ASSERT_NE(expected, actual)
<< "The Dart isolate was expected to show a time different from the "
<< "prior timezone eventually, but that didn't happen after multiple "
<< "retries.";
// Tell the isolate to exit its loop.
ASSERT_FALSE(fixture_latch.IsSignaledForTest());
continue_fixture = false;
fixture_latch.Signal();
DestroyShell(std::move(shell));
#endif // OS_FUCHSIA
}
} // namespace testing
} // namespace flutter
| engine/shell/common/shell_fuchsia_unittests.cc/0 | {
"file_path": "engine/shell/common/shell_fuchsia_unittests.cc",
"repo_id": "engine",
"token_count": 3487
} | 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.
#include <strstream>
#define FML_USED_ON_EMBEDDER
#include <algorithm>
#include <chrono>
#include <ctime>
#include <future>
#include <memory>
#include <thread>
#include <utility>
#include <vector>
#if SHELL_ENABLE_GL
#include <EGL/egl.h>
#endif // SHELL_ENABLE_GL
#include "assets/asset_resolver.h"
#include "assets/directory_asset_bundle.h"
#include "common/graphics/persistent_cache.h"
#include "flutter/flow/layers/backdrop_filter_layer.h"
#include "flutter/flow/layers/clip_rect_layer.h"
#include "flutter/flow/layers/display_list_layer.h"
#include "flutter/flow/layers/layer_raster_cache_item.h"
#include "flutter/flow/layers/platform_view_layer.h"
#include "flutter/flow/layers/transform_layer.h"
#include "flutter/fml/backtrace.h"
#include "flutter/fml/command_line.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/shell_test.h"
#include "flutter/shell/common/shell_test_external_view_embedder.h"
#include "flutter/shell/common/shell_test_platform_view.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/common/thread_host.h"
#include "flutter/shell/common/vsync_waiter_fallback.h"
#include "flutter/shell/common/vsync_waiters_test.h"
#include "flutter/shell/version/version.h"
#include "flutter/testing/mock_canvas.h"
#include "flutter/testing/testing.h"
#include "gmock/gmock.h"
#include "impeller/core/runtime_types.h"
#include "third_party/rapidjson/include/rapidjson/writer.h"
#include "third_party/skia/include/codec/SkCodecAnimation.h"
#include "third_party/tonic/converter/dart_converter.h"
#ifdef SHELL_ENABLE_VULKAN
#include "flutter/vulkan/vulkan_application.h" // nogncheck
#endif
// CREATE_NATIVE_ENTRY is leaky by design
// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape)
namespace flutter {
namespace testing {
constexpr int64_t kImplicitViewId = 0ll;
using ::testing::_;
using ::testing::Return;
namespace {
class MockPlatformViewDelegate : public PlatformView::Delegate {
MOCK_METHOD(void,
OnPlatformViewCreated,
(std::unique_ptr<Surface> surface),
(override));
MOCK_METHOD(void, OnPlatformViewDestroyed, (), (override));
MOCK_METHOD(void, OnPlatformViewScheduleFrame, (), (override));
MOCK_METHOD(void,
OnPlatformViewSetNextFrameCallback,
(const fml::closure& closure),
(override));
MOCK_METHOD(void,
OnPlatformViewSetViewportMetrics,
(int64_t view_id, const ViewportMetrics& metrics),
(override));
MOCK_METHOD(void,
OnPlatformViewDispatchPlatformMessage,
(std::unique_ptr<PlatformMessage> message),
(override));
MOCK_METHOD(void,
OnPlatformViewDispatchPointerDataPacket,
(std::unique_ptr<PointerDataPacket> packet),
(override));
MOCK_METHOD(void,
OnPlatformViewDispatchSemanticsAction,
(int32_t id, SemanticsAction action, fml::MallocMapping args),
(override));
MOCK_METHOD(void,
OnPlatformViewSetSemanticsEnabled,
(bool enabled),
(override));
MOCK_METHOD(void,
OnPlatformViewSetAccessibilityFeatures,
(int32_t flags),
(override));
MOCK_METHOD(void,
OnPlatformViewRegisterTexture,
(std::shared_ptr<Texture> texture),
(override));
MOCK_METHOD(void,
OnPlatformViewUnregisterTexture,
(int64_t texture_id),
(override));
MOCK_METHOD(void,
OnPlatformViewMarkTextureFrameAvailable,
(int64_t texture_id),
(override));
MOCK_METHOD(const Settings&,
OnPlatformViewGetSettings,
(),
(const, override));
MOCK_METHOD(void,
LoadDartDeferredLibrary,
(intptr_t loading_unit_id,
std::unique_ptr<const fml::Mapping> snapshot_data,
std::unique_ptr<const fml::Mapping> snapshot_instructions),
(override));
MOCK_METHOD(void,
LoadDartDeferredLibraryError,
(intptr_t loading_unit_id,
const std::string error_message,
bool transient),
(override));
MOCK_METHOD(void,
UpdateAssetResolverByType,
(std::unique_ptr<AssetResolver> updated_asset_resolver,
AssetResolver::AssetResolverType type),
(override));
};
class MockSurface : public Surface {
public:
MOCK_METHOD(bool, IsValid, (), (override));
MOCK_METHOD(std::unique_ptr<SurfaceFrame>,
AcquireFrame,
(const SkISize& size),
(override));
MOCK_METHOD(SkMatrix, GetRootTransformation, (), (const, override));
MOCK_METHOD(GrDirectContext*, GetContext, (), (override));
MOCK_METHOD(std::unique_ptr<GLContextResult>,
MakeRenderContextCurrent,
(),
(override));
MOCK_METHOD(bool, ClearRenderContext, (), (override));
};
class MockPlatformView : public PlatformView {
public:
MockPlatformView(MockPlatformViewDelegate& delegate,
const TaskRunners& task_runners)
: PlatformView(delegate, task_runners) {}
MOCK_METHOD(std::unique_ptr<Surface>, CreateRenderingSurface, (), (override));
MOCK_METHOD(std::shared_ptr<PlatformMessageHandler>,
GetPlatformMessageHandler,
(),
(const, override));
};
class TestPlatformView : public PlatformView {
public:
TestPlatformView(Shell& shell, const TaskRunners& task_runners)
: PlatformView(shell, task_runners) {}
MOCK_METHOD(std::unique_ptr<Surface>, CreateRenderingSurface, (), (override));
};
class MockPlatformMessageHandler : public PlatformMessageHandler {
public:
MOCK_METHOD(void,
HandlePlatformMessage,
(std::unique_ptr<PlatformMessage> message),
(override));
MOCK_METHOD(bool,
DoesHandlePlatformMessageOnPlatformThread,
(),
(const, override));
MOCK_METHOD(void,
InvokePlatformMessageResponseCallback,
(int response_id, std::unique_ptr<fml::Mapping> mapping),
(override));
MOCK_METHOD(void,
InvokePlatformMessageEmptyResponseCallback,
(int response_id),
(override));
};
class MockPlatformMessageResponse : public PlatformMessageResponse {
public:
static fml::RefPtr<MockPlatformMessageResponse> Create() {
return fml::AdoptRef(new MockPlatformMessageResponse());
}
MOCK_METHOD(void, Complete, (std::unique_ptr<fml::Mapping> data), (override));
MOCK_METHOD(void, CompleteEmpty, (), (override));
};
} // namespace
class TestAssetResolver : public AssetResolver {
public:
TestAssetResolver(bool valid, AssetResolver::AssetResolverType type)
: valid_(valid), type_(type) {}
bool IsValid() const override { return true; }
// This is used to identify if replacement was made or not.
bool IsValidAfterAssetManagerChange() const override { return valid_; }
AssetResolver::AssetResolverType GetType() const override { return type_; }
std::unique_ptr<fml::Mapping> GetAsMapping(
const std::string& asset_name) const override {
return nullptr;
}
std::vector<std::unique_ptr<fml::Mapping>> GetAsMappings(
const std::string& asset_pattern,
const std::optional<std::string>& subdir) const override {
return {};
};
bool operator==(const AssetResolver& other) const override {
return this == &other;
}
private:
bool valid_;
AssetResolver::AssetResolverType type_;
};
class ThreadCheckingAssetResolver : public AssetResolver {
public:
explicit ThreadCheckingAssetResolver(
std::shared_ptr<fml::ConcurrentMessageLoop> concurrent_loop)
: concurrent_loop_(std::move(concurrent_loop)) {}
// |AssetResolver|
bool IsValid() const override { return true; }
// |AssetResolver|
bool IsValidAfterAssetManagerChange() const override { return true; }
// |AssetResolver|
AssetResolverType GetType() const {
return AssetResolverType::kApkAssetProvider;
}
// |AssetResolver|
std::unique_ptr<fml::Mapping> GetAsMapping(
const std::string& asset_name) const override {
if (asset_name == "FontManifest.json") {
// This file is loaded directly by the engine.
return nullptr;
}
mapping_requests.push_back(asset_name);
EXPECT_TRUE(concurrent_loop_->RunsTasksOnCurrentThread())
<< fml::BacktraceHere();
return nullptr;
}
mutable std::vector<std::string> mapping_requests;
bool operator==(const AssetResolver& other) const override {
return this == &other;
}
private:
std::shared_ptr<fml::ConcurrentMessageLoop> concurrent_loop_;
};
static bool ValidateShell(Shell* shell) {
if (!shell) {
return false;
}
if (!shell->IsSetup()) {
return false;
}
ShellTest::PlatformViewNotifyCreated(shell);
{
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), [shell, &latch]() {
shell->GetPlatformView()->NotifyDestroyed();
latch.Signal();
});
latch.Wait();
}
return true;
}
static bool RasterizerIsTornDown(Shell* shell) {
fml::AutoResetWaitableEvent latch;
bool is_torn_down = false;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetRasterTaskRunner(),
[shell, &latch, &is_torn_down]() {
is_torn_down = shell->GetRasterizer()->IsTornDown();
latch.Signal();
});
latch.Wait();
return is_torn_down;
}
static void ValidateDestroyPlatformView(Shell* shell) {
ASSERT_TRUE(shell != nullptr);
ASSERT_TRUE(shell->IsSetup());
ASSERT_FALSE(RasterizerIsTornDown(shell));
ShellTest::PlatformViewNotifyDestroyed(shell);
ASSERT_TRUE(RasterizerIsTornDown(shell));
}
static std::string CreateFlagsString(std::vector<const char*>& flags) {
if (flags.empty()) {
return "";
}
std::string flags_string = flags[0];
for (size_t i = 1; i < flags.size(); ++i) {
flags_string += ",";
flags_string += flags[i];
}
return flags_string;
}
static void TestDartVmFlags(std::vector<const char*>& flags) {
std::string flags_string = CreateFlagsString(flags);
const std::vector<fml::CommandLine::Option> options = {
fml::CommandLine::Option("dart-flags", flags_string)};
fml::CommandLine command_line("", options, std::vector<std::string>());
flutter::Settings settings = flutter::SettingsFromCommandLine(command_line);
EXPECT_EQ(settings.dart_flags.size(), flags.size());
for (size_t i = 0; i < flags.size(); ++i) {
EXPECT_EQ(settings.dart_flags[i], flags[i]);
}
}
static void PostSync(const fml::RefPtr<fml::TaskRunner>& task_runner,
const fml::closure& task) {
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(task_runner, [&latch, &task] {
task();
latch.Signal();
});
latch.Wait();
}
static sk_sp<DisplayList> MakeSizedDisplayList(int width, int height) {
DisplayListBuilder builder(SkRect::MakeXYWH(0, 0, width, height));
builder.DrawRect(SkRect::MakeXYWH(0, 0, width, height),
DlPaint(DlColor::kRed()));
return builder.Build();
}
TEST_F(ShellTest, InitializeWithInvalidThreads) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
TaskRunners task_runners("test", nullptr, nullptr, nullptr, nullptr);
auto shell = CreateShell(settings, task_runners);
ASSERT_FALSE(shell);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, InitializeWithDifferentThreads) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
std::string name_prefix = "io.flutter.test." + GetCurrentTestName() + ".";
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
name_prefix, ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster |
ThreadHost::Type::kIo | ThreadHost::Type::kUi));
ASSERT_EQ(thread_host.name_prefix, name_prefix);
TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(),
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(ValidateShell(shell.get()));
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, InitializeWithSingleThread) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform);
auto task_runner = thread_host.platform_thread->GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, InitializeWithSingleThreadWhichIsTheCallingThread) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(ValidateShell(shell.get()));
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest,
InitializeWithMultipleThreadButCallingThreadAsPlatformThread) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kRaster | ThreadHost::Type::kIo |
ThreadHost::Type::kUi);
fml::MessageLoop::EnsureInitializedForCurrentThread();
TaskRunners task_runners("test",
fml::MessageLoop::GetCurrent().GetTaskRunner(),
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
auto shell = Shell::Create(
flutter::PlatformData(), task_runners, settings,
[](Shell& shell) {
// This is unused in the platform view as we are not using the simulated
// vsync mechanism. We should have better DI in the tests.
const auto vsync_clock = std::make_shared<ShellTestVsyncClock>();
return ShellTestPlatformView::Create(
shell, shell.GetTaskRunners(), vsync_clock,
[task_runners = shell.GetTaskRunners()]() {
return static_cast<std::unique_ptr<VsyncWaiter>>(
std::make_unique<VsyncWaiterFallback>(task_runners));
},
ShellTestPlatformView::BackendType::kDefaultBackend, nullptr,
shell.GetIsGpuDisabledSyncSwitch());
},
[](Shell& shell) { return std::make_unique<Rasterizer>(shell); });
ASSERT_TRUE(ValidateShell(shell.get()));
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, InitializeWithDisabledGpu) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform);
auto task_runner = thread_host.platform_thread->GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
auto shell = CreateShell({
.settings = settings,
.task_runners = task_runners,
.is_gpu_disabled = true,
});
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
bool is_disabled = false;
shell->GetIsGpuDisabledSyncSwitch()->Execute(
fml::SyncSwitch::Handlers().SetIfTrue([&] { is_disabled = true; }));
ASSERT_TRUE(is_disabled);
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, InitializeWithGPUAndPlatformThreadsTheSame) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform | ThreadHost::Type::kIo |
ThreadHost::Type::kUi);
TaskRunners task_runners(
"test",
thread_host.platform_thread->GetTaskRunner(), // platform
thread_host.platform_thread->GetTaskRunner(), // raster
thread_host.ui_thread->GetTaskRunner(), // ui
thread_host.io_thread->GetTaskRunner() // io
);
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, FixturesAreFunctional) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
configuration.SetEntrypoint("fixturesAreFunctionalMain");
fml::AutoResetWaitableEvent main_latch;
AddNativeCallback(
"SayHiFromFixturesAreFunctionalMain",
CREATE_NATIVE_ENTRY([&main_latch](auto args) { main_latch.Signal(); }));
RunEngine(shell.get(), std::move(configuration));
main_latch.Wait();
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
DestroyShell(std::move(shell));
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, SecondaryIsolateBindingsAreSetupViaShellSettings) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
configuration.SetEntrypoint("testCanLaunchSecondaryIsolate");
fml::CountDownLatch latch(2);
AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&latch](auto args) {
latch.CountDown();
}));
RunEngine(shell.get(), std::move(configuration));
latch.Wait();
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
DestroyShell(std::move(shell));
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, LastEntrypoint) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
std::string entry_point = "fixturesAreFunctionalMain";
configuration.SetEntrypoint(entry_point);
fml::AutoResetWaitableEvent main_latch;
std::string last_entry_point;
AddNativeCallback(
"SayHiFromFixturesAreFunctionalMain", CREATE_NATIVE_ENTRY([&](auto args) {
last_entry_point = shell->GetEngine()->GetLastEntrypoint();
main_latch.Signal();
}));
RunEngine(shell.get(), std::move(configuration));
main_latch.Wait();
EXPECT_EQ(entry_point, last_entry_point);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
DestroyShell(std::move(shell));
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, LastEntrypointArgs) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
std::string entry_point = "fixturesAreFunctionalMain";
std::vector<std::string> entry_point_args = {"arg1"};
configuration.SetEntrypoint(entry_point);
configuration.SetEntrypointArgs(entry_point_args);
fml::AutoResetWaitableEvent main_latch;
std::vector<std::string> last_entry_point_args;
AddNativeCallback(
"SayHiFromFixturesAreFunctionalMain", CREATE_NATIVE_ENTRY([&](auto args) {
last_entry_point_args = shell->GetEngine()->GetLastEntrypointArgs();
main_latch.Signal();
}));
RunEngine(shell.get(), std::move(configuration));
main_latch.Wait();
#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG)
EXPECT_EQ(last_entry_point_args, entry_point_args);
#else
ASSERT_TRUE(last_entry_point_args.empty());
#endif
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
DestroyShell(std::move(shell));
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, DisallowedDartVMFlag) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "This test flakes on Fuchsia. https://fxbug.dev/110006 ";
#else
// Run this test in a thread-safe manner, otherwise gtest will complain.
::testing::FLAGS_gtest_death_test_style = "threadsafe";
const std::vector<fml::CommandLine::Option> options = {
fml::CommandLine::Option("dart-flags", "--verify_after_gc")};
fml::CommandLine command_line("", options, std::vector<std::string>());
// Upon encountering a disallowed Dart flag the process terminates.
const char* expected =
"Encountered disallowed Dart VM flag: --verify_after_gc";
ASSERT_DEATH(flutter::SettingsFromCommandLine(command_line), expected);
#endif // OS_FUCHSIA
}
TEST_F(ShellTest, AllowedDartVMFlag) {
std::vector<const char*> flags = {
"--enable-isolate-groups",
"--no-enable-isolate-groups",
};
#if !FLUTTER_RELEASE
flags.push_back("--max_profile_depth 1");
flags.push_back("--random_seed 42");
flags.push_back("--max_subtype_cache_entries=22");
if (!DartVM::IsRunningPrecompiledCode()) {
flags.push_back("--enable_mirrors");
}
#endif
TestDartVmFlags(flags);
}
TEST_F(ShellTest, NoNeedToReportTimingsByDefault) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
ASSERT_FALSE(GetNeedsReportTimings(shell.get()));
// This assertion may or may not be the direct result of needs_report_timings_
// being false. The count could be 0 simply because we just cleared
// unreported timings by reporting them. Hence this can't replace the
// ASSERT_FALSE(GetNeedsReportTimings(shell.get())) check. We added
// this assertion for an additional confidence that we're not pushing
// back to unreported timings unnecessarily.
//
// Conversely, do not assert UnreportedTimingsCount(shell.get()) to be
// positive in any tests. Otherwise those tests will be flaky as the clearing
// of unreported timings is unpredictive.
ASSERT_EQ(UnreportedTimingsCount(shell.get()), 0);
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, NeedsReportTimingsIsSetWithCallback) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("dummyReportTimingsMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
ASSERT_TRUE(GetNeedsReportTimings(shell.get()));
DestroyShell(std::move(shell));
}
static void CheckFrameTimings(const std::vector<FrameTiming>& timings,
fml::TimePoint start,
fml::TimePoint finish) {
fml::TimePoint last_frame_start;
for (size_t i = 0; i < timings.size(); i += 1) {
// Ensure that timings are sorted.
ASSERT_TRUE(timings[i].Get(FrameTiming::kPhases[0]) >= last_frame_start);
last_frame_start = timings[i].Get(FrameTiming::kPhases[0]);
fml::TimePoint last_phase_time;
for (auto phase : FrameTiming::kPhases) {
// raster finish wall time doesn't use the same clock base
// as rest of the frame timings.
if (phase == FrameTiming::kRasterFinishWallTime) {
continue;
}
ASSERT_TRUE(timings[i].Get(phase) >= start);
ASSERT_TRUE(timings[i].Get(phase) <= finish);
// phases should have weakly increasing time points
ASSERT_TRUE(last_phase_time <= timings[i].Get(phase));
last_phase_time = timings[i].Get(phase);
}
}
}
TEST_F(ShellTest, ReportTimingsIsCalled) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// We MUST put |start| after |CreateShell| because the clock source will be
// reset through |TimePoint::SetClockSource()| in
// |DartVMInitializer::Initialize()| within |CreateShell()|.
fml::TimePoint start = fml::TimePoint::Now();
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
configuration.SetEntrypoint("reportTimingsMain");
fml::AutoResetWaitableEvent reportLatch;
std::vector<int64_t> timestamps;
auto nativeTimingCallback = [&reportLatch,
×tamps](Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
ASSERT_EQ(timestamps.size(), 0ul);
timestamps = tonic::DartConverter<std::vector<int64_t>>::FromArguments(
args, 0, exception);
reportLatch.Signal();
};
AddNativeCallback("NativeReportTimingsCallback",
CREATE_NATIVE_ENTRY(nativeTimingCallback));
RunEngine(shell.get(), std::move(configuration));
// Pump many frames so we can trigger the report quickly instead of waiting
// for the 1 second threshold.
for (int i = 0; i < 200; i += 1) {
PumpOneFrame(shell.get());
}
reportLatch.Wait();
DestroyShell(std::move(shell));
fml::TimePoint finish = fml::TimePoint::Now();
ASSERT_TRUE(!timestamps.empty());
ASSERT_TRUE(timestamps.size() % FrameTiming::kCount == 0);
std::vector<FrameTiming> timings(timestamps.size() / FrameTiming::kCount);
for (size_t i = 0; i * FrameTiming::kCount < timestamps.size(); i += 1) {
for (auto phase : FrameTiming::kPhases) {
timings[i].Set(
phase,
fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromMicroseconds(
timestamps[i * FrameTiming::kCount + phase])));
}
}
CheckFrameTimings(timings, start, finish);
}
TEST_F(ShellTest, FrameRasterizedCallbackIsCalled) {
auto settings = CreateSettingsForFixture();
FrameTiming timing;
fml::AutoResetWaitableEvent timingLatch;
settings.frame_rasterized_callback = [&timing,
&timingLatch](const FrameTiming& t) {
timing = t;
timingLatch.Signal();
};
std::unique_ptr<Shell> shell = CreateShell(settings);
// Wait to make |start| bigger than zero
using namespace std::chrono_literals;
std::this_thread::sleep_for(1ms);
// We MUST put |start| after |CreateShell()| because the clock source will be
// reset through |TimePoint::SetClockSource()| in
// |DartVMInitializer::Initialize()| within |CreateShell()|.
fml::TimePoint start = fml::TimePoint::Now();
for (auto phase : FrameTiming::kPhases) {
timing.Set(phase, fml::TimePoint());
// Check that the time points are initially smaller than start, so
// CheckFrameTimings will fail if they're not properly set later.
ASSERT_TRUE(timing.Get(phase) < start);
}
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("onBeginFrameMain");
int64_t frame_target_time;
auto nativeOnBeginFrame = [&frame_target_time](Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
frame_target_time =
tonic::DartConverter<int64_t>::FromArguments(args, 0, exception);
};
AddNativeCallback("NativeOnBeginFrame",
CREATE_NATIVE_ENTRY(nativeOnBeginFrame));
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
// Check that timing is properly set. This implies that
// settings.frame_rasterized_callback is called.
timingLatch.Wait();
fml::TimePoint finish = fml::TimePoint::Now();
std::vector<FrameTiming> timings = {timing};
CheckFrameTimings(timings, start, finish);
// Check that onBeginFrame, which is the frame_target_time, is after
// FrameTiming's build start
int64_t build_start =
timing.Get(FrameTiming::kBuildStart).ToEpochDelta().ToMicroseconds();
ASSERT_GT(frame_target_time, build_start);
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, ExternalEmbedderNoThreadMerger) {
auto settings = CreateSettingsForFixture();
fml::AutoResetWaitableEvent end_frame_latch;
bool end_frame_called = false;
auto end_frame_callback =
[&](bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
ASSERT_TRUE(raster_thread_merger.get() == nullptr);
ASSERT_FALSE(should_resubmit_frame);
end_frame_called = true;
end_frame_latch.Signal();
};
auto external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kResubmitFrame, false);
auto shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
end_frame_latch.Wait();
ASSERT_TRUE(end_frame_called);
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, PushBackdropFilterToVisitedPlatformViews) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. "
"https://github.com/flutter/flutter/issues/59816 ";
#else
auto settings = CreateSettingsForFixture();
std::shared_ptr<ShellTestExternalViewEmbedder> external_view_embedder;
fml::AutoResetWaitableEvent end_frame_latch;
bool end_frame_called = false;
std::vector<int64_t> visited_platform_views;
MutatorsStack stack_50;
MutatorsStack stack_75;
auto end_frame_callback =
[&](bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
if (end_frame_called) {
return;
}
ASSERT_TRUE(raster_thread_merger.get() == nullptr);
ASSERT_FALSE(should_resubmit_frame);
end_frame_called = true;
visited_platform_views =
external_view_embedder->GetVisitedPlatformViews();
stack_50 = external_view_embedder->GetStack(50);
stack_75 = external_view_embedder->GetStack(75);
end_frame_latch.Signal();
};
external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kResubmitFrame, false);
auto shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto platform_view_layer = std::make_shared<PlatformViewLayer>(
SkPoint::Make(10, 10), SkSize::Make(10, 10), 50);
root->Add(platform_view_layer);
auto transform_layer =
std::make_shared<TransformLayer>(SkMatrix::Translate(1, 1));
root->Add(transform_layer);
auto clip_rect_layer = std::make_shared<ClipRectLayer>(
SkRect::MakeLTRB(0, 0, 30, 30), Clip::kHardEdge);
transform_layer->Add(clip_rect_layer);
auto filter = std::make_shared<DlBlurImageFilter>(5, 5, DlTileMode::kClamp);
auto backdrop_filter_layer =
std::make_shared<BackdropFilterLayer>(filter, DlBlendMode::kSrcOver);
clip_rect_layer->Add(backdrop_filter_layer);
auto platform_view_layer2 = std::make_shared<PlatformViewLayer>(
SkPoint::Make(10, 10), SkSize::Make(10, 10), 75);
backdrop_filter_layer->Add(platform_view_layer2);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
end_frame_latch.Wait();
ASSERT_EQ(visited_platform_views, (std::vector<int64_t>{50, 75}));
ASSERT_TRUE(stack_75.is_empty());
ASSERT_FALSE(stack_50.is_empty());
auto filter = DlBlurImageFilter(5, 5, DlTileMode::kClamp);
auto mutator = *stack_50.Begin();
ASSERT_EQ(mutator->GetType(), MutatorType::kBackdropFilter);
ASSERT_EQ(mutator->GetFilterMutation().GetFilter(), filter);
// Make sure the filterRect is in global coordinates (contains the (1,1)
// translation).
ASSERT_EQ(mutator->GetFilterMutation().GetFilterRect(),
SkRect::MakeLTRB(1, 1, 31, 31));
DestroyShell(std::move(shell));
#endif // OS_FUCHSIA
}
// TODO(https://github.com/flutter/flutter/issues/59816): Enable on fuchsia.
TEST_F(ShellTest,
ExternalEmbedderEndFrameIsCalledWhenPostPrerollResultIsResubmit) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. "
"https://github.com/flutter/flutter/issues/59816 ";
#else
auto settings = CreateSettingsForFixture();
fml::AutoResetWaitableEvent end_frame_latch;
bool end_frame_called = false;
auto end_frame_callback =
[&](bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
ASSERT_TRUE(raster_thread_merger.get() != nullptr);
ASSERT_TRUE(should_resubmit_frame);
end_frame_called = true;
end_frame_latch.Signal();
};
auto external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kResubmitFrame, true);
auto shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
end_frame_latch.Wait();
ASSERT_TRUE(end_frame_called);
DestroyShell(std::move(shell));
#endif // OS_FUCHSIA
}
TEST_F(ShellTest, OnPlatformViewDestroyDisablesThreadMerger) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. "
"https://github.com/flutter/flutter/issues/59816 ";
#else
auto settings = CreateSettingsForFixture();
fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger;
auto end_frame_callback =
[&](bool should_resubmit_frame,
fml::RefPtr<fml::RasterThreadMerger> thread_merger) {
raster_thread_merger = std::move(thread_merger);
};
auto external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kSuccess, true);
auto shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
auto result = shell->WaitForFirstFrame(fml::TimeDelta::Max());
// Wait for the rasterizer to process the frame. WaitForFirstFrame only waits
// for the Animator, but end_frame_callback is called by the Rasterizer.
PostSync(shell->GetTaskRunners().GetRasterTaskRunner(), [] {});
ASSERT_TRUE(result.ok()) << "Result: " << static_cast<int>(result.code())
<< ": " << result.message();
ASSERT_TRUE(raster_thread_merger->IsEnabled());
ValidateDestroyPlatformView(shell.get());
ASSERT_TRUE(raster_thread_merger->IsEnabled());
// Validate the platform view can be recreated and destroyed again
ValidateShell(shell.get());
ASSERT_TRUE(raster_thread_merger->IsEnabled());
DestroyShell(std::move(shell));
#endif // OS_FUCHSIA
}
TEST_F(ShellTest, OnPlatformViewDestroyAfterMergingThreads) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. "
"https://github.com/flutter/flutter/issues/59816 ";
#else
const int ThreadMergingLease = 10;
auto settings = CreateSettingsForFixture();
fml::AutoResetWaitableEvent end_frame_latch;
std::shared_ptr<ShellTestExternalViewEmbedder> external_view_embedder;
auto end_frame_callback =
[&](bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
if (should_resubmit_frame && !raster_thread_merger->IsMerged()) {
raster_thread_merger->MergeWithLease(ThreadMergingLease);
ASSERT_TRUE(raster_thread_merger->IsMerged());
external_view_embedder->UpdatePostPrerollResult(
PostPrerollResult::kSuccess);
}
end_frame_latch.Signal();
};
external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kSuccess, true);
// Set resubmit once to trigger thread merging.
external_view_embedder->UpdatePostPrerollResult(
PostPrerollResult::kResubmitFrame);
auto shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
// Pump one frame to trigger thread merging.
end_frame_latch.Wait();
// Pump another frame to ensure threads are merged and a regular layer tree is
// submitted.
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
// Threads are merged here. PlatformViewNotifyDestroy should be executed
// successfully.
ASSERT_TRUE(fml::TaskRunnerChecker::RunsOnTheSameThread(
shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(),
shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId()));
ValidateDestroyPlatformView(shell.get());
// Ensure threads are unmerged after platform view destroy
ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread(
shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(),
shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId()));
// Validate the platform view can be recreated and destroyed again
ValidateShell(shell.get());
DestroyShell(std::move(shell));
#endif // OS_FUCHSIA
}
TEST_F(ShellTest, OnPlatformViewDestroyWhenThreadsAreMerging) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. "
"https://github.com/flutter/flutter/issues/59816 ";
#else
const int kThreadMergingLease = 10;
auto settings = CreateSettingsForFixture();
fml::AutoResetWaitableEvent end_frame_latch;
auto end_frame_callback =
[&](bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
if (should_resubmit_frame && !raster_thread_merger->IsMerged()) {
raster_thread_merger->MergeWithLease(kThreadMergingLease);
}
end_frame_latch.Signal();
};
// Start with a regular layer tree with `PostPrerollResult::kSuccess` so we
// can later check if the rasterizer is tore down using
// |ValidateDestroyPlatformView|
auto external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kSuccess, true);
auto shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
// Pump one frame and threads aren't merged
end_frame_latch.Wait();
ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread(
shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(),
shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId()));
// Pump a frame with `PostPrerollResult::kResubmitFrame` to start merging
// threads
external_view_embedder->UpdatePostPrerollResult(
PostPrerollResult::kResubmitFrame);
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
// Now destroy the platform view immediately.
// Two things can happen here:
// 1. Threads haven't merged. 2. Threads has already merged.
// |Shell:OnPlatformViewDestroy| should be able to handle both cases.
ValidateDestroyPlatformView(shell.get());
// Ensure threads are unmerged after platform view destroy
ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread(
shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(),
shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId()));
// Validate the platform view can be recreated and destroyed again
ValidateShell(shell.get());
DestroyShell(std::move(shell));
#endif // OS_FUCHSIA
}
TEST_F(ShellTest,
OnPlatformViewDestroyWithThreadMergerWhileThreadsAreUnmerged) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. "
"https://github.com/flutter/flutter/issues/59816 ";
#else
auto settings = CreateSettingsForFixture();
fml::AutoResetWaitableEvent end_frame_latch;
auto end_frame_callback =
[&](bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
end_frame_latch.Signal();
};
auto external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kSuccess, true);
auto shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
end_frame_latch.Wait();
// Threads should not be merged.
ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread(
shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(),
shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId()));
ValidateDestroyPlatformView(shell.get());
// Ensure threads are unmerged after platform view destroy
ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread(
shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(),
shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId()));
// Validate the platform view can be recreated and destroyed again
ValidateShell(shell.get());
DestroyShell(std::move(shell));
#endif // OS_FUCHSIA
}
TEST_F(ShellTest, OnPlatformViewDestroyWithoutRasterThreadMerger) {
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
// Threads should not be merged.
ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread(
shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(),
shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId()));
ValidateDestroyPlatformView(shell.get());
// Ensure threads are unmerged after platform view destroy
ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread(
shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(),
shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId()));
// Validate the platform view can be recreated and destroyed again
ValidateShell(shell.get());
DestroyShell(std::move(shell));
}
// TODO(https://github.com/flutter/flutter/issues/59816): Enable on fuchsia.
TEST_F(ShellTest, OnPlatformViewDestroyWithStaticThreadMerging) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. "
"https://github.com/flutter/flutter/issues/59816 ";
#else
auto settings = CreateSettingsForFixture();
fml::AutoResetWaitableEvent end_frame_latch;
auto end_frame_callback =
[&](bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
end_frame_latch.Signal();
};
auto external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kSuccess, true);
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform | ThreadHost::Type::kIo |
ThreadHost::Type::kUi);
TaskRunners task_runners(
"test",
thread_host.platform_thread->GetTaskRunner(), // platform
thread_host.platform_thread->GetTaskRunner(), // raster
thread_host.ui_thread->GetTaskRunner(), // ui
thread_host.io_thread->GetTaskRunner() // io
);
auto shell = CreateShell({
.settings = settings,
.task_runners = task_runners,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
end_frame_latch.Wait();
ValidateDestroyPlatformView(shell.get());
// Validate the platform view can be recreated and destroyed again
ValidateShell(shell.get());
DestroyShell(std::move(shell), task_runners);
#endif // OS_FUCHSIA
}
TEST_F(ShellTest, GetUsedThisFrameShouldBeSetBeforeEndFrame) {
auto settings = CreateSettingsForFixture();
fml::AutoResetWaitableEvent end_frame_latch;
std::shared_ptr<ShellTestExternalViewEmbedder> external_view_embedder;
bool used_this_frame = true;
auto end_frame_callback =
[&](bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
// We expect `used_this_frame` to be false.
used_this_frame = external_view_embedder->GetUsedThisFrame();
end_frame_latch.Signal();
};
external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kSuccess, true);
auto shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
end_frame_latch.Wait();
ASSERT_FALSE(used_this_frame);
// Validate the platform view can be recreated and destroyed again
ValidateShell(shell.get());
DestroyShell(std::move(shell));
}
// TODO(https://github.com/flutter/flutter/issues/66056): Deflake on all other
// platforms
TEST_F(ShellTest, DISABLED_SkipAndSubmitFrame) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. "
"https://github.com/flutter/flutter/issues/59816 ";
#else
auto settings = CreateSettingsForFixture();
fml::AutoResetWaitableEvent end_frame_latch;
std::shared_ptr<ShellTestExternalViewEmbedder> external_view_embedder;
auto end_frame_callback =
[&](bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
if (should_resubmit_frame && !raster_thread_merger->IsMerged()) {
raster_thread_merger->MergeWithLease(10);
external_view_embedder->UpdatePostPrerollResult(
PostPrerollResult::kSuccess);
}
end_frame_latch.Signal();
};
external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
end_frame_callback, PostPrerollResult::kSkipAndRetryFrame, true);
auto shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
ASSERT_EQ(0, external_view_embedder->GetSubmittedFrameCount());
PumpOneFrame(shell.get());
// `EndFrame` changed the post preroll result to `kSuccess`.
end_frame_latch.Wait();
// Let the resubmitted frame to run and `GetSubmittedFrameCount` should be
// called.
end_frame_latch.Wait();
// 2 frames are submitted because `kSkipAndRetryFrame`, but only the 2nd frame
// should be submitted with `external_view_embedder`, hence the below check.
ASSERT_EQ(1, external_view_embedder->GetSubmittedFrameCount());
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
#endif // OS_FUCHSIA
}
TEST(SettingsTest, FrameTimingSetsAndGetsProperly) {
// Ensure that all phases are in kPhases.
ASSERT_EQ(sizeof(FrameTiming::kPhases),
FrameTiming::kCount * sizeof(FrameTiming::Phase));
int lastPhaseIndex = -1;
FrameTiming timing;
for (auto phase : FrameTiming::kPhases) {
ASSERT_TRUE(phase > lastPhaseIndex); // Ensure that kPhases are in order.
lastPhaseIndex = phase;
auto fake_time =
fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromMicroseconds(phase));
timing.Set(phase, fake_time);
ASSERT_TRUE(timing.Get(phase) == fake_time);
}
}
TEST_F(ShellTest, ReportTimingsIsCalledImmediatelyAfterTheFirstFrame) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
configuration.SetEntrypoint("reportTimingsMain");
fml::AutoResetWaitableEvent reportLatch;
std::vector<int64_t> timestamps;
auto nativeTimingCallback = [&reportLatch,
×tamps](Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
ASSERT_EQ(timestamps.size(), 0ul);
timestamps = tonic::DartConverter<std::vector<int64_t>>::FromArguments(
args, 0, exception);
reportLatch.Signal();
};
AddNativeCallback("NativeReportTimingsCallback",
CREATE_NATIVE_ENTRY(nativeTimingCallback));
ASSERT_TRUE(configuration.IsValid());
RunEngine(shell.get(), std::move(configuration));
for (int i = 0; i < 10; i += 1) {
PumpOneFrame(shell.get());
}
reportLatch.Wait();
DestroyShell(std::move(shell));
// Check for the immediate callback of the first frame that doesn't wait for
// the other 9 frames to be rasterized.
ASSERT_EQ(timestamps.size(), FrameTiming::kCount);
}
TEST_F(ShellTest, WaitForFirstFrame) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Max());
ASSERT_TRUE(result.ok());
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, WaitForFirstFrameZeroSizeFrame) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get(), ViewContent::DummyView({1.0, 0.0, 0.0, 22, 0}));
fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Zero());
EXPECT_FALSE(result.ok());
EXPECT_EQ(result.message(), "timeout");
EXPECT_EQ(result.code(), fml::StatusCode::kDeadlineExceeded);
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, WaitForFirstFrameTimeout) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Zero());
ASSERT_FALSE(result.ok());
ASSERT_EQ(result.code(), fml::StatusCode::kDeadlineExceeded);
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, WaitForFirstFrameMultiple) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Max());
ASSERT_TRUE(result.ok());
for (int i = 0; i < 100; ++i) {
result = shell->WaitForFirstFrame(fml::TimeDelta::Zero());
ASSERT_TRUE(result.ok());
}
DestroyShell(std::move(shell));
}
/// Makes sure that WaitForFirstFrame works if we rendered a frame with the
/// single-thread setup.
TEST_F(ShellTest, WaitForFirstFrameInlined) {
Settings settings = CreateSettingsForFixture();
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
fml::AutoResetWaitableEvent event;
task_runner->PostTask([&shell, &event] {
fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Max());
ASSERT_FALSE(result.ok());
ASSERT_EQ(result.code(), fml::StatusCode::kFailedPrecondition);
event.Signal();
});
ASSERT_FALSE(event.WaitWithTimeout(fml::TimeDelta::Max()));
DestroyShell(std::move(shell), task_runners);
}
static size_t GetRasterizerResourceCacheBytesSync(const Shell& shell) {
size_t bytes = 0;
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell.GetTaskRunners().GetRasterTaskRunner(), [&]() {
if (auto rasterizer = shell.GetRasterizer()) {
bytes = rasterizer->GetResourceCacheMaxBytes().value_or(0U);
}
latch.Signal();
});
latch.Wait();
return bytes;
}
TEST_F(ShellTest, MultipleFluttersSetResourceCacheBytes) {
TaskRunners task_runners = GetTaskRunnersForFixture();
auto settings = CreateSettingsForFixture();
settings.resource_cache_max_bytes_threshold = 4000000U;
GrMockOptions main_context_options;
sk_sp<GrDirectContext> main_context =
GrDirectContext::MakeMock(&main_context_options);
Shell::CreateCallback<PlatformView> platform_view_create_callback =
[task_runners, main_context](flutter::Shell& shell) {
auto result = std::make_unique<TestPlatformView>(shell, task_runners);
ON_CALL(*result, CreateRenderingSurface())
.WillByDefault(::testing::Invoke([main_context] {
auto surface = std::make_unique<MockSurface>();
ON_CALL(*surface, GetContext())
.WillByDefault(Return(main_context.get()));
ON_CALL(*surface, IsValid()).WillByDefault(Return(true));
ON_CALL(*surface, MakeRenderContextCurrent())
.WillByDefault(::testing::Invoke([] {
return std::make_unique<GLContextDefaultResult>(true);
}));
return surface;
}));
return result;
};
auto shell = CreateShell({
.settings = settings,
.task_runners = task_runners,
.platform_view_create_callback = platform_view_create_callback,
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() {
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{1.0, 100, 100, 22, 0});
});
// first cache bytes
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(480000U));
auto shell_spawn_callback = [&]() {
std::unique_ptr<Shell> spawn;
PostSync(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[this, &spawn, &spawner = shell, platform_view_create_callback]() {
auto configuration =
RunConfiguration::InferFromSettings(CreateSettingsForFixture());
configuration.SetEntrypoint("emptyMain");
spawn = spawner->Spawn(
std::move(configuration), "", platform_view_create_callback,
[](Shell& shell) { return std::make_unique<Rasterizer>(shell); });
ASSERT_NE(nullptr, spawn.get());
ASSERT_TRUE(ValidateShell(spawn.get()));
});
return spawn;
};
std::unique_ptr<Shell> second_shell = shell_spawn_callback();
PlatformViewNotifyCreated(second_shell.get());
PostSync(second_shell->GetTaskRunners().GetPlatformTaskRunner(),
[&second_shell]() {
second_shell->GetPlatformView()->SetViewportMetrics(
kImplicitViewId, {1.0, 100, 100, 22, 0});
});
// first cache bytes + second cache bytes
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(960000U));
PostSync(second_shell->GetTaskRunners().GetPlatformTaskRunner(),
[&second_shell]() {
second_shell->GetPlatformView()->SetViewportMetrics(
kImplicitViewId, {1.0, 100, 300, 22, 0});
});
// first cache bytes + second cache bytes
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(1920000U));
std::unique_ptr<Shell> third_shell = shell_spawn_callback();
PlatformViewNotifyCreated(third_shell.get());
PostSync(third_shell->GetTaskRunners().GetPlatformTaskRunner(),
[&third_shell]() {
third_shell->GetPlatformView()->SetViewportMetrics(
kImplicitViewId, {1.0, 400, 100, 22, 0});
});
// first cache bytes + second cache bytes + third cache bytes
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(3840000U));
PostSync(third_shell->GetTaskRunners().GetPlatformTaskRunner(),
[&third_shell]() {
third_shell->GetPlatformView()->SetViewportMetrics(
kImplicitViewId, {1.0, 800, 100, 22, 0});
});
// max bytes threshold
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(4000000U));
DestroyShell(std::move(third_shell), task_runners);
// max bytes threshold
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(4000000U));
PostSync(second_shell->GetTaskRunners().GetPlatformTaskRunner(),
[&second_shell]() {
second_shell->GetPlatformView()->SetViewportMetrics(
kImplicitViewId, {1.0, 100, 100, 22, 0});
});
// first cache bytes + second cache bytes
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(960000U));
DestroyShell(std::move(second_shell), task_runners);
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, SetResourceCacheSize) {
Settings settings = CreateSettingsForFixture();
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
// The Vulkan and GL backends set different default values for the resource
// cache size. The default backend (specified by the default param of
// `CreateShell` in this test) will only resolve to Vulkan (in
// `ShellTestPlatformView::Create`) if GL is disabled. This situation arises
// when targeting the Fuchsia Emulator.
#if defined(SHELL_ENABLE_VULKAN) && !defined(SHELL_ENABLE_GL)
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
vulkan::kGrCacheMaxByteSize);
#elif defined(SHELL_ENABLE_METAL)
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(256 * (1 << 20)));
#else
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(24 * (1 << 20)));
#endif
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() {
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{1.0, 400, 200, 22, 0});
});
PumpOneFrame(shell.get());
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), 3840000U);
std::string request_json = R"json({
"method": "Skia.setResourceCacheMaxBytes",
"args": 10000
})json";
auto data =
fml::MallocMapping::Copy(request_json.c_str(), request_json.length());
auto platform_message = std::make_unique<PlatformMessage>(
"flutter/skia", std::move(data), nullptr);
SendEnginePlatformMessage(shell.get(), std::move(platform_message));
PumpOneFrame(shell.get());
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), 10000U);
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() {
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{1.0, 800, 400, 22, 0});
});
PumpOneFrame(shell.get());
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), 10000U);
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, SetResourceCacheSizeEarly) {
Settings settings = CreateSettingsForFixture();
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() {
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{1.0, 400, 200, 22, 0});
});
PumpOneFrame(shell.get());
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(3840000U));
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, SetResourceCacheSizeNotifiesDart) {
Settings settings = CreateSettingsForFixture();
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() {
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{1.0, 400, 200, 22, 0});
});
PumpOneFrame(shell.get());
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("testSkiaResourceCacheSendsResponse");
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(3840000U));
fml::AutoResetWaitableEvent latch;
AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&latch](auto args) {
latch.Signal();
}));
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
latch.Wait();
EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell),
static_cast<size_t>(10000U));
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, CanCreateImagefromDecompressedBytes) {
Settings settings = CreateSettingsForFixture();
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("canCreateImageFromDecompressedData");
fml::AutoResetWaitableEvent latch;
AddNativeCallback("NotifyWidthHeight",
CREATE_NATIVE_ENTRY([&latch](auto args) {
auto width = tonic::DartConverter<int>::FromDart(
Dart_GetNativeArgument(args, 0));
auto height = tonic::DartConverter<int>::FromDart(
Dart_GetNativeArgument(args, 1));
ASSERT_EQ(width, 10);
ASSERT_EQ(height, 10);
latch.Signal();
}));
RunEngine(shell.get(), std::move(configuration));
latch.Wait();
DestroyShell(std::move(shell), task_runners);
}
class MockTexture : public Texture {
public:
MockTexture(int64_t textureId,
std::shared_ptr<fml::AutoResetWaitableEvent> latch)
: Texture(textureId), latch_(std::move(latch)) {}
~MockTexture() override = default;
// Called from raster thread.
void Paint(PaintContext& context,
const SkRect& bounds,
bool freeze,
const DlImageSampling) override {}
void OnGrContextCreated() override {}
void OnGrContextDestroyed() override {}
void MarkNewFrameAvailable() override {
frames_available_++;
latch_->Signal();
}
void OnTextureUnregistered() override {
unregistered_ = true;
latch_->Signal();
}
bool unregistered() { return unregistered_; }
int frames_available() { return frames_available_; }
private:
bool unregistered_ = false;
int frames_available_ = 0;
std::shared_ptr<fml::AutoResetWaitableEvent> latch_;
};
TEST_F(ShellTest, TextureFrameMarkedAvailableAndUnregister) {
Settings settings = CreateSettingsForFixture();
auto configuration = RunConfiguration::InferFromSettings(settings);
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(ValidateShell(shell.get()));
PlatformViewNotifyCreated(shell.get());
RunEngine(shell.get(), std::move(configuration));
std::shared_ptr<fml::AutoResetWaitableEvent> latch =
std::make_shared<fml::AutoResetWaitableEvent>();
std::shared_ptr<MockTexture> mockTexture =
std::make_shared<MockTexture>(0, latch);
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetRasterTaskRunner(), [&]() {
shell->GetPlatformView()->RegisterTexture(mockTexture);
shell->GetPlatformView()->MarkTextureFrameAvailable(0);
});
latch->Wait();
EXPECT_EQ(mockTexture->frames_available(), 1);
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetRasterTaskRunner(),
[&]() { shell->GetPlatformView()->UnregisterTexture(0); });
latch->Wait();
EXPECT_EQ(mockTexture->unregistered(), true);
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, IsolateCanAccessPersistentIsolateData) {
const std::string message = "dummy isolate launch data.";
Settings settings = CreateSettingsForFixture();
settings.persistent_isolate_data =
std::make_shared<fml::DataMapping>(message);
TaskRunners task_runners("test", // label
GetCurrentTaskRunner(), // platform
CreateNewThread(), // raster
CreateNewThread(), // ui
CreateNewThread() // io
);
fml::AutoResetWaitableEvent message_latch;
AddNativeCallback("NotifyMessage",
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
const auto message_from_dart =
tonic::DartConverter<std::string>::FromDart(
Dart_GetNativeArgument(args, 0));
ASSERT_EQ(message, message_from_dart);
message_latch.Signal();
}));
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("canAccessIsolateLaunchData");
fml::AutoResetWaitableEvent event;
shell->RunEngine(std::move(configuration), [&](auto result) {
ASSERT_EQ(result, Engine::RunStatus::Success);
});
message_latch.Wait();
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, CanScheduleFrameFromPlatform) {
Settings settings = CreateSettingsForFixture();
TaskRunners task_runners = GetTaskRunnersForFixture();
fml::AutoResetWaitableEvent latch;
AddNativeCallback(
"NotifyNative",
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); }));
fml::AutoResetWaitableEvent check_latch;
AddNativeCallback("NativeOnBeginFrame",
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
check_latch.Signal();
}));
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("onBeginFrameWithNotifyNativeMain");
RunEngine(shell.get(), std::move(configuration));
// Wait for the application to attach the listener.
latch.Wait();
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[&shell]() { shell->GetPlatformView()->ScheduleFrame(); });
check_latch.Wait();
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, SecondaryVsyncCallbackShouldBeCalledAfterVsyncCallback) {
bool is_on_begin_frame_called = false;
bool is_secondary_callback_called = false;
bool test_started = false;
Settings settings = CreateSettingsForFixture();
TaskRunners task_runners = GetTaskRunnersForFixture();
fml::AutoResetWaitableEvent latch;
AddNativeCallback(
"NotifyNative",
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); }));
fml::CountDownLatch count_down_latch(2);
AddNativeCallback("NativeOnBeginFrame",
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
if (!test_started) {
return;
}
EXPECT_FALSE(is_on_begin_frame_called);
EXPECT_FALSE(is_secondary_callback_called);
is_on_begin_frame_called = true;
count_down_latch.CountDown();
}));
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.task_runners = task_runners,
});
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("onBeginFrameWithNotifyNativeMain");
RunEngine(shell.get(), std::move(configuration));
// Wait for the application to attach the listener.
latch.Wait();
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(), [&]() {
shell->GetEngine()->ScheduleSecondaryVsyncCallback(0, [&]() {
if (!test_started) {
return;
}
EXPECT_TRUE(is_on_begin_frame_called);
EXPECT_FALSE(is_secondary_callback_called);
is_secondary_callback_called = true;
count_down_latch.CountDown();
});
shell->GetEngine()->ScheduleFrame();
test_started = true;
});
count_down_latch.Wait();
EXPECT_TRUE(is_on_begin_frame_called);
EXPECT_TRUE(is_secondary_callback_called);
DestroyShell(std::move(shell), task_runners);
}
static void LogSkData(const sk_sp<SkData>& data, const char* title) {
FML_LOG(ERROR) << "---------- " << title;
std::ostringstream ostr;
for (size_t i = 0; i < data->size();) {
ostr << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<int>(data->bytes()[i]) << " ";
i++;
if (i % 16 == 0 || i == data->size()) {
FML_LOG(ERROR) << ostr.str();
ostr.str("");
ostr.clear();
}
}
}
TEST_F(ShellTest, Screenshot) {
auto settings = CreateSettingsForFixture();
fml::AutoResetWaitableEvent firstFrameLatch;
settings.frame_rasterized_callback =
[&firstFrameLatch](const FrameTiming& t) { firstFrameLatch.Signal(); };
std::unique_ptr<Shell> shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
LayerTreeBuilder builder = [&](const std::shared_ptr<ContainerLayer>& root) {
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(10, 10), MakeSizedDisplayList(80, 80), false, false);
root->Add(display_list_layer);
};
PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder));
firstFrameLatch.Wait();
std::promise<Rasterizer::Screenshot> screenshot_promise;
auto screenshot_future = screenshot_promise.get_future();
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetRasterTaskRunner(),
[&screenshot_promise, &shell]() {
auto rasterizer = shell->GetRasterizer();
screenshot_promise.set_value(rasterizer->ScreenshotLastLayerTree(
Rasterizer::ScreenshotType::CompressedImage, false));
});
auto fixtures_dir =
fml::OpenDirectory(GetFixturesPath(), false, fml::FilePermission::kRead);
auto reference_png = fml::FileMapping::CreateReadOnly(
fixtures_dir, "shelltest_screenshot.png");
// Use MakeWithoutCopy instead of MakeWithCString because we don't want to
// encode the null sentinel
sk_sp<SkData> reference_data = SkData::MakeWithoutCopy(
reference_png->GetMapping(), reference_png->GetSize());
sk_sp<SkData> screenshot_data = screenshot_future.get().data;
if (!reference_data->equals(screenshot_data.get())) {
LogSkData(reference_data, "reference");
LogSkData(screenshot_data, "screenshot");
ASSERT_TRUE(false);
}
DestroyShell(std::move(shell));
}
// Compares local times as seen by the dart isolate and as seen by this test
// fixture, to a resolution of 1 hour.
//
// This verifies that (1) the isolate is able to get a timezone (doesn't lock
// up for example), and (2) that the host and the isolate agree on what the
// timezone is.
TEST_F(ShellTest, LocaltimesMatch) {
fml::AutoResetWaitableEvent latch;
std::string dart_isolate_time_str;
// See fixtures/shell_test.dart, the callback NotifyLocalTime is declared
// there.
AddNativeCallback("NotifyLocalTime", CREATE_NATIVE_ENTRY([&](auto args) {
dart_isolate_time_str =
tonic::DartConverter<std::string>::FromDart(
Dart_GetNativeArgument(args, 0));
latch.Signal();
}));
auto settings = CreateSettingsForFixture();
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("localtimesMatch");
std::unique_ptr<Shell> shell = CreateShell(settings);
ASSERT_NE(shell.get(), nullptr);
RunEngine(shell.get(), std::move(configuration));
latch.Wait();
char timestr[200];
const time_t timestamp = time(nullptr);
const struct tm* local_time = localtime(×tamp);
ASSERT_NE(local_time, nullptr)
<< "Could not get local time: errno=" << errno << ": " << strerror(errno);
// Example: "2020-02-26 14" for 2pm on February 26, 2020.
const size_t format_size =
strftime(timestr, sizeof(timestr), "%Y-%m-%d %H", local_time);
ASSERT_NE(format_size, 0UL)
<< "strftime failed: host time: " << std::string(timestr)
<< " dart isolate time: " << dart_isolate_time_str;
const std::string host_local_time_str = timestr;
ASSERT_EQ(dart_isolate_time_str, host_local_time_str)
<< "Local times in the dart isolate and the local time seen by the test "
<< "differ by more than 1 hour, but are expected to be about equal";
DestroyShell(std::move(shell));
}
/// An image generator that always creates a 1x1 single-frame green image.
class SinglePixelImageGenerator : public ImageGenerator {
public:
SinglePixelImageGenerator()
: info_(SkImageInfo::MakeN32(1, 1, SkAlphaType::kOpaque_SkAlphaType)){};
~SinglePixelImageGenerator() = default;
const SkImageInfo& GetInfo() { return info_; }
unsigned int GetFrameCount() const { return 1; }
unsigned int GetPlayCount() const { return 1; }
const ImageGenerator::FrameInfo GetFrameInfo(unsigned int frame_index) {
return {std::nullopt, 0, SkCodecAnimation::DisposalMethod::kKeep};
}
SkISize GetScaledDimensions(float scale) {
return SkISize::Make(info_.width(), info_.height());
}
bool GetPixels(const SkImageInfo& info,
void* pixels,
size_t row_bytes,
unsigned int frame_index,
std::optional<unsigned int> prior_frame) {
assert(info.width() == 1);
assert(info.height() == 1);
assert(row_bytes == 4);
reinterpret_cast<uint32_t*>(pixels)[0] = 0x00ff00ff;
return true;
};
private:
SkImageInfo info_;
};
TEST_F(ShellTest, CanRegisterImageDecoders) {
fml::AutoResetWaitableEvent latch;
AddNativeCallback("NotifyWidthHeight", CREATE_NATIVE_ENTRY([&](auto args) {
auto width = tonic::DartConverter<int>::FromDart(
Dart_GetNativeArgument(args, 0));
auto height = tonic::DartConverter<int>::FromDart(
Dart_GetNativeArgument(args, 1));
ASSERT_EQ(width, 1);
ASSERT_EQ(height, 1);
latch.Signal();
}));
auto settings = CreateSettingsForFixture();
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("canRegisterImageDecoders");
std::unique_ptr<Shell> shell = CreateShell(settings);
ASSERT_NE(shell.get(), nullptr);
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() {
shell->RegisterImageDecoder(
[](const sk_sp<SkData>& buffer) {
return std::make_unique<SinglePixelImageGenerator>();
},
100);
});
RunEngine(shell.get(), std::move(configuration));
latch.Wait();
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, OnServiceProtocolGetSkSLsWorks) {
fml::ScopedTemporaryDirectory base_dir;
ASSERT_TRUE(base_dir.fd().is_valid());
PersistentCache::SetCacheDirectoryPath(base_dir.path());
PersistentCache::ResetCacheForProcess();
// Create 2 dummy SkSL cache file IE (base32 encoding of A), II (base32
// encoding of B) with content x and y.
std::vector<std::string> components = {
"flutter_engine", GetFlutterEngineVersion(), "skia", GetSkiaVersion(),
PersistentCache::kSkSLSubdirName};
auto sksl_dir = fml::CreateDirectory(base_dir.fd(), components,
fml::FilePermission::kReadWrite);
const std::string x_key_str = "A";
const std::string x_value_str = "x";
sk_sp<SkData> x_key =
SkData::MakeWithCopy(x_key_str.data(), x_key_str.size());
sk_sp<SkData> x_value =
SkData::MakeWithCopy(x_value_str.data(), x_value_str.size());
auto x_data = PersistentCache::BuildCacheObject(*x_key, *x_value);
const std::string y_key_str = "B";
const std::string y_value_str = "y";
sk_sp<SkData> y_key =
SkData::MakeWithCopy(y_key_str.data(), y_key_str.size());
sk_sp<SkData> y_value =
SkData::MakeWithCopy(y_value_str.data(), y_value_str.size());
auto y_data = PersistentCache::BuildCacheObject(*y_key, *y_value);
ASSERT_TRUE(fml::WriteAtomically(sksl_dir, "x_cache", *x_data));
ASSERT_TRUE(fml::WriteAtomically(sksl_dir, "y_cache", *y_data));
Settings settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
ServiceProtocol::Handler::ServiceProtocolMap empty_params;
rapidjson::Document document;
OnServiceProtocol(shell.get(), ServiceProtocolEnum::kGetSkSLs,
shell->GetTaskRunners().GetIOTaskRunner(), empty_params,
&document);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
DestroyShell(std::move(shell));
const std::string expected_json1 =
"{\"type\":\"GetSkSLs\",\"SkSLs\":{\"II\":\"eQ==\",\"IE\":\"eA==\"}}";
const std::string expected_json2 =
"{\"type\":\"GetSkSLs\",\"SkSLs\":{\"IE\":\"eA==\",\"II\":\"eQ==\"}}";
bool json_is_expected = (expected_json1 == buffer.GetString()) ||
(expected_json2 == buffer.GetString());
ASSERT_TRUE(json_is_expected) << buffer.GetString() << " is not equal to "
<< expected_json1 << " or " << expected_json2;
}
TEST_F(ShellTest, RasterizerScreenshot) {
Settings settings = CreateSettingsForFixture();
auto configuration = RunConfiguration::InferFromSettings(settings);
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(ValidateShell(shell.get()));
PlatformViewNotifyCreated(shell.get());
RunEngine(shell.get(), std::move(configuration));
auto latch = std::make_shared<fml::AutoResetWaitableEvent>();
PumpOneFrame(shell.get());
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetRasterTaskRunner(), [&shell, &latch]() {
Rasterizer::Screenshot screenshot =
shell->GetRasterizer()->ScreenshotLastLayerTree(
Rasterizer::ScreenshotType::CompressedImage, true);
EXPECT_NE(screenshot.data, nullptr);
latch->Signal();
});
latch->Wait();
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, RasterizerMakeRasterSnapshot) {
Settings settings = CreateSettingsForFixture();
auto configuration = RunConfiguration::InferFromSettings(settings);
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(ValidateShell(shell.get()));
PlatformViewNotifyCreated(shell.get());
RunEngine(shell.get(), std::move(configuration));
auto latch = std::make_shared<fml::AutoResetWaitableEvent>();
PumpOneFrame(shell.get());
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetRasterTaskRunner(), [&shell, &latch]() {
SnapshotDelegate* delegate =
reinterpret_cast<Rasterizer*>(shell->GetRasterizer().get());
sk_sp<DlImage> image = delegate->MakeRasterSnapshot(
MakeSizedDisplayList(50, 50), SkISize::Make(50, 50));
EXPECT_NE(image, nullptr);
latch->Signal();
});
latch->Wait();
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, OnServiceProtocolEstimateRasterCacheMemoryWorks) {
Settings settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// 1. Construct a picture and a picture layer to be raster cached.
sk_sp<DisplayList> display_list = MakeSizedDisplayList(10, 10);
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(0, 0), MakeSizedDisplayList(100, 100), false, false);
display_list_layer->set_paint_bounds(SkRect::MakeWH(100, 100));
// 2. Rasterize the picture and the picture layer in the raster cache.
std::promise<bool> rasterized;
shell->GetTaskRunners().GetRasterTaskRunner()->PostTask(
[&shell, &rasterized, &display_list, &display_list_layer] {
std::vector<RasterCacheItem*> raster_cache_items;
auto* compositor_context = shell->GetRasterizer()->compositor_context();
auto& raster_cache = compositor_context->raster_cache();
LayerStateStack state_stack;
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PaintContext paint_context = {
// clang-format off
.state_stack = state_stack,
.canvas = nullptr,
.gr_context = nullptr,
.dst_color_space = nullptr,
.view_embedder = nullptr,
.raster_time = raster_time,
.ui_time = ui_time,
.texture_registry = nullptr,
.raster_cache = &raster_cache,
// clang-format on
};
PrerollContext preroll_context = {
// clang-format off
.raster_cache = &raster_cache,
.gr_context = nullptr,
.view_embedder = nullptr,
.state_stack = state_stack,
.dst_color_space = nullptr,
.surface_needs_readback = false,
.raster_time = raster_time,
.ui_time = ui_time,
.texture_registry = nullptr,
.has_platform_view = false,
.has_texture_layer = false,
.raster_cached_entries = &raster_cache_items,
// clang-format on
};
// 2.1. Rasterize the picture. Call Draw multiple times to pass the
// access threshold (default to 3) so a cache can be generated.
MockCanvas dummy_canvas;
DlPaint paint;
bool picture_cache_generated;
DisplayListRasterCacheItem display_list_raster_cache_item(
display_list, SkPoint(), true, false);
for (int i = 0; i < 4; i += 1) {
SkMatrix matrix = SkMatrix::I();
state_stack.set_preroll_delegate(matrix);
display_list_raster_cache_item.PrerollSetup(&preroll_context, matrix);
display_list_raster_cache_item.PrerollFinalize(&preroll_context,
matrix);
picture_cache_generated =
display_list_raster_cache_item.need_caching();
state_stack.set_delegate(&dummy_canvas);
display_list_raster_cache_item.TryToPrepareRasterCache(paint_context);
display_list_raster_cache_item.Draw(paint_context, &dummy_canvas,
&paint);
}
ASSERT_TRUE(picture_cache_generated);
// 2.2. Rasterize the picture layer.
LayerRasterCacheItem layer_raster_cache_item(display_list_layer.get());
state_stack.set_preroll_delegate(SkMatrix::I());
layer_raster_cache_item.PrerollSetup(&preroll_context, SkMatrix::I());
layer_raster_cache_item.PrerollFinalize(&preroll_context,
SkMatrix::I());
state_stack.set_delegate(&dummy_canvas);
layer_raster_cache_item.TryToPrepareRasterCache(paint_context);
layer_raster_cache_item.Draw(paint_context, &dummy_canvas, &paint);
rasterized.set_value(true);
});
rasterized.get_future().wait();
// 3. Call the service protocol and check its output.
ServiceProtocol::Handler::ServiceProtocolMap empty_params;
rapidjson::Document document;
OnServiceProtocol(
shell.get(), ServiceProtocolEnum::kEstimateRasterCacheMemory,
shell->GetTaskRunners().GetRasterTaskRunner(), empty_params, &document);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
std::string expected_json =
"{\"type\":\"EstimateRasterCacheMemory\",\"layerBytes\":40024,\"picture"
"Bytes\":424}";
std::string actual_json = buffer.GetString();
ASSERT_EQ(actual_json, expected_json);
DestroyShell(std::move(shell));
}
// ktz
TEST_F(ShellTest, OnServiceProtocolRenderFrameWithRasterStatsWorks) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("scene_with_red_box");
RunEngine(shell.get(), std::move(configuration));
// Set a non-zero viewport metrics, otherwise the scene would be discarded.
PostSync(shell->GetTaskRunners().GetUITaskRunner(),
[engine = shell->GetEngine()]() {
engine->SetViewportMetrics(kImplicitViewId,
ViewportMetrics{1, 1, 1, 22, 0});
});
PumpOneFrame(shell.get(), ViewContent::NoViews());
ServiceProtocol::Handler::ServiceProtocolMap empty_params;
rapidjson::Document document;
OnServiceProtocol(
shell.get(), ServiceProtocolEnum::kRenderFrameWithRasterStats,
shell->GetTaskRunners().GetRasterTaskRunner(), empty_params, &document);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
// It would be better to parse out the json and check for the validity of
// fields. Below checks approximate what needs to be checked, this can not be
// an exact check since duration will not exactly match.
#ifdef SHELL_ENABLE_METAL
std::string expected_json =
"\"snapshot\":[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,3,32,0,"
"0,2,88,8,6,0,0,0,154,118,130,112,0,0,0,1,115,82,71,66,0,174,206,28,233,"
"0,0,0,4,115,66,73,84,8,8,8,8,124,8,100,136,0,0,7,103,73,68,65,84,120,"
"156,237,206,65,13,192,48,0,3,177,211,248,115,78,73,172,234,199,70,224,"
"86,91,45,0,0,128,203,190,215,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
"0,224,47,7,195,182,3,255,101,111,186,90,0,0,0,0,73,69,78,68,174,66,96,"
"130]";
#else
std::string expected_json =
"\"snapshot\":[137,80,78,71,13,10,26,10,0,"
"0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,6,0,0,0,31,21,196,137,0,0,0,1,115,"
"82,71,66,0,174,206,28,233,0,0,0,4,115,66,73,84,8,8,8,8,124,8,100,136,0,"
"0,0,13,73,68,65,84,8,153,99,248,207,192,240,31,0,5,0,1,255,171,206,54,"
"137,0,0,0,0,73,69,78,68,174,66,96,130]";
#endif
std::string actual_json = buffer.GetString();
EXPECT_THAT(actual_json, ::testing::HasSubstr(expected_json));
EXPECT_THAT(actual_json,
::testing::HasSubstr("{\"type\":\"RenderFrameWithRasterStats\""));
EXPECT_THAT(actual_json, ::testing::HasSubstr("\"duration_micros\""));
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
}
#if defined(FML_OS_MACOSX)
TEST_F(ShellTest, OnServiceProtocolRenderFrameWithRasterStatsDisableImpeller) {
auto settings = CreateSettingsForFixture();
settings.enable_impeller = true;
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.rendering_backend =
ShellTestPlatformView::BackendType::kMetalBackend,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("scene_with_red_box");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get(), ViewContent::NoViews());
ServiceProtocol::Handler::ServiceProtocolMap empty_params;
rapidjson::Document document;
OnServiceProtocol(
shell.get(), ServiceProtocolEnum::kRenderFrameWithRasterStats,
shell->GetTaskRunners().GetRasterTaskRunner(), empty_params, &document);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
std::string actual_json = buffer.GetString();
std::string expected_json =
"{\"code\":-32000,\"message\":\"Raster status not supported on Impeller "
"backend.\"}";
ASSERT_EQ(actual_json, expected_json);
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
}
#endif // FML_OS_MACOSX
// TODO(https://github.com/flutter/flutter/issues/100273): Disabled due to
// flakiness.
// TODO(https://github.com/flutter/flutter/issues/100299): Fix it when
// re-enabling.
TEST_F(ShellTest, DISABLED_DiscardLayerTreeOnResize) {
auto settings = CreateSettingsForFixture();
SkISize wrong_size = SkISize::Make(400, 100);
SkISize expected_size = SkISize::Make(400, 200);
fml::AutoResetWaitableEvent end_frame_latch;
auto end_frame_callback =
[&](bool should_merge_thread,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
end_frame_latch.Signal();
};
auto external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
std::move(end_frame_callback), PostPrerollResult::kSuccess, false);
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[&shell, &expected_size]() {
shell->GetPlatformView()->SetViewportMetrics(
kImplicitViewId,
{1.0, static_cast<double>(expected_size.width()),
static_cast<double>(expected_size.height()), 22, 0});
});
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get(), ViewContent::DummyView(
static_cast<double>(wrong_size.width()),
static_cast<double>(wrong_size.height())));
end_frame_latch.Wait();
// Wrong size, no frames are submitted.
ASSERT_EQ(0, external_view_embedder->GetSubmittedFrameCount());
PumpOneFrame(shell.get(), ViewContent::DummyView(
static_cast<double>(expected_size.width()),
static_cast<double>(expected_size.height())));
end_frame_latch.Wait();
// Expected size, 1 frame submitted.
ASSERT_EQ(1, external_view_embedder->GetSubmittedFrameCount());
ASSERT_EQ(expected_size, external_view_embedder->GetLastSubmittedFrameSize());
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
}
// TODO(https://github.com/flutter/flutter/issues/100273): Disabled due to
// flakiness.
// TODO(https://github.com/flutter/flutter/issues/100299): Fix it when
// re-enabling.
TEST_F(ShellTest, DISABLED_DiscardResubmittedLayerTreeOnResize) {
auto settings = CreateSettingsForFixture();
SkISize origin_size = SkISize::Make(400, 100);
SkISize new_size = SkISize::Make(400, 200);
fml::AutoResetWaitableEvent end_frame_latch;
fml::AutoResetWaitableEvent resize_latch;
std::shared_ptr<ShellTestExternalViewEmbedder> external_view_embedder;
fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger_ref;
auto end_frame_callback =
[&](bool should_merge_thread,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
if (!raster_thread_merger_ref) {
raster_thread_merger_ref = raster_thread_merger;
}
if (should_merge_thread) {
raster_thread_merger->MergeWithLease(10);
external_view_embedder->UpdatePostPrerollResult(
PostPrerollResult::kSuccess);
}
end_frame_latch.Signal();
if (should_merge_thread) {
resize_latch.Wait();
}
};
external_view_embedder = std::make_shared<ShellTestExternalViewEmbedder>(
std::move(end_frame_callback), PostPrerollResult::kResubmitFrame, true);
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.shell_test_external_view_embedder = external_view_embedder,
}),
});
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[&shell, &origin_size]() {
shell->GetPlatformView()->SetViewportMetrics(
kImplicitViewId,
{1.0, static_cast<double>(origin_size.width()),
static_cast<double>(origin_size.height()), 22, 0});
});
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get(), ViewContent::DummyView(
static_cast<double>(origin_size.width()),
static_cast<double>(origin_size.height())));
end_frame_latch.Wait();
ASSERT_EQ(0, external_view_embedder->GetSubmittedFrameCount());
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[&shell, &new_size, &resize_latch]() {
shell->GetPlatformView()->SetViewportMetrics(
kImplicitViewId, {1.0, static_cast<double>(new_size.width()),
static_cast<double>(new_size.height()), 22, 0});
resize_latch.Signal();
});
end_frame_latch.Wait();
// The frame resubmitted with origin size should be discarded after the
// viewport metrics changed.
ASSERT_EQ(0, external_view_embedder->GetSubmittedFrameCount());
// Threads will be merged at the end of this frame.
PumpOneFrame(shell.get(),
ViewContent::DummyView(static_cast<double>(new_size.width()),
static_cast<double>(new_size.height())));
end_frame_latch.Wait();
ASSERT_TRUE(raster_thread_merger_ref->IsMerged());
ASSERT_EQ(1, external_view_embedder->GetSubmittedFrameCount());
ASSERT_EQ(new_size, external_view_embedder->GetLastSubmittedFrameSize());
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, IgnoresInvalidMetrics) {
fml::AutoResetWaitableEvent latch;
double last_device_pixel_ratio;
double last_width;
double last_height;
auto native_report_device_pixel_ratio = [&](Dart_NativeArguments args) {
auto dpr_handle = Dart_GetNativeArgument(args, 0);
ASSERT_TRUE(Dart_IsDouble(dpr_handle));
Dart_DoubleValue(dpr_handle, &last_device_pixel_ratio);
ASSERT_FALSE(last_device_pixel_ratio == 0.0);
auto width_handle = Dart_GetNativeArgument(args, 1);
ASSERT_TRUE(Dart_IsDouble(width_handle));
Dart_DoubleValue(width_handle, &last_width);
ASSERT_FALSE(last_width == 0.0);
auto height_handle = Dart_GetNativeArgument(args, 2);
ASSERT_TRUE(Dart_IsDouble(height_handle));
Dart_DoubleValue(height_handle, &last_height);
ASSERT_FALSE(last_height == 0.0);
latch.Signal();
};
Settings settings = CreateSettingsForFixture();
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
AddNativeCallback("ReportMetrics",
CREATE_NATIVE_ENTRY(native_report_device_pixel_ratio));
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("reportMetrics");
RunEngine(shell.get(), std::move(configuration));
task_runner->PostTask([&]() {
// This one is invalid for having 0 pixel ratio.
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{0.0, 400, 200, 22, 0});
task_runner->PostTask([&]() {
// This one is invalid for having 0 width.
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{0.8, 0.0, 200, 22, 0});
task_runner->PostTask([&]() {
// This one is invalid for having 0 height.
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{0.8, 400, 0.0, 22, 0});
task_runner->PostTask([&]() {
// This one makes it through.
shell->GetPlatformView()->SetViewportMetrics(
kImplicitViewId, {0.8, 400, 200.0, 22, 0});
});
});
});
});
latch.Wait();
ASSERT_EQ(last_device_pixel_ratio, 0.8);
ASSERT_EQ(last_width, 400.0);
ASSERT_EQ(last_height, 200.0);
latch.Reset();
task_runner->PostTask([&]() {
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{1.2, 600, 300, 22, 0});
});
latch.Wait();
ASSERT_EQ(last_device_pixel_ratio, 1.2);
ASSERT_EQ(last_width, 600.0);
ASSERT_EQ(last_height, 300.0);
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, IgnoresMetricsUpdateToInvalidView) {
fml::AutoResetWaitableEvent latch;
double last_device_pixel_ratio;
// This callback will be called whenever any view's metrics change.
auto native_report_device_pixel_ratio = [&](Dart_NativeArguments args) {
// The correct call will have a DPR of 3.
auto dpr_handle = Dart_GetNativeArgument(args, 0);
ASSERT_TRUE(Dart_IsDouble(dpr_handle));
Dart_DoubleValue(dpr_handle, &last_device_pixel_ratio);
ASSERT_TRUE(last_device_pixel_ratio > 2.5);
latch.Signal();
};
Settings settings = CreateSettingsForFixture();
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
AddNativeCallback("ReportMetrics",
CREATE_NATIVE_ENTRY(native_report_device_pixel_ratio));
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("reportMetrics");
RunEngine(shell.get(), std::move(configuration));
task_runner->PostTask([&]() {
// This one is invalid for having an nonexistent view ID.
// Also, it has a DPR of 2.0 for detection.
shell->GetPlatformView()->SetViewportMetrics(2, {2.0, 400, 200, 22, 0});
task_runner->PostTask([&]() {
// This one is valid with DPR 3.0.
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId,
{3.0, 400, 200, 22, 0});
});
});
latch.Wait();
ASSERT_EQ(last_device_pixel_ratio, 3.0);
latch.Reset();
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, OnServiceProtocolSetAssetBundlePathWorks) {
Settings settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
RunConfiguration configuration =
RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("canAccessResourceFromAssetDir");
// Verify isolate can load a known resource with the
// default asset directory - kernel_blob.bin
fml::AutoResetWaitableEvent latch;
// Callback used to signal whether the resource was loaded successfully.
bool can_access_resource = false;
auto native_can_access_resource = [&can_access_resource,
&latch](Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
can_access_resource =
tonic::DartConverter<bool>::FromArguments(args, 0, exception);
latch.Signal();
};
AddNativeCallback("NotifyCanAccessResource",
CREATE_NATIVE_ENTRY(native_can_access_resource));
// Callback used to delay the asset load until after the service
// protocol method has finished.
auto native_notify_set_asset_bundle_path =
[&shell](Dart_NativeArguments args) {
// Update the asset directory to a bonus path.
ServiceProtocol::Handler::ServiceProtocolMap params;
params["assetDirectory"] = "assetDirectory";
rapidjson::Document document;
OnServiceProtocol(shell.get(), ServiceProtocolEnum::kSetAssetBundlePath,
shell->GetTaskRunners().GetUITaskRunner(), params,
&document);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
};
AddNativeCallback("NotifySetAssetBundlePath",
CREATE_NATIVE_ENTRY(native_notify_set_asset_bundle_path));
RunEngine(shell.get(), std::move(configuration));
latch.Wait();
ASSERT_TRUE(can_access_resource);
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, EngineRootIsolateLaunchesDontTakeVMDataSettings) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
// Make sure the shell launch does not kick off the creation of the VM
// instance by already creating one upfront.
auto vm_settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(vm_settings);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
auto settings = vm_settings;
fml::AutoResetWaitableEvent isolate_create_latch;
settings.root_isolate_create_callback = [&](const auto& isolate) {
isolate_create_latch.Signal();
};
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
RunEngine(shell.get(), std::move(configuration));
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
DestroyShell(std::move(shell));
isolate_create_latch.Wait();
}
TEST_F(ShellTest, AssetManagerSingle) {
fml::ScopedTemporaryDirectory asset_dir;
fml::UniqueFD asset_dir_fd = fml::OpenDirectory(
asset_dir.path().c_str(), false, fml::FilePermission::kRead);
std::string filename = "test_name";
std::string content = "test_content";
bool success = fml::WriteAtomically(asset_dir_fd, filename.c_str(),
fml::DataMapping(content));
ASSERT_TRUE(success);
AssetManager asset_manager;
asset_manager.PushBack(
std::make_unique<DirectoryAssetBundle>(std::move(asset_dir_fd), false));
auto mapping = asset_manager.GetAsMapping(filename);
ASSERT_TRUE(mapping != nullptr);
std::string result(reinterpret_cast<const char*>(mapping->GetMapping()),
mapping->GetSize());
ASSERT_TRUE(result == content);
}
TEST_F(ShellTest, AssetManagerMulti) {
fml::ScopedTemporaryDirectory asset_dir;
fml::UniqueFD asset_dir_fd = fml::OpenDirectory(
asset_dir.path().c_str(), false, fml::FilePermission::kRead);
std::vector<std::string> filenames = {
"good0",
"bad0",
"good1",
"bad1",
};
for (const auto& filename : filenames) {
bool success = fml::WriteAtomically(asset_dir_fd, filename.c_str(),
fml::DataMapping(filename));
ASSERT_TRUE(success);
}
AssetManager asset_manager;
asset_manager.PushBack(
std::make_unique<DirectoryAssetBundle>(std::move(asset_dir_fd), false));
auto mappings = asset_manager.GetAsMappings("(.*)", std::nullopt);
EXPECT_EQ(mappings.size(), 4u);
std::vector<std::string> expected_results = {
"good0",
"good1",
};
mappings = asset_manager.GetAsMappings("(.*)good(.*)", std::nullopt);
ASSERT_EQ(mappings.size(), expected_results.size());
for (auto& mapping : mappings) {
std::string result(reinterpret_cast<const char*>(mapping->GetMapping()),
mapping->GetSize());
EXPECT_NE(
std::find(expected_results.begin(), expected_results.end(), result),
expected_results.end());
}
}
#if defined(OS_FUCHSIA)
TEST_F(ShellTest, AssetManagerMultiSubdir) {
std::string subdir_path = "subdir";
fml::ScopedTemporaryDirectory asset_dir;
fml::UniqueFD asset_dir_fd = fml::OpenDirectory(
asset_dir.path().c_str(), false, fml::FilePermission::kRead);
fml::UniqueFD subdir_fd =
fml::OpenDirectory((asset_dir.path() + "/" + subdir_path).c_str(), true,
fml::FilePermission::kReadWrite);
std::vector<std::string> filenames = {
"bad0",
"notgood", // this is to make sure the pattern (.*)good(.*) only
// matches things in the subdirectory
};
std::vector<std::string> subdir_filenames = {
"good0",
"good1",
"bad1",
};
for (auto filename : filenames) {
bool success = fml::WriteAtomically(asset_dir_fd, filename.c_str(),
fml::DataMapping(filename));
ASSERT_TRUE(success);
}
for (auto filename : subdir_filenames) {
bool success = fml::WriteAtomically(subdir_fd, filename.c_str(),
fml::DataMapping(filename));
ASSERT_TRUE(success);
}
AssetManager asset_manager;
asset_manager.PushBack(
std::make_unique<DirectoryAssetBundle>(std::move(asset_dir_fd), false));
auto mappings = asset_manager.GetAsMappings("(.*)", std::nullopt);
EXPECT_EQ(mappings.size(), 5u);
mappings = asset_manager.GetAsMappings("(.*)", subdir_path);
EXPECT_EQ(mappings.size(), 3u);
std::vector<std::string> expected_results = {
"good0",
"good1",
};
mappings = asset_manager.GetAsMappings("(.*)good(.*)", subdir_path);
ASSERT_EQ(mappings.size(), expected_results.size());
for (auto& mapping : mappings) {
std::string result(reinterpret_cast<const char*>(mapping->GetMapping()),
mapping->GetSize());
ASSERT_NE(
std::find(expected_results.begin(), expected_results.end(), result),
expected_results.end());
}
}
#endif // OS_FUCHSIA
TEST_F(ShellTest, Spawn) {
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
configuration.SetEntrypoint("fixturesAreFunctionalMain");
auto second_configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(second_configuration.IsValid());
second_configuration.SetEntrypoint("testCanLaunchSecondaryIsolate");
const std::string initial_route("/foo");
fml::AutoResetWaitableEvent main_latch;
std::string last_entry_point;
// Fulfill native function for the first Shell's entrypoint.
AddNativeCallback(
"SayHiFromFixturesAreFunctionalMain", CREATE_NATIVE_ENTRY([&](auto args) {
last_entry_point = shell->GetEngine()->GetLastEntrypoint();
main_latch.Signal();
}));
// Fulfill native function for the second Shell's entrypoint.
fml::CountDownLatch second_latch(2);
AddNativeCallback(
// The Dart native function names aren't very consistent but this is
// just the native function name of the second vm entrypoint in the
// fixture.
"NotifyNative",
CREATE_NATIVE_ENTRY([&](auto args) { second_latch.CountDown(); }));
RunEngine(shell.get(), std::move(configuration));
main_latch.Wait();
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
// Check first Shell ran the first entrypoint.
ASSERT_EQ("fixturesAreFunctionalMain", last_entry_point);
PostSync(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[this, &spawner = shell, &second_configuration, &second_latch,
initial_route]() {
MockPlatformViewDelegate platform_view_delegate;
auto spawn = spawner->Spawn(
std::move(second_configuration), initial_route,
[&platform_view_delegate](Shell& shell) {
auto result = std::make_unique<MockPlatformView>(
platform_view_delegate, shell.GetTaskRunners());
ON_CALL(*result, CreateRenderingSurface())
.WillByDefault(::testing::Invoke(
[] { return std::make_unique<MockSurface>(); }));
return result;
},
[](Shell& shell) { return std::make_unique<Rasterizer>(shell); });
ASSERT_NE(nullptr, spawn.get());
ASSERT_TRUE(ValidateShell(spawn.get()));
PostSync(spawner->GetTaskRunners().GetUITaskRunner(), [&spawn, &spawner,
initial_route] {
// Check second shell ran the second entrypoint.
ASSERT_EQ("testCanLaunchSecondaryIsolate",
spawn->GetEngine()->GetLastEntrypoint());
ASSERT_EQ(initial_route, spawn->GetEngine()->InitialRoute());
ASSERT_NE(spawner->GetEngine()
->GetRuntimeController()
->GetRootIsolateGroup(),
0u);
ASSERT_EQ(spawner->GetEngine()
->GetRuntimeController()
->GetRootIsolateGroup(),
spawn->GetEngine()
->GetRuntimeController()
->GetRootIsolateGroup());
auto spawner_snapshot_delegate = spawner->GetEngine()
->GetRuntimeController()
->GetSnapshotDelegate();
auto spawn_snapshot_delegate =
spawn->GetEngine()->GetRuntimeController()->GetSnapshotDelegate();
PostSync(spawner->GetTaskRunners().GetRasterTaskRunner(),
[spawner_snapshot_delegate, spawn_snapshot_delegate] {
ASSERT_NE(spawner_snapshot_delegate.get(),
spawn_snapshot_delegate.get());
});
});
PostSync(
spawner->GetTaskRunners().GetIOTaskRunner(), [&spawner, &spawn] {
ASSERT_EQ(spawner->GetIOManager()->GetResourceContext().get(),
spawn->GetIOManager()->GetResourceContext().get());
});
// Before destroying the shell, wait for expectations of the spawned
// isolate to be met.
second_latch.Wait();
DestroyShell(std::move(spawn));
});
DestroyShell(std::move(shell));
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, SpawnWithDartEntrypointArgs) {
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
configuration.SetEntrypoint("canReceiveArgumentsWhenEngineRun");
const std::vector<std::string> entrypoint_args{"foo", "bar"};
configuration.SetEntrypointArgs(entrypoint_args);
auto second_configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(second_configuration.IsValid());
second_configuration.SetEntrypoint("canReceiveArgumentsWhenEngineSpawn");
const std::vector<std::string> second_entrypoint_args{"arg1", "arg2"};
second_configuration.SetEntrypointArgs(second_entrypoint_args);
const std::string initial_route("/foo");
fml::AutoResetWaitableEvent main_latch;
std::string last_entry_point;
// Fulfill native function for the first Shell's entrypoint.
AddNativeCallback("NotifyNativeWhenEngineRun",
CREATE_NATIVE_ENTRY(([&](Dart_NativeArguments args) {
ASSERT_TRUE(tonic::DartConverter<bool>::FromDart(
Dart_GetNativeArgument(args, 0)));
last_entry_point =
shell->GetEngine()->GetLastEntrypoint();
main_latch.Signal();
})));
fml::AutoResetWaitableEvent second_latch;
// Fulfill native function for the second Shell's entrypoint.
AddNativeCallback("NotifyNativeWhenEngineSpawn",
CREATE_NATIVE_ENTRY(([&](Dart_NativeArguments args) {
ASSERT_TRUE(tonic::DartConverter<bool>::FromDart(
Dart_GetNativeArgument(args, 0)));
last_entry_point =
shell->GetEngine()->GetLastEntrypoint();
second_latch.Signal();
})));
RunEngine(shell.get(), std::move(configuration));
main_latch.Wait();
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
// Check first Shell ran the first entrypoint.
ASSERT_EQ("canReceiveArgumentsWhenEngineRun", last_entry_point);
PostSync(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[this, &spawner = shell, &second_configuration, &second_latch,
initial_route]() {
MockPlatformViewDelegate platform_view_delegate;
auto spawn = spawner->Spawn(
std::move(second_configuration), initial_route,
[&platform_view_delegate](Shell& shell) {
auto result = std::make_unique<MockPlatformView>(
platform_view_delegate, shell.GetTaskRunners());
ON_CALL(*result, CreateRenderingSurface())
.WillByDefault(::testing::Invoke(
[] { return std::make_unique<MockSurface>(); }));
return result;
},
[](Shell& shell) { return std::make_unique<Rasterizer>(shell); });
ASSERT_NE(nullptr, spawn.get());
ASSERT_TRUE(ValidateShell(spawn.get()));
PostSync(spawner->GetTaskRunners().GetUITaskRunner(),
[&spawn, &spawner, initial_route] {
// Check second shell ran the second entrypoint.
ASSERT_EQ("canReceiveArgumentsWhenEngineSpawn",
spawn->GetEngine()->GetLastEntrypoint());
ASSERT_EQ(initial_route, spawn->GetEngine()->InitialRoute());
ASSERT_NE(spawner->GetEngine()
->GetRuntimeController()
->GetRootIsolateGroup(),
0u);
ASSERT_EQ(spawner->GetEngine()
->GetRuntimeController()
->GetRootIsolateGroup(),
spawn->GetEngine()
->GetRuntimeController()
->GetRootIsolateGroup());
});
PostSync(
spawner->GetTaskRunners().GetIOTaskRunner(), [&spawner, &spawn] {
ASSERT_EQ(spawner->GetIOManager()->GetResourceContext().get(),
spawn->GetIOManager()->GetResourceContext().get());
});
// Before destroying the shell, wait for expectations of the spawned
// isolate to be met.
second_latch.Wait();
DestroyShell(std::move(spawn));
});
DestroyShell(std::move(shell));
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, IOManagerIsSharedBetweenParentAndSpawnedShell) {
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [this,
&spawner = shell,
&settings] {
auto second_configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(second_configuration.IsValid());
second_configuration.SetEntrypoint("emptyMain");
const std::string initial_route("/foo");
MockPlatformViewDelegate platform_view_delegate;
auto spawn = spawner->Spawn(
std::move(second_configuration), initial_route,
[&platform_view_delegate](Shell& shell) {
auto result = std::make_unique<MockPlatformView>(
platform_view_delegate, shell.GetTaskRunners());
ON_CALL(*result, CreateRenderingSurface())
.WillByDefault(::testing::Invoke(
[] { return std::make_unique<MockSurface>(); }));
return result;
},
[](Shell& shell) { return std::make_unique<Rasterizer>(shell); });
ASSERT_TRUE(ValidateShell(spawn.get()));
PostSync(spawner->GetTaskRunners().GetIOTaskRunner(), [&spawner, &spawn] {
ASSERT_NE(spawner->GetIOManager().get(), nullptr);
ASSERT_EQ(spawner->GetIOManager().get(), spawn->GetIOManager().get());
});
// Destroy the child shell.
DestroyShell(std::move(spawn));
});
// Destroy the parent shell.
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, IOManagerInSpawnedShellIsNotNullAfterParentShellDestroyed) {
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
PostSync(shell->GetTaskRunners().GetUITaskRunner(), [&shell] {
// We must get engine on UI thread.
auto runtime_controller = shell->GetEngine()->GetRuntimeController();
PostSync(shell->GetTaskRunners().GetIOTaskRunner(),
[&shell, &runtime_controller] {
// We must get io_manager on IO thread.
auto io_manager = runtime_controller->GetIOManager();
// Check io_manager existence.
ASSERT_NE(io_manager.get(), nullptr);
ASSERT_NE(io_manager->GetSkiaUnrefQueue().get(), nullptr);
// Get io_manager directly from shell and check its existence.
ASSERT_NE(shell->GetIOManager().get(), nullptr);
});
});
std::unique_ptr<Shell> spawn;
PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell, &settings,
&spawn] {
auto second_configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(second_configuration.IsValid());
second_configuration.SetEntrypoint("emptyMain");
const std::string initial_route("/foo");
MockPlatformViewDelegate platform_view_delegate;
auto child = shell->Spawn(
std::move(second_configuration), initial_route,
[&platform_view_delegate](Shell& shell) {
auto result = std::make_unique<MockPlatformView>(
platform_view_delegate, shell.GetTaskRunners());
ON_CALL(*result, CreateRenderingSurface())
.WillByDefault(::testing::Invoke(
[] { return std::make_unique<MockSurface>(); }));
return result;
},
[](Shell& shell) { return std::make_unique<Rasterizer>(shell); });
spawn = std::move(child);
});
// Destroy the parent shell.
DestroyShell(std::move(shell));
PostSync(spawn->GetTaskRunners().GetUITaskRunner(), [&spawn] {
// We must get engine on UI thread.
auto runtime_controller = spawn->GetEngine()->GetRuntimeController();
PostSync(spawn->GetTaskRunners().GetIOTaskRunner(),
[&spawn, &runtime_controller] {
// We must get io_manager on IO thread.
auto io_manager = runtime_controller->GetIOManager();
// Check io_manager existence here.
ASSERT_NE(io_manager.get(), nullptr);
ASSERT_NE(io_manager->GetSkiaUnrefQueue().get(), nullptr);
// Get io_manager directly from shell and check its existence.
ASSERT_NE(spawn->GetIOManager().get(), nullptr);
});
});
// Destroy the child shell.
DestroyShell(std::move(spawn));
}
TEST_F(ShellTest, ImageGeneratorRegistryNotNullAfterParentShellDestroyed) {
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
std::unique_ptr<Shell> spawn;
PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell, &settings,
&spawn] {
auto second_configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(second_configuration.IsValid());
second_configuration.SetEntrypoint("emptyMain");
const std::string initial_route("/foo");
MockPlatformViewDelegate platform_view_delegate;
auto child = shell->Spawn(
std::move(second_configuration), initial_route,
[&platform_view_delegate](Shell& shell) {
auto result = std::make_unique<MockPlatformView>(
platform_view_delegate, shell.GetTaskRunners());
ON_CALL(*result, CreateRenderingSurface())
.WillByDefault(::testing::Invoke(
[] { return std::make_unique<MockSurface>(); }));
return result;
},
[](Shell& shell) { return std::make_unique<Rasterizer>(shell); });
spawn = std::move(child);
});
PostSync(spawn->GetTaskRunners().GetUITaskRunner(), [&spawn] {
std::shared_ptr<const DartIsolate> isolate =
spawn->GetEngine()->GetRuntimeController()->GetRootIsolate().lock();
ASSERT_TRUE(isolate);
ASSERT_TRUE(isolate->GetImageGeneratorRegistry());
});
// Destroy the parent shell.
DestroyShell(std::move(shell));
PostSync(spawn->GetTaskRunners().GetUITaskRunner(), [&spawn] {
std::shared_ptr<const DartIsolate> isolate =
spawn->GetEngine()->GetRuntimeController()->GetRootIsolate().lock();
ASSERT_TRUE(isolate);
ASSERT_TRUE(isolate->GetImageGeneratorRegistry());
});
// Destroy the child shell.
DestroyShell(std::move(spawn));
}
TEST_F(ShellTest, UpdateAssetResolverByTypeReplaces) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
auto asset_manager = configuration.GetAssetManager();
shell->RunEngine(std::move(configuration), [&](auto result) {
ASSERT_EQ(result, Engine::RunStatus::Success);
});
auto platform_view =
std::make_unique<PlatformView>(*shell.get(), task_runners);
auto old_resolver = std::make_unique<TestAssetResolver>(
true, AssetResolver::AssetResolverType::kApkAssetProvider);
ASSERT_TRUE(old_resolver->IsValid());
asset_manager->PushBack(std::move(old_resolver));
auto updated_resolver = std::make_unique<TestAssetResolver>(
false, AssetResolver::AssetResolverType::kApkAssetProvider);
ASSERT_FALSE(updated_resolver->IsValidAfterAssetManagerChange());
platform_view->UpdateAssetResolverByType(
std::move(updated_resolver),
AssetResolver::AssetResolverType::kApkAssetProvider);
auto resolvers = asset_manager->TakeResolvers();
ASSERT_EQ(resolvers.size(), 2ull);
ASSERT_TRUE(resolvers[0]->IsValidAfterAssetManagerChange());
ASSERT_FALSE(resolvers[1]->IsValidAfterAssetManagerChange());
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, UpdateAssetResolverByTypeAppends) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
auto asset_manager = configuration.GetAssetManager();
shell->RunEngine(std::move(configuration), [&](auto result) {
ASSERT_EQ(result, Engine::RunStatus::Success);
});
auto platform_view =
std::make_unique<PlatformView>(*shell.get(), task_runners);
auto updated_resolver = std::make_unique<TestAssetResolver>(
false, AssetResolver::AssetResolverType::kApkAssetProvider);
ASSERT_FALSE(updated_resolver->IsValidAfterAssetManagerChange());
platform_view->UpdateAssetResolverByType(
std::move(updated_resolver),
AssetResolver::AssetResolverType::kApkAssetProvider);
auto resolvers = asset_manager->TakeResolvers();
ASSERT_EQ(resolvers.size(), 2ull);
ASSERT_TRUE(resolvers[0]->IsValidAfterAssetManagerChange());
ASSERT_FALSE(resolvers[1]->IsValidAfterAssetManagerChange());
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, UpdateAssetResolverByTypeNull) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
"io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform));
auto task_runner = thread_host.platform_thread->GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
auto asset_manager = configuration.GetAssetManager();
RunEngine(shell.get(), std::move(configuration));
auto platform_view =
std::make_unique<PlatformView>(*shell.get(), task_runners);
auto old_resolver = std::make_unique<TestAssetResolver>(
true, AssetResolver::AssetResolverType::kApkAssetProvider);
ASSERT_TRUE(old_resolver->IsValid());
asset_manager->PushBack(std::move(old_resolver));
platform_view->UpdateAssetResolverByType(
nullptr, AssetResolver::AssetResolverType::kApkAssetProvider);
auto resolvers = asset_manager->TakeResolvers();
ASSERT_EQ(resolvers.size(), 2ull);
ASSERT_TRUE(resolvers[0]->IsValidAfterAssetManagerChange());
ASSERT_TRUE(resolvers[1]->IsValidAfterAssetManagerChange());
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, UpdateAssetResolverByTypeDoesNotReplaceMismatchType) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
auto asset_manager = configuration.GetAssetManager();
shell->RunEngine(std::move(configuration), [&](auto result) {
ASSERT_EQ(result, Engine::RunStatus::Success);
});
auto platform_view =
std::make_unique<PlatformView>(*shell.get(), task_runners);
auto old_resolver = std::make_unique<TestAssetResolver>(
true, AssetResolver::AssetResolverType::kAssetManager);
ASSERT_TRUE(old_resolver->IsValid());
asset_manager->PushBack(std::move(old_resolver));
auto updated_resolver = std::make_unique<TestAssetResolver>(
false, AssetResolver::AssetResolverType::kApkAssetProvider);
ASSERT_FALSE(updated_resolver->IsValidAfterAssetManagerChange());
platform_view->UpdateAssetResolverByType(
std::move(updated_resolver),
AssetResolver::AssetResolverType::kApkAssetProvider);
auto resolvers = asset_manager->TakeResolvers();
ASSERT_EQ(resolvers.size(), 3ull);
ASSERT_TRUE(resolvers[0]->IsValidAfterAssetManagerChange());
ASSERT_TRUE(resolvers[1]->IsValidAfterAssetManagerChange());
ASSERT_FALSE(resolvers[2]->IsValidAfterAssetManagerChange());
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, CanCreateShellsWithGLBackend) {
#if !SHELL_ENABLE_GL
// GL emulation does not exist on Fuchsia.
GTEST_SKIP();
#else
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.rendering_backend = ShellTestPlatformView::BackendType::kGLBackend,
}),
});
ASSERT_NE(shell, nullptr);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
PlatformViewNotifyCreated(shell.get());
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
#endif // !SHELL_ENABLE_GL
}
TEST_F(ShellTest, CanCreateShellsWithVulkanBackend) {
#if !SHELL_ENABLE_VULKAN
GTEST_SKIP();
#else
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.rendering_backend =
ShellTestPlatformView::BackendType::kVulkanBackend,
}),
});
ASSERT_NE(shell, nullptr);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
PlatformViewNotifyCreated(shell.get());
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
#endif // !SHELL_ENABLE_VULKAN
}
TEST_F(ShellTest, CanCreateShellsWithMetalBackend) {
#if !SHELL_ENABLE_METAL
GTEST_SKIP();
#else
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.rendering_backend =
ShellTestPlatformView::BackendType::kMetalBackend,
}),
});
ASSERT_NE(shell, nullptr);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
PlatformViewNotifyCreated(shell.get());
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
#endif // !SHELL_ENABLE_METAL
}
TEST_F(ShellTest, UserTagSetOnStartup) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
// Make sure the shell launch does not kick off the creation of the VM
// instance by already creating one upfront.
auto vm_settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(vm_settings);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
auto settings = vm_settings;
fml::AutoResetWaitableEvent isolate_create_latch;
// ensure that "AppStartUpTag" is set during isolate creation.
settings.root_isolate_create_callback = [&](const DartIsolate& isolate) {
Dart_Handle current_tag = Dart_GetCurrentUserTag();
Dart_Handle startup_tag = Dart_NewUserTag("AppStartUp");
EXPECT_TRUE(Dart_IdentityEquals(current_tag, startup_tag));
isolate_create_latch.Signal();
};
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
RunEngine(shell.get(), std::move(configuration));
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
DestroyShell(std::move(shell));
isolate_create_latch.Wait();
}
TEST_F(ShellTest, PrefetchDefaultFontManager) {
auto settings = CreateSettingsForFixture();
settings.prefetched_default_font_manager = true;
std::unique_ptr<Shell> shell;
auto get_font_manager_count = [&] {
fml::AutoResetWaitableEvent latch;
size_t font_manager_count;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
[this, &shell, &latch, &font_manager_count]() {
font_manager_count =
GetFontCollection(shell.get())->GetFontManagersCount();
latch.Signal();
});
latch.Wait();
return font_manager_count;
};
size_t initial_font_manager_count = 0;
settings.root_isolate_create_callback = [&](const auto& isolate) {
ASSERT_GT(initial_font_manager_count, 0ul);
// Should not have fetched the default font manager yet, since the root
// isolate was only just created.
ASSERT_EQ(get_font_manager_count(), initial_font_manager_count);
};
shell = CreateShell(settings);
initial_font_manager_count = get_font_manager_count();
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
// If the prefetched_default_font_manager flag is set, then the default font
// manager will not be added until the engine starts running.
ASSERT_EQ(get_font_manager_count(), initial_font_manager_count + 1);
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, OnPlatformViewCreatedWhenUIThreadIsBusy) {
// This test will deadlock if the threading logic in
// Shell::OnCreatePlatformView is wrong.
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(shell->GetTaskRunners().GetUITaskRunner(),
[&latch]() { latch.Wait(); });
ShellTest::PlatformViewNotifyCreated(shell.get());
latch.Signal();
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, UIWorkAfterOnPlatformViewDestroyed) {
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("drawFrames");
fml::AutoResetWaitableEvent latch;
fml::AutoResetWaitableEvent notify_native_latch;
AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) {
notify_native_latch.Signal();
latch.Wait();
}));
RunEngine(shell.get(), std::move(configuration));
// Wait to make sure we get called back from Dart and thus have latched
// the UI thread before we create/destroy the platform view.
notify_native_latch.Wait();
ShellTest::PlatformViewNotifyCreated(shell.get());
fml::AutoResetWaitableEvent destroy_latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[&shell, &destroy_latch]() {
shell->GetPlatformView()->NotifyDestroyed();
destroy_latch.Signal();
});
destroy_latch.Wait();
// Unlatch the UI thread and let it send us a scene to render.
latch.Signal();
// Flush the UI task runner to make sure we process the render/scheduleFrame
// request.
fml::AutoResetWaitableEvent ui_flush_latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
[&ui_flush_latch]() { ui_flush_latch.Signal(); });
ui_flush_latch.Wait();
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, UsesPlatformMessageHandler) {
TaskRunners task_runners = GetTaskRunnersForFixture();
auto settings = CreateSettingsForFixture();
MockPlatformViewDelegate platform_view_delegate;
auto platform_message_handler =
std::make_shared<MockPlatformMessageHandler>();
int message_id = 1;
EXPECT_CALL(*platform_message_handler, HandlePlatformMessage(_));
EXPECT_CALL(*platform_message_handler,
InvokePlatformMessageEmptyResponseCallback(message_id));
Shell::CreateCallback<PlatformView> platform_view_create_callback =
[&platform_view_delegate, task_runners,
platform_message_handler](flutter::Shell& shell) {
auto result = std::make_unique<MockPlatformView>(platform_view_delegate,
task_runners);
EXPECT_CALL(*result, GetPlatformMessageHandler())
.WillOnce(Return(platform_message_handler));
return result;
};
auto shell = CreateShell({
.settings = settings,
.task_runners = task_runners,
.platform_view_create_callback = platform_view_create_callback,
});
EXPECT_EQ(platform_message_handler, shell->GetPlatformMessageHandler());
PostSync(task_runners.GetUITaskRunner(), [&shell]() {
size_t data_size = 4;
fml::MallocMapping bytes =
fml::MallocMapping(static_cast<uint8_t*>(malloc(data_size)), data_size);
fml::RefPtr<MockPlatformMessageResponse> response =
MockPlatformMessageResponse::Create();
auto message = std::make_unique<PlatformMessage>(
/*channel=*/"foo", /*data=*/std::move(bytes), /*response=*/response);
(static_cast<Engine::Delegate*>(shell.get()))
->OnEngineHandlePlatformMessage(std::move(message));
});
shell->GetPlatformMessageHandler()
->InvokePlatformMessageEmptyResponseCallback(message_id);
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, SpawnWorksWithOnError) {
auto settings = CreateSettingsForFixture();
auto shell = CreateShell(settings);
ASSERT_TRUE(ValidateShell(shell.get()));
auto configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(configuration.IsValid());
configuration.SetEntrypoint("onErrorA");
auto second_configuration = RunConfiguration::InferFromSettings(settings);
ASSERT_TRUE(second_configuration.IsValid());
second_configuration.SetEntrypoint("onErrorB");
fml::CountDownLatch latch(2);
AddNativeCallback(
"NotifyErrorA", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto string_handle = Dart_GetNativeArgument(args, 0);
const char* c_str;
Dart_StringToCString(string_handle, &c_str);
EXPECT_STREQ(c_str, "Exception: I should be coming from A");
latch.CountDown();
}));
AddNativeCallback(
"NotifyErrorB", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto string_handle = Dart_GetNativeArgument(args, 0);
const char* c_str;
Dart_StringToCString(string_handle, &c_str);
EXPECT_STREQ(c_str, "Exception: I should be coming from B");
latch.CountDown();
}));
RunEngine(shell.get(), std::move(configuration));
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
PostSync(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[this, &spawner = shell, &second_configuration, &latch]() {
::testing::NiceMock<MockPlatformViewDelegate> platform_view_delegate;
auto spawn = spawner->Spawn(
std::move(second_configuration), "",
[&platform_view_delegate](Shell& shell) {
auto result =
std::make_unique<::testing::NiceMock<MockPlatformView>>(
platform_view_delegate, shell.GetTaskRunners());
ON_CALL(*result, CreateRenderingSurface())
.WillByDefault(::testing::Invoke([] {
return std::make_unique<::testing::NiceMock<MockSurface>>();
}));
return result;
},
[](Shell& shell) { return std::make_unique<Rasterizer>(shell); });
ASSERT_NE(nullptr, spawn.get());
ASSERT_TRUE(ValidateShell(spawn.get()));
// Before destroying the shell, wait for expectations of the spawned
// isolate to be met.
latch.Wait();
DestroyShell(std::move(spawn));
});
DestroyShell(std::move(shell));
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, ImmutableBufferLoadsAssetOnBackgroundThread) {
Settings settings = CreateSettingsForFixture();
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
fml::CountDownLatch latch(1);
AddNativeCallback("NotifyNative",
CREATE_NATIVE_ENTRY([&](auto args) { latch.CountDown(); }));
// Create the surface needed by rasterizer
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("testThatAssetLoadingHappensOnWorkerThread");
auto asset_manager = configuration.GetAssetManager();
auto test_resolver = std::make_unique<ThreadCheckingAssetResolver>(
shell->GetDartVM()->GetConcurrentMessageLoop());
auto leaked_resolver = test_resolver.get();
asset_manager->PushBack(std::move(test_resolver));
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
latch.Wait();
EXPECT_EQ(leaked_resolver->mapping_requests[0], "DoesNotExist");
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, PictureToImageSync) {
#if !SHELL_ENABLE_GL
// This test uses the GL backend.
GTEST_SKIP();
#else
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.rendering_backend = ShellTestPlatformView::BackendType::kGLBackend,
}),
});
AddNativeCallback("NativeOnBeforeToImageSync",
CREATE_NATIVE_ENTRY([&](auto args) {
// nop
}));
fml::CountDownLatch latch(2);
AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) {
// Teardown and set up rasterizer again.
PlatformViewNotifyDestroyed(shell.get());
PlatformViewNotifyCreated(shell.get());
latch.CountDown();
}));
ASSERT_NE(shell, nullptr);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
PlatformViewNotifyCreated(shell.get());
configuration.SetEntrypoint("toImageSync");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
latch.Wait();
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
#endif // !SHELL_ENABLE_GL
}
TEST_F(ShellTest, PictureToImageSyncImpellerNoSurface) {
#if !SHELL_ENABLE_METAL
// This test uses the Metal backend.
GTEST_SKIP();
#else
auto settings = CreateSettingsForFixture();
settings.enable_impeller = true;
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.rendering_backend =
ShellTestPlatformView::BackendType::kMetalBackend,
}),
});
AddNativeCallback("NativeOnBeforeToImageSync",
CREATE_NATIVE_ENTRY([&](auto args) {
// nop
}));
fml::CountDownLatch latch(2);
AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) {
// Teardown and set up rasterizer again.
PlatformViewNotifyDestroyed(shell.get());
PlatformViewNotifyCreated(shell.get());
latch.CountDown();
}));
ASSERT_NE(shell, nullptr);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
// Important: Do not create the platform view yet!
// This test is making sure that the rasterizer can create the texture
// as expected without a surface.
configuration.SetEntrypoint("toImageSync");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
latch.Wait();
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
#endif // !SHELL_ENABLE_METAL
}
#if SHELL_ENABLE_GL
// This test uses the GL backend and refers to symbols in egl.h
TEST_F(ShellTest, PictureToImageSyncWithTrampledContext) {
// make it easier to trample the GL context by running on a single task
// runner.
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform);
auto task_runner = thread_host.platform_thread->GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.task_runners = task_runners,
.platform_view_create_callback = ShellTestPlatformViewBuilder({
.rendering_backend = ShellTestPlatformView::BackendType::kGLBackend,
}),
});
AddNativeCallback(
"NativeOnBeforeToImageSync", CREATE_NATIVE_ENTRY([&](auto args) {
// Trample the GL context. If the rasterizer fails
// to make the right one current again, test will
// fail.
::eglMakeCurrent(::eglGetCurrentDisplay(), NULL, NULL, NULL);
}));
fml::CountDownLatch latch(2);
AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) {
// Teardown and set up rasterizer again.
PlatformViewNotifyDestroyed(shell.get());
PlatformViewNotifyCreated(shell.get());
latch.CountDown();
}));
ASSERT_NE(shell, nullptr);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
PlatformViewNotifyCreated(shell.get());
configuration.SetEntrypoint("toImageSync");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
latch.Wait();
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell), task_runners);
}
#endif // SHELL_ENABLE_GL
TEST_F(ShellTest, PluginUtilitiesCallbackHandleErrorHandling) {
auto settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings);
fml::AutoResetWaitableEvent latch;
bool test_passed;
AddNativeCallback("NotifyNativeBool", CREATE_NATIVE_ENTRY([&](auto args) {
Dart_Handle exception = nullptr;
test_passed = tonic::DartConverter<bool>::FromArguments(
args, 0, exception);
latch.Signal();
}));
ASSERT_NE(shell, nullptr);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
PlatformViewNotifyCreated(shell.get());
configuration.SetEntrypoint("testPluginUtilitiesCallbackHandle");
RunEngine(shell.get(), std::move(configuration));
PumpOneFrame(shell.get());
latch.Wait();
ASSERT_TRUE(test_passed);
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell));
}
TEST_F(ShellTest, NotifyIdleRejectsPastAndNearFuture) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform | ThreadHost::kUi |
ThreadHost::kIo | ThreadHost::kRaster);
auto platform_task_runner = thread_host.platform_thread->GetTaskRunner();
TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(),
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
fml::AutoResetWaitableEvent latch;
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("emptyMain");
RunEngine(shell.get(), std::move(configuration));
fml::TaskRunner::RunNowOrPostTask(
task_runners.GetUITaskRunner(), [&latch, &shell]() {
auto runtime_controller = const_cast<RuntimeController*>(
shell->GetEngine()->GetRuntimeController());
auto now = fml::TimeDelta::FromMicroseconds(Dart_TimelineGetMicros());
EXPECT_FALSE(runtime_controller->NotifyIdle(
now - fml::TimeDelta::FromMilliseconds(10)));
EXPECT_FALSE(runtime_controller->NotifyIdle(now));
EXPECT_FALSE(runtime_controller->NotifyIdle(
now + fml::TimeDelta::FromNanoseconds(100)));
EXPECT_TRUE(runtime_controller->NotifyIdle(
now + fml::TimeDelta::FromMilliseconds(100)));
latch.Signal();
});
latch.Wait();
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, NotifyIdleNotCalledInLatencyMode) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform | ThreadHost::kUi |
ThreadHost::kIo | ThreadHost::kRaster);
auto platform_task_runner = thread_host.platform_thread->GetTaskRunner();
TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(),
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
// we start off in balanced mode, where we expect idle notifications to
// succeed. After the first `NotifyNativeBool` we expect to be in latency
// mode, where we expect idle notifications to fail.
fml::CountDownLatch latch(2);
AddNativeCallback(
"NotifyNativeBool", CREATE_NATIVE_ENTRY([&](auto args) {
Dart_Handle exception = nullptr;
bool is_in_latency_mode =
tonic::DartConverter<bool>::FromArguments(args, 0, exception);
auto runtime_controller = const_cast<RuntimeController*>(
shell->GetEngine()->GetRuntimeController());
bool success =
runtime_controller->NotifyIdle(fml::TimeDelta::FromMicroseconds(
Dart_TimelineGetMicros() + 100000));
EXPECT_EQ(success, !is_in_latency_mode);
latch.CountDown();
}));
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("performanceModeImpactsNotifyIdle");
RunEngine(shell.get(), std::move(configuration));
latch.Wait();
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, NotifyDestroyed) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform | ThreadHost::kUi |
ThreadHost::kIo | ThreadHost::kRaster);
auto platform_task_runner = thread_host.platform_thread->GetTaskRunner();
TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(),
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
auto shell = CreateShell(settings, task_runners);
ASSERT_TRUE(DartVMRef::IsInstanceRunning());
ASSERT_TRUE(ValidateShell(shell.get()));
fml::CountDownLatch latch(1);
AddNativeCallback("NotifyDestroyed", CREATE_NATIVE_ENTRY([&](auto args) {
auto runtime_controller = const_cast<RuntimeController*>(
shell->GetEngine()->GetRuntimeController());
bool success = runtime_controller->NotifyDestroyed();
EXPECT_TRUE(success);
latch.CountDown();
}));
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("callNotifyDestroyed");
RunEngine(shell.get(), std::move(configuration));
latch.Wait();
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
}
TEST_F(ShellTest, PrintsErrorWhenPlatformMessageSentFromWrongThread) {
#if FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG || OS_FUCHSIA
GTEST_SKIP() << "Test is for debug mode only on non-fuchsia targets.";
#else
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform);
auto task_runner = thread_host.platform_thread->GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
auto shell = CreateShell(settings, task_runners);
{
fml::testing::LogCapture log_capture;
// The next call will result in a thread checker violation.
fml::ThreadChecker::DisableNextThreadCheckFailure();
SendPlatformMessage(shell.get(), std::make_unique<PlatformMessage>(
"com.test.plugin", nullptr));
EXPECT_THAT(
log_capture.str(),
::testing::EndsWith(
"The 'com.test.plugin' channel sent a message from native to "
"Flutter on a non-platform thread. Platform channel messages "
"must be sent on the platform thread. Failure to do so may "
"result in data loss or crashes, and must be fixed in the "
"plugin or application code creating that channel.\nSee "
"https://docs.flutter.dev/platform-integration/"
"platform-channels#channels-and-platform-threading for more "
"information.\n"));
}
{
fml::testing::LogCapture log_capture;
// The next call will result in a thread checker violation.
fml::ThreadChecker::DisableNextThreadCheckFailure();
SendPlatformMessage(shell.get(), std::make_unique<PlatformMessage>(
"com.test.plugin", nullptr));
EXPECT_EQ(log_capture.str(), "");
}
DestroyShell(std::move(shell), task_runners);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
#endif
}
TEST_F(ShellTest, DiesIfSoftwareRenderingAndImpellerAreEnabledDeathTest) {
#if defined(OS_FUCHSIA)
GTEST_SKIP() << "Fuchsia";
#else
::testing::FLAGS_gtest_death_test_style = "threadsafe";
Settings settings = CreateSettingsForFixture();
settings.enable_impeller = true;
settings.enable_software_rendering = true;
ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform);
auto task_runner = thread_host.platform_thread->GetTaskRunner();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
EXPECT_DEATH_IF_SUPPORTED(
CreateShell(settings, task_runners),
"Software rendering is incompatible with Impeller.");
#endif // OS_FUCHSIA
}
// Parse the arguments of NativeReportViewIdsCallback and
// store them in hasImplicitView and viewIds.
static void ParseViewIdsCallback(const Dart_NativeArguments& args,
bool* hasImplicitView,
std::vector<int64_t>* viewIds) {
Dart_Handle exception = nullptr;
viewIds->clear();
*hasImplicitView =
tonic::DartConverter<bool>::FromArguments(args, 0, exception);
ASSERT_EQ(exception, nullptr);
*viewIds = tonic::DartConverter<std::vector<int64_t>>::FromArguments(
args, 1, exception);
ASSERT_EQ(exception, nullptr);
}
TEST_F(ShellTest, ShellStartsWithImplicitView) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
auto task_runner = CreateNewThread();
TaskRunners task_runners("test", task_runner, task_runner, task_runner,
task_runner);
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell);
bool hasImplicitView;
std::vector<int64_t> viewIds;
fml::AutoResetWaitableEvent reportLatch;
auto nativeViewIdsCallback = [&reportLatch, &hasImplicitView,
&viewIds](Dart_NativeArguments args) {
ParseViewIdsCallback(args, &hasImplicitView, &viewIds);
reportLatch.Signal();
};
AddNativeCallback("NativeReportViewIdsCallback",
CREATE_NATIVE_ENTRY(nativeViewIdsCallback));
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("testReportViewIds");
RunEngine(shell.get(), std::move(configuration));
reportLatch.Wait();
ASSERT_TRUE(hasImplicitView);
ASSERT_EQ(viewIds.size(), 1u);
ASSERT_EQ(viewIds[0], 0ll);
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell), task_runners);
}
// Tests that Shell::AddView and Shell::RemoveView works.
TEST_F(ShellTest, ShellCanAddViewOrRemoveView) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
"io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster |
ThreadHost::Type::kIo | ThreadHost::Type::kUi));
TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(),
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell);
bool hasImplicitView;
std::vector<int64_t> viewIds;
fml::AutoResetWaitableEvent reportLatch;
auto nativeViewIdsCallback = [&reportLatch, &hasImplicitView,
&viewIds](Dart_NativeArguments args) {
ParseViewIdsCallback(args, &hasImplicitView, &viewIds);
reportLatch.Signal();
};
AddNativeCallback("NativeReportViewIdsCallback",
CREATE_NATIVE_ENTRY(nativeViewIdsCallback));
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("testReportViewIds");
RunEngine(shell.get(), std::move(configuration));
reportLatch.Wait();
ASSERT_TRUE(hasImplicitView);
ASSERT_EQ(viewIds.size(), 1u);
ASSERT_EQ(viewIds[0], 0ll);
PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(),
[&shell] { shell->AddView(2, ViewportMetrics{}); });
reportLatch.Wait();
ASSERT_TRUE(hasImplicitView);
ASSERT_EQ(viewIds.size(), 2u);
ASSERT_EQ(viewIds[1], 2ll);
PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell] {
shell->RemoveView(2, [](bool removed) { ASSERT_TRUE(removed); });
});
reportLatch.Wait();
ASSERT_TRUE(hasImplicitView);
ASSERT_EQ(viewIds.size(), 1u);
ASSERT_EQ(viewIds[0], 0ll);
PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(),
[&shell] { shell->AddView(4, ViewportMetrics{}); });
reportLatch.Wait();
ASSERT_TRUE(hasImplicitView);
ASSERT_EQ(viewIds.size(), 2u);
ASSERT_EQ(viewIds[1], 4ll);
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell), task_runners);
}
// Parse the arguments of NativeReportViewWidthsCallback and
// store them in viewWidths.
static void ParseViewWidthsCallback(const Dart_NativeArguments& args,
std::map<int64_t, int64_t>* viewWidths) {
Dart_Handle exception = nullptr;
viewWidths->clear();
std::vector<int64_t> viewWidthPacket =
tonic::DartConverter<std::vector<int64_t>>::FromArguments(args, 0,
exception);
ASSERT_EQ(exception, nullptr);
ASSERT_EQ(viewWidthPacket.size() % 2, 0ul);
for (size_t packetIndex = 0; packetIndex < viewWidthPacket.size();
packetIndex += 2) {
(*viewWidths)[viewWidthPacket[packetIndex]] =
viewWidthPacket[packetIndex + 1];
}
}
// Ensure that PlatformView::SetViewportMetrics and Shell::AddView that were
// dispatched before the isolate is run have been flushed to the Dart VM when
// the main function starts.
TEST_F(ShellTest, ShellFlushesPlatformStatesByMain) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
"io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster |
ThreadHost::Type::kIo | ThreadHost::Type::kUi));
TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(),
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell);
PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell] {
auto platform_view = shell->GetPlatformView();
// The construtor for ViewportMetrics{_, width, _, _, _} (only the 2nd
// argument matters in this test).
platform_view->SetViewportMetrics(0, ViewportMetrics{1, 10, 1, 0, 0});
shell->AddView(1, ViewportMetrics{1, 30, 1, 0, 0});
platform_view->SetViewportMetrics(0, ViewportMetrics{1, 20, 1, 0, 0});
});
bool first_report = true;
std::map<int64_t, int64_t> viewWidths;
fml::AutoResetWaitableEvent reportLatch;
auto nativeViewWidthsCallback = [&reportLatch, &viewWidths,
&first_report](Dart_NativeArguments args) {
EXPECT_TRUE(first_report);
first_report = false;
ParseViewWidthsCallback(args, &viewWidths);
reportLatch.Signal();
};
AddNativeCallback("NativeReportViewWidthsCallback",
CREATE_NATIVE_ENTRY(nativeViewWidthsCallback));
PlatformViewNotifyCreated(shell.get());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("testReportViewWidths");
RunEngine(shell.get(), std::move(configuration));
reportLatch.Wait();
EXPECT_EQ(viewWidths.size(), 2u);
EXPECT_EQ(viewWidths[0], 20ll);
EXPECT_EQ(viewWidths[1], 30ll);
PlatformViewNotifyDestroyed(shell.get());
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, RuntimeStageBackendDefaultsToSkSLWithoutImpeller) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
settings.enable_impeller = false;
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
"io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster |
ThreadHost::Type::kIo | ThreadHost::Type::kUi));
TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(),
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell);
fml::AutoResetWaitableEvent latch;
AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&latch](auto args) {
auto backend =
UIDartState::Current()->GetRuntimeStageBackend();
EXPECT_EQ(backend, impeller::RuntimeStageBackend::kSkSL);
latch.Signal();
}));
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("mainNotifyNative");
RunEngine(shell.get(), std::move(configuration));
latch.Wait();
DestroyShell(std::move(shell), task_runners);
}
#if IMPELLER_SUPPORTS_RENDERING
TEST_F(ShellTest, RuntimeStageBackendWithImpeller) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
Settings settings = CreateSettingsForFixture();
settings.enable_impeller = true;
ThreadHost thread_host(ThreadHost::ThreadHostConfig(
"io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster |
ThreadHost::Type::kIo | ThreadHost::Type::kUi));
TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(),
thread_host.raster_thread->GetTaskRunner(),
thread_host.ui_thread->GetTaskRunner(),
thread_host.io_thread->GetTaskRunner());
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell);
fml::AutoResetWaitableEvent latch;
impeller::Context::BackendType impeller_backend;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[platform_view = shell->GetPlatformView(), &latch, &impeller_backend]() {
auto impeller_context = platform_view->GetImpellerContext();
EXPECT_TRUE(impeller_context);
impeller_backend = impeller_context->GetBackendType();
latch.Signal();
});
latch.Wait();
AddNativeCallback(
"NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) {
auto backend = UIDartState::Current()->GetRuntimeStageBackend();
switch (impeller_backend) {
case impeller::Context::BackendType::kMetal:
EXPECT_EQ(backend, impeller::RuntimeStageBackend::kMetal);
break;
case impeller::Context::BackendType::kOpenGLES:
EXPECT_EQ(backend, impeller::RuntimeStageBackend::kOpenGLES);
break;
case impeller::Context::BackendType::kVulkan:
EXPECT_EQ(backend, impeller::RuntimeStageBackend::kVulkan);
break;
}
latch.Signal();
}));
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("mainNotifyNative");
RunEngine(shell.get(), std::move(configuration));
latch.Wait();
DestroyShell(std::move(shell), task_runners);
}
#endif // IMPELLER_SUPPORTS_RENDERING
} // namespace testing
} // namespace flutter
// NOLINTEND(clang-analyzer-core.StackAddressEscape)
| engine/shell/common/shell_unittests.cc/0 | {
"file_path": "engine/shell/common/shell_unittests.cc",
"repo_id": "engine",
"token_count": 73002
} | 341 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_DISPLAY_H_
#define FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_DISPLAY_H_
#include <optional>
#include "display.h"
#include "flutter/fml/macros.h"
#include "variable_refresh_rate_reporter.h"
namespace flutter {
/// A Display where the refresh rate can change over time.
class VariableRefreshRateDisplay : public Display {
public:
explicit VariableRefreshRateDisplay(
DisplayId display_id,
const std::weak_ptr<VariableRefreshRateReporter>& refresh_rate_reporter,
double width,
double height,
double device_pixel_ratio);
~VariableRefreshRateDisplay() = default;
// |Display|
double GetRefreshRate() const override;
private:
const std::weak_ptr<VariableRefreshRateReporter> refresh_rate_reporter_;
FML_DISALLOW_COPY_AND_ASSIGN(VariableRefreshRateDisplay);
};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_DISPLAY_H_
| engine/shell/common/variable_refresh_rate_display.h/0 | {
"file_path": "engine/shell/common/variable_refresh_rate_display.h",
"repo_id": "engine",
"token_count": 388
} | 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.
#ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_GL_IMPELLER_H_
#define FLUTTER_SHELL_GPU_GPU_SURFACE_GL_IMPELLER_H_
#include "flutter/common/graphics/gl_context_switch.h"
#include "flutter/flow/surface.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/impeller/aiks/aiks_context.h"
#include "flutter/impeller/renderer/context.h"
#include "flutter/shell/gpu/gpu_surface_gl_delegate.h"
namespace flutter {
class GPUSurfaceGLImpeller final : public Surface {
public:
explicit GPUSurfaceGLImpeller(GPUSurfaceGLDelegate* delegate,
std::shared_ptr<impeller::Context> context,
bool render_to_surface);
// |Surface|
~GPUSurfaceGLImpeller() override;
// |Surface|
bool IsValid() override;
private:
GPUSurfaceGLDelegate* delegate_ = nullptr;
std::shared_ptr<impeller::Context> impeller_context_;
bool render_to_surface_ = true;
std::shared_ptr<impeller::Renderer> impeller_renderer_;
std::shared_ptr<impeller::AiksContext> aiks_context_;
bool is_valid_ = false;
fml::TaskRunnerAffineWeakPtrFactory<GPUSurfaceGLImpeller> weak_factory_;
// |Surface|
std::unique_ptr<SurfaceFrame> AcquireFrame(const SkISize& size) override;
// |Surface|
SkMatrix GetRootTransformation() const override;
// |Surface|
GrDirectContext* GetContext() override;
// |Surface|
std::unique_ptr<GLContextResult> MakeRenderContextCurrent() override;
// |Surface|
bool ClearRenderContext() override;
// |Surface|
bool AllowsDrawingWhenGpuDisabled() const override;
// |Surface|
bool EnableRasterCache() const override;
// |Surface|
std::shared_ptr<impeller::AiksContext> GetAiksContext() const override;
FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceGLImpeller);
};
} // namespace flutter
#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_GL_IMPELLER_H_
| engine/shell/gpu/gpu_surface_gl_impeller.h/0 | {
"file_path": "engine/shell/gpu/gpu_surface_gl_impeller.h",
"repo_id": "engine",
"token_count": 779
} | 343 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_SKIA_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_SKIA_H_
#include <jni.h>
#include <memory>
#include "flutter/fml/macros.h"
#include "flutter/shell/gpu/gpu_surface_gl_skia.h"
#include "flutter/shell/platform/android/android_context_gl_skia.h"
#include "flutter/shell/platform/android/android_environment_gl.h"
#include "flutter/shell/platform/android/jni/platform_view_android_jni.h"
#include "flutter/shell/platform/android/surface/android_surface.h"
namespace flutter {
class AndroidSurfaceGLSkia final : public GPUSurfaceGLDelegate,
public AndroidSurface {
public:
explicit AndroidSurfaceGLSkia(
const std::shared_ptr<AndroidContextGLSkia>& android_context);
~AndroidSurfaceGLSkia() override;
// |AndroidSurface|
bool IsValid() const override;
// |AndroidSurface|
std::unique_ptr<Surface> CreateGPUSurface(
GrDirectContext* gr_context) override;
// |AndroidSurface|
void TeardownOnScreenContext() override;
// |AndroidSurface|
bool OnScreenSurfaceResize(const SkISize& size) override;
// |AndroidSurface|
bool ResourceContextMakeCurrent() override;
// |AndroidSurface|
bool ResourceContextClearCurrent() override;
// |AndroidSurface|
bool SetNativeWindow(fml::RefPtr<AndroidNativeWindow> window) override;
// |AndroidSurface|
virtual std::unique_ptr<Surface> CreateSnapshotSurface() override;
// |GPUSurfaceGLDelegate|
std::unique_ptr<GLContextResult> GLContextMakeCurrent() override;
// |GPUSurfaceGLDelegate|
bool GLContextClearCurrent() override;
// |GPUSurfaceGLDelegate|
SurfaceFrame::FramebufferInfo GLContextFramebufferInfo() const override;
// |GPUSurfaceGLDelegate|
void GLContextSetDamageRegion(const std::optional<SkIRect>& region) override;
// |GPUSurfaceGLDelegate|
bool GLContextPresent(const GLPresentInfo& present_info) override;
// |GPUSurfaceGLDelegate|
GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const override;
// |GPUSurfaceGLDelegate|
sk_sp<const GrGLInterface> GetGLInterface() const override;
// Obtain a raw pointer to the on-screen AndroidEGLSurface.
//
// This method is intended for use in tests. Callers must not
// delete the returned pointer.
AndroidEGLSurface* GetOnscreenSurface() const {
return onscreen_surface_.get();
}
private:
std::shared_ptr<AndroidContextGLSkia> android_context_;
fml::RefPtr<AndroidNativeWindow> native_window_;
std::unique_ptr<AndroidEGLSurface> onscreen_surface_;
std::unique_ptr<AndroidEGLSurface> offscreen_surface_;
FML_DISALLOW_COPY_AND_ASSIGN(AndroidSurfaceGLSkia);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_SKIA_H_
| engine/shell/platform/android/android_surface_gl_skia.h/0 | {
"file_path": "engine/shell/platform/android/android_surface_gl_skia.h",
"repo_id": "engine",
"token_count": 1012
} | 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/android/external_view_embedder/surface_pool.h"
#include <utility>
namespace flutter {
OverlayLayer::OverlayLayer(int id,
std::unique_ptr<AndroidSurface> android_surface,
std::unique_ptr<Surface> surface)
: id(id),
android_surface(std::move(android_surface)),
surface(std::move(surface)){};
OverlayLayer::~OverlayLayer() = default;
SurfacePool::SurfacePool() = default;
SurfacePool::~SurfacePool() = default;
std::shared_ptr<OverlayLayer> SurfacePool::GetLayer(
GrDirectContext* gr_context,
const AndroidContext& android_context,
const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade,
const std::shared_ptr<AndroidSurfaceFactory>& surface_factory) {
std::lock_guard lock(mutex_);
// Destroy current layers in the pool if the frame size has changed.
if (requested_frame_size_ != current_frame_size_) {
DestroyLayersLocked(jni_facade);
}
intptr_t gr_context_key = reinterpret_cast<intptr_t>(gr_context);
// Allocate a new surface if there isn't one available.
if (available_layer_index_ >= layers_.size()) {
std::unique_ptr<AndroidSurface> android_surface =
surface_factory->CreateSurface();
FML_CHECK(android_surface && android_surface->IsValid())
<< "Could not create an OpenGL, Vulkan or Software surface to set up "
"rendering.";
std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata> java_metadata =
jni_facade->FlutterViewCreateOverlaySurface();
FML_CHECK(java_metadata->window);
android_surface->SetNativeWindow(java_metadata->window);
std::unique_ptr<Surface> surface =
android_surface->CreateGPUSurface(gr_context);
std::shared_ptr<OverlayLayer> layer =
std::make_shared<OverlayLayer>(java_metadata->id, //
std::move(android_surface), //
std::move(surface) //
);
layer->gr_context_key = gr_context_key;
layers_.push_back(layer);
}
std::shared_ptr<OverlayLayer> layer = layers_[available_layer_index_];
// Since the surfaces are recycled, it's possible that the GrContext is
// different.
if (gr_context_key != layer->gr_context_key) {
layer->gr_context_key = gr_context_key;
// The overlay already exists, but the GrContext was changed so we need to
// recreate the rendering surface with the new GrContext.
std::unique_ptr<Surface> surface =
layer->android_surface->CreateGPUSurface(gr_context);
layer->surface = std::move(surface);
}
available_layer_index_++;
current_frame_size_ = requested_frame_size_;
return layer;
}
void SurfacePool::RecycleLayers() {
std::lock_guard lock(mutex_);
available_layer_index_ = 0;
}
bool SurfacePool::HasLayers() {
std::lock_guard lock(mutex_);
return !layers_.empty();
}
void SurfacePool::DestroyLayers(
const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) {
std::lock_guard lock(mutex_);
DestroyLayersLocked(jni_facade);
}
void SurfacePool::DestroyLayersLocked(
const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) {
if (layers_.empty()) {
return;
}
jni_facade->FlutterViewDestroyOverlaySurfaces();
layers_.clear();
available_layer_index_ = 0;
}
std::vector<std::shared_ptr<OverlayLayer>> SurfacePool::GetUnusedLayers() {
std::lock_guard lock(mutex_);
std::vector<std::shared_ptr<OverlayLayer>> results;
for (size_t i = available_layer_index_; i < layers_.size(); i++) {
results.push_back(layers_[i]);
}
return results;
}
void SurfacePool::SetFrameSize(SkISize frame_size) {
std::lock_guard lock(mutex_);
requested_frame_size_ = frame_size;
}
} // namespace flutter
| engine/shell/platform/android/external_view_embedder/surface_pool.cc/0 | {
"file_path": "engine/shell/platform/android/external_view_embedder/surface_pool.cc",
"repo_id": "engine",
"token_count": 1479
} | 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.
package io.flutter;
/** A replacement of utilities from android.os.Build. */
public class Build {
/** For use in place of the Android Build.VERSION_CODES class. */
public static class API_LEVELS {
public static final int API_21 = 21;
public static final int API_22 = 22;
public static final int API_23 = 23;
public static final int API_24 = 24;
public static final int API_25 = 25;
public static final int API_26 = 26;
public static final int API_27 = 27;
public static final int API_28 = 28;
public static final int API_29 = 29;
public static final int API_30 = 30;
public static final int API_31 = 31;
public static final int API_32 = 32;
public static final int API_33 = 33;
public static final int API_34 = 34;
public static final int API_35 = 35;
}
}
| engine/shell/platform/android/io/flutter/Build.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/Build.java",
"repo_id": "engine",
"token_count": 315
} | 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.
package io.flutter.embedding.android;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import io.flutter.embedding.engine.FlutterEngine;
/**
* Configures a {@link io.flutter.embedding.engine.FlutterEngine} after it is created, e.g., adds
* plugins.
*
* <p>This interface may be applied to a {@link androidx.fragment.app.FragmentActivity} that owns a
* {@code FlutterFragment}.
*/
public interface FlutterEngineConfigurator {
/**
* Configures the given {@link io.flutter.embedding.engine.FlutterEngine}.
*
* <p>This method is called after the given {@link io.flutter.embedding.engine.FlutterEngine} has
* been attached to the owning {@code FragmentActivity}. See {@link
* io.flutter.embedding.engine.plugins.activity.ActivityControlSurface#attachToActivity(
* ExclusiveAppComponent, Lifecycle)}.
*
* <p>It is possible that the owning {@code FragmentActivity} opted not to connect itself as an
* {@link io.flutter.embedding.engine.plugins.activity.ActivityControlSurface}. In that case, any
* configuration, e.g., plugins, must not expect or depend upon an available {@code Activity} at
* the time that this method is invoked.
*
* @param flutterEngine The Flutter engine.
*/
void configureFlutterEngine(@NonNull FlutterEngine flutterEngine);
/**
* Cleans up references that were established in {@link #configureFlutterEngine(FlutterEngine)}
* before the host is destroyed or detached.
*
* @param flutterEngine The Flutter engine.
*/
void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine);
}
| engine/shell/platform/android/io/flutter/embedding/android/FlutterEngineConfigurator.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/android/FlutterEngineConfigurator.java",
"repo_id": "engine",
"token_count": 535
} | 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.
package io.flutter.embedding.android;
/**
* Transparency mode for a Flutter UI.
*
* <p>{@code TransparencyMode} impacts the visual behavior and performance of a {@link
* FlutterSurfaceView}, which is displayed when a Flutter UI uses {@link RenderMode#surface}.
*
* <p>{@code TransparencyMode} does not impact {@link FlutterTextureView}, which is displayed when a
* Flutter UI uses {@link RenderMode#texture}, because a {@link FlutterTextureView} automatically
* comes with transparency.
*/
public enum TransparencyMode {
/**
* Renders a Flutter UI without any transparency. This affects Flutter UI's with {@link
* RenderMode#surface} by introducing a base color of black, and places the {@link
* FlutterSurfaceView}'s {@code Window} behind all other content.
*
* <p>In {@link RenderMode#surface}, this mode is the most performant and is a good choice for
* fullscreen Flutter UIs that will not undergo {@code Fragment} transactions. If this mode is
* used within a {@code Fragment}, and that {@code Fragment} is replaced by another one, a brief
* black flicker may be visible during the switch.
*/
opaque,
/**
* Renders a Flutter UI with transparency. This affects Flutter UI's in {@link RenderMode#surface}
* by allowing background transparency, and places the {@link FlutterSurfaceView}'s {@code Window}
* on top of all other content.
*
* <p>In {@link RenderMode#surface}, this mode is less performant than {@link #opaque}, but this
* mode avoids the black flicker problem that {@link #opaque} has when going through {@code
* Fragment} transactions. Consider using this {@code TransparencyMode} if you intend to switch
* {@code Fragment}s at runtime that contain a Flutter UI.
*/
transparent
}
| engine/shell/platform/android/io/flutter/embedding/android/TransparencyMode.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/android/TransparencyMode.java",
"repo_id": "engine",
"token_count": 550
} | 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.
package io.flutter.embedding.engine.loader;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import androidx.annotation.NonNull;
import java.io.IOException;
import org.json.JSONArray;
import org.xmlpull.v1.XmlPullParserException;
/** Loads application information given a Context. */
public final class ApplicationInfoLoader {
// XML Attribute keys supported in AndroidManifest.xml
public static final String PUBLIC_AOT_SHARED_LIBRARY_NAME =
FlutterLoader.class.getName() + '.' + FlutterLoader.AOT_SHARED_LIBRARY_NAME;
public static final String PUBLIC_VM_SNAPSHOT_DATA_KEY =
FlutterLoader.class.getName() + '.' + FlutterLoader.VM_SNAPSHOT_DATA_KEY;
public static final String PUBLIC_ISOLATE_SNAPSHOT_DATA_KEY =
FlutterLoader.class.getName() + '.' + FlutterLoader.ISOLATE_SNAPSHOT_DATA_KEY;
public static final String PUBLIC_FLUTTER_ASSETS_DIR_KEY =
FlutterLoader.class.getName() + '.' + FlutterLoader.FLUTTER_ASSETS_DIR_KEY;
public static final String NETWORK_POLICY_METADATA_KEY = "io.flutter.network-policy";
public static final String PUBLIC_AUTOMATICALLY_REGISTER_PLUGINS_METADATA_KEY =
"io.flutter." + FlutterLoader.AUTOMATICALLY_REGISTER_PLUGINS_KEY;
@NonNull
private static ApplicationInfo getApplicationInfo(@NonNull Context applicationContext) {
try {
return applicationContext
.getPackageManager()
.getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
}
private static String getString(Bundle metadata, String key) {
if (metadata == null) {
return null;
}
return metadata.getString(key, null);
}
private static boolean getBoolean(Bundle metadata, String key, boolean defaultValue) {
if (metadata == null) {
return defaultValue;
}
return metadata.getBoolean(key, defaultValue);
}
private static String getNetworkPolicy(ApplicationInfo appInfo, Context context) {
// We cannot use reflection to look at networkSecurityConfigRes because
// Android throws an error when we try to access fields marked as This member is not intended
// for public use, and is only visible for testing..
// Instead we rely on metadata.
Bundle metadata = appInfo.metaData;
if (metadata == null) {
return null;
}
int networkSecurityConfigRes = metadata.getInt(NETWORK_POLICY_METADATA_KEY, 0);
if (networkSecurityConfigRes <= 0) {
return null;
}
JSONArray output = new JSONArray();
try {
XmlResourceParser xrp = context.getResources().getXml(networkSecurityConfigRes);
xrp.next();
int eventType = xrp.getEventType();
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
if (xrp.getName().equals("domain-config")) {
parseDomainConfig(xrp, output, false);
}
}
eventType = xrp.next();
}
} catch (IOException | XmlPullParserException e) {
return null;
}
return output.toString();
}
private static void parseDomainConfig(
XmlResourceParser xrp, JSONArray output, boolean inheritedCleartextPermitted)
throws IOException, XmlPullParserException {
boolean cleartextTrafficPermitted =
xrp.getAttributeBooleanValue(
null, "cleartextTrafficPermitted", inheritedCleartextPermitted);
while (true) {
int eventType = xrp.next();
if (eventType == XmlResourceParser.START_TAG) {
if (xrp.getName().equals("domain")) {
// There can be multiple domains.
parseDomain(xrp, output, cleartextTrafficPermitted);
} else if (xrp.getName().equals("domain-config")) {
parseDomainConfig(xrp, output, cleartextTrafficPermitted);
} else {
skipTag(xrp);
}
} else if (eventType == XmlResourceParser.END_TAG) {
break;
}
}
}
private static void skipTag(XmlResourceParser xrp) throws IOException, XmlPullParserException {
String name = xrp.getName();
int eventType = xrp.getEventType();
while (eventType != XmlResourceParser.END_TAG || xrp.getName() != name) {
eventType = xrp.next();
}
}
private static void parseDomain(
XmlResourceParser xrp, JSONArray output, boolean cleartextPermitted)
throws IOException, XmlPullParserException {
boolean includeSubDomains = xrp.getAttributeBooleanValue(null, "includeSubdomains", false);
xrp.next();
if (xrp.getEventType() != XmlResourceParser.TEXT) {
throw new IllegalStateException("Expected text");
}
String domain = xrp.getText().trim();
JSONArray outputArray = new JSONArray();
outputArray.put(domain);
outputArray.put(includeSubDomains);
outputArray.put(cleartextPermitted);
output.put(outputArray);
xrp.next();
if (xrp.getEventType() != XmlResourceParser.END_TAG) {
throw new IllegalStateException("Expected end of domain tag");
}
}
/**
* Initialize our Flutter config values by obtaining them from the manifest XML file, falling back
* to default values.
*/
@NonNull
public static FlutterApplicationInfo load(@NonNull Context applicationContext) {
ApplicationInfo appInfo = getApplicationInfo(applicationContext);
return new FlutterApplicationInfo(
getString(appInfo.metaData, PUBLIC_AOT_SHARED_LIBRARY_NAME),
getString(appInfo.metaData, PUBLIC_VM_SNAPSHOT_DATA_KEY),
getString(appInfo.metaData, PUBLIC_ISOLATE_SNAPSHOT_DATA_KEY),
getString(appInfo.metaData, PUBLIC_FLUTTER_ASSETS_DIR_KEY),
getNetworkPolicy(appInfo, applicationContext),
appInfo.nativeLibraryDir,
getBoolean(appInfo.metaData, PUBLIC_AUTOMATICALLY_REGISTER_PLUGINS_METADATA_KEY, true));
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/loader/ApplicationInfoLoader.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/loader/ApplicationInfoLoader.java",
"repo_id": "engine",
"token_count": 2225
} | 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.
package io.flutter.embedding.engine.plugins.contentprovider;
import android.content.ContentProvider;
import androidx.annotation.NonNull;
/**
* Binding that gives {@link ContentProviderAware} plugins access to an associated {@link
* ContentProvider}.
*/
public interface ContentProviderPluginBinding {
/**
* Returns the {@link ContentProvider} that is currently attached to the {@link
* io.flutter.embedding.engine.FlutterEngine} that owns this {@code
* ContentProviderAwarePluginBinding}.
*/
@NonNull
ContentProvider getContentProvider();
}
| engine/shell/platform/android/io/flutter/embedding/engine/plugins/contentprovider/ContentProviderPluginBinding.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/contentprovider/ContentProviderPluginBinding.java",
"repo_id": "engine",
"token_count": 200
} | 350 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.embedding.engine.systemchannels;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.StandardMethodCodec;
import java.util.HashMap;
import java.util.Map;
/**
* Event message channel for keyboard events to/from the Flutter framework.
*
* <p>Receives asynchronous messages from the framework to query the engine known pressed state.
*/
public class KeyboardChannel {
public final MethodChannel channel;
private KeyboardMethodHandler keyboardMethodHandler;
@NonNull
public final MethodChannel.MethodCallHandler parsingMethodHandler =
new MethodChannel.MethodCallHandler() {
Map<Long, Long> pressedState = new HashMap<>();
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
if (keyboardMethodHandler == null) {
// Returns an empty pressed state when the engine did not get a chance to register
// a method handler for this channel.
result.success(pressedState);
} else {
switch (call.method) {
case "getKeyboardState":
try {
pressedState = keyboardMethodHandler.getKeyboardState();
} catch (IllegalStateException exception) {
result.error("error", exception.getMessage(), null);
}
result.success(pressedState);
break;
default:
result.notImplemented();
break;
}
}
}
};
public KeyboardChannel(@NonNull BinaryMessenger messenger) {
channel = new MethodChannel(messenger, "flutter/keyboard", StandardMethodCodec.INSTANCE);
channel.setMethodCallHandler(parsingMethodHandler);
}
/**
* Sets the {@link KeyboardMethodHandler} which receives all requests to query the keyboard state.
*/
public void setKeyboardMethodHandler(@Nullable KeyboardMethodHandler keyboardMethodHandler) {
this.keyboardMethodHandler = keyboardMethodHandler;
}
public interface KeyboardMethodHandler {
/**
* Returns the keyboard pressed states.
*
* @return A map whose keys are physical keyboard key IDs and values are the corresponding
* logical keyboard key IDs.
*/
Map<Long, Long> getKeyboardState();
}
}
| engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/KeyboardChannel.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/KeyboardChannel.java",
"repo_id": "engine",
"token_count": 950
} | 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.
package io.flutter.plugin.common;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import java.nio.ByteBuffer;
/**
* Facility for communicating with Flutter using asynchronous message passing with binary messages.
* The Flutter Dart code should use <a
* href="https://api.flutter.dev/flutter/services/BinaryMessages-class.html">BinaryMessages</a> to
* participate.
*
* <p>{@code BinaryMessenger} is expected to be utilized from a single thread throughout the
* duration of its existence. If created on the main thread, then all invocations should take place
* on the main thread. If created on a background thread, then all invocations should take place on
* that background thread.
*
* @see BasicMessageChannel , which supports message passing with Strings and semi-structured
* messages.
* @see MethodChannel , which supports communication using asynchronous method invocation.
* @see EventChannel , which supports communication using event streams.
*/
public interface BinaryMessenger {
/**
* An abstraction over the threading policy used to invoke message handlers.
*
* <p>These are generated by calling methods like {@link
* BinaryMessenger#makeBackgroundTaskQueue(TaskQueueOptions)} and can be passed into platform
* channels' constructors to control the threading policy for handling platform channels'
* messages.
*/
public interface TaskQueue {}
/** Options that control how a TaskQueue should operate and be created. */
public static class TaskQueueOptions {
private boolean isSerial = true;
public boolean getIsSerial() {
return isSerial;
}
/**
* Setter for `isSerial` property.
*
* <p>When this is true all tasks performed by the TaskQueue will be forced to happen serially
* (one completes before the other begins).
*/
public TaskQueueOptions setIsSerial(boolean isSerial) {
this.isSerial = isSerial;
return this;
}
}
/**
* Creates a TaskQueue that executes the tasks serially on a background thread.
*
* <p>There is no guarantee that the tasks will execute on the same thread, just that execution is
* serial. This is could be problematic if your code relies on ThreadLocal storage or
* introspection about what thread is actually executing.
*/
@UiThread
default TaskQueue makeBackgroundTaskQueue() {
return makeBackgroundTaskQueue(new TaskQueueOptions());
}
/**
* Creates a TaskQueue that executes the tasks serially on a background thread.
*
* <p>{@link TaskQueueOptions} can be used to configure the task queue to execute tasks
* concurrently. Doing so can be more performant, though users need to ensure that the task
* handlers are thread-safe.
*/
@UiThread
default TaskQueue makeBackgroundTaskQueue(TaskQueueOptions options) {
// TODO(92582): Remove default implementation when it is safe for Google Flutter users.
throw new UnsupportedOperationException("makeBackgroundTaskQueue not implemented.");
}
/**
* Sends a binary message to the Flutter application.
*
* @param channel the name {@link String} of the logical channel used for the message.
* @param message the message payload, a direct-allocated {@link ByteBuffer} with the message
* bytes between position zero and current position, or null.
*/
@UiThread
void send(@NonNull String channel, @Nullable ByteBuffer message);
/**
* Sends a binary message to the Flutter application, optionally expecting a reply.
*
* <p>Any uncaught exception thrown by the reply callback will be caught and logged.
*
* @param channel the name {@link String} of the logical channel used for the message.
* @param message the message payload, a direct-allocated {@link ByteBuffer} with the message
* bytes between position zero and current position, or null.
* @param callback a {@link BinaryReply} callback invoked when the Flutter application responds to
* the message, possibly null.
*/
@UiThread
void send(@NonNull String channel, @Nullable ByteBuffer message, @Nullable BinaryReply callback);
/**
* Registers a handler to be invoked when the Flutter application sends a message to its host
* platform.
*
* <p>Registration overwrites any previous registration for the same channel name. Use a null
* handler to deregister.
*
* <p>If no handler has been registered for a particular channel, any incoming message on that
* channel will be handled silently by sending a null reply.
*
* @param channel the name {@link String} of the channel.
* @param handler a {@link BinaryMessageHandler} to be invoked on incoming messages, or null.
*/
@UiThread
void setMessageHandler(@NonNull String channel, @Nullable BinaryMessageHandler handler);
/**
* Registers a handler to be invoked when the Flutter application sends a message to its host
* platform.
*
* <p>Registration overwrites any previous registration for the same channel name. Use a null
* handler to deregister.
*
* <p>If no handler has been registered for a particular channel, any incoming message on that
* channel will be handled silently by sending a null reply.
*
* @param channel the name {@link String} of the channel.
* @param handler a {@link BinaryMessageHandler} to be invoked on incoming messages, or null.
* @param taskQueue a {@link BinaryMessenger.TaskQueue} that specifies what thread will execute
* the handler. Specifying null means execute on the platform thread.
*/
@UiThread
default void setMessageHandler(
@NonNull String channel,
@Nullable BinaryMessageHandler handler,
@Nullable TaskQueue taskQueue) {
// TODO(92582): Remove default implementation when it is safe for Google Flutter users.
if (taskQueue != null) {
throw new UnsupportedOperationException(
"setMessageHandler called with nonnull taskQueue is not supported.");
}
setMessageHandler(channel, handler);
}
/**
* Enables the ability to queue messages received from Dart.
*
* <p>This is useful when there are pending channel handler registrations. For example, Dart may
* be initialized concurrently, and prior to the registration of the channel handlers. This
* implies that Dart may start sending messages while plugins are being registered.
*/
default void enableBufferingIncomingMessages() {
throw new UnsupportedOperationException("enableBufferingIncomingMessages not implemented.");
}
/**
* Disables the ability to queue messages received from Dart.
*
* <p>This can be used after all pending channel handlers have been registered.
*/
default void disableBufferingIncomingMessages() {
throw new UnsupportedOperationException("disableBufferingIncomingMessages not implemented.");
}
/** Handler for incoming binary messages from Flutter. */
interface BinaryMessageHandler {
/**
* Handles the specified message.
*
* <p>Handler implementations must reply to all incoming messages, by submitting a single reply
* message to the given {@link BinaryReply}. Failure to do so will result in lingering Flutter
* reply handlers. The reply may be submitted asynchronously.
*
* <p>Any uncaught exception thrown by this method will be caught by the messenger
* implementation and logged, and a null reply message will be sent back to Flutter.
*
* @param message the message {@link ByteBuffer} payload, possibly null.
* @param reply A {@link BinaryReply} used for submitting a reply back to Flutter.
*/
@UiThread
void onMessage(@Nullable ByteBuffer message, @NonNull BinaryReply reply);
}
/**
* Binary message reply callback. Used to submit a reply to an incoming message from Flutter. Also
* used in the dual capacity to handle a reply received from Flutter after sending a message.
*/
interface BinaryReply {
/**
* Handles the specified reply.
*
* @param reply the reply payload, a direct-allocated {@link ByteBuffer} or null. Senders of
* outgoing replies must place the reply bytes between position zero and current position.
* Reply receivers can read from the buffer directly.
*/
void reply(@Nullable ByteBuffer reply);
}
}
| engine/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.java",
"repo_id": "engine",
"token_count": 2364
} | 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.
package io.flutter.plugin.editing;
import static io.flutter.Build.API_LEVELS;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Insets;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowInsetsAnimation;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import java.util.List;
// Loosely based off of
// https://github.com/android/user-interface-samples/blob/main/WindowInsetsAnimation/app/src/main/java/com/google/android/samples/insetsanimation/RootViewDeferringInsetsCallback.kt
//
// When the IME is shown or hidden, it immediately sends an onApplyWindowInsets call
// with the final state of the IME. This initial call disrupts the animation, which
// causes a flicker in the beginning.
//
// To fix this, this class extends WindowInsetsAnimation.Callback and implements
// OnApplyWindowInsetsListener. We capture and defer the initial call to
// onApplyWindowInsets while the animation completes. When the animation
// finishes, we can then release the call by invoking it in the onEnd callback
//
// The WindowInsetsAnimation.Callback extension forwards the new state of the
// IME inset from onProgress() to the framework. We also make use of the
// onStart callback to detect which calls to onApplyWindowInsets would
// interrupt the animation and defer it.
//
// By implementing OnApplyWindowInsetsListener, we are able to capture Android's
// attempts to call the FlutterView's onApplyWindowInsets. When a call to onStart
// occurs, we can mark any non-animation calls to onApplyWindowInsets() that
// occurs between prepare and start as deferred by using this class' wrapper
// implementation to cache the WindowInsets passed in and turn the current call into
// a no-op. When onEnd indicates the end of the animation, the deferred call is
// dispatched again, this time avoiding any flicker since the animation is now
// complete.
@VisibleForTesting
@TargetApi(API_LEVELS.API_30)
@RequiresApi(API_LEVELS.API_30)
@SuppressLint({"NewApi", "Override"})
@Keep
class ImeSyncDeferringInsetsCallback {
private final int deferredInsetTypes = WindowInsets.Type.ime();
private View view;
private WindowInsets lastWindowInsets;
private AnimationCallback animationCallback;
private InsetsListener insetsListener;
// True when an animation that matches deferredInsetTypes is active.
//
// While this is active, this class will capture the initial window inset
// sent into lastWindowInsets by flagging needsSave to true, and will hold
// onto the intitial inset until the animation is completed, when it will
// re-dispatch the inset change.
private boolean animating = false;
// When an animation begins, android sends a WindowInset with the final
// state of the animation. When needsSave is true, we know to capture this
// initial WindowInset.
//
// Certain actions, like dismissing the keyboard, can trigger multiple
// animations that are slightly offset in start time. To capture the
// correct final insets in these situations we update needsSave to true
// in each onPrepare callback, so that we save the latest final state
// to apply in onEnd.
private boolean needsSave = false;
ImeSyncDeferringInsetsCallback(@NonNull View view) {
this.view = view;
this.animationCallback = new AnimationCallback();
this.insetsListener = new InsetsListener();
}
// Add this object's event listeners to its view.
void install() {
view.setWindowInsetsAnimationCallback(animationCallback);
view.setOnApplyWindowInsetsListener(insetsListener);
}
// Remove this object's event listeners from its view.
void remove() {
view.setWindowInsetsAnimationCallback(null);
view.setOnApplyWindowInsetsListener(null);
}
@VisibleForTesting
View.OnApplyWindowInsetsListener getInsetsListener() {
return insetsListener;
}
@VisibleForTesting
WindowInsetsAnimation.Callback getAnimationCallback() {
return animationCallback;
}
// WindowInsetsAnimation.Callback was introduced in API level 30. The callback
// subclass is separated into an inner class in order to avoid warnings from
// the Android class loader on older platforms.
@Keep
private class AnimationCallback extends WindowInsetsAnimation.Callback {
AnimationCallback() {
super(WindowInsetsAnimation.Callback.DISPATCH_MODE_CONTINUE_ON_SUBTREE);
}
@Override
public void onPrepare(WindowInsetsAnimation animation) {
needsSave = true;
if ((animation.getTypeMask() & deferredInsetTypes) != 0) {
animating = true;
}
}
@Override
public WindowInsets onProgress(
WindowInsets insets, List<WindowInsetsAnimation> runningAnimations) {
if (!animating || needsSave) {
return insets;
}
boolean matching = false;
for (WindowInsetsAnimation animation : runningAnimations) {
if ((animation.getTypeMask() & deferredInsetTypes) != 0) {
matching = true;
continue;
}
}
if (!matching) {
return insets;
}
// The IME insets include the height of the navigation bar. If the app isn't laid out behind
// the navigation bar, this causes the IME insets to be too large during the animation.
// To fix this, we subtract the navigationBars bottom inset if the system UI flags for laying
// out behind the navigation bar aren't present.
int excludedInsets = 0;
int systemUiFlags = view.getWindowSystemUiVisibility();
if ((systemUiFlags & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) == 0
&& (systemUiFlags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
excludedInsets = insets.getInsets(WindowInsets.Type.navigationBars()).bottom;
}
WindowInsets.Builder builder = new WindowInsets.Builder(lastWindowInsets);
Insets newImeInsets =
Insets.of(
0, 0, 0, Math.max(insets.getInsets(deferredInsetTypes).bottom - excludedInsets, 0));
builder.setInsets(deferredInsetTypes, newImeInsets);
// Directly call onApplyWindowInsets of the view as we do not want to pass through
// the onApplyWindowInsets defined in this class, which would consume the insets
// as if they were a non-animation inset change and cache it for re-dispatch in
// onEnd instead.
view.onApplyWindowInsets(builder.build());
return insets;
}
@Override
public void onEnd(WindowInsetsAnimation animation) {
if (animating && (animation.getTypeMask() & deferredInsetTypes) != 0) {
// If we deferred the IME insets and an IME animation has finished, we need to reset
// the flags
animating = false;
// And finally dispatch the deferred insets to the view now.
// Ideally we would just call view.requestApplyInsets() and let the normal dispatch
// cycle happen, but this happens too late resulting in a visual flicker.
// Instead we manually dispatch the most recent WindowInsets to the view.
if (lastWindowInsets != null && view != null) {
view.dispatchApplyWindowInsets(lastWindowInsets);
}
}
}
}
private class InsetsListener implements View.OnApplyWindowInsetsListener {
@Override
public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) {
ImeSyncDeferringInsetsCallback.this.view = view;
if (needsSave) {
// Store the view and insets for us in onEnd() below. This captured inset
// is not part of the animation and instead, represents the final state
// of the inset after the animation is completed. Thus, we defer the processing
// of this WindowInset until the animation completes.
lastWindowInsets = windowInsets;
needsSave = false;
}
if (animating) {
// While animation is running, we consume the insets to prevent disrupting
// the animation, which skips this implementation and calls the view's
// onApplyWindowInsets directly to avoid being consumed here.
return WindowInsets.CONSUMED;
}
// If no animation is happening, pass the insets on to the view's own
// inset handling.
return view.onApplyWindowInsets(windowInsets);
}
}
}
| engine/shell/platform/android/io/flutter/plugin/editing/ImeSyncDeferringInsetsCallback.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/editing/ImeSyncDeferringInsetsCallback.java",
"repo_id": "engine",
"token_count": 2695
} | 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.
package io.flutter.plugin.platform;
import android.view.Surface;
/**
* A PlatformViewRenderTarget interface allows an Android Platform View to be rendered into an
* offscreen buffer (usually a texture is involved) that the engine can compose into the
* FlutterView.
*/
public interface PlatformViewRenderTarget {
// Called when the render target should be resized.
public void resize(int width, int height);
// Returns the currently specified width.
public int getWidth();
// Returns the currently specified height.
public int getHeight();
// The id of this render target.
public long getId();
// Releases backing resources.
public void release();
// Returns true in the case that backing resource have been released.
public boolean isReleased();
// Returns the Surface to be rendered on to.
public Surface getSurface();
// Schedules a frame to be drawn.
public default void scheduleFrame() {}
}
| engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewRenderTarget.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewRenderTarget.java",
"repo_id": "engine",
"token_count": 270
} | 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.
package io.flutter.util;
import androidx.annotation.NonNull;
import androidx.tracing.Trace;
public final class TraceSection implements AutoCloseable {
/**
* Factory used to support the try-with-resource construct.
*
* <p>To get scoped trace events, use the try-with-resource construct, for instance:
*
* <pre>{@code
* try (TraceSection e = TraceSection.scoped("MyTraceEvent")) {
* // code.
* }
* }</pre>
*/
public static TraceSection scoped(String name) {
return new TraceSection(name);
}
/** Constructor used to support the try-with-resource construct. */
private TraceSection(String name) {
begin(name);
}
@Override
public void close() {
end();
}
private static String cropSectionName(@NonNull String sectionName) {
return sectionName.length() < 124 ? sectionName : sectionName.substring(0, 124) + "...";
}
/**
* Wraps Trace.beginSection to ensure that the line length stays below 127 code units.
*
* @param sectionName The string to display as the section name in the trace.
*/
public static void begin(@NonNull String sectionName) {
Trace.beginSection(cropSectionName(sectionName));
}
/** Wraps Trace.endSection. */
public static void end() throws RuntimeException {
Trace.endSection();
}
/**
* Wraps Trace.beginAsyncSection to ensure that the line length stays below 127 code units.
*
* @param sectionName The string to display as the section name in the trace.
* @param cookie Unique integer defining the section.
*/
public static void beginAsyncSection(String sectionName, int cookie) {
Trace.beginAsyncSection(cropSectionName(sectionName), cookie);
}
/** Wraps Trace.endAsyncSection to ensure that the line length stays below 127 code units. */
public static void endAsyncSection(String sectionName, int cookie) {
Trace.endAsyncSection(cropSectionName(sectionName), cookie);
}
}
| engine/shell/platform/android/io/flutter/util/TraceSection.java/0 | {
"file_path": "engine/shell/platform/android/io/flutter/util/TraceSection.java",
"repo_id": "engine",
"token_count": 624
} | 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.
#include "flutter/fml/platform/android/jni_util.h"
#include "flutter/shell/platform/android/android_image_generator.h"
#include "flutter/shell/platform/android/flutter_main.h"
#include "flutter/shell/platform/android/platform_view_android.h"
#include "flutter/shell/platform/android/vsync_waiter_android.h"
// This is called by the VM when the shared library is first loaded.
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
// Initialize the Java VM.
fml::jni::InitJavaVM(vm);
JNIEnv* env = fml::jni::AttachCurrentThread();
bool result = false;
// Register FlutterMain.
result = flutter::FlutterMain::Register(env);
FML_CHECK(result);
// Register PlatformView
result = flutter::PlatformViewAndroid::Register(env);
FML_CHECK(result);
// Register VSyncWaiter.
result = flutter::VsyncWaiterAndroid::Register(env);
FML_CHECK(result);
// Register AndroidImageDecoder.
result = flutter::AndroidImageGenerator::Register(env);
FML_CHECK(result);
return JNI_VERSION_1_4;
}
| engine/shell/platform/android/library_loader.cc/0 | {
"file_path": "engine/shell/platform/android/library_loader.cc",
"repo_id": "engine",
"token_count": 378
} | 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_ANDROID_SURFACE_ANDROID_NATIVE_WINDOW_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_NATIVE_WINDOW_H_
#include "flutter/fml/build_config.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/ref_counted.h"
#include "third_party/skia/include/core/SkSize.h"
#if FML_OS_ANDROID
#include <android/native_window.h>
#endif // FML_OS_ANDROID
namespace flutter {
class AndroidNativeWindow
: public fml::RefCountedThreadSafe<AndroidNativeWindow> {
public:
#if FML_OS_ANDROID
using Handle = ANativeWindow*;
#else // FML_OS_ANDROID
using Handle = std::nullptr_t;
#endif // FML_OS_ANDROID
bool IsValid() const;
Handle handle() const;
SkISize GetSize() const;
/// Returns true when this AndroidNativeWindow is not backed by a real window
/// (used for testing).
bool IsFakeWindow() const { return is_fake_window_; }
private:
Handle window_;
const bool is_fake_window_;
/// Creates a native window with the given handle. Handle ownership is assumed
/// by this instance of the native window.
explicit AndroidNativeWindow(Handle window);
explicit AndroidNativeWindow(Handle window, bool is_fake_window);
~AndroidNativeWindow();
FML_FRIEND_MAKE_REF_COUNTED(AndroidNativeWindow);
FML_FRIEND_REF_COUNTED_THREAD_SAFE(AndroidNativeWindow);
FML_DISALLOW_COPY_AND_ASSIGN(AndroidNativeWindow);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_NATIVE_WINDOW_H_
| engine/shell/platform/android/surface/android_native_window.h/0 | {
"file_path": "engine/shell/platform/android/surface/android_native_window.h",
"repo_id": "engine",
"token_count": 572
} | 357 |
package io.flutter.embedding.android;
import static io.flutter.Build.API_LEVELS;
import static junit.framework.TestCase.assertEquals;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.annotation.TargetApi;
import android.content.Context;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.embedding.engine.renderer.FlutterRenderer;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
@TargetApi(API_LEVELS.API_28)
public class AndroidTouchProcessorTest {
@Mock FlutterRenderer mockRenderer;
AndroidTouchProcessor touchProcessor;
@Captor ArgumentCaptor<ByteBuffer> packetCaptor;
@Captor ArgumentCaptor<Integer> packetSizeCaptor;
// Used for mock events in SystemClock.uptimeMillis() time base.
// 2 days in milliseconds
final long eventTimeMilliseconds = 172800000;
final float pressure = 0.8f;
// https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/gestures/events.dart
final int enginePrimaryStylusButton = 0x02;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
touchProcessor = new AndroidTouchProcessor(mockRenderer, false);
}
private long readTimeStamp(ByteBuffer buffer) {
return buffer.getLong(1 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private long readPointerChange(ByteBuffer buffer) {
return buffer.getLong(2 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private long readPointerDeviceKind(ByteBuffer buffer) {
return buffer.getLong(3 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private long readPointerSignalKind(ByteBuffer buffer) {
return buffer.getLong(4 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private long readDevice(ByteBuffer buffer) {
return buffer.getLong(5 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readPointerPhysicalX(ByteBuffer buffer) {
return buffer.getDouble(7 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readPointerPhysicalY(ByteBuffer buffer) {
return buffer.getDouble(8 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private long readButtons(ByteBuffer buffer) {
return buffer.getLong(11 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readObscured(ByteBuffer buffer) {
return buffer.getDouble(12 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readSynthesized(ByteBuffer buffer) {
return buffer.getDouble(13 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readPressure(ByteBuffer buffer) {
return buffer.getDouble(14 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readPressureMin(ByteBuffer buffer) {
return buffer.getDouble(15 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readPressureMax(ByteBuffer buffer) {
return buffer.getDouble(16 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readDistance(ByteBuffer buffer) {
return buffer.getDouble(17 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readDistanceMax(ByteBuffer buffer) {
return buffer.getDouble(18 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readSize(ByteBuffer buffer) {
return buffer.getDouble(19 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readRadiusMajor(ByteBuffer buffer) {
return buffer.getDouble(20 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readRadiusMinor(ByteBuffer buffer) {
return buffer.getDouble(21 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readRadiusMin(ByteBuffer buffer) {
return buffer.getDouble(22 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readRadiusMax(ByteBuffer buffer) {
return buffer.getDouble(23 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readStylusTilt(ByteBuffer buffer) {
return buffer.getDouble(25 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readScrollDeltaX(ByteBuffer buffer) {
return buffer.getDouble(27 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readScrollDeltaY(ByteBuffer buffer) {
return buffer.getDouble(28 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readPointerPanX(ByteBuffer buffer) {
return buffer.getDouble(29 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readPointerPanY(ByteBuffer buffer) {
return buffer.getDouble(30 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readPointerPanDeltaX(ByteBuffer buffer) {
return buffer.getDouble(31 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readPointerPanDeltaY(ByteBuffer buffer) {
return buffer.getDouble(32 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readScale(ByteBuffer buffer) {
return buffer.getDouble(33 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private double readRotation(ByteBuffer buffer) {
return buffer.getDouble(34 * AndroidTouchProcessor.BYTES_PER_FIELD);
}
private class MotionEventMocker {
int pointerId;
int source;
int toolType;
MotionEventMocker(int pointerId, int source, int toolType) {
this.pointerId = pointerId;
this.source = source;
this.toolType = toolType;
}
MotionEvent mockEvent(int action, float x, float y, int buttonState) {
return mockEvent(action, x, y, buttonState, x, y, x, y, x, x, y);
}
MotionEvent mockEvent(
int action,
float x,
float y,
int buttonState,
float hScroll,
float vScroll,
float axisDistance,
float axisTilt,
float size,
float toolMajor,
float toolMinor) {
MotionEvent event = mock(MotionEvent.class);
when(event.getDevice()).thenReturn(null);
when(event.getSource()).thenReturn(source);
when(event.getEventTime()).thenReturn(eventTimeMilliseconds);
when(event.getPointerCount()).thenReturn(1);
when(event.getActionMasked()).thenReturn(action);
final int actionIndex = 0;
when(event.getActionIndex()).thenReturn(actionIndex);
when(event.getButtonState()).thenReturn(buttonState);
when(event.getPointerId(actionIndex)).thenReturn(pointerId);
when(event.getX(actionIndex)).thenReturn(x);
when(event.getY(actionIndex)).thenReturn(y);
when(event.getToolType(actionIndex)).thenReturn(toolType);
when(event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)).thenReturn(true);
when(event.getAxisValue(MotionEvent.AXIS_HSCROLL, pointerId)).thenReturn(hScroll);
when(event.getAxisValue(MotionEvent.AXIS_VSCROLL, pointerId)).thenReturn(vScroll);
when(event.getAxisValue(MotionEvent.AXIS_DISTANCE, pointerId)).thenReturn(axisDistance);
when(event.getAxisValue(MotionEvent.AXIS_TILT, pointerId)).thenReturn(axisTilt);
when(event.getPressure(actionIndex)).thenReturn(pressure);
when(event.getSize(actionIndex)).thenReturn(size);
when(event.getToolMajor(actionIndex)).thenReturn(toolMajor);
when(event.getToolMinor(actionIndex)).thenReturn(toolMinor);
return event;
}
}
@Test
public void normalTouch() {
MotionEventMocker mocker =
new MotionEventMocker(0, InputDevice.SOURCE_TOUCHSCREEN, MotionEvent.TOOL_TYPE_FINGER);
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0));
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.DOWN, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.TOUCH, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(0.0, readPointerPhysicalX(packet));
assertEquals(0.0, readPointerPhysicalY(packet));
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_MOVE, 10.0f, 5.0f, 0));
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.MOVE, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.TOUCH, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(10.0, readPointerPhysicalX(packet));
assertEquals(5.0, readPointerPhysicalY(packet));
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_UP, 10.0f, 5.0f, 0));
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.UP, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.TOUCH, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(10.0, readPointerPhysicalX(packet));
assertEquals(5.0, readPointerPhysicalY(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void trackpadGesture() {
MotionEventMocker mocker =
new MotionEventMocker(1, InputDevice.SOURCE_MOUSE, MotionEvent.TOOL_TYPE_MOUSE);
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0));
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_START, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(0.0, readPointerPhysicalX(packet));
assertEquals(0.0, readPointerPhysicalY(packet));
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_MOVE, 10.0f, 5.0f, 0));
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_UPDATE, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(0.0, readPointerPhysicalX(packet));
assertEquals(0.0, readPointerPhysicalY(packet));
assertEquals(10.0, readPointerPanX(packet));
assertEquals(5.0, readPointerPanY(packet));
// Always zero.
assertEquals(0.0, readPointerPanDeltaX(packet));
assertEquals(0.0, readPointerPanDeltaY(packet));
assertEquals(0.0, readRotation(packet));
// Always 1.
assertEquals(1.0, readScale(packet));
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_UP, 10.0f, 5.0f, 0));
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_END, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(0.0, readPointerPhysicalX(packet));
assertEquals(0.0, readPointerPhysicalY(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void mouse() {
MotionEventMocker mocker =
new MotionEventMocker(2, InputDevice.SOURCE_MOUSE, MotionEvent.TOOL_TYPE_MOUSE);
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 1));
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.DOWN, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.MOUSE, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(0.0, readPointerPhysicalX(packet));
assertEquals(0.0, readPointerPhysicalY(packet));
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_MOVE, 10.0f, 5.0f, 1));
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.MOVE, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.MOUSE, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(10.0, readPointerPhysicalX(packet));
assertEquals(5.0, readPointerPhysicalY(packet));
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_UP, 10.0f, 5.0f, 1));
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.UP, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.MOUSE, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(10.0, readPointerPhysicalX(packet));
assertEquals(5.0, readPointerPhysicalY(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void unexpectedMaskedAction() {
// Regression test for https://github.com/flutter/flutter/issues/111068
MotionEventMocker mocker =
new MotionEventMocker(1, InputDevice.SOURCE_STYLUS, MotionEvent.TOOL_TYPE_STYLUS);
// ACTION_BUTTON_PRESS is not handled by AndroidTouchProcessor, nothing should be dispatched.
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_BUTTON_PRESS, 0.0f, 0.0f, 0));
verify(mockRenderer, never()).dispatchPointerDataPacket(ByteBuffer.allocate(0), 0);
}
@Test
@Config(minSdk = API_LEVELS.API_26)
public void scrollWheelAbove26() {
// Pointer id must be zero to match actionIndex in mocked event.
final int pointerId = 0;
MotionEventMocker mocker =
new MotionEventMocker(
pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE);
final float horizontalScrollValue = -1f;
final float verticalScrollValue = .5f;
final Context context = ApplicationProvider.getApplicationContext();
final double horizontalScaleFactor =
ViewConfiguration.get(context).getScaledHorizontalScrollFactor();
final double verticalScaleFactor =
ViewConfiguration.get(context).getScaledVerticalScrollFactor();
// Zero verticalScaleFactor will cause this test to miss bugs.
assertEquals("zero horizontal scale factor", true, horizontalScaleFactor != 0);
assertEquals("zero vertical scale factor", true, verticalScaleFactor != 0);
final MotionEvent event =
mocker.mockEvent(
MotionEvent.ACTION_SCROLL,
0.0f,
0.0f,
1,
horizontalScrollValue,
verticalScrollValue,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f);
boolean handled = touchProcessor.onGenericMotionEvent(event, context);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
assertEquals(-horizontalScrollValue * horizontalScaleFactor, readScrollDeltaX(packet));
assertEquals(-verticalScrollValue * verticalScaleFactor, readScrollDeltaY(packet));
verify(event).getAxisValue(MotionEvent.AXIS_HSCROLL, pointerId);
verify(event).getAxisValue(MotionEvent.AXIS_VSCROLL, pointerId);
inOrder.verifyNoMoreInteractions();
}
@Test
@Config(sdk = API_LEVELS.API_25)
public void scrollWheelBelow26() {
// Pointer id must be zero to match actionIndex in mocked event.
final int pointerId = 0;
MotionEventMocker mocker =
new MotionEventMocker(
pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE);
final float horizontalScrollValue = -1f;
final float verticalScrollValue = .5f;
final Context context = ApplicationProvider.getApplicationContext();
final MotionEvent event =
mocker.mockEvent(
MotionEvent.ACTION_SCROLL,
0.0f,
0.0f,
1,
horizontalScrollValue,
verticalScrollValue,
0.0f,
0.0f,
0.0f,
0.0f,
0.0f);
boolean handled = touchProcessor.onGenericMotionEvent(event, context);
assertEquals(true, handled);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
// Magic number from roboletric's theme.
final double magicScrollFactor = 64;
assertEquals(-horizontalScrollValue * magicScrollFactor, readScrollDeltaX(packet));
assertEquals(-verticalScrollValue * magicScrollFactor, readScrollDeltaY(packet));
verify(event).getAxisValue(MotionEvent.AXIS_HSCROLL, pointerId);
verify(event).getAxisValue(MotionEvent.AXIS_VSCROLL, pointerId);
// Trigger default values.
touchProcessor.onGenericMotionEvent(event, null);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
assertEquals(
(double) -horizontalScrollValue * AndroidTouchProcessor.DEFAULT_HORIZONTAL_SCROLL_FACTOR,
readScrollDeltaX(packet));
assertEquals(
(double) -verticalScrollValue * AndroidTouchProcessor.DEFAULT_VERTICAL_SCROLL_FACTOR,
readScrollDeltaY(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void timeStamp() {
final int pointerId = 0;
MotionEventMocker mocker =
new MotionEventMocker(
pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE);
final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_SCROLL, 1f, 1f, 1);
boolean handled = touchProcessor.onTouchEvent(event);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
assertEquals(TimeUnit.MILLISECONDS.toMicros(eventTimeMilliseconds), readTimeStamp(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void device() {
final int pointerId = 2;
MotionEventMocker mocker =
new MotionEventMocker(
pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE);
final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_SCROLL, 1f, 1f, 1);
boolean handled = touchProcessor.onTouchEvent(event);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
assertEquals(pointerId, readDevice(packet));
verify(event).getPointerId(0);
inOrder.verifyNoMoreInteractions();
}
@Test
public void physicalXPhysicalY() {
MotionEventMocker mocker =
new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE);
final float x = 10.0f;
final float y = 20.0f;
final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, x, y, 0);
boolean handled = touchProcessor.onTouchEvent(event);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
assertEquals((double) x, readPointerPhysicalX(packet));
assertEquals((double) y, readPointerPhysicalY(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void obscured() {
MotionEventMocker mocker =
new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE);
final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, 10.0f, 20.0f, 0);
boolean handled = touchProcessor.onTouchEvent(event);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
// Always zero.
assertEquals(0.0, readObscured(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void synthesized() {
MotionEventMocker mocker =
new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE);
final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, 10.0f, 20.0f, 0);
boolean handled = touchProcessor.onTouchEvent(event);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
// Always zero.
assertEquals(0.0, readSynthesized(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void pressure() {
MotionEventMocker mocker =
new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE);
final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, 10.0f, 20.0f, 0);
boolean handled = touchProcessor.onTouchEvent(event);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
// Always zero.
assertEquals((double) pressure, readPressure(packet));
// Verify default range with null device.
assertEquals(0.0, readPressureMin(packet));
assertEquals(1.0, readPressureMax(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void stylusDistance() {
MotionEventMocker mocker =
new MotionEventMocker(0, InputDevice.SOURCE_STYLUS, MotionEvent.TOOL_TYPE_STYLUS);
final float distance = 10.0f;
final float tilt = 20.0f;
final MotionEvent event =
mocker.mockEvent(
MotionEvent.ACTION_DOWN,
0.0f,
0.0f,
MotionEvent.BUTTON_STYLUS_PRIMARY,
0.0f,
0.0f,
distance,
tilt,
0.0f,
0.0f,
0.0f);
boolean handled = touchProcessor.onTouchEvent(event);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerDeviceKind.STYLUS, readPointerDeviceKind(packet));
assertEquals((double) distance, readDistance(packet));
// Always zero.
assertEquals(0.0, readDistanceMax(packet));
assertEquals((double) tilt, readStylusTilt(packet));
assertEquals(enginePrimaryStylusButton, readButtons(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void sizeAndRadius() {
MotionEventMocker mocker =
new MotionEventMocker(0, InputDevice.SOURCE_STYLUS, MotionEvent.TOOL_TYPE_STYLUS);
final float size = 10.0f;
final float radiusMajor = 20.0f;
final float radiusMinor = 30.0f;
final MotionEvent event =
mocker.mockEvent(
MotionEvent.ACTION_DOWN,
0.0f,
0.0f,
0,
0.0f,
0.0f,
0.0f,
0.0f,
size,
radiusMajor,
radiusMinor);
boolean handled = touchProcessor.onTouchEvent(event);
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
verify(event).getSize(0);
verify(event).getToolMajor(0);
verify(event).getToolMinor(0);
assertEquals((double) size, readSize(packet));
assertEquals((double) radiusMajor, readRadiusMajor(packet));
assertEquals((double) radiusMinor, readRadiusMinor(packet));
// Always zero.
assertEquals(0.0, readRadiusMin(packet));
assertEquals(0.0, readRadiusMax(packet));
inOrder.verifyNoMoreInteractions();
}
@Test
public void unexpectedPointerChange() {
// Regression test for https://github.com/flutter/flutter/issues/129765
MotionEventMocker mocker =
new MotionEventMocker(0, InputDevice.SOURCE_MOUSE, MotionEvent.TOOL_TYPE_MOUSE);
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0));
InOrder inOrder = inOrder(mockRenderer);
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
ByteBuffer packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_START, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(0.0, readPointerPhysicalX(packet));
assertEquals(0.0, readPointerPhysicalY(packet));
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_MOVE, 10.0f, 5.0f, 0));
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_UPDATE, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(0.0, readPointerPhysicalX(packet));
assertEquals(0.0, readPointerPhysicalY(packet));
assertEquals(10.0, readPointerPanX(packet));
assertEquals(5.0, readPointerPanY(packet));
touchProcessor.onGenericMotionEvent(
mocker.mockEvent(MotionEvent.ACTION_SCROLL, 0.0f, 0.0f, 0),
ApplicationProvider.getApplicationContext());
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
packet.rewind();
while (packet.hasRemaining()) {
assertEquals(0, packet.get());
}
touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_UP, 10.0f, 5.0f, 0));
inOrder
.verify(mockRenderer)
.dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture());
packet = packetCaptor.getValue();
assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_END, readPointerChange(packet));
assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet));
assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet));
assertEquals(0.0, readPointerPhysicalX(packet));
assertEquals(0.0, readPointerPhysicalY(packet));
inOrder.verifyNoMoreInteractions();
}
}
| engine/shell/platform/android/test/io/flutter/embedding/android/AndroidTouchProcessorTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/android/AndroidTouchProcessorTest.java",
"repo_id": "engine",
"token_count": 10927
} | 358 |
package io.flutter.embedding.engine;
import static io.flutter.Build.API_LEVELS;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.LocaleList;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorsStack;
import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener;
import io.flutter.embedding.engine.systemchannels.LocalizationChannel;
import io.flutter.plugin.localization.LocalizationPlugin;
import io.flutter.plugin.platform.PlatformViewsController;
import java.nio.ByteBuffer;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;
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_24) // LocaleList and scriptCode are API 24+.
public class FlutterJNITest {
@Test
public void itAllowsFirstFrameListenersToRemoveThemselvesInline() {
// --- Test Setup ---
FlutterJNI flutterJNI = new FlutterJNI();
AtomicInteger callbackInvocationCount = new AtomicInteger(0);
FlutterUiDisplayListener callback =
new FlutterUiDisplayListener() {
@Override
public void onFlutterUiDisplayed() {
callbackInvocationCount.incrementAndGet();
flutterJNI.removeIsDisplayingFlutterUiListener(this);
}
@Override
public void onFlutterUiNoLongerDisplayed() {}
};
flutterJNI.addIsDisplayingFlutterUiListener(callback);
// --- Execute Test ---
flutterJNI.onFirstFrame();
// --- Verify Results ---
assertEquals(1, callbackInvocationCount.get());
// --- Execute Test ---
// The callback removed itself from the listener list. A second call doesn't call the callback.
flutterJNI.onFirstFrame();
// --- Verify Results ---
assertEquals(1, callbackInvocationCount.get());
}
@Test
public void computePlatformResolvedLocaleCallsLocalizationPluginProperly() {
// --- Test Setup ---
FlutterJNI flutterJNI = new FlutterJNI();
Context context = mock(Context.class);
Resources resources = mock(Resources.class);
Configuration config = mock(Configuration.class);
DartExecutor dartExecutor = mock(DartExecutor.class);
LocaleList localeList =
new LocaleList(new Locale("es", "MX"), new Locale("zh", "CN"), new Locale("en", "US"));
when(context.getResources()).thenReturn(resources);
when(resources.getConfiguration()).thenReturn(config);
when(config.getLocales()).thenReturn(localeList);
flutterJNI.setLocalizationPlugin(
new LocalizationPlugin(context, new LocalizationChannel(dartExecutor)));
String[] supportedLocales =
new String[] {
"fr", "FR", "",
"zh", "", "",
"en", "CA", ""
};
String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales);
assertEquals(result.length, 3);
assertEquals(result[0], "zh");
assertEquals(result[1], "");
assertEquals(result[2], "");
supportedLocales =
new String[] {
"fr", "FR", "",
"ar", "", "",
"en", "CA", ""
};
result = flutterJNI.computePlatformResolvedLocale(supportedLocales);
assertEquals(result.length, 3);
assertEquals(result[0], "en");
assertEquals(result[1], "CA");
assertEquals(result[2], "");
supportedLocales =
new String[] {
"fr", "FR", "",
"ar", "", "",
"en", "US", ""
};
result = flutterJNI.computePlatformResolvedLocale(supportedLocales);
assertEquals(result.length, 3);
assertEquals(result[0], "en");
assertEquals(result[1], "US");
assertEquals(result[2], "");
supportedLocales =
new String[] {
"ar", "", "",
"es", "MX", "",
"en", "US", ""
};
result = flutterJNI.computePlatformResolvedLocale(supportedLocales);
assertEquals(result.length, 3);
assertEquals(result[0], "es");
assertEquals(result[1], "MX");
assertEquals(result[2], "");
// Empty supportedLocales.
supportedLocales = new String[] {};
result = flutterJNI.computePlatformResolvedLocale(supportedLocales);
assertEquals(result.length, 0);
// Empty preferredLocales.
supportedLocales =
new String[] {
"fr", "FR", "",
"zh", "", "",
"en", "CA", ""
};
localeList = new LocaleList();
when(config.getLocales()).thenReturn(localeList);
result = flutterJNI.computePlatformResolvedLocale(supportedLocales);
// The first locale is default.
assertEquals(result.length, 3);
assertEquals(result[0], "fr");
assertEquals(result[1], "FR");
assertEquals(result[2], "");
}
public void onDisplayPlatformView_callsPlatformViewsController() {
PlatformViewsController platformViewsController = mock(PlatformViewsController.class);
FlutterJNI flutterJNI = new FlutterJNI();
flutterJNI.setPlatformViewsController(platformViewsController);
FlutterMutatorsStack stack = new FlutterMutatorsStack();
// --- Execute Test ---
flutterJNI.onDisplayPlatformView(
/*viewId=*/ 1,
/*x=*/ 10,
/*y=*/ 20,
/*width=*/ 100,
/*height=*/ 200,
/*viewWidth=*/ 100,
/*viewHeight=*/ 200,
/*mutatorsStack=*/ stack);
// --- Verify Results ---
verify(platformViewsController, times(1))
.onDisplayPlatformView(
/*viewId=*/ 1,
/*x=*/ 10,
/*y=*/ 20,
/*width=*/ 100,
/*height=*/ 200,
/*viewWidth=*/ 100,
/*viewHeight=*/ 200,
/*mutatorsStack=*/ stack);
}
@Test
public void onDisplayOverlaySurface_callsPlatformViewsController() {
PlatformViewsController platformViewsController = mock(PlatformViewsController.class);
FlutterJNI flutterJNI = new FlutterJNI();
flutterJNI.setPlatformViewsController(platformViewsController);
// --- Execute Test ---
flutterJNI.onDisplayOverlaySurface(
/*id=*/ 1, /*x=*/ 10, /*y=*/ 20, /*width=*/ 100, /*height=*/ 200);
// --- Verify Results ---
verify(platformViewsController, times(1))
.onDisplayOverlaySurface(/*id=*/ 1, /*x=*/ 10, /*y=*/ 20, /*width=*/ 100, /*height=*/ 200);
}
@Test
public void onBeginFrame_callsPlatformViewsController() {
PlatformViewsController platformViewsController = mock(PlatformViewsController.class);
// --- Test Setup ---
FlutterJNI flutterJNI = new FlutterJNI();
flutterJNI.setPlatformViewsController(platformViewsController);
// --- Execute Test ---
flutterJNI.onBeginFrame();
// --- Verify Results ---
verify(platformViewsController, times(1)).onBeginFrame();
}
@Test
public void onEndFrame_callsPlatformViewsController() {
PlatformViewsController platformViewsController = mock(PlatformViewsController.class);
// --- Test Setup ---
FlutterJNI flutterJNI = new FlutterJNI();
flutterJNI.setPlatformViewsController(platformViewsController);
// --- Execute Test ---
flutterJNI.onEndFrame();
// --- Verify Results ---
verify(platformViewsController, times(1)).onEndFrame();
}
@Test
public void createOverlaySurface_callsPlatformViewsController() {
PlatformViewsController platformViewsController = mock(PlatformViewsController.class);
FlutterJNI flutterJNI = new FlutterJNI();
flutterJNI.setPlatformViewsController(platformViewsController);
// --- Execute Test ---
flutterJNI.createOverlaySurface();
// --- Verify Results ---
verify(platformViewsController, times(1)).createOverlaySurface();
}
@Test(expected = IllegalArgumentException.class)
public void invokePlatformMessageResponseCallback_wantsDirectBuffer() {
FlutterJNI flutterJNI = new FlutterJNI();
ByteBuffer buffer = ByteBuffer.allocate(4);
flutterJNI.invokePlatformMessageResponseCallback(0, buffer, buffer.position());
}
@Test
public void setRefreshRateFPS_callsUpdateRefreshRate() {
FlutterJNI flutterJNI = spy(new FlutterJNI());
// --- Execute Test ---
flutterJNI.setRefreshRateFPS(120.0f);
// --- Verify Results ---
verify(flutterJNI, times(1)).updateRefreshRate();
}
}
| engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterJNITest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterJNITest.java",
"repo_id": "engine",
"token_count": 3282
} | 359 |
package io.flutter.embedding.engine.systemchannels;
import static io.flutter.Build.API_LEVELS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
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.annotation.TargetApi;
import android.util.SparseArray;
import android.view.InputDevice;
import android.view.KeyEvent;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.JSONMessageCodec;
import io.flutter.util.FakeKeyEvent;
import java.nio.ByteBuffer;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.Resetter;
import org.robolectric.shadow.api.Shadow;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
@TargetApi(API_LEVELS.API_24)
public class KeyEventChannelTest {
KeyEvent keyEvent;
@Mock BinaryMessenger fakeMessenger;
boolean[] handled;
KeyEventChannel keyEventChannel;
private void sendReply(boolean handled, BinaryMessenger.BinaryReply messengerReply)
throws JSONException {
JSONObject reply = new JSONObject();
reply.put("handled", true);
ByteBuffer binaryReply = JSONMessageCodec.INSTANCE.encodeMessage(reply);
assertNotNull(binaryReply);
binaryReply.rewind();
messengerReply.reply(binaryReply);
}
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
keyEvent = new FakeKeyEvent(KeyEvent.ACTION_DOWN, 65);
handled = new boolean[] {false};
keyEventChannel = new KeyEventChannel(fakeMessenger);
}
@After
public void tearDown() {
ShadowInputDevice.reset();
}
@Test
@Config(shadows = {ShadowInputDevice.class})
public void keyDownEventIsSentToFramework() throws JSONException {
final InputDevice device = mock(InputDevice.class);
when(device.isVirtual()).thenReturn(false);
when(device.getName()).thenReturn("keyboard");
ShadowInputDevice.sDeviceIds = new int[] {0};
ShadowInputDevice.addDevice(0, device);
KeyEventChannel.FlutterKeyEvent flutterKeyEvent =
new KeyEventChannel.FlutterKeyEvent(keyEvent, null);
keyEventChannel.sendFlutterKeyEvent(
flutterKeyEvent,
false,
(isHandled) -> {
handled[0] = isHandled;
});
ArgumentCaptor<ByteBuffer> byteBufferArgumentCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
ArgumentCaptor<BinaryMessenger.BinaryReply> replyArgumentCaptor =
ArgumentCaptor.forClass(BinaryMessenger.BinaryReply.class);
verify(fakeMessenger, times(1))
.send(any(), byteBufferArgumentCaptor.capture(), replyArgumentCaptor.capture());
ByteBuffer capturedMessage = byteBufferArgumentCaptor.getValue();
capturedMessage.rewind();
JSONObject message = (JSONObject) JSONMessageCodec.INSTANCE.decodeMessage(capturedMessage);
assertNotNull(message);
assertEquals("keydown", message.get("type"));
// Simulate a reply, and see that it is handled.
sendReply(true, replyArgumentCaptor.getValue());
assertTrue(handled[0]);
}
@Test
@Config(shadows = {ShadowInputDevice.class})
public void keyUpEventIsSentToFramework() throws JSONException {
final InputDevice device = mock(InputDevice.class);
when(device.isVirtual()).thenReturn(false);
when(device.getName()).thenReturn("keyboard");
ShadowInputDevice.sDeviceIds = new int[] {0};
ShadowInputDevice.addDevice(0, device);
keyEvent = new FakeKeyEvent(KeyEvent.ACTION_UP, 65);
KeyEventChannel.FlutterKeyEvent flutterKeyEvent =
new KeyEventChannel.FlutterKeyEvent(keyEvent, null);
keyEventChannel.sendFlutterKeyEvent(
flutterKeyEvent,
false,
(isHandled) -> {
handled[0] = isHandled;
});
ArgumentCaptor<ByteBuffer> byteBufferArgumentCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
ArgumentCaptor<BinaryMessenger.BinaryReply> replyArgumentCaptor =
ArgumentCaptor.forClass(BinaryMessenger.BinaryReply.class);
verify(fakeMessenger, times(1))
.send(any(), byteBufferArgumentCaptor.capture(), replyArgumentCaptor.capture());
ByteBuffer capturedMessage = byteBufferArgumentCaptor.getValue();
capturedMessage.rewind();
JSONObject message = (JSONObject) JSONMessageCodec.INSTANCE.decodeMessage(capturedMessage);
assertNotNull(message);
assertEquals("keydown", message.get("type"));
// Simulate a reply, and see that it is handled.
sendReply(true, replyArgumentCaptor.getValue());
assertTrue(handled[0]);
}
@Implements(InputDevice.class)
public static class ShadowInputDevice extends org.robolectric.shadows.ShadowInputDevice {
public static int[] sDeviceIds;
private static SparseArray<InputDevice> sDeviceMap = new SparseArray<>();
private int mDeviceId;
@Implementation
protected static int[] getDeviceIds() {
return sDeviceIds;
}
@Implementation
protected static InputDevice getDevice(int id) {
return sDeviceMap.get(id);
}
public static void addDevice(int id, InputDevice device) {
sDeviceMap.append(id, device);
}
@Resetter
public static void reset() {
sDeviceIds = null;
sDeviceMap.clear();
}
@Implementation
protected int getId() {
return mDeviceId;
}
public static InputDevice makeInputDevicebyId(int id) {
final InputDevice inputDevice = Shadow.newInstanceOf(InputDevice.class);
final ShadowInputDevice shadowInputDevice = Shadow.extract(inputDevice);
shadowInputDevice.setId(id);
return inputDevice;
}
public void setId(int id) {
mDeviceId = id;
}
}
}
| engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyEventChannelTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyEventChannelTest.java",
"repo_id": "engine",
"token_count": 2170
} | 360 |
package io.flutter.plugin.editing;
import static org.junit.Assert.assertEquals;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
public class TextEditingDeltaTest {
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testConstructorTextEditingDelta() {
final CharSequence oldText = "hell";
final CharSequence textAfterChange = "hello";
final int oldComposingStart = 0;
final int oldComposingEnd = 4;
final int startOfReplacementText = 0;
final int endOfReplacementText = textAfterChange.length();
final int newSelectionStart = 5;
final int newSelectionEnd = 5;
final int newComposingStart = 0;
final int newComposingEnd = 5;
final TextEditingDelta delta =
new TextEditingDelta(
oldText,
oldComposingStart,
oldComposingEnd,
textAfterChange,
newSelectionStart,
newSelectionEnd,
newComposingStart,
newComposingEnd);
assertEquals(oldText, delta.getOldText());
assertEquals(textAfterChange, delta.getDeltaText());
assertEquals(oldComposingStart, delta.getDeltaStart());
assertEquals(oldComposingEnd, delta.getDeltaEnd());
assertEquals(newSelectionStart, delta.getNewSelectionStart());
assertEquals(newSelectionEnd, delta.getNewSelectionEnd());
assertEquals(newComposingStart, delta.getNewComposingStart());
assertEquals(newComposingEnd, delta.getNewComposingEnd());
}
@Test
public void testNonTextUpdateConstructorTextEditingDelta() {
final CharSequence oldText = "hello";
final int newSelectionStart = 3;
final int newSelectionEnd = 3;
final int newComposingStart = 0;
final int newComposingEnd = 5;
final TextEditingDelta delta =
new TextEditingDelta(
oldText, newSelectionStart, newSelectionEnd, newComposingStart, newComposingEnd);
assertEquals(oldText, delta.getOldText());
assertEquals("", delta.getDeltaText());
assertEquals(-1, delta.getDeltaStart());
assertEquals(-1, delta.getDeltaEnd());
assertEquals(newSelectionStart, delta.getNewSelectionStart());
assertEquals(newSelectionEnd, delta.getNewSelectionEnd());
assertEquals(newComposingStart, delta.getNewComposingStart());
assertEquals(newComposingEnd, delta.getNewComposingEnd());
}
}
| engine/shell/platform/android/test/io/flutter/plugin/editing/TextEditingDeltaTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/plugin/editing/TextEditingDeltaTest.java",
"repo_id": "engine",
"token_count": 943
} | 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.
package io.flutter.util;
import static io.flutter.Build.API_LEVELS;
import static org.junit.Assert.assertTrue;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
public class HandlerCompatTest {
@Test
@Config(sdk = API_LEVELS.API_28)
public void createAsync_createsAnAsyncHandler() {
Handler handler = Handler.createAsync(Looper.getMainLooper());
Message message = Message.obtain();
handler.sendMessageAtTime(message, 0);
assertTrue(message.isAsynchronous());
}
}
| engine/shell/platform/android/test/io/flutter/util/HandlerCompatTest.java/0 | {
"file_path": "engine/shell/platform/android/test/io/flutter/util/HandlerCompatTest.java",
"repo_id": "engine",
"token_count": 282
} | 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_COMMON_ACCESSIBILITY_BRIDGE_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_ACCESSIBILITY_BRIDGE_H_
#include <unordered_map>
#include "flutter/fml/mapping.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/third_party/accessibility/ax/ax_event_generator.h"
#include "flutter/third_party/accessibility/ax/ax_tree.h"
#include "flutter/third_party/accessibility/ax/ax_tree_observer.h"
#include "flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate.h"
#include "flutter/third_party/accessibility/ax/platform/ax_platform_tree_manager.h"
#include "flutter_platform_node_delegate.h"
namespace flutter {
//------------------------------------------------------------------------------
/// Use this class to maintain an accessibility tree. This class consumes
/// semantics updates from the embedder API and produces an accessibility tree
/// in the native format.
///
/// The bridge creates an AXTree to hold the semantics data that comes from
/// Flutter semantics updates. The tree holds AXNode[s] which contain the
/// semantics information for semantics node. The AXTree resemble the Flutter
/// semantics tree in the Flutter framework. The bridge also uses
/// FlutterPlatformNodeDelegate to wrap each AXNode in order to provide
/// an accessibility tree in the native format.
///
/// To use this class, one must subclass this class and provide their own
/// implementation of FlutterPlatformNodeDelegate.
///
/// AccessibilityBridge must be created as a shared_ptr, since some methods
/// acquires its weak_ptr.
class AccessibilityBridge
: public std::enable_shared_from_this<AccessibilityBridge>,
public FlutterPlatformNodeDelegate::OwnerBridge,
public ui::AXPlatformTreeManager,
private ui::AXTreeObserver {
public:
//-----------------------------------------------------------------------------
/// @brief Creates a new instance of a accessibility bridge.
AccessibilityBridge();
virtual ~AccessibilityBridge();
//------------------------------------------------------------------------------
/// @brief Adds a semantics node update to the pending semantics update.
/// Calling this method alone will NOT update the semantics tree.
/// To flush the pending updates, call the CommitUpdates().
///
/// @param[in] node A reference to the semantics node update.
void AddFlutterSemanticsNodeUpdate(const FlutterSemanticsNode2& node);
//------------------------------------------------------------------------------
/// @brief Adds a custom semantics action update to the pending semantics
/// update. Calling this method alone will NOT update the
/// semantics tree. To flush the pending updates, call the
/// CommitUpdates().
///
/// @param[in] action A reference to the custom semantics action
/// update.
void AddFlutterSemanticsCustomActionUpdate(
const FlutterSemanticsCustomAction2& action);
//------------------------------------------------------------------------------
/// @brief Flushes the pending updates and applies them to this
/// accessibility bridge. Calling this with no pending updates
/// does nothing, and callers should call this method at the end
/// of an atomic batch to avoid leaving the tree in a unstable
/// state. For example if a node reparents from A to B, callers
/// should only call this method when both removal from A and
/// addition to B are in the pending updates.
void CommitUpdates();
//------------------------------------------------------------------------------
/// @brief Get the flutter platform node delegate with the given id from
/// this accessibility bridge. Returns expired weak_ptr if the
/// delegate associated with the id does not exist or has been
/// removed from the accessibility tree.
///
/// @param[in] id The id of the flutter accessibility node you want
/// to retrieve.
std::weak_ptr<FlutterPlatformNodeDelegate>
GetFlutterPlatformNodeDelegateFromID(AccessibilityNodeId id) const;
//------------------------------------------------------------------------------
/// @brief Get the ax tree data from this accessibility bridge. The tree
/// data contains information such as the id of the node that
/// has the keyboard focus or the text selection range.
const ui::AXTreeData& GetAXTreeData() const;
//------------------------------------------------------------------------------
/// @brief Gets all pending accessibility events generated during
/// semantics updates. This is useful when deciding how to handle
/// events in AccessibilityBridgeDelegate::OnAccessibilityEvent in
/// case one may decide to handle an event differently based on
/// all pending events.
const std::vector<ui::AXEventGenerator::TargetedEvent> GetPendingEvents()
const;
// |AXTreeManager|
ui::AXNode* GetNodeFromTree(const ui::AXTreeID tree_id,
const ui::AXNode::AXID node_id) const override;
// |AXTreeManager|
ui::AXNode* GetNodeFromTree(const ui::AXNode::AXID node_id) const override;
// |AXTreeManager|
ui::AXTreeID GetTreeID() const override;
// |AXTreeManager|
ui::AXTreeID GetParentTreeID() const override;
// |AXTreeManager|
ui::AXNode* GetRootAsAXNode() const override;
// |AXTreeManager|
ui::AXNode* GetParentNodeFromParentTreeAsAXNode() const override;
// |AXTreeManager|
ui::AXTree* GetTree() const override;
// |AXPlatformTreeManager|
ui::AXPlatformNode* GetPlatformNodeFromTree(
const ui::AXNode::AXID node_id) const override;
// |AXPlatformTreeManager|
ui::AXPlatformNode* GetPlatformNodeFromTree(
const ui::AXNode& node) const override;
// |AXPlatformTreeManager|
ui::AXPlatformNodeDelegate* RootDelegate() const override;
protected:
//---------------------------------------------------------------------------
/// @brief Handle accessibility events generated due to accessibility
/// tree changes. These events are needed to be sent to native
/// accessibility system. See ui::AXEventGenerator::Event for
/// possible events.
///
/// @param[in] targeted_event The object that contains both the
/// generated event and the event target.
virtual void OnAccessibilityEvent(
ui::AXEventGenerator::TargetedEvent targeted_event) = 0;
//---------------------------------------------------------------------------
/// @brief Creates a platform specific FlutterPlatformNodeDelegate.
/// Ownership passes to the caller. This method will be called
/// whenever a new AXNode is created in AXTree. Each platform
/// needs to implement this method in order to inject its
/// subclass into the accessibility bridge.
virtual std::shared_ptr<FlutterPlatformNodeDelegate>
CreateFlutterPlatformNodeDelegate() = 0;
private:
// See FlutterSemanticsNode in embedder.h
typedef struct {
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;
std::string label;
std::string hint;
std::string value;
std::string increased_value;
std::string decreased_value;
std::string tooltip;
FlutterTextDirection text_direction;
FlutterRect rect;
FlutterTransformation transform;
std::vector<int32_t> children_in_traversal_order;
std::vector<int32_t> custom_accessibility_actions;
} SemanticsNode;
// See FlutterSemanticsCustomAction in embedder.h
typedef struct {
int32_t id;
FlutterSemanticsAction override_action;
std::string label;
std::string hint;
} SemanticsCustomAction;
std::unordered_map<AccessibilityNodeId,
std::shared_ptr<FlutterPlatformNodeDelegate>>
id_wrapper_map_;
std::unique_ptr<ui::AXTree> tree_;
ui::AXEventGenerator event_generator_;
std::unordered_map<int32_t, SemanticsNode> pending_semantics_node_updates_;
std::unordered_map<int32_t, SemanticsCustomAction>
pending_semantics_custom_action_updates_;
AccessibilityNodeId last_focused_id_ = ui::AXNode::kInvalidAXID;
void InitAXTree(const ui::AXTreeUpdate& initial_state);
// Create an update that removes any nodes that will be reparented by
// pending_semantics_updates_. Returns std::nullopt if none are reparented.
std::optional<ui::AXTreeUpdate> CreateRemoveReparentedNodesUpdate();
void GetSubTreeList(const SemanticsNode& target,
std::vector<SemanticsNode>& result);
void ConvertFlutterUpdate(const SemanticsNode& node,
ui::AXTreeUpdate& tree_update);
void SetRoleFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetStateFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetActionsFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetBooleanAttributesFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetIntAttributesFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetIntListAttributesFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetStringListAttributesFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetNameFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetValueFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetTooltipFromFlutterUpdate(ui::AXNodeData& node_data,
const SemanticsNode& node);
void SetTreeData(const SemanticsNode& node, ui::AXTreeUpdate& tree_update);
SemanticsNode FromFlutterSemanticsNode(
const FlutterSemanticsNode2& flutter_node);
SemanticsCustomAction FromFlutterSemanticsCustomAction(
const FlutterSemanticsCustomAction2& flutter_custom_action);
// |AXTreeObserver|
void OnNodeWillBeDeleted(ui::AXTree* tree, ui::AXNode* node) override;
// |AXTreeObserver|
void OnSubtreeWillBeDeleted(ui::AXTree* tree, ui::AXNode* node) override;
// |AXTreeObserver|
void OnNodeCreated(ui::AXTree* tree, ui::AXNode* node) override;
// |AXTreeObserver|
void OnNodeDeleted(ui::AXTree* tree, AccessibilityNodeId node_id) override;
// |AXTreeObserver|
void OnNodeReparented(ui::AXTree* tree, ui::AXNode* node) override;
// |AXTreeObserver|
void OnRoleChanged(ui::AXTree* tree,
ui::AXNode* node,
ax::mojom::Role old_role,
ax::mojom::Role new_role) override;
// |AXTreeObserver|
void OnAtomicUpdateFinished(
ui::AXTree* tree,
bool root_changed,
const std::vector<ui::AXTreeObserver::Change>& changes) override;
// |FlutterPlatformNodeDelegate::OwnerBridge|
void SetLastFocusedId(AccessibilityNodeId node_id) override;
// |FlutterPlatformNodeDelegate::OwnerBridge|
AccessibilityNodeId GetLastFocusedId() override;
// |FlutterPlatformNodeDelegate::OwnerBridge|
gfx::NativeViewAccessible GetNativeAccessibleFromId(
AccessibilityNodeId id) override;
// |FlutterPlatformNodeDelegate::OwnerBridge|
gfx::RectF RelativeToGlobalBounds(const ui::AXNode* node,
bool& offscreen,
bool clip_bounds) override;
BASE_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_ACCESSIBILITY_BRIDGE_H_
| engine/shell/platform/common/accessibility_bridge.h/0 | {
"file_path": "engine/shell/platform/common/accessibility_bridge.h",
"repo_id": "engine",
"token_count": 4449
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BINARY_MESSENGER_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BINARY_MESSENGER_H_
#include <functional>
#include <string>
namespace flutter {
// A binary message reply callback.
//
// Used for submitting a binary reply back to a Flutter message sender.
typedef std::function<void(const uint8_t* reply, size_t reply_size)>
BinaryReply;
// A message handler callback.
//
// Used for receiving messages from Flutter and providing an asynchronous reply.
typedef std::function<
void(const uint8_t* message, size_t message_size, BinaryReply reply)>
BinaryMessageHandler;
// A protocol for a class that handles communication of binary data on named
// channels to and from the Flutter engine.
class BinaryMessenger {
public:
virtual ~BinaryMessenger() = default;
// Sends a binary message to the Flutter engine on the specified channel.
//
// If |reply| is provided, it will be called back with the response from the
// engine.
virtual void Send(const std::string& channel,
const uint8_t* message,
size_t message_size,
BinaryReply reply = nullptr) const = 0;
// Registers a message handler for incoming binary messages from the Flutter
// side on the specified channel.
//
// Replaces any existing handler. Provide a null handler to unregister the
// existing handler.
virtual void SetMessageHandler(const std::string& channel,
BinaryMessageHandler handler) = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BINARY_MESSENGER_H_
| engine/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h",
"repo_id": "engine",
"token_count": 636
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_CODEC_SERIALIZER_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_CODEC_SERIALIZER_H_
#include "byte_streams.h"
#include "encodable_value.h"
namespace flutter {
// Encapsulates the logic for encoding/decoding EncodableValues to/from the
// standard codec binary representation.
//
// This can be subclassed to extend the standard codec with support for new
// types.
class StandardCodecSerializer {
public:
virtual ~StandardCodecSerializer();
// Returns the shared serializer instance.
static const StandardCodecSerializer& GetInstance();
// Prevent copying.
StandardCodecSerializer(StandardCodecSerializer const&) = delete;
StandardCodecSerializer& operator=(StandardCodecSerializer const&) = delete;
// Reads and returns the next value from |stream|.
EncodableValue ReadValue(ByteStreamReader* stream) const;
// Writes the encoding of |value| to |stream|, including the initial type
// discrimination byte.
//
// Can be overridden by a subclass to extend the codec.
virtual void WriteValue(const EncodableValue& value,
ByteStreamWriter* stream) const;
protected:
// Codecs require long-lived serializers, so clients should always use
// GetInstance().
StandardCodecSerializer();
// Reads and returns the next value from |stream|, whose discrimination byte
// was |type|.
//
// The discrimination byte will already have been read from the stream when
// this is called.
//
// Can be overridden by a subclass to extend the codec.
virtual EncodableValue ReadValueOfType(uint8_t type,
ByteStreamReader* stream) const;
// Reads the variable-length size from the current position in |stream|.
size_t ReadSize(ByteStreamReader* stream) const;
// Writes the variable-length size encoding to |stream|.
void WriteSize(size_t size, ByteStreamWriter* stream) const;
private:
// Reads a fixed-type list whose values are of type T from the current
// position in |stream|, and returns it as the corresponding EncodableValue.
// |T| must correspond to one of the supported list value types of
// EncodableValue.
template <typename T>
EncodableValue ReadVector(ByteStreamReader* stream) const;
// Writes |vector| to |stream| as a fixed-type list. |T| must correspond to
// one of the supported list value types of EncodableValue.
template <typename T>
void WriteVector(const std::vector<T> vector, ByteStreamWriter* stream) const;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_CODEC_SERIALIZER_H_
| engine/shell/platform/common/client_wrapper/include/flutter/standard_codec_serializer.h/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/include/flutter/standard_codec_serializer.h",
"repo_id": "engine",
"token_count": 903
} | 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_COMMON_CLIENT_WRAPPER_TESTING_TEST_CODEC_EXTENSIONS_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_TEST_CODEC_EXTENSIONS_H_
#include "flutter/shell/platform/common/client_wrapper/include/flutter/encodable_value.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_codec_serializer.h"
namespace flutter {
// A representation of a point, for custom type testing of a simple type.
class Point {
public:
Point(int x, int y) : x_(x), y_(y) {}
~Point() = default;
int x() const { return x_; }
int y() const { return y_; }
bool operator==(const Point& other) const {
return x_ == other.x_ && y_ == other.y_;
}
private:
int x_;
int y_;
};
// A typed binary data object with extra fields, for custom type testing of a
// variable-length type that includes types handled by the core standard codec.
class SomeData {
public:
SomeData(const std::string& label, const std::vector<uint8_t>& data)
: label_(label), data_(data) {}
~SomeData() = default;
const std::string& label() const { return label_; }
const std::vector<uint8_t>& data() const { return data_; }
private:
std::string label_;
std::vector<uint8_t> data_;
};
// Codec extension for Point.
class PointExtensionSerializer : public StandardCodecSerializer {
public:
PointExtensionSerializer();
virtual ~PointExtensionSerializer();
static const PointExtensionSerializer& GetInstance();
// |TestCodecSerializer|
EncodableValue ReadValueOfType(uint8_t type,
ByteStreamReader* stream) const override;
// |TestCodecSerializer|
void WriteValue(const EncodableValue& value,
ByteStreamWriter* stream) const override;
private:
static constexpr uint8_t kPointType = 128;
};
// Codec extension for SomeData.
class SomeDataExtensionSerializer : public StandardCodecSerializer {
public:
SomeDataExtensionSerializer();
virtual ~SomeDataExtensionSerializer();
static const SomeDataExtensionSerializer& GetInstance();
// |TestCodecSerializer|
EncodableValue ReadValueOfType(uint8_t type,
ByteStreamReader* stream) const override;
// |TestCodecSerializer|
void WriteValue(const EncodableValue& value,
ByteStreamWriter* stream) const override;
private:
static constexpr uint8_t kSomeDataType = 129;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_TEST_CODEC_EXTENSIONS_H_
| engine/shell/platform/common/client_wrapper/testing/test_codec_extensions.h/0 | {
"file_path": "engine/shell/platform/common/client_wrapper/testing/test_codec_extensions.h",
"repo_id": "engine",
"token_count": 936
} | 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.
#include "flutter/shell/platform/common/json_message_codec.h"
#include <limits>
#include <map>
#include <vector>
#include "gtest/gtest.h"
namespace flutter {
namespace {
// Validates round-trip encoding and decoding of |value|.
static void CheckEncodeDecode(const rapidjson::Document& value) {
const JsonMessageCodec& codec = JsonMessageCodec::GetInstance();
auto encoded = codec.EncodeMessage(value);
ASSERT_TRUE(encoded);
auto decoded = codec.DecodeMessage(*encoded);
EXPECT_EQ(value, *decoded);
}
} // namespace
// Tests that a JSON document with various data types round-trips correctly.
TEST(JsonMessageCodec, EncodeDecode) {
// NOLINTNEXTLINE(clang-analyzer-core.NullDereference)
rapidjson::Document array(rapidjson::kArrayType);
auto& allocator = array.GetAllocator();
array.PushBack("string", allocator);
rapidjson::Value map(rapidjson::kObjectType);
map.AddMember("a", -7, allocator);
map.AddMember("b", std::numeric_limits<int>::max(), allocator);
map.AddMember("c", 3.14159, allocator);
map.AddMember("d", true, allocator);
map.AddMember("e", rapidjson::Value(), allocator);
array.PushBack(map, allocator);
CheckEncodeDecode(array);
}
} // namespace flutter
| engine/shell/platform/common/json_message_codec_unittests.cc/0 | {
"file_path": "engine/shell/platform/common/json_message_codec_unittests.cc",
"repo_id": "engine",
"token_count": 457
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_COMMON_TEXT_EDITING_DELTA_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_TEXT_EDITING_DELTA_H_
#include <string>
#include "flutter/fml/string_conversion.h"
#include "flutter/shell/platform/common/text_range.h"
namespace flutter {
/// A change in the state of an input field.
struct TextEditingDelta {
TextEditingDelta(const std::u16string& text_before_change,
const TextRange& range,
const std::u16string& text);
TextEditingDelta(const std::string& text_before_change,
const TextRange& range,
const std::string& text);
explicit TextEditingDelta(const std::u16string& text);
explicit TextEditingDelta(const std::string& text);
virtual ~TextEditingDelta() = default;
/// Get the old_text_ value.
///
/// All strings are stored as UTF16 but converted to UTF8 when accessed.
std::string old_text() const { return fml::Utf16ToUtf8(old_text_); }
/// Get the delta_text value.
///
/// All strings are stored as UTF16 but converted to UTF8 when accessed.
std::string delta_text() const { return fml::Utf16ToUtf8(delta_text_); }
/// Get the delta_start_ value.
int delta_start() const { return delta_start_; }
/// Get the delta_end_ value.
int delta_end() const { return delta_end_; }
bool operator==(const TextEditingDelta& rhs) const {
return old_text_ == rhs.old_text_ && delta_text_ == rhs.delta_text_ &&
delta_start_ == rhs.delta_start_ && delta_end_ == rhs.delta_end_;
}
bool operator!=(const TextEditingDelta& rhs) const { return !(*this == rhs); }
TextEditingDelta(const TextEditingDelta& other) = default;
TextEditingDelta& operator=(const TextEditingDelta& other) = default;
private:
std::u16string old_text_;
std::u16string delta_text_;
int delta_start_;
int delta_end_;
void set_old_text(const std::u16string& old_text) { old_text_ = old_text; }
void set_delta_text(const std::u16string& delta_text) {
delta_text_ = delta_text;
}
void set_delta_start(int delta_start) { delta_start_ = delta_start; }
void set_delta_end(int delta_end) { delta_end_ = delta_end; }
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_TEXT_EDITING_DELTA_H_
| engine/shell/platform/common/text_editing_delta.h/0 | {
"file_path": "engine/shell/platform/common/text_editing_delta.h",
"repo_id": "engine",
"token_count": 892
} | 368 |
// Copyright 2013 The Flutter 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_COMMAND_LINE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_COMMAND_LINE_H_
#import <Foundation/Foundation.h>
#include "flutter/fml/command_line.h"
#include "flutter/fml/macros.h"
namespace flutter {
fml::CommandLine CommandLineFromNSProcessInfo(
NSProcessInfo* processInfoOrNil = nil);
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_COMMAND_LINE_H_
| engine/shell/platform/darwin/common/command_line.h/0 | {
"file_path": "engine/shell/platform/darwin/common/command_line.h",
"repo_id": "engine",
"token_count": 222
} | 369 |
// Copyright 2013 The Flutter 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/Source/FlutterStandardCodecHelper.h"
#import "flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodec_Internal.h"
FLUTTER_ASSERT_ARC
#pragma mark - Codec for basic message channel
@implementation FlutterStandardMessageCodec {
FlutterStandardReaderWriter* _readerWriter;
}
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
FlutterStandardReaderWriter* readerWriter = [[FlutterStandardReaderWriter alloc] init];
_sharedInstance = [[FlutterStandardMessageCodec alloc] initWithReaderWriter:readerWriter];
}
return _sharedInstance;
}
+ (instancetype)codecWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter {
return [[FlutterStandardMessageCodec alloc] initWithReaderWriter:readerWriter];
}
- (instancetype)initWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_readerWriter = readerWriter;
return self;
}
- (NSData*)encode:(id)message {
if (message == nil) {
return nil;
}
NSMutableData* data = [NSMutableData dataWithCapacity:32];
FlutterStandardWriter* writer = [_readerWriter writerWithData:data];
[writer writeValue:message];
return data;
}
- (id)decode:(NSData*)message {
if ([message length] == 0) {
return nil;
}
FlutterStandardReader* reader = [_readerWriter readerWithData:message];
id value = [reader readValue];
NSAssert(![reader hasMore], @"Corrupted standard message");
return value;
}
@end
#pragma mark - Codec for method channel
@implementation FlutterStandardMethodCodec {
FlutterStandardReaderWriter* _readerWriter;
}
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
FlutterStandardReaderWriter* readerWriter = [[FlutterStandardReaderWriter alloc] init];
_sharedInstance = [[FlutterStandardMethodCodec alloc] initWithReaderWriter:readerWriter];
}
return _sharedInstance;
}
+ (instancetype)codecWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter {
return [[FlutterStandardMethodCodec alloc] initWithReaderWriter:readerWriter];
}
- (instancetype)initWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_readerWriter = readerWriter;
return self;
}
- (NSData*)encodeMethodCall:(FlutterMethodCall*)call {
NSMutableData* data = [NSMutableData dataWithCapacity:32];
FlutterStandardWriter* writer = [_readerWriter writerWithData:data];
[writer writeValue:call.method];
[writer writeValue:call.arguments];
return data;
}
- (NSData*)encodeSuccessEnvelope:(id)result {
NSMutableData* data = [NSMutableData dataWithCapacity:32];
FlutterStandardWriter* writer = [_readerWriter writerWithData:data];
[writer writeByte:0];
[writer writeValue:result];
return data;
}
- (NSData*)encodeErrorEnvelope:(FlutterError*)error {
NSMutableData* data = [NSMutableData dataWithCapacity:32];
FlutterStandardWriter* writer = [_readerWriter writerWithData:data];
[writer writeByte:1];
[writer writeValue:error.code];
[writer writeValue:error.message];
[writer writeValue:error.details];
return data;
}
- (FlutterMethodCall*)decodeMethodCall:(NSData*)message {
FlutterStandardReader* reader = [_readerWriter readerWithData:message];
id value1 = [reader readValue];
id value2 = [reader readValue];
NSAssert(![reader hasMore], @"Corrupted standard method call");
NSAssert([value1 isKindOfClass:[NSString class]], @"Corrupted standard method call");
return [FlutterMethodCall methodCallWithMethodName:value1 arguments:value2];
}
- (id)decodeEnvelope:(NSData*)envelope {
FlutterStandardReader* reader = [_readerWriter readerWithData:envelope];
UInt8 flag = [reader readByte];
NSAssert(flag <= 1, @"Corrupted standard envelope");
id result;
switch (flag) {
case 0: {
result = [reader readValue];
NSAssert(![reader hasMore], @"Corrupted standard envelope");
} break;
case 1: {
id code = [reader readValue];
id message = [reader readValue];
id details = [reader readValue];
NSAssert(![reader hasMore], @"Corrupted standard envelope");
NSAssert([code isKindOfClass:[NSString class]], @"Invalid standard envelope");
NSAssert(message == nil || [message isKindOfClass:[NSString class]],
@"Invalid standard envelope");
result = [FlutterError errorWithCode:code message:message details:details];
} break;
}
return result;
}
@end
using namespace flutter;
#pragma mark - Standard serializable types
@implementation FlutterStandardTypedData
+ (instancetype)typedDataWithBytes:(NSData*)data {
return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeUInt8];
}
+ (instancetype)typedDataWithInt32:(NSData*)data {
return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeInt32];
}
+ (instancetype)typedDataWithInt64:(NSData*)data {
return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeInt64];
}
+ (instancetype)typedDataWithFloat32:(NSData*)data {
return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeFloat32];
}
+ (instancetype)typedDataWithFloat64:(NSData*)data {
return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeFloat64];
}
+ (instancetype)typedDataWithData:(NSData*)data type:(FlutterStandardDataType)type {
return [[FlutterStandardTypedData alloc] initWithData:data type:type];
}
- (instancetype)initWithData:(NSData*)data type:(FlutterStandardDataType)type {
UInt8 elementSize = elementSizeForFlutterStandardDataType(type);
NSAssert(data, @"Data cannot be nil");
NSAssert(data.length % elementSize == 0, @"Data must contain integral number of elements");
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_data = [data copy];
_type = type;
_elementSize = elementSize;
_elementCount = data.length / elementSize;
return self;
}
- (BOOL)isEqual:(id)object {
if (self == object) {
return YES;
}
if (![object isKindOfClass:[FlutterStandardTypedData class]]) {
return NO;
}
FlutterStandardTypedData* other = (FlutterStandardTypedData*)object;
return self.type == other.type && self.elementCount == other.elementCount &&
[self.data isEqual:other.data];
}
- (NSUInteger)hash {
return [self.data hash] ^ self.type;
}
@end
#pragma mark - Writer and reader of standard codec
@implementation FlutterStandardWriter {
NSMutableData* _data;
}
- (instancetype)initWithData:(NSMutableData*)data {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_data = data;
return self;
}
- (void)writeByte:(UInt8)value {
FlutterStandardCodecHelperWriteByte((__bridge CFMutableDataRef)_data, value);
}
- (void)writeBytes:(const void*)bytes length:(NSUInteger)length {
FlutterStandardCodecHelperWriteBytes((__bridge CFMutableDataRef)_data, bytes, length);
}
- (void)writeData:(NSData*)data {
FlutterStandardCodecHelperWriteData((__bridge CFMutableDataRef)_data, (__bridge CFDataRef)data);
}
- (void)writeSize:(UInt32)size {
FlutterStandardCodecHelperWriteSize((__bridge CFMutableDataRef)_data, size);
}
- (void)writeAlignment:(UInt8)alignment {
FlutterStandardCodecHelperWriteAlignment((__bridge CFMutableDataRef)_data, alignment);
}
- (void)writeUTF8:(NSString*)value {
FlutterStandardCodecHelperWriteUTF8((__bridge CFMutableDataRef)_data,
(__bridge CFStringRef)value);
}
static FlutterStandardCodecObjcType GetWriteType(id value) {
if (value == nil || (__bridge CFNullRef)value == kCFNull) {
return FlutterStandardCodecObjcTypeNil;
} else if ([value isKindOfClass:[NSNumber class]]) {
return FlutterStandardCodecObjcTypeNSNumber;
} else if ([value isKindOfClass:[NSString class]]) {
return FlutterStandardCodecObjcTypeNSString;
} else if ([value isKindOfClass:[FlutterStandardTypedData class]]) {
return FlutterStandardCodecObjcTypeFlutterStandardTypedData;
} else if ([value isKindOfClass:[NSData class]]) {
return FlutterStandardCodecObjcTypeNSData;
} else if ([value isKindOfClass:[NSArray class]]) {
return FlutterStandardCodecObjcTypeNSArray;
} else if ([value isKindOfClass:[NSDictionary class]]) {
return FlutterStandardCodecObjcTypeNSDictionary;
} else {
return FlutterStandardCodecObjcTypeUnknown;
}
}
struct WriteKeyValuesInfo {
CFTypeRef writer;
CFMutableDataRef data;
};
static void WriteKeyValues(CFTypeRef key, CFTypeRef value, void* context) {
WriteKeyValuesInfo* info = (WriteKeyValuesInfo*)context;
FastWriteValueOfType(info->writer, info->data, key);
FastWriteValueOfType(info->writer, info->data, value);
}
// Recurses into WriteValueOfType directly if it is writing a known type,
// otherwise recurses with objc_msgSend.
static void FastWriteValueOfType(CFTypeRef writer, CFMutableDataRef data, CFTypeRef value) {
FlutterStandardCodecObjcType type = GetWriteType((__bridge id)value);
if (type != FlutterStandardCodecObjcTypeUnknown) {
WriteValueOfType(writer, data, type, value);
} else {
[(__bridge FlutterStandardWriter*)writer writeValue:(__bridge id)value];
}
}
static void WriteValueOfType(CFTypeRef writer,
CFMutableDataRef data,
FlutterStandardCodecObjcType type,
CFTypeRef value) {
switch (type) {
case FlutterStandardCodecObjcTypeNil:
FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldNil);
break;
case FlutterStandardCodecObjcTypeNSNumber: {
CFNumberRef number = (CFNumberRef)value;
BOOL success = FlutterStandardCodecHelperWriteNumber(data, number);
if (!success) {
NSLog(@"Unsupported value: %@ of number type %ld", value, CFNumberGetType(number));
NSCAssert(NO, @"Unsupported value for standard codec");
}
break;
}
case FlutterStandardCodecObjcTypeNSString: {
CFStringRef string = (CFStringRef)value;
FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldString);
FlutterStandardCodecHelperWriteUTF8(data, string);
break;
}
case FlutterStandardCodecObjcTypeFlutterStandardTypedData: {
FlutterStandardTypedData* typedData = (__bridge FlutterStandardTypedData*)value;
FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldForDataType(typedData.type));
FlutterStandardCodecHelperWriteSize(data, typedData.elementCount);
FlutterStandardCodecHelperWriteAlignment(data, typedData.elementSize);
FlutterStandardCodecHelperWriteData(data, (__bridge CFDataRef)typedData.data);
break;
}
case FlutterStandardCodecObjcTypeNSData:
WriteValueOfType(writer, data, FlutterStandardCodecObjcTypeFlutterStandardTypedData,
(__bridge CFTypeRef)
[FlutterStandardTypedData typedDataWithBytes:(__bridge NSData*)value]);
break;
case FlutterStandardCodecObjcTypeNSArray: {
CFArrayRef array = (CFArrayRef)value;
FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldList);
CFIndex count = CFArrayGetCount(array);
FlutterStandardCodecHelperWriteSize(data, count);
for (CFIndex i = 0; i < count; ++i) {
FastWriteValueOfType(writer, data, CFArrayGetValueAtIndex(array, i));
}
break;
}
case FlutterStandardCodecObjcTypeNSDictionary: {
CFDictionaryRef dict = (CFDictionaryRef)value;
FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldMap);
CFIndex count = CFDictionaryGetCount(dict);
FlutterStandardCodecHelperWriteSize(data, count);
WriteKeyValuesInfo info = {
.writer = writer,
.data = data,
};
CFDictionaryApplyFunction(dict, WriteKeyValues, (void*)&info);
break;
}
case FlutterStandardCodecObjcTypeUnknown: {
id objc_value = (__bridge id)value;
NSLog(@"Unsupported value: %@ of type %@", objc_value, [objc_value class]);
NSCAssert(NO, @"Unsupported value for standard codec");
break;
}
}
}
- (void)writeValue:(id)value {
FlutterStandardCodecObjcType type = GetWriteType(value);
WriteValueOfType((__bridge CFTypeRef)self, (__bridge CFMutableDataRef)self->_data, type,
(__bridge CFTypeRef)value);
}
@end
@implementation FlutterStandardReader {
NSData* _data;
NSRange _range;
}
- (instancetype)initWithData:(NSData*)data {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_data = [data copy];
_range = NSMakeRange(0, 0);
return self;
}
- (BOOL)hasMore {
return _range.location < _data.length;
}
- (void)readBytes:(void*)destination length:(NSUInteger)length {
FlutterStandardCodecHelperReadBytes(&_range.location, length, destination,
(__bridge CFDataRef)_data);
}
- (UInt8)readByte {
return FlutterStandardCodecHelperReadByte(&_range.location, (__bridge CFDataRef)_data);
}
- (UInt32)readSize {
return FlutterStandardCodecHelperReadSize(&_range.location, (__bridge CFDataRef)_data);
}
- (NSData*)readData:(NSUInteger)length {
_range.length = length;
NSData* data = [_data subdataWithRange:_range];
_range.location += _range.length;
return data;
}
- (NSString*)readUTF8 {
return (__bridge NSString*)FlutterStandardCodecHelperReadUTF8(&_range.location,
(__bridge CFDataRef)_data);
}
- (void)readAlignment:(UInt8)alignment {
FlutterStandardCodecHelperReadAlignment(&_range.location, alignment);
}
- (nullable id)readValue {
return (__bridge id)ReadValue((__bridge CFTypeRef)self);
}
static CFTypeRef ReadValue(CFTypeRef user_data) {
FlutterStandardReader* reader = (__bridge FlutterStandardReader*)user_data;
uint8_t type = FlutterStandardCodecHelperReadByte(&reader->_range.location,
(__bridge CFDataRef)reader->_data);
return (__bridge CFTypeRef)[reader readValueOfType:type];
}
static CFTypeRef ReadTypedDataOfType(FlutterStandardField field, CFTypeRef user_data) {
FlutterStandardReader* reader = (__bridge FlutterStandardReader*)user_data;
unsigned long* location = &reader->_range.location;
CFDataRef data = (__bridge CFDataRef)reader->_data;
FlutterStandardDataType type = FlutterStandardDataTypeForField(field);
UInt64 elementCount = FlutterStandardCodecHelperReadSize(location, data);
UInt64 elementSize = elementSizeForFlutterStandardDataType(type);
FlutterStandardCodecHelperReadAlignment(location, elementSize);
UInt64 length = elementCount * elementSize;
NSRange range = NSMakeRange(*location, length);
// Note: subdataWithRange performs better than CFDataCreate and
// CFDataCreateBytesNoCopy crashes.
NSData* bytes = [(__bridge NSData*)data subdataWithRange:range];
*location += length;
return (__bridge CFTypeRef)[FlutterStandardTypedData typedDataWithData:bytes type:type];
}
- (nullable id)readValueOfType:(UInt8)type {
return (__bridge id)FlutterStandardCodecHelperReadValueOfType(
&_range.location, (__bridge CFDataRef)_data, type, ReadValue, ReadTypedDataOfType,
(__bridge CFTypeRef)self);
}
@end
@implementation FlutterStandardReaderWriter
- (FlutterStandardWriter*)writerWithData:(NSMutableData*)data {
return [[FlutterStandardWriter alloc] initWithData:data];
}
- (FlutterStandardReader*)readerWithData:(NSData*)data {
return [[FlutterStandardReader alloc] initWithData:data];
}
@end
| engine/shell/platform/darwin/common/framework/Source/FlutterStandardCodec.mm/0 | {
"file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterStandardCodec.mm",
"repo_id": "engine",
"token_count": 5492
} | 370 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h"
#include "flutter/display_list/image/dl_image.h"
#include "impeller/base/validation.h"
#include "impeller/display_list/dl_image_impeller.h"
#include "impeller/renderer/backend/metal/texture_mtl.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkYUVAInfo.h"
#include "third_party/skia/include/gpu/GpuTypes.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "third_party/skia/include/gpu/GrYUVABackendTextures.h"
#include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h"
#include "third_party/skia/include/ports/SkCFObject.h"
FLUTTER_ASSERT_ARC
@implementation FlutterDarwinExternalTextureMetal {
CVMetalTextureCacheRef _textureCache;
NSObject<FlutterTexture>* _externalTexture;
BOOL _textureFrameAvailable;
sk_sp<flutter::DlImage> _externalImage;
CVPixelBufferRef _lastPixelBuffer;
OSType _pixelFormat;
BOOL _enableImpeller;
}
- (instancetype)initWithTextureCache:(nonnull CVMetalTextureCacheRef)textureCache
textureID:(int64_t)textureID
texture:(NSObject<FlutterTexture>*)texture
enableImpeller:(BOOL)enableImpeller {
if (self = [super init]) {
_textureCache = textureCache;
CFRetain(_textureCache);
_textureID = textureID;
_externalTexture = texture;
_enableImpeller = enableImpeller;
return self;
}
return nil;
}
- (void)dealloc {
CVPixelBufferRelease(_lastPixelBuffer);
if (_textureCache) {
CVMetalTextureCacheFlush(_textureCache, // cache
0 // options (must be zero)
);
CFRelease(_textureCache);
}
}
- (void)paintContext:(flutter::Texture::PaintContext&)context
bounds:(const SkRect&)bounds
freeze:(BOOL)freeze
sampling:(const flutter::DlImageSampling)sampling {
const bool needsUpdatedTexture = (!freeze && _textureFrameAvailable) || !_externalImage;
if (needsUpdatedTexture) {
[self onNeedsUpdatedTexture:context];
}
if (_externalImage) {
context.canvas->DrawImageRect(_externalImage, // image
SkRect::Make(_externalImage->bounds()), // source rect
bounds, // destination rect
sampling, // sampling
context.paint, // paint
flutter::DlCanvas::SrcRectConstraint::kStrict // enforce edges
);
}
}
- (void)onNeedsUpdatedTexture:(flutter::Texture::PaintContext&)context {
CVPixelBufferRef pixelBuffer = [_externalTexture copyPixelBuffer];
if (pixelBuffer) {
CVPixelBufferRelease(_lastPixelBuffer);
_lastPixelBuffer = pixelBuffer;
_pixelFormat = CVPixelBufferGetPixelFormatType(_lastPixelBuffer);
}
// If the application told us there was a texture frame available but did not provide one when
// asked for it, reuse the previous texture but make sure to ask again the next time around.
sk_sp<flutter::DlImage> image = [self wrapExternalPixelBuffer:_lastPixelBuffer context:context];
if (image) {
_externalImage = image;
_textureFrameAvailable = false;
}
}
- (void)onGrContextCreated {
// External images in this backend have no thread affinity and are not tied to the context in any
// way. Instead, they are tied to the Metal device which is associated with the cache already and
// is consistent throughout the shell run.
}
- (void)onGrContextDestroyed {
// The image must be reset because it is tied to the onscreen context. But the pixel buffer that
// created the image is still around. In case of context reacquisition, that last pixel
// buffer will be used to materialize the image in case the application fails to provide a new
// one.
_externalImage.reset();
CVMetalTextureCacheFlush(_textureCache, // cache
0 // options (must be zero)
);
}
- (void)markNewFrameAvailable {
_textureFrameAvailable = YES;
}
- (void)onTextureUnregistered {
if ([_externalTexture respondsToSelector:@selector(onTextureUnregistered:)]) {
[_externalTexture onTextureUnregistered:_externalTexture];
}
}
#pragma mark - External texture skia wrapper methods.
- (sk_sp<flutter::DlImage>)wrapExternalPixelBuffer:(CVPixelBufferRef)pixelBuffer
context:(flutter::Texture::PaintContext&)context {
if (!pixelBuffer) {
return nullptr;
}
sk_sp<flutter::DlImage> image = nullptr;
if (_pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange ||
_pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) {
image = [self wrapNV12ExternalPixelBuffer:pixelBuffer context:context];
} else {
image = [self wrapRGBAExternalPixelBuffer:pixelBuffer context:context];
}
if (!image) {
FML_DLOG(ERROR) << "Could not wrap Metal texture as a display list image.";
}
return image;
}
- (sk_sp<flutter::DlImage>)wrapNV12ExternalPixelBuffer:(CVPixelBufferRef)pixelBuffer
context:(flutter::Texture::PaintContext&)context {
SkISize textureSize =
SkISize::Make(CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer));
CVMetalTextureRef yMetalTexture = nullptr;
{
CVReturn cvReturn =
CVMetalTextureCacheCreateTextureFromImage(/*allocator=*/kCFAllocatorDefault,
/*textureCache=*/_textureCache,
/*sourceImage=*/pixelBuffer,
/*textureAttributes=*/nullptr,
/*pixelFormat=*/MTLPixelFormatR8Unorm,
/*width=*/textureSize.width(),
/*height=*/textureSize.height(),
/*planeIndex=*/0u,
/*texture=*/&yMetalTexture);
if (cvReturn != kCVReturnSuccess) {
FML_DLOG(ERROR) << "Could not create Metal texture from pixel buffer: CVReturn " << cvReturn;
return nullptr;
}
}
CVMetalTextureRef uvMetalTexture = nullptr;
{
CVReturn cvReturn =
CVMetalTextureCacheCreateTextureFromImage(/*allocator=*/kCFAllocatorDefault,
/*textureCache=*/_textureCache,
/*sourceImage=*/pixelBuffer,
/*textureAttributes=*/nullptr,
/*pixelFormat=*/MTLPixelFormatRG8Unorm,
/*width=*/textureSize.width() / 2,
/*height=*/textureSize.height() / 2,
/*planeIndex=*/1u,
/*texture=*/&uvMetalTexture);
if (cvReturn != kCVReturnSuccess) {
FML_DLOG(ERROR) << "Could not create Metal texture from pixel buffer: CVReturn " << cvReturn;
return nullptr;
}
}
id<MTLTexture> yTex = CVMetalTextureGetTexture(yMetalTexture);
CVBufferRelease(yMetalTexture);
id<MTLTexture> uvTex = CVMetalTextureGetTexture(uvMetalTexture);
CVBufferRelease(uvMetalTexture);
if (_enableImpeller) {
impeller::TextureDescriptor yDesc;
yDesc.storage_mode = impeller::StorageMode::kHostVisible;
yDesc.format = impeller::PixelFormat::kR8UNormInt;
yDesc.size = {textureSize.width(), textureSize.height()};
yDesc.mip_count = 1;
auto yTexture = impeller::TextureMTL::Wrapper(yDesc, yTex);
yTexture->SetCoordinateSystem(impeller::TextureCoordinateSystem::kUploadFromHost);
impeller::TextureDescriptor uvDesc;
uvDesc.storage_mode = impeller::StorageMode::kHostVisible;
uvDesc.format = impeller::PixelFormat::kR8G8UNormInt;
uvDesc.size = {textureSize.width() / 2, textureSize.height() / 2};
uvDesc.mip_count = 1;
auto uvTexture = impeller::TextureMTL::Wrapper(uvDesc, uvTex);
uvTexture->SetCoordinateSystem(impeller::TextureCoordinateSystem::kUploadFromHost);
impeller::YUVColorSpace yuvColorSpace =
_pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
? impeller::YUVColorSpace::kBT601LimitedRange
: impeller::YUVColorSpace::kBT601FullRange;
return impeller::DlImageImpeller::MakeFromYUVTextures(context.aiks_context, yTexture, uvTexture,
yuvColorSpace);
}
SkYUVColorSpace colorSpace = _pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
? kRec601_Limited_SkYUVColorSpace
: kJPEG_Full_SkYUVColorSpace;
auto skImage = [FlutterDarwinExternalTextureSkImageWrapper wrapYUVATexture:yTex
UVTex:uvTex
YUVColorSpace:colorSpace
grContext:context.gr_context
width:textureSize.width()
height:textureSize.height()];
if (!skImage) {
return nullptr;
}
// This image should not escape local use by this flutter::Texture implementation
return flutter::DlImage::Make(skImage);
}
- (sk_sp<flutter::DlImage>)wrapRGBAExternalPixelBuffer:(CVPixelBufferRef)pixelBuffer
context:(flutter::Texture::PaintContext&)context {
SkISize textureSize =
SkISize::Make(CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer));
CVMetalTextureRef metalTexture = nullptr;
CVReturn cvReturn =
CVMetalTextureCacheCreateTextureFromImage(/*allocator=*/kCFAllocatorDefault,
/*textureCache=*/_textureCache,
/*sourceImage=*/pixelBuffer,
/*textureAttributes=*/nullptr,
/*pixelFormat=*/MTLPixelFormatBGRA8Unorm,
/*width=*/textureSize.width(),
/*height=*/textureSize.height(),
/*planeIndex=*/0u,
/*texture=*/&metalTexture);
if (cvReturn != kCVReturnSuccess) {
FML_DLOG(ERROR) << "Could not create Metal texture from pixel buffer: CVReturn " << cvReturn;
return nullptr;
}
id<MTLTexture> rgbaTex = CVMetalTextureGetTexture(metalTexture);
CVBufferRelease(metalTexture);
if (_enableImpeller) {
impeller::TextureDescriptor desc;
desc.storage_mode = impeller::StorageMode::kHostVisible;
desc.format = impeller::PixelFormat::kB8G8R8A8UNormInt;
desc.size = {textureSize.width(), textureSize.height()};
desc.mip_count = 1;
auto texture = impeller::TextureMTL::Wrapper(desc, rgbaTex);
texture->SetCoordinateSystem(impeller::TextureCoordinateSystem::kUploadFromHost);
return impeller::DlImageImpeller::Make(texture);
}
auto skImage = [FlutterDarwinExternalTextureSkImageWrapper wrapRGBATexture:rgbaTex
grContext:context.gr_context
width:textureSize.width()
height:textureSize.height()];
if (!skImage) {
return nullptr;
}
// This image should not escape local use by this flutter::Texture implementation
return flutter::DlImage::Make(skImage);
}
@end
@implementation FlutterDarwinExternalTextureSkImageWrapper
+ (sk_sp<SkImage>)wrapYUVATexture:(id<MTLTexture>)yTex
UVTex:(id<MTLTexture>)uvTex
YUVColorSpace:(SkYUVColorSpace)colorSpace
grContext:(nonnull GrDirectContext*)grContext
width:(size_t)width
height:(size_t)height {
GrMtlTextureInfo ySkiaTextureInfo;
ySkiaTextureInfo.fTexture = sk_cfp<const void*>{(__bridge_retained const void*)yTex};
GrBackendTexture skiaBackendTextures[2];
skiaBackendTextures[0] = GrBackendTexture(/*width=*/width,
/*height=*/height,
/*mipMapped=*/skgpu::Mipmapped::kNo,
/*mtlInfo=*/ySkiaTextureInfo);
GrMtlTextureInfo uvSkiaTextureInfo;
uvSkiaTextureInfo.fTexture = sk_cfp<const void*>{(__bridge_retained const void*)uvTex};
skiaBackendTextures[1] = GrBackendTexture(/*width=*/width,
/*height=*/height,
/*mipMapped=*/skgpu::Mipmapped::kNo,
/*mtlInfo=*/uvSkiaTextureInfo);
SkYUVAInfo yuvaInfo(skiaBackendTextures[0].dimensions(), SkYUVAInfo::PlaneConfig::kY_UV,
SkYUVAInfo::Subsampling::k444, colorSpace);
GrYUVABackendTextures yuvaBackendTextures(yuvaInfo, skiaBackendTextures,
kTopLeft_GrSurfaceOrigin);
return SkImages::TextureFromYUVATextures(grContext, yuvaBackendTextures,
/*imageColorSpace=*/nullptr,
/*releaseProc*/ nullptr, /*releaseContext*/ nullptr);
}
+ (sk_sp<SkImage>)wrapRGBATexture:(id<MTLTexture>)rgbaTex
grContext:(nonnull GrDirectContext*)grContext
width:(size_t)width
height:(size_t)height {
GrMtlTextureInfo skiaTextureInfo;
skiaTextureInfo.fTexture = sk_cfp<const void*>{(__bridge_retained const void*)rgbaTex};
GrBackendTexture skiaBackendTexture(/*width=*/width,
/*height=*/height,
/*mipMapped=*/skgpu::Mipmapped ::kNo,
/*mtlInfo=*/skiaTextureInfo);
return SkImages::BorrowTextureFrom(grContext, skiaBackendTexture, kTopLeft_GrSurfaceOrigin,
kBGRA_8888_SkColorType, kPremul_SkAlphaType,
/*colorSpace=*/nullptr, /*releaseProc*/ nullptr,
/*releaseContext*/ nullptr);
}
@end
| engine/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm/0 | {
"file_path": "engine/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm",
"repo_id": "engine",
"token_count": 7356
} | 371 |
// Copyright 2013 The Flutter 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/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h"
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h"
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate_Test.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h"
FLUTTER_ASSERT_ARC
@interface FlutterAppDelegateTest : XCTestCase
@property(strong) FlutterAppDelegate* appDelegate;
@property(strong) id mockMainBundle;
@property(strong) id mockNavigationChannel;
// Retain callback until the tests are done.
// https://github.com/flutter/flutter/issues/74267
@property(strong) id mockEngineFirstFrameCallback;
@end
@implementation FlutterAppDelegateTest
- (void)setUp {
[super setUp];
id mockMainBundle = OCMClassMock([NSBundle class]);
OCMStub([mockMainBundle mainBundle]).andReturn(mockMainBundle);
self.mockMainBundle = mockMainBundle;
FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init];
self.appDelegate = appDelegate;
FlutterViewController* viewController = OCMClassMock([FlutterViewController class]);
FlutterMethodChannel* navigationChannel = OCMClassMock([FlutterMethodChannel class]);
self.mockNavigationChannel = navigationChannel;
FlutterEngine* engine = OCMClassMock([FlutterEngine class]);
OCMStub([engine navigationChannel]).andReturn(navigationChannel);
OCMStub([viewController engine]).andReturn(engine);
id mockEngineFirstFrameCallback = [OCMArg invokeBlockWithArgs:@NO, nil];
self.mockEngineFirstFrameCallback = mockEngineFirstFrameCallback;
OCMStub([engine waitForFirstFrame:3.0 callback:mockEngineFirstFrameCallback]);
appDelegate.rootFlutterViewControllerGetter = ^{
return viewController;
};
}
- (void)tearDown {
// Explicitly stop mocking the NSBundle class property.
[self.mockMainBundle stopMocking];
[super tearDown];
}
- (void)testLaunchUrl {
OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"])
.andReturn(@YES);
BOOL result =
[self.appDelegate application:[UIApplication sharedApplication]
openURL:[NSURL URLWithString:@"http://myApp/custom/route?query=test"]
options:@{}];
XCTAssertTrue(result);
OCMVerify([self.mockNavigationChannel
invokeMethod:@"pushRouteInformation"
arguments:@{@"location" : @"http://myApp/custom/route?query=test"}]);
}
- (void)testLaunchUrlWithDeepLinkingNotSet {
OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"])
.andReturn(nil);
BOOL result =
[self.appDelegate application:[UIApplication sharedApplication]
openURL:[NSURL URLWithString:@"http://myApp/custom/route?query=test"]
options:@{}];
XCTAssertFalse(result);
OCMReject([self.mockNavigationChannel invokeMethod:OCMOCK_ANY arguments:OCMOCK_ANY]);
}
- (void)testLaunchUrlWithDeepLinkingDisabled {
OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"])
.andReturn(@NO);
BOOL result =
[self.appDelegate application:[UIApplication sharedApplication]
openURL:[NSURL URLWithString:@"http://myApp/custom/route?query=test"]
options:@{}];
XCTAssertFalse(result);
OCMReject([self.mockNavigationChannel invokeMethod:OCMOCK_ANY arguments:OCMOCK_ANY]);
}
- (void)testLaunchUrlWithQueryParameterAndFragment {
OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"])
.andReturn(@YES);
BOOL result = [self.appDelegate
application:[UIApplication sharedApplication]
openURL:[NSURL URLWithString:@"http://myApp/custom/route?query=test#fragment"]
options:@{}];
XCTAssertTrue(result);
OCMVerify([self.mockNavigationChannel
invokeMethod:@"pushRouteInformation"
arguments:@{@"location" : @"http://myApp/custom/route?query=test#fragment"}]);
}
- (void)testLaunchUrlWithFragmentNoQueryParameter {
OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"])
.andReturn(@YES);
BOOL result =
[self.appDelegate application:[UIApplication sharedApplication]
openURL:[NSURL URLWithString:@"http://myApp/custom/route#fragment"]
options:@{}];
XCTAssertTrue(result);
OCMVerify([self.mockNavigationChannel
invokeMethod:@"pushRouteInformation"
arguments:@{@"location" : @"http://myApp/custom/route#fragment"}]);
}
- (void)testReleasesWindowOnDealloc {
__weak UIWindow* weakWindow;
@autoreleasepool {
id mockWindow = OCMClassMock([UIWindow class]);
FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init];
appDelegate.window = mockWindow;
weakWindow = mockWindow;
XCTAssertNotNil(weakWindow);
[mockWindow stopMocking];
mockWindow = nil;
appDelegate = nil;
}
// App delegate has released the window.
XCTAssertNil(weakWindow);
}
#pragma mark - Deep linking
- (void)testUniversalLinkPushRouteInformation {
OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"])
.andReturn(@YES);
NSUserActivity* userActivity = [[NSUserActivity alloc] initWithActivityType:@"com.example.test"];
userActivity.webpageURL = [NSURL URLWithString:@"http://myApp/custom/route?query=test"];
BOOL result = [self.appDelegate
application:[UIApplication sharedApplication]
continueUserActivity:userActivity
restorationHandler:^(NSArray<id<UIUserActivityRestoring>>* __nullable restorableObjects){
}];
XCTAssertTrue(result);
OCMVerify([self.mockNavigationChannel
invokeMethod:@"pushRouteInformation"
arguments:@{@"location" : @"http://myApp/custom/route?query=test"}]);
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterAppDelegateTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterAppDelegateTest.mm",
"repo_id": "engine",
"token_count": 2305
} | 372 |
// Copyright 2013 The Flutter 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/Headers/FlutterEngineGroup.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h"
@implementation FlutterEngineGroupOptions
- (void)dealloc {
[_entrypoint release];
[_libraryURI release];
[_initialRoute release];
[_entrypointArgs release];
[super dealloc];
}
@end
@interface FlutterEngineGroup ()
@property(nonatomic, copy) NSString* name;
@property(nonatomic, retain) NSMutableArray<NSValue*>* engines;
@property(nonatomic, retain) FlutterDartProject* project;
@end
@implementation FlutterEngineGroup {
int _enginesCreatedCount;
}
- (instancetype)initWithName:(NSString*)name project:(nullable FlutterDartProject*)project {
self = [super init];
if (self) {
_name = [name copy];
_engines = [[NSMutableArray<NSValue*> alloc] init];
_project = [project retain];
}
return self;
}
- (void)dealloc {
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center removeObserver:self];
[_name release];
[_engines release];
[_project release];
[super dealloc];
}
- (FlutterEngine*)makeEngineWithEntrypoint:(nullable NSString*)entrypoint
libraryURI:(nullable NSString*)libraryURI {
return [self makeEngineWithEntrypoint:entrypoint libraryURI:libraryURI initialRoute:nil];
}
- (FlutterEngine*)makeEngineWithEntrypoint:(nullable NSString*)entrypoint
libraryURI:(nullable NSString*)libraryURI
initialRoute:(nullable NSString*)initialRoute {
FlutterEngineGroupOptions* options = [[[FlutterEngineGroupOptions alloc] init] autorelease];
options.entrypoint = entrypoint;
options.libraryURI = libraryURI;
options.initialRoute = initialRoute;
return [self makeEngineWithOptions:options];
}
- (FlutterEngine*)makeEngineWithOptions:(nullable FlutterEngineGroupOptions*)options {
NSString* entrypoint = options.entrypoint;
NSString* libraryURI = options.libraryURI;
NSString* initialRoute = options.initialRoute;
NSArray<NSString*>* entrypointArgs = options.entrypointArgs;
FlutterEngine* engine;
if (self.engines.count <= 0) {
engine = [self makeEngine];
[engine runWithEntrypoint:entrypoint
libraryURI:libraryURI
initialRoute:initialRoute
entrypointArgs:entrypointArgs];
} else {
FlutterEngine* spawner = (FlutterEngine*)[self.engines[0] pointerValue];
engine = [spawner spawnWithEntrypoint:entrypoint
libraryURI:libraryURI
initialRoute:initialRoute
entrypointArgs:entrypointArgs];
}
[_engines addObject:[NSValue valueWithPointer:engine]];
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(onEngineWillBeDealloced:)
name:kFlutterEngineWillDealloc
object:engine];
return engine;
}
- (FlutterEngine*)makeEngine {
NSString* engineName = [NSString stringWithFormat:@"%@.%d", self.name, ++_enginesCreatedCount];
FlutterEngine* result = [[FlutterEngine alloc] initWithName:engineName project:self.project];
return [result autorelease];
}
- (void)onEngineWillBeDealloced:(NSNotification*)notification {
[_engines removeObject:[NSValue valueWithPointer:notification.object]];
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterEngineGroup.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterEngineGroup.mm",
"repo_id": "engine",
"token_count": 1284
} | 373 |
// Copyright 2013 The Flutter 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 <IOSurface/IOSurfaceObjC.h>
#include <Metal/Metal.h>
#include <UIKit/UIKit.h>
#include "flutter/fml/logging.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h"
@interface DisplayLinkManager : NSObject
@property(class, nonatomic, readonly) BOOL maxRefreshRateEnabledOnIPhone;
+ (double)displayRefreshRate;
@end
@class FlutterTexture;
@class FlutterDrawable;
extern CFTimeInterval display_link_target;
@interface FlutterMetalLayer () {
id<MTLDevice> _preferredDevice;
CGSize _drawableSize;
NSUInteger _nextDrawableId;
NSMutableSet<FlutterTexture*>* _availableTextures;
NSUInteger _totalTextures;
FlutterTexture* _front;
// There must be a CADisplayLink scheduled *on main thread* otherwise
// core animation only updates layers 60 times a second.
CADisplayLink* _displayLink;
NSUInteger _displayLinkPauseCountdown;
// Used to track whether the content was set during this display link.
// When unlocking phone the layer (main thread) display link and raster thread
// display link get out of sync for several seconds. Even worse, layer display
// link does not seem to reflect actual vsync. Forcing the layer link
// to max rate (instead range) temporarily seems to fix the issue.
BOOL _didSetContentsDuringThisDisplayLinkPeriod;
// Whether layer displayLink is forced to max rate.
BOOL _displayLinkForcedMaxRate;
}
- (void)presentTexture:(FlutterTexture*)texture;
- (void)returnTexture:(FlutterTexture*)texture;
@end
@interface FlutterTexture : NSObject {
id<MTLTexture> _texture;
IOSurface* _surface;
CFTimeInterval _presentedTime;
}
@property(readonly, nonatomic) id<MTLTexture> texture;
@property(readonly, nonatomic) IOSurface* surface;
@property(readwrite, nonatomic) CFTimeInterval presentedTime;
@property(readwrite, atomic) BOOL waitingForCompletion;
@end
@implementation FlutterTexture
@synthesize texture = _texture;
@synthesize surface = _surface;
@synthesize presentedTime = _presentedTime;
@synthesize waitingForCompletion;
- (instancetype)initWithTexture:(id<MTLTexture>)texture surface:(IOSurface*)surface {
if (self = [super init]) {
_texture = texture;
_surface = surface;
}
return self;
}
@end
@interface FlutterDrawable : NSObject <FlutterMetalDrawable> {
FlutterTexture* _texture;
__weak FlutterMetalLayer* _layer;
NSUInteger _drawableId;
BOOL _presented;
}
- (instancetype)initWithTexture:(FlutterTexture*)texture
layer:(FlutterMetalLayer*)layer
drawableId:(NSUInteger)drawableId;
@end
@implementation FlutterDrawable
- (instancetype)initWithTexture:(FlutterTexture*)texture
layer:(FlutterMetalLayer*)layer
drawableId:(NSUInteger)drawableId {
if (self = [super init]) {
_texture = texture;
_layer = layer;
_drawableId = drawableId;
}
return self;
}
- (id<MTLTexture>)texture {
return self->_texture.texture;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
- (CAMetalLayer*)layer {
return (id)self->_layer;
}
#pragma clang diagnostic pop
- (NSUInteger)drawableID {
return self->_drawableId;
}
- (CFTimeInterval)presentedTime {
return 0;
}
- (void)present {
[_layer presentTexture:self->_texture];
self->_presented = YES;
}
- (void)dealloc {
if (!_presented) {
[_layer returnTexture:self->_texture];
}
}
- (void)addPresentedHandler:(nonnull MTLDrawablePresentedHandler)block {
FML_LOG(WARNING) << "FlutterMetalLayer drawable does not implement addPresentedHandler:";
}
- (void)presentAtTime:(CFTimeInterval)presentationTime {
FML_LOG(WARNING) << "FlutterMetalLayer drawable does not implement presentAtTime:";
}
- (void)presentAfterMinimumDuration:(CFTimeInterval)duration {
FML_LOG(WARNING) << "FlutterMetalLayer drawable does not implement presentAfterMinimumDuration:";
}
- (void)flutterPrepareForPresent:(nonnull id<MTLCommandBuffer>)commandBuffer {
FlutterTexture* texture = _texture;
texture.waitingForCompletion = YES;
[commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> buffer) {
texture.waitingForCompletion = NO;
}];
}
@end
@implementation FlutterMetalLayer
@synthesize preferredDevice = _preferredDevice;
@synthesize device = _device;
@synthesize pixelFormat = _pixelFormat;
@synthesize framebufferOnly = _framebufferOnly;
@synthesize colorspace = _colorspace;
@synthesize wantsExtendedDynamicRangeContent = _wantsExtendedDynamicRangeContent;
- (instancetype)init {
if (self = [super init]) {
_preferredDevice = MTLCreateSystemDefaultDevice();
self.device = self.preferredDevice;
self.pixelFormat = MTLPixelFormatBGRA8Unorm;
_availableTextures = [[NSMutableSet alloc] init];
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(onDisplayLink:)];
[self setMaxRefreshRate:[DisplayLinkManager displayRefreshRate] forceMax:NO];
[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setMaxRefreshRate:(double)refreshRate forceMax:(BOOL)forceMax {
// This is copied from vsync_waiter_ios.mm. The vsync waiter has display link scheduled on UI
// thread which does not trigger actual core animation frame. As a workaround FlutterMetalLayer
// has it's own displaylink scheduled on main thread, which is used to trigger core animation
// frame allowing for 120hz updates.
if (!DisplayLinkManager.maxRefreshRateEnabledOnIPhone) {
return;
}
double maxFrameRate = fmax(refreshRate, 60);
double minFrameRate = fmax(maxFrameRate / 2, 60);
if (@available(iOS 15.0, *)) {
_displayLink.preferredFrameRateRange =
CAFrameRateRangeMake(forceMax ? maxFrameRate : minFrameRate, maxFrameRate, maxFrameRate);
} else {
_displayLink.preferredFramesPerSecond = maxFrameRate;
}
}
- (void)onDisplayLink:(CADisplayLink*)link {
_didSetContentsDuringThisDisplayLinkPeriod = NO;
// Do not pause immediately, this seems to prevent 120hz while touching.
if (_displayLinkPauseCountdown == 3) {
_displayLink.paused = YES;
if (_displayLinkForcedMaxRate) {
[self setMaxRefreshRate:[DisplayLinkManager displayRefreshRate] forceMax:NO];
_displayLinkForcedMaxRate = NO;
}
} else {
++_displayLinkPauseCountdown;
}
}
- (BOOL)isKindOfClass:(Class)aClass {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
// Pretend that we're a CAMetalLayer so that the rest of Flutter plays along
if ([aClass isEqual:[CAMetalLayer class]]) {
return YES;
}
#pragma clang diagnostic pop
return [super isKindOfClass:aClass];
}
- (void)setDrawableSize:(CGSize)drawableSize {
[_availableTextures removeAllObjects];
_front = nil;
_totalTextures = 0;
_drawableSize = drawableSize;
}
- (void)didEnterBackground:(id)notification {
[_availableTextures removeAllObjects];
_totalTextures = _front != nil ? 1 : 0;
_displayLink.paused = YES;
}
- (CGSize)drawableSize {
return _drawableSize;
}
- (IOSurface*)createIOSurface {
unsigned pixelFormat;
unsigned bytesPerElement;
if (self.pixelFormat == MTLPixelFormatRGBA16Float) {
pixelFormat = kCVPixelFormatType_64RGBAHalf;
bytesPerElement = 8;
} else if (self.pixelFormat == MTLPixelFormatBGRA8Unorm) {
pixelFormat = kCVPixelFormatType_32BGRA;
bytesPerElement = 4;
} else {
FML_LOG(ERROR) << "Unsupported pixel format: " << self.pixelFormat;
return nil;
}
size_t bytesPerRow =
IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, _drawableSize.width * bytesPerElement);
size_t totalBytes =
IOSurfaceAlignProperty(kIOSurfaceAllocSize, _drawableSize.height * bytesPerRow);
NSDictionary* options = @{
(id)kIOSurfaceWidth : @(_drawableSize.width),
(id)kIOSurfaceHeight : @(_drawableSize.height),
(id)kIOSurfacePixelFormat : @(pixelFormat),
(id)kIOSurfaceBytesPerElement : @(bytesPerElement),
(id)kIOSurfaceBytesPerRow : @(bytesPerRow),
(id)kIOSurfaceAllocSize : @(totalBytes),
};
IOSurfaceRef res = IOSurfaceCreate((CFDictionaryRef)options);
if (res == nil) {
FML_LOG(ERROR) << "Failed to create IOSurface with options "
<< options.debugDescription.UTF8String;
return nil;
}
if (self.colorspace != nil) {
CFStringRef name = CGColorSpaceGetName(self.colorspace);
IOSurfaceSetValue(res, CFSTR("IOSurfaceColorSpace"), name);
} else {
IOSurfaceSetValue(res, CFSTR("IOSurfaceColorSpace"), kCGColorSpaceSRGB);
}
return (__bridge_transfer IOSurface*)res;
}
- (FlutterTexture*)nextTexture {
CFTimeInterval start = CACurrentMediaTime();
while (true) {
FlutterTexture* texture = [self tryNextTexture];
if (texture != nil) {
return texture;
}
CFTimeInterval elapsed = CACurrentMediaTime() - start;
if (elapsed > 1.0) {
NSLog(@"Waited %f seconds for a drawable, giving up.", elapsed);
return nil;
}
}
}
- (FlutterTexture*)tryNextTexture {
@synchronized(self) {
if (_front != nil && _front.waitingForCompletion) {
return nil;
}
if (_totalTextures < 3) {
++_totalTextures;
IOSurface* surface = [self createIOSurface];
if (surface == nil) {
return nil;
}
MTLTextureDescriptor* textureDescriptor =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:_pixelFormat
width:_drawableSize.width
height:_drawableSize.height
mipmapped:NO];
if (_framebufferOnly) {
textureDescriptor.usage = MTLTextureUsageRenderTarget;
} else {
textureDescriptor.usage =
MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite;
}
id<MTLTexture> texture = [self.device newTextureWithDescriptor:textureDescriptor
iosurface:(__bridge IOSurfaceRef)surface
plane:0];
FlutterTexture* flutterTexture = [[FlutterTexture alloc] initWithTexture:texture
surface:surface];
return flutterTexture;
} else {
// Prefer surface that is not in use and has been presented the longest
// time ago.
// When isInUse is false, the surface is definitely not used by the compositor.
// When isInUse is true, the surface may be used by the compositor.
// When both surfaces are in use, the one presented earlier will be returned.
// The assumption here is that the compositor is already aware of the
// newer texture and is unlikely to read from the older one, even though it
// has not decreased the use count yet (there seems to be certain latency).
FlutterTexture* res = nil;
for (FlutterTexture* texture in _availableTextures) {
if (res == nil) {
res = texture;
} else if (res.surface.isInUse && !texture.surface.isInUse) {
// prefer texture that is not in use.
res = texture;
} else if (res.surface.isInUse == texture.surface.isInUse &&
texture.presentedTime < res.presentedTime) {
// prefer texture with older presented time.
res = texture;
}
}
if (res != nil) {
[_availableTextures removeObject:res];
}
return res;
}
}
}
- (id<CAMetalDrawable>)nextDrawable {
FlutterTexture* texture = [self nextTexture];
if (texture == nil) {
return nil;
}
FlutterDrawable* drawable = [[FlutterDrawable alloc] initWithTexture:texture
layer:self
drawableId:_nextDrawableId++];
return drawable;
}
- (void)presentOnMainThread:(FlutterTexture*)texture {
// This is needed otherwise frame gets skipped on touch begin / end. Go figure.
// Might also be placebo
[self setNeedsDisplay];
[CATransaction begin];
[CATransaction setDisableActions:YES];
self.contents = texture.surface;
[CATransaction commit];
_displayLink.paused = NO;
_displayLinkPauseCountdown = 0;
if (!_didSetContentsDuringThisDisplayLinkPeriod) {
_didSetContentsDuringThisDisplayLinkPeriod = YES;
} else if (!_displayLinkForcedMaxRate) {
_displayLinkForcedMaxRate = YES;
[self setMaxRefreshRate:[DisplayLinkManager displayRefreshRate] forceMax:YES];
}
}
- (void)presentTexture:(FlutterTexture*)texture {
@synchronized(self) {
if (_front != nil) {
[_availableTextures addObject:_front];
}
_front = texture;
texture.presentedTime = CACurrentMediaTime();
if ([NSThread isMainThread]) {
[self presentOnMainThread:texture];
} else {
// Core animation layers can only be updated on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
[self presentOnMainThread:texture];
});
}
}
}
- (void)returnTexture:(FlutterTexture*)texture {
@synchronized(self) {
[_availableTextures addObject:texture];
}
}
+ (BOOL)enabled {
static BOOL enabled = NO;
static BOOL didCheckInfoPlist = NO;
if (!didCheckInfoPlist) {
didCheckInfoPlist = YES;
NSNumber* use_flutter_metal_layer =
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTUseFlutterMetalLayer"];
if (use_flutter_metal_layer != nil && [use_flutter_metal_layer boolValue]) {
enabled = YES;
FML_LOG(WARNING) << "Using FlutterMetalLayer. This is an experimental feature.";
}
}
return enabled;
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm",
"repo_id": "engine",
"token_count": 5459
} | 374 |
// Copyright 2013 The Flutter 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/FlutterRestorationPlugin.h"
#import <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.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/FlutterViewController_Internal.h"
FLUTTER_ASSERT_ARC
@interface FlutterRestorationPlugin ()
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result;
@end
@interface FlutterRestorationPluginTest : XCTestCase
@end
@implementation FlutterRestorationPluginTest {
id restorationChannel;
}
- (void)setUp {
[super setUp];
restorationChannel = OCMClassMock([FlutterMethodChannel class]);
}
- (void)tearDown {
[restorationChannel stopMocking];
[super tearDown];
}
#pragma mark - Tests
- (void)testRestoratonViewControllerEncodeAndDecode {
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test"
project:nil
allowHeadlessExecution:YES
restorationEnabled:YES];
[engine run];
FlutterViewController* flutterViewController =
[[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
FlutterRestorationPlugin* restorationPlugin = flutterViewController.restorationPlugin;
NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding];
[restorationPlugin setRestorationData:data];
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initRequiringSecureCoding:YES];
[flutterViewController encodeRestorableStateWithCoder:archiver];
[restorationPlugin setRestorationData:nil];
NSKeyedUnarchiver* unarchiver =
[[NSKeyedUnarchiver alloc] initForReadingWithData:archiver.encodedData];
[flutterViewController decodeRestorableStateWithCoder:unarchiver];
XCTAssert([[restorationPlugin restorationData] isEqualToData:data],
"Restoration state data must be equal");
}
- (void)testRestorationEnabledWaitsForData {
FlutterRestorationPlugin* restorationPlugin =
[[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES];
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil];
__block id capturedResult;
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
capturedResult = result;
}];
XCTAssertNil(capturedResult);
NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding];
[restorationPlugin setRestorationData:data];
XCTAssertEqual([capturedResult count], 2u);
XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES);
XCTAssertEqualObjects([[capturedResult objectForKey:@"data"] data], data);
}
- (void)testRestorationDisabledRespondsRightAway {
FlutterRestorationPlugin* restorationPlugin =
[[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:NO];
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil];
__block id capturedResult;
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
capturedResult = result;
}];
XCTAssertEqual([capturedResult count], 1u);
XCTAssertEqual([capturedResult objectForKey:@"enabled"], @NO);
}
- (void)testRespondsRightAwayWhenDataIsSet {
FlutterRestorationPlugin* restorationPlugin =
[[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES];
NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding];
[restorationPlugin setRestorationData:data];
__block id capturedResult;
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil];
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
capturedResult = result;
}];
XCTAssertEqual([capturedResult count], 2u);
XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES);
XCTAssertEqualObjects([[capturedResult objectForKey:@"data"] data], data);
}
- (void)testRespondsWithNoDataWhenRestorationIsCompletedWithoutData {
FlutterRestorationPlugin* restorationPlugin =
[[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES];
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil];
__block id capturedResult;
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
capturedResult = result;
}];
XCTAssertNil(capturedResult);
[restorationPlugin markRestorationComplete];
XCTAssertEqual([capturedResult count], 1u);
XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES);
}
- (void)testRespondsRightAwayWithNoDataWhenRestorationIsCompleted {
FlutterRestorationPlugin* restorationPlugin =
[[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES];
[restorationPlugin markRestorationComplete];
__block id capturedResult;
FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil];
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
capturedResult = result;
}];
XCTAssertEqual([capturedResult count], 1u);
XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES);
}
- (void)testReturnsDataSetByFramework {
FlutterRestorationPlugin* restorationPlugin =
[[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES];
[restorationPlugin markRestorationComplete];
NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding];
FlutterMethodCall* methodCall = [FlutterMethodCall
methodCallWithMethodName:@"put"
arguments:[FlutterStandardTypedData typedDataWithBytes:data]];
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
XCTAssertNil(result);
}];
XCTAssertEqualObjects([restorationPlugin restorationData], data);
}
- (void)testRespondsWithDataSetByFramework {
FlutterRestorationPlugin* restorationPlugin =
[[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES];
[restorationPlugin markRestorationComplete];
NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding];
FlutterMethodCall* methodCall = [FlutterMethodCall
methodCallWithMethodName:@"put"
arguments:[FlutterStandardTypedData typedDataWithBytes:data]];
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
XCTAssertNil(result);
}];
XCTAssertEqualObjects([restorationPlugin restorationData], data);
__block id capturedResult;
methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil];
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
capturedResult = result;
}];
XCTAssertEqual([capturedResult count], 2u);
XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES);
XCTAssertEqualObjects([[capturedResult objectForKey:@"data"] data], data);
}
- (void)testResetClearsData {
FlutterRestorationPlugin* restorationPlugin =
[[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES];
[restorationPlugin markRestorationComplete];
NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding];
FlutterMethodCall* methodCall = [FlutterMethodCall
methodCallWithMethodName:@"put"
arguments:[FlutterStandardTypedData typedDataWithBytes:data]];
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
XCTAssertNil(result);
}];
XCTAssertEqualObjects([restorationPlugin restorationData], data);
[restorationPlugin reset];
XCTAssertNil([restorationPlugin restorationData]);
__block id capturedResult;
methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil];
[restorationPlugin handleMethodCall:methodCall
result:^(id _Nullable result) {
capturedResult = result;
}];
XCTAssertEqual([capturedResult count], 1u);
XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES);
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterRestorationPluginTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterRestorationPluginTest.mm",
"repo_id": "engine",
"token_count": 3674
} | 375 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/93360
// The only point of this file is to ensure that the Flutter framework umbrella header can be
// cleanly imported from an Objective-C translation unit. The target that uses this file copies the
// headers to a path that simulates how users would actually import the framework outside of the
// engine source root.
#import <Flutter/Flutter.h>
| engine/shell/platform/darwin/ios/framework/Source/FlutterUmbrellaImport.m/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterUmbrellaImport.m",
"repo_id": "engine",
"token_count": 148
} | 376 |
// Copyright 2013 The Flutter 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/SemanticsObject.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h"
namespace {
flutter::SemanticsAction GetSemanticsActionForScrollDirection(
UIAccessibilityScrollDirection direction) {
// To describe the vertical scroll direction, UIAccessibilityScrollDirection uses the
// direction the scroll bar moves in and SemanticsAction uses the direction the finger
// moves in. However, the horizontal scroll direction matches the SemanticsAction direction.
// That is way the following maps vertical opposite of the SemanticsAction, but the horizontal
// maps directly.
switch (direction) {
case UIAccessibilityScrollDirectionRight:
case UIAccessibilityScrollDirectionPrevious: // TODO(abarth): Support RTL using
// _node.textDirection.
return flutter::SemanticsAction::kScrollRight;
case UIAccessibilityScrollDirectionLeft:
case UIAccessibilityScrollDirectionNext: // TODO(abarth): Support RTL using
// _node.textDirection.
return flutter::SemanticsAction::kScrollLeft;
case UIAccessibilityScrollDirectionUp:
return flutter::SemanticsAction::kScrollDown;
case UIAccessibilityScrollDirectionDown:
return flutter::SemanticsAction::kScrollUp;
}
FML_DCHECK(false); // Unreachable
return flutter::SemanticsAction::kScrollUp;
}
SkM44 GetGlobalTransform(SemanticsObject* reference) {
SkM44 globalTransform = [reference node].transform;
for (SemanticsObject* parent = [reference parent]; parent; parent = parent.parent) {
globalTransform = parent.node.transform * globalTransform;
}
return globalTransform;
}
SkPoint ApplyTransform(SkPoint& point, const SkM44& transform) {
SkV4 vector = transform.map(point.x(), point.y(), 0, 1);
return SkPoint::Make(vector.x / vector.w, vector.y / vector.w);
}
CGPoint ConvertPointToGlobal(SemanticsObject* reference, CGPoint local_point) {
SkM44 globalTransform = GetGlobalTransform(reference);
SkPoint point = SkPoint::Make(local_point.x, local_point.y);
point = ApplyTransform(point, globalTransform);
// `rect` is in the physical pixel coordinate system. iOS expects the accessibility frame in
// the logical pixel coordinate system. Therefore, we divide by the `scale` (pixel ratio) to
// convert.
UIScreen* screen = [[[reference bridge]->view() window] screen];
// Screen can be nil if the FlutterView is covered by another native view.
CGFloat scale = screen == nil ? [UIScreen mainScreen].scale : screen.scale;
auto result = CGPointMake(point.x() / scale, point.y() / scale);
return [[reference bridge]->view() convertPoint:result toView:nil];
}
CGRect ConvertRectToGlobal(SemanticsObject* reference, CGRect local_rect) {
SkM44 globalTransform = GetGlobalTransform(reference);
SkPoint quad[4] = {
SkPoint::Make(local_rect.origin.x, local_rect.origin.y), // top left
SkPoint::Make(local_rect.origin.x + local_rect.size.width, local_rect.origin.y), // top right
SkPoint::Make(local_rect.origin.x + local_rect.size.width,
local_rect.origin.y + local_rect.size.height), // bottom right
SkPoint::Make(local_rect.origin.x,
local_rect.origin.y + local_rect.size.height) // bottom left
};
for (auto& point : quad) {
point = ApplyTransform(point, globalTransform);
}
SkRect rect;
NSCAssert(rect.setBoundsCheck(quad, 4), @"Transformed points can't form a rect");
rect.setBounds(quad, 4);
// `rect` is in the physical pixel coordinate system. iOS expects the accessibility frame in
// the logical pixel coordinate system. Therefore, we divide by the `scale` (pixel ratio) to
// convert.
UIScreen* screen = [[[reference bridge]->view() window] screen];
// Screen can be nil if the FlutterView is covered by another native view.
CGFloat scale = screen == nil ? [UIScreen mainScreen].scale : screen.scale;
auto result =
CGRectMake(rect.x() / scale, rect.y() / scale, rect.width() / scale, rect.height() / scale);
return UIAccessibilityConvertFrameToScreenCoordinates(result, [reference bridge]->view());
}
} // namespace
@interface FlutterSwitchSemanticsObject ()
@property(nonatomic, readonly) UISwitch* nativeSwitch;
@end
@implementation FlutterSwitchSemanticsObject
- (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
uid:(int32_t)uid {
self = [super initWithBridge:bridge uid:uid];
if (self) {
_nativeSwitch = [[UISwitch alloc] init];
}
return self;
}
- (void)dealloc {
[_nativeSwitch release];
[super dealloc];
}
- (NSMethodSignature*)methodSignatureForSelector:(SEL)sel {
NSMethodSignature* result = [super methodSignatureForSelector:sel];
if (!result) {
result = [_nativeSwitch methodSignatureForSelector:sel];
}
return result;
}
- (void)forwardInvocation:(NSInvocation*)anInvocation {
[anInvocation setTarget:_nativeSwitch];
[anInvocation invoke];
}
- (NSString*)accessibilityValue {
if ([self node].HasFlag(flutter::SemanticsFlags::kIsToggled) ||
[self node].HasFlag(flutter::SemanticsFlags::kIsChecked)) {
_nativeSwitch.on = YES;
} else {
_nativeSwitch.on = NO;
}
if (![self isAccessibilityBridgeAlive]) {
return nil;
} else {
return _nativeSwitch.accessibilityValue;
}
}
- (UIAccessibilityTraits)accessibilityTraits {
if ([self node].HasFlag(flutter::SemanticsFlags::kIsEnabled)) {
_nativeSwitch.enabled = YES;
} else {
_nativeSwitch.enabled = NO;
}
return _nativeSwitch.accessibilityTraits;
}
@end // FlutterSwitchSemanticsObject
@interface FlutterScrollableSemanticsObject ()
@property(nonatomic, retain) FlutterSemanticsScrollView* scrollView;
@end
@implementation FlutterScrollableSemanticsObject
- (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
uid:(int32_t)uid {
self = [super initWithBridge:bridge uid:uid];
if (self) {
_scrollView = [[FlutterSemanticsScrollView alloc] initWithSemanticsObject:self];
[_scrollView setShowsHorizontalScrollIndicator:NO];
[_scrollView setShowsVerticalScrollIndicator:NO];
[self.bridge->view() addSubview:_scrollView];
}
return self;
}
- (void)dealloc {
[_scrollView removeFromSuperview];
_scrollView.semanticsObject = nil;
[_scrollView release];
[super dealloc];
}
- (void)accessibilityBridgeDidFinishUpdate {
// In order to make iOS think this UIScrollView is scrollable, the following
// requirements must be true.
// 1. contentSize must be bigger than the frame size.
// 2. The scrollable isAccessibilityElement must return YES
//
// Once the requirements are met, the iOS uses contentOffset to determine
// what scroll actions are available. e.g. If the view scrolls vertically and
// contentOffset is 0.0, only the scroll down action is available.
[_scrollView setFrame:[self accessibilityFrame]];
[_scrollView setContentSize:[self contentSizeInternal]];
[_scrollView setContentOffset:[self contentOffsetInternal] animated:NO];
}
- (id)nativeAccessibility {
return _scrollView;
}
// private methods
- (float)scrollExtentMax {
if (![self isAccessibilityBridgeAlive]) {
return 0.0f;
}
float scrollExtentMax = self.node.scrollExtentMax;
if (isnan(scrollExtentMax)) {
scrollExtentMax = 0.0f;
} else if (!isfinite(scrollExtentMax)) {
scrollExtentMax = kScrollExtentMaxForInf + [self scrollPosition];
}
return scrollExtentMax;
}
- (float)scrollPosition {
if (![self isAccessibilityBridgeAlive]) {
return 0.0f;
}
float scrollPosition = self.node.scrollPosition;
if (isnan(scrollPosition)) {
scrollPosition = 0.0f;
}
NSCAssert(isfinite(scrollPosition), @"The scrollPosition must not be infinity");
return scrollPosition;
}
- (CGSize)contentSizeInternal {
CGRect result;
const SkRect& rect = self.node.rect;
if (self.node.actions & flutter::kVerticalScrollSemanticsActions) {
result = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height() + [self scrollExtentMax]);
} else if (self.node.actions & flutter::kHorizontalScrollSemanticsActions) {
result = CGRectMake(rect.x(), rect.y(), rect.width() + [self scrollExtentMax], rect.height());
} else {
result = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
}
return ConvertRectToGlobal(self, result).size;
}
- (CGPoint)contentOffsetInternal {
CGPoint result;
CGPoint origin = _scrollView.frame.origin;
const SkRect& rect = self.node.rect;
if (self.node.actions & flutter::kVerticalScrollSemanticsActions) {
result = ConvertPointToGlobal(self, CGPointMake(rect.x(), rect.y() + [self scrollPosition]));
} else if (self.node.actions & flutter::kHorizontalScrollSemanticsActions) {
result = ConvertPointToGlobal(self, CGPointMake(rect.x() + [self scrollPosition], rect.y()));
} else {
result = origin;
}
return CGPointMake(result.x - origin.x, result.y - origin.y);
}
@end // FlutterScrollableSemanticsObject
@implementation FlutterCustomAccessibilityAction {
}
@end
@interface SemanticsObject ()
/** Should only be called in conjunction with setting child/parent relationship. */
- (void)privateSetParent:(SemanticsObject*)parent;
@end
@implementation SemanticsObject {
fml::scoped_nsobject<SemanticsObjectContainer> _container;
NSMutableArray<SemanticsObject*>* _children;
NSMutableArray<SemanticsObject*>* _childrenInHitTestOrder;
BOOL _inDealloc;
}
#pragma mark - Override base class designated initializers
// Method declared as unavailable in the interface
- (instancetype)init {
[self release];
[super doesNotRecognizeSelector:_cmd];
return nil;
}
#pragma mark - Designated initializers
- (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
uid:(int32_t)uid {
FML_DCHECK(bridge) << "bridge must be set";
FML_DCHECK(uid >= kRootNodeId);
// Initialize with the UIView as the container.
// The UIView will not necessarily be accessibility parent for this object.
// The bridge informs the OS of the actual structure via
// `accessibilityContainer` and `accessibilityElementAtIndex`.
self = [super initWithAccessibilityContainer:bridge->view()];
if (self) {
_bridge = bridge;
_uid = uid;
_children = [[NSMutableArray alloc] init];
_childrenInHitTestOrder = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc {
for (SemanticsObject* child in _children) {
[child privateSetParent:nil];
}
[_children removeAllObjects];
[_childrenInHitTestOrder removeAllObjects];
[_children release];
[_childrenInHitTestOrder release];
_parent = nil;
_container.get().semanticsObject = nil;
_inDealloc = YES;
[super dealloc];
}
#pragma mark - Semantic object property accesser
- (void)setChildren:(NSArray<SemanticsObject*>*)children {
for (SemanticsObject* child in _children) {
[child privateSetParent:nil];
}
[_children release];
_children = [[NSMutableArray alloc] initWithArray:children];
for (SemanticsObject* child in _children) {
[child privateSetParent:self];
}
}
- (void)setChildrenInHitTestOrder:(NSArray<SemanticsObject*>*)childrenInHitTestOrder {
for (SemanticsObject* child in _childrenInHitTestOrder) {
[child privateSetParent:nil];
}
[_childrenInHitTestOrder release];
_childrenInHitTestOrder = [[NSMutableArray alloc] initWithArray:childrenInHitTestOrder];
for (SemanticsObject* child in _childrenInHitTestOrder) {
[child privateSetParent:self];
}
}
- (BOOL)hasChildren {
return [self.children count] != 0;
}
#pragma mark - Semantic object method
- (BOOL)isAccessibilityBridgeAlive {
return [self bridge].get() != nil;
}
- (void)setSemanticsNode:(const flutter::SemanticsNode*)node {
_node = *node;
}
- (void)accessibilityBridgeDidFinishUpdate { /* Do nothing by default */
}
/**
* Whether calling `setSemanticsNode:` with `node` would cause a layout change.
*/
- (BOOL)nodeWillCauseLayoutChange:(const flutter::SemanticsNode*)node {
return [self node].rect != node->rect || [self node].transform != node->transform;
}
/**
* Whether calling `setSemanticsNode:` with `node` would cause a scroll event.
*/
- (BOOL)nodeWillCauseScroll:(const flutter::SemanticsNode*)node {
return !isnan([self node].scrollPosition) && !isnan(node->scrollPosition) &&
[self node].scrollPosition != node->scrollPosition;
}
/**
* Whether calling `setSemanticsNode:` with `node` should trigger an
* announcement.
*/
- (BOOL)nodeShouldTriggerAnnouncement:(const flutter::SemanticsNode*)node {
// The node dropped the live region flag, if it ever had one.
if (!node || !node->HasFlag(flutter::SemanticsFlags::kIsLiveRegion)) {
return NO;
}
// The node has gained a new live region flag, always announce.
if (![self node].HasFlag(flutter::SemanticsFlags::kIsLiveRegion)) {
return YES;
}
// The label has updated, and the new node has a live region flag.
return [self node].label != node->label;
}
- (void)replaceChildAtIndex:(NSInteger)index withChild:(SemanticsObject*)child {
SemanticsObject* oldChild = _children[index];
[oldChild privateSetParent:nil];
[child privateSetParent:self];
[_children replaceObjectAtIndex:index withObject:child];
}
- (NSString*)routeName {
// Returns the first non-null and non-empty semantic label of a child
// with an NamesRoute flag. Otherwise returns nil.
if ([self node].HasFlag(flutter::SemanticsFlags::kNamesRoute)) {
NSString* newName = [self accessibilityLabel];
if (newName != nil && [newName length] > 0) {
return newName;
}
}
if ([self hasChildren]) {
for (SemanticsObject* child in self.children) {
NSString* newName = [child routeName];
if (newName != nil && [newName length] > 0) {
return newName;
}
}
}
return nil;
}
- (id)nativeAccessibility {
return self;
}
#pragma mark - Semantic object private method
- (void)privateSetParent:(SemanticsObject*)parent {
_parent = parent;
}
- (NSAttributedString*)createAttributedStringFromString:(NSString*)string
withAttributes:
(const flutter::StringAttributes&)attributes {
NSMutableAttributedString* attributedString =
[[[NSMutableAttributedString alloc] initWithString:string] autorelease];
for (const auto& attribute : attributes) {
NSRange range = NSMakeRange(attribute->start, attribute->end - attribute->start);
switch (attribute->type) {
case flutter::StringAttributeType::kLocale: {
std::shared_ptr<flutter::LocaleStringAttribute> locale_attribute =
std::static_pointer_cast<flutter::LocaleStringAttribute>(attribute);
NSDictionary* attributeDict = @{
UIAccessibilitySpeechAttributeLanguage : @(locale_attribute->locale.data()),
};
[attributedString setAttributes:attributeDict range:range];
break;
}
case flutter::StringAttributeType::kSpellOut: {
if (@available(iOS 13.0, *)) {
NSDictionary* attributeDict = @{
UIAccessibilitySpeechAttributeSpellOut : @YES,
};
[attributedString setAttributes:attributeDict range:range];
}
break;
}
}
}
return attributedString;
}
- (void)showOnScreen {
[self bridge]->DispatchSemanticsAction([self uid], flutter::SemanticsAction::kShowOnScreen);
}
#pragma mark - UIAccessibility overrides
- (BOOL)isAccessibilityElement {
if (![self isAccessibilityBridgeAlive]) {
return false;
}
// Note: hit detection will only apply to elements that report
// -isAccessibilityElement of YES. The framework will continue scanning the
// entire element tree looking for such a hit.
// We enforce in the framework that no other useful semantics are merged with these nodes.
if ([self node].HasFlag(flutter::SemanticsFlags::kScopesRoute)) {
return false;
}
return [self isFocusable];
}
- (bool)isFocusable {
// If the node is scrollable AND hidden OR
// The node has a label, value, or hint OR
// The node has non-scrolling related actions.
//
// The kIsHidden flag set with the scrollable flag means this node is now
// hidden but still is a valid target for a11y focus in the tree, e.g. a list
// item that is currently off screen but the a11y navigation needs to know
// about.
return (([self node].flags & flutter::kScrollableSemanticsFlags) != 0 &&
([self node].flags & static_cast<int32_t>(flutter::SemanticsFlags::kIsHidden)) != 0) ||
![self node].label.empty() || ![self node].value.empty() || ![self node].hint.empty() ||
([self node].actions & ~flutter::kScrollableSemanticsActions) != 0;
}
- (void)collectRoutes:(NSMutableArray<SemanticsObject*>*)edges {
if ([self node].HasFlag(flutter::SemanticsFlags::kScopesRoute)) {
[edges addObject:self];
}
if ([self hasChildren]) {
for (SemanticsObject* child in self.children) {
[child collectRoutes:edges];
}
}
}
- (BOOL)onCustomAccessibilityAction:(FlutterCustomAccessibilityAction*)action {
if (![self node].HasAction(flutter::SemanticsAction::kCustomAction)) {
return NO;
}
int32_t action_id = action.uid;
std::vector<uint8_t> args;
args.push_back(3); // type=int32.
args.push_back(action_id);
args.push_back(action_id >> 8);
args.push_back(action_id >> 16);
args.push_back(action_id >> 24);
[self bridge]->DispatchSemanticsAction(
[self uid], flutter::SemanticsAction::kCustomAction,
fml::MallocMapping::Copy(args.data(), args.size() * sizeof(uint8_t)));
return YES;
}
- (NSString*)accessibilityIdentifier {
if (![self isAccessibilityBridgeAlive]) {
return nil;
}
if ([self node].identifier.empty()) {
return nil;
}
return @([self node].identifier.data());
}
- (NSString*)accessibilityLabel {
if (![self isAccessibilityBridgeAlive]) {
return nil;
}
NSString* label = nil;
if (![self node].label.empty()) {
label = @([self node].label.data());
}
if (![self node].tooltip.empty()) {
label = label ? [NSString stringWithFormat:@"%@\n%@", label, @([self node].tooltip.data())]
: @([self node].tooltip.data());
}
return label;
}
- (bool)containsPoint:(CGPoint)point {
// The point is in global coordinates, so use the global rect here.
return CGRectContainsPoint([self globalRect], point);
}
// Finds the first eligiable semantics object in hit test order.
- (id)search:(CGPoint)point {
// Search children in hit test order.
for (SemanticsObject* child in [self childrenInHitTestOrder]) {
if ([child containsPoint:point]) {
id childSearchResult = [child search:point];
if (childSearchResult != nil) {
return childSearchResult;
}
}
}
// Check if the current semantic object should be returned.
if ([self containsPoint:point] && [self isFocusable]) {
return self.nativeAccessibility;
}
return nil;
}
// iOS uses this method to determine the hittest results when users touch
// explore in VoiceOver.
//
// For overlapping UIAccessibilityElements (e.g. a stack) in IOS, the focus
// goes to the smallest object before IOS 16, but to the top-left object in
// IOS 16. Overrides this method to focus the first eligiable semantics
// object in hit test order.
- (id)_accessibilityHitTest:(CGPoint)point withEvent:(UIEvent*)event {
return [self search:point];
}
// iOS calls this method when this item is swipe-to-focusd in VoiceOver.
- (BOOL)accessibilityScrollToVisible {
[self showOnScreen];
return YES;
}
// iOS calls this method when this item is swipe-to-focusd in VoiceOver.
- (BOOL)accessibilityScrollToVisibleWithChild:(id)child {
if ([child isKindOfClass:[SemanticsObject class]]) {
[child showOnScreen];
return YES;
}
return NO;
}
- (NSAttributedString*)accessibilityAttributedLabel {
NSString* label = [self accessibilityLabel];
if (label.length == 0) {
return nil;
}
return [self createAttributedStringFromString:label withAttributes:[self node].labelAttributes];
}
- (NSString*)accessibilityHint {
if (![self isAccessibilityBridgeAlive]) {
return nil;
}
if ([self node].hint.empty()) {
return nil;
}
return @([self node].hint.data());
}
- (NSAttributedString*)accessibilityAttributedHint {
NSString* hint = [self accessibilityHint];
if (hint.length == 0) {
return nil;
}
return [self createAttributedStringFromString:hint withAttributes:[self node].hintAttributes];
}
- (NSString*)accessibilityValue {
if (![self isAccessibilityBridgeAlive]) {
return nil;
}
if (![self node].value.empty()) {
return @([self node].value.data());
}
// iOS does not announce values of native radio buttons.
if ([self node].HasFlag(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup)) {
return nil;
}
// FlutterSwitchSemanticsObject should supercede these conditionals.
if ([self node].HasFlag(flutter::SemanticsFlags::kHasToggledState) ||
[self node].HasFlag(flutter::SemanticsFlags::kHasCheckedState)) {
if ([self node].HasFlag(flutter::SemanticsFlags::kIsToggled) ||
[self node].HasFlag(flutter::SemanticsFlags::kIsChecked)) {
return @"1";
} else {
return @"0";
}
}
return nil;
}
- (NSAttributedString*)accessibilityAttributedValue {
NSString* value = [self accessibilityValue];
if (value.length == 0) {
return nil;
}
return [self createAttributedStringFromString:value withAttributes:[self node].valueAttributes];
}
- (CGRect)accessibilityFrame {
if (![self isAccessibilityBridgeAlive]) {
return CGRectMake(0, 0, 0, 0);
}
if ([self node].HasFlag(flutter::SemanticsFlags::kIsHidden)) {
return [super accessibilityFrame];
}
return [self globalRect];
}
- (CGRect)globalRect {
const SkRect& rect = [self node].rect;
CGRect localRect = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
return ConvertRectToGlobal(self, localRect);
}
#pragma mark - UIAccessibilityElement protocol
- (void)setAccessibilityContainer:(id)container {
// Explicit noop. The containers are calculated lazily in `accessibilityContainer`.
// See also: https://github.com/flutter/flutter/issues/54366
}
- (id)accessibilityContainer {
if (_inDealloc) {
// In iOS9, `accessibilityContainer` will be called by `[UIAccessibilityElementSuperCategory
// dealloc]` during `[super dealloc]`. And will crash when accessing `_children` which has
// called `[_children release]` in `[SemanticsObject dealloc]`.
// https://github.com/flutter/flutter/issues/87247
return nil;
}
if (![self isAccessibilityBridgeAlive]) {
return nil;
}
if ([self hasChildren] || [self uid] == kRootNodeId) {
if (_container == nil) {
_container.reset([[SemanticsObjectContainer alloc] initWithSemanticsObject:self
bridge:[self bridge]]);
}
return _container.get();
}
if ([self parent] == nil) {
// This can happen when we have released the accessibility tree but iOS is
// still holding onto our objects. iOS can take some time before it
// realizes that the tree has changed.
return nil;
}
return [[self parent] accessibilityContainer];
}
#pragma mark - UIAccessibilityAction overrides
- (BOOL)accessibilityActivate {
if (![self isAccessibilityBridgeAlive]) {
return NO;
}
if (![self node].HasAction(flutter::SemanticsAction::kTap)) {
return NO;
}
[self bridge]->DispatchSemanticsAction([self uid], flutter::SemanticsAction::kTap);
return YES;
}
- (void)accessibilityIncrement {
if (![self isAccessibilityBridgeAlive]) {
return;
}
if ([self node].HasAction(flutter::SemanticsAction::kIncrease)) {
[self node].value = [self node].increasedValue;
[self bridge]->DispatchSemanticsAction([self uid], flutter::SemanticsAction::kIncrease);
}
}
- (void)accessibilityDecrement {
if (![self isAccessibilityBridgeAlive]) {
return;
}
if ([self node].HasAction(flutter::SemanticsAction::kDecrease)) {
[self node].value = [self node].decreasedValue;
[self bridge]->DispatchSemanticsAction([self uid], flutter::SemanticsAction::kDecrease);
}
}
- (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction {
if (![self isAccessibilityBridgeAlive]) {
return NO;
}
flutter::SemanticsAction action = GetSemanticsActionForScrollDirection(direction);
if (![self node].HasAction(action)) {
return NO;
}
[self bridge]->DispatchSemanticsAction([self uid], action);
return YES;
}
- (BOOL)accessibilityPerformEscape {
if (![self isAccessibilityBridgeAlive]) {
return NO;
}
if (![self node].HasAction(flutter::SemanticsAction::kDismiss)) {
return NO;
}
[self bridge]->DispatchSemanticsAction([self uid], flutter::SemanticsAction::kDismiss);
return YES;
}
#pragma mark UIAccessibilityFocus overrides
- (void)accessibilityElementDidBecomeFocused {
if (![self isAccessibilityBridgeAlive]) {
return;
}
[self bridge]->AccessibilityObjectDidBecomeFocused([self uid]);
if ([self node].HasFlag(flutter::SemanticsFlags::kIsHidden) ||
[self node].HasFlag(flutter::SemanticsFlags::kIsHeader)) {
[self showOnScreen];
}
if ([self node].HasAction(flutter::SemanticsAction::kDidGainAccessibilityFocus)) {
[self bridge]->DispatchSemanticsAction([self uid],
flutter::SemanticsAction::kDidGainAccessibilityFocus);
}
}
- (void)accessibilityElementDidLoseFocus {
if (![self isAccessibilityBridgeAlive]) {
return;
}
[self bridge]->AccessibilityObjectDidLoseFocus([self uid]);
if ([self node].HasAction(flutter::SemanticsAction::kDidLoseAccessibilityFocus)) {
[self bridge]->DispatchSemanticsAction([self uid],
flutter::SemanticsAction::kDidLoseAccessibilityFocus);
}
}
@end
@implementation FlutterSemanticsObject {
}
#pragma mark - Override base class designated initializers
// Method declared as unavailable in the interface
- (instancetype)init {
[self release];
[super doesNotRecognizeSelector:_cmd];
return nil;
}
#pragma mark - Designated initializers
- (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
uid:(int32_t)uid {
self = [super initWithBridge:bridge uid:uid];
return self;
}
#pragma mark - UIAccessibility overrides
- (UIAccessibilityTraits)accessibilityTraits {
UIAccessibilityTraits traits = UIAccessibilityTraitNone;
if ([self node].HasAction(flutter::SemanticsAction::kIncrease) ||
[self node].HasAction(flutter::SemanticsAction::kDecrease)) {
traits |= UIAccessibilityTraitAdjustable;
}
// This should also capture radio buttons.
if ([self node].HasFlag(flutter::SemanticsFlags::kHasToggledState) ||
[self node].HasFlag(flutter::SemanticsFlags::kHasCheckedState)) {
traits |= UIAccessibilityTraitButton;
}
if ([self node].HasFlag(flutter::SemanticsFlags::kIsSelected)) {
traits |= UIAccessibilityTraitSelected;
}
if ([self node].HasFlag(flutter::SemanticsFlags::kIsButton)) {
traits |= UIAccessibilityTraitButton;
}
if ([self node].HasFlag(flutter::SemanticsFlags::kHasEnabledState) &&
![self node].HasFlag(flutter::SemanticsFlags::kIsEnabled)) {
traits |= UIAccessibilityTraitNotEnabled;
}
if ([self node].HasFlag(flutter::SemanticsFlags::kIsHeader)) {
traits |= UIAccessibilityTraitHeader;
}
if ([self node].HasFlag(flutter::SemanticsFlags::kIsImage)) {
traits |= UIAccessibilityTraitImage;
}
if ([self node].HasFlag(flutter::SemanticsFlags::kIsLiveRegion)) {
traits |= UIAccessibilityTraitUpdatesFrequently;
}
if ([self node].HasFlag(flutter::SemanticsFlags::kIsLink)) {
traits |= UIAccessibilityTraitLink;
}
if (traits == UIAccessibilityTraitNone && ![self hasChildren] &&
[[self accessibilityLabel] length] != 0 &&
![self node].HasFlag(flutter::SemanticsFlags::kIsTextField)) {
traits = UIAccessibilityTraitStaticText;
}
return traits;
}
@end
@interface FlutterPlatformViewSemanticsContainer ()
@property(nonatomic, retain) UIView* platformView;
@end
@implementation FlutterPlatformViewSemanticsContainer
- (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
uid:(int32_t)uid
platformView:(nonnull FlutterTouchInterceptingView*)platformView {
if (self = [super initWithBridge:bridge uid:uid]) {
_platformView = [platformView retain];
[platformView setFlutterAccessibilityContainer:self];
}
return self;
}
- (void)dealloc {
[_platformView release];
_platformView = nil;
[super dealloc];
}
- (id)nativeAccessibility {
return _platformView;
}
@end
@implementation SemanticsObjectContainer {
SemanticsObject* _semanticsObject;
fml::WeakPtr<flutter::AccessibilityBridgeIos> _bridge;
}
#pragma mark - initializers
// Method declared as unavailable in the interface
- (instancetype)init {
[self release];
[super doesNotRecognizeSelector:_cmd];
return nil;
}
- (instancetype)initWithSemanticsObject:(SemanticsObject*)semanticsObject
bridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge {
FML_DCHECK(semanticsObject) << "semanticsObject must be set";
// Initialize with the UIView as the container.
// The UIView will not necessarily be accessibility parent for this object.
// The bridge informs the OS of the actual structure via
// `accessibilityContainer` and `accessibilityElementAtIndex`.
self = [super initWithAccessibilityContainer:bridge->view()];
if (self) {
_semanticsObject = semanticsObject;
_bridge = bridge;
}
return self;
}
#pragma mark - UIAccessibilityContainer overrides
- (NSInteger)accessibilityElementCount {
NSInteger count = [[_semanticsObject children] count] + 1;
return count;
}
- (nullable id)accessibilityElementAtIndex:(NSInteger)index {
if (index < 0 || index >= [self accessibilityElementCount]) {
return nil;
}
if (index == 0) {
return _semanticsObject.nativeAccessibility;
}
SemanticsObject* child = [_semanticsObject children][index - 1];
if ([child hasChildren]) {
return [child accessibilityContainer];
}
return child.nativeAccessibility;
}
- (NSInteger)indexOfAccessibilityElement:(id)element {
if (element == _semanticsObject.nativeAccessibility) {
return 0;
}
NSArray<SemanticsObject*>* children = [_semanticsObject children];
for (size_t i = 0; i < [children count]; i++) {
SemanticsObject* child = children[i];
if ((![child hasChildren] && child.nativeAccessibility == element) ||
([child hasChildren] && [child.nativeAccessibility accessibilityContainer] == element)) {
return i + 1;
}
}
return NSNotFound;
}
#pragma mark - UIAccessibilityElement protocol
- (BOOL)isAccessibilityElement {
return NO;
}
- (CGRect)accessibilityFrame {
return [_semanticsObject accessibilityFrame];
}
- (id)accessibilityContainer {
if (!_bridge) {
return nil;
}
return ([_semanticsObject uid] == kRootNodeId)
? _bridge->view()
: [[_semanticsObject parent] accessibilityContainer];
}
#pragma mark - UIAccessibilityAction overrides
- (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction {
return [_semanticsObject accessibilityScroll:direction];
}
@end
| engine/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm",
"repo_id": "engine",
"token_count": 10933
} | 377 |
// Copyright 2013 The Flutter 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/shell/platform/darwin/ios/framework/Source/connection_collection.h"
@interface ConnectionCollectionTest : XCTestCase
@end
@implementation ConnectionCollectionTest
- (void)testSimple {
auto connections = std::make_unique<flutter::ConnectionCollection>();
flutter::ConnectionCollection::Connection connection = connections->AquireConnection("foo");
XCTAssertTrue(connections->CleanupConnection(connection) == "foo");
XCTAssertTrue(connections->CleanupConnection(connection).empty());
}
@end
| engine/shell/platform/darwin/ios/framework/Source/connection_collection_test.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/connection_collection_test.mm",
"repo_id": "engine",
"token_count": 212
} | 378 |
// Copyright 2013 The Flutter 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_EXTERNAL_TEXTURE_METAL_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_TEXTURE_METAL_H_
#include "flutter/common/graphics/texture.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h"
namespace flutter {
class IOSExternalTextureMetal final : public Texture {
public:
explicit IOSExternalTextureMetal(
const fml::scoped_nsobject<FlutterDarwinExternalTextureMetal>&
darwin_external_texture_metal);
// |Texture|
~IOSExternalTextureMetal();
private:
fml::scoped_nsobject<FlutterDarwinExternalTextureMetal>
darwin_external_texture_metal_;
// |Texture|
void Paint(PaintContext& context,
const SkRect& bounds,
bool freeze,
const DlImageSampling sampling) override;
// |Texture|
void OnGrContextCreated() override;
// |Texture|
void OnGrContextDestroyed() override;
// |Texture|
void MarkNewFrameAvailable() override;
// |Texture|
void OnTextureUnregistered() override;
FML_DISALLOW_COPY_AND_ASSIGN(IOSExternalTextureMetal);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_TEXTURE_METAL_H_
| engine/shell/platform/darwin/ios/ios_external_texture_metal.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/ios_external_texture_metal.h",
"repo_id": "engine",
"token_count": 542
} | 379 |
// Copyright 2013 The Flutter 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/platform_view_ios.h"
#include <memory>
#include <utility>
#include "flutter/common/task_runners.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/trace_event.h"
#include "flutter/shell/common/shell_io_manager.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h"
namespace flutter {
PlatformViewIOS::AccessibilityBridgeManager::AccessibilityBridgeManager(
const std::function<void(bool)>& set_semantics_enabled)
: AccessibilityBridgeManager(set_semantics_enabled, nullptr) {}
PlatformViewIOS::AccessibilityBridgeManager::AccessibilityBridgeManager(
const std::function<void(bool)>& set_semantics_enabled,
AccessibilityBridge* bridge)
: accessibility_bridge_(bridge), set_semantics_enabled_(set_semantics_enabled) {
if (bridge) {
set_semantics_enabled_(true);
}
}
void PlatformViewIOS::AccessibilityBridgeManager::Set(std::unique_ptr<AccessibilityBridge> bridge) {
accessibility_bridge_ = std::move(bridge);
set_semantics_enabled_(true);
}
void PlatformViewIOS::AccessibilityBridgeManager::Clear() {
set_semantics_enabled_(false);
accessibility_bridge_.reset();
}
PlatformViewIOS::PlatformViewIOS(
PlatformView::Delegate& delegate,
const std::shared_ptr<IOSContext>& context,
const std::shared_ptr<FlutterPlatformViewsController>& platform_views_controller,
const flutter::TaskRunners& task_runners)
: PlatformView(delegate, task_runners),
ios_context_(context),
platform_views_controller_(platform_views_controller),
accessibility_bridge_([this](bool enabled) { PlatformView::SetSemanticsEnabled(enabled); }),
platform_message_handler_(
new PlatformMessageHandlerIos(task_runners.GetPlatformTaskRunner())) {}
PlatformViewIOS::PlatformViewIOS(
PlatformView::Delegate& delegate,
IOSRenderingAPI rendering_api,
const std::shared_ptr<FlutterPlatformViewsController>& platform_views_controller,
const flutter::TaskRunners& task_runners,
const std::shared_ptr<fml::ConcurrentTaskRunner>& worker_task_runner,
const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch)
: PlatformViewIOS(
delegate,
IOSContext::Create(
rendering_api,
delegate.OnPlatformViewGetSettings().enable_impeller ? IOSRenderingBackend::kImpeller
: IOSRenderingBackend::kSkia,
static_cast<MsaaSampleCount>(delegate.OnPlatformViewGetSettings().msaa_samples),
is_gpu_disabled_sync_switch),
platform_views_controller,
task_runners) {}
PlatformViewIOS::~PlatformViewIOS() = default;
// |PlatformView|
void PlatformViewIOS::HandlePlatformMessage(std::unique_ptr<flutter::PlatformMessage> message) {
platform_message_handler_->HandlePlatformMessage(std::move(message));
}
fml::WeakNSObject<FlutterViewController> PlatformViewIOS::GetOwnerViewController() const {
return owner_controller_;
}
void PlatformViewIOS::SetOwnerViewController(
const fml::WeakNSObject<FlutterViewController>& owner_controller) {
FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());
std::lock_guard<std::mutex> guard(ios_surface_mutex_);
if (ios_surface_ || !owner_controller) {
NotifyDestroyed();
ios_surface_.reset();
accessibility_bridge_.Clear();
}
owner_controller_ = owner_controller;
// Add an observer that will clear out the owner_controller_ ivar and
// the accessibility_bridge_ in case the view controller is deleted.
dealloc_view_controller_observer_.reset(
[[[NSNotificationCenter defaultCenter] addObserverForName:FlutterViewControllerWillDealloc
object:owner_controller_.get()
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification* note) {
// Implicit copy of 'this' is fine.
accessibility_bridge_.Clear();
owner_controller_.reset();
}] retain]);
if (owner_controller_ && [owner_controller_.get() isViewLoaded]) {
this->attachView();
}
// Do not call `NotifyCreated()` here - let FlutterViewController take care
// of that when its Viewport is sized. If `NotifyCreated()` is called here,
// it can occasionally get invoked before the viewport is sized resulting in
// a framebuffer that will not be able to completely attach.
}
void PlatformViewIOS::attachView() {
FML_DCHECK(owner_controller_);
FML_DCHECK(owner_controller_.get().isViewLoaded)
<< "FlutterViewController's view should be loaded "
"before attaching to PlatformViewIOS.";
auto flutter_view = static_cast<FlutterView*>(owner_controller_.get().view);
auto ca_layer = fml::scoped_nsobject<CALayer>{[[flutter_view layer] retain]};
ios_surface_ = IOSSurface::Create(ios_context_, ca_layer);
FML_DCHECK(ios_surface_ != nullptr);
if (accessibility_bridge_) {
accessibility_bridge_.Set(std::make_unique<AccessibilityBridge>(
owner_controller_.get(), this, [owner_controller_.get() platformViewsController]));
}
}
PointerDataDispatcherMaker PlatformViewIOS::GetDispatcherMaker() {
return [](DefaultPointerDataDispatcher::Delegate& delegate) {
return std::make_unique<SmoothPointerDataDispatcher>(delegate);
};
}
void PlatformViewIOS::RegisterExternalTexture(int64_t texture_id,
NSObject<FlutterTexture>* texture) {
RegisterTexture(ios_context_->CreateExternalTexture(
texture_id, fml::scoped_nsobject<NSObject<FlutterTexture>>{[texture retain]}));
}
// |PlatformView|
std::unique_ptr<Surface> PlatformViewIOS::CreateRenderingSurface() {
FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread());
std::lock_guard<std::mutex> guard(ios_surface_mutex_);
if (!ios_surface_) {
FML_DLOG(INFO) << "Could not CreateRenderingSurface, this PlatformViewIOS "
"has no ViewController.";
return nullptr;
}
return ios_surface_->CreateGPUSurface(ios_context_->GetMainContext().get());
}
// |PlatformView|
std::shared_ptr<ExternalViewEmbedder> PlatformViewIOS::CreateExternalViewEmbedder() {
return std::make_shared<IOSExternalViewEmbedder>(platform_views_controller_, ios_context_);
}
// |PlatformView|
sk_sp<GrDirectContext> PlatformViewIOS::CreateResourceContext() const {
return ios_context_->CreateResourceContext();
}
// |PlatformView|
std::shared_ptr<impeller::Context> PlatformViewIOS::GetImpellerContext() const {
return ios_context_->GetImpellerContext();
}
// |PlatformView|
void PlatformViewIOS::SetSemanticsEnabled(bool enabled) {
if (!owner_controller_) {
FML_LOG(WARNING) << "Could not set semantics to enabled, this "
"PlatformViewIOS has no ViewController.";
return;
}
if (enabled && !accessibility_bridge_) {
accessibility_bridge_.Set(std::make_unique<AccessibilityBridge>(
owner_controller_.get(), this, [owner_controller_.get() platformViewsController]));
} else if (!enabled && accessibility_bridge_) {
accessibility_bridge_.Clear();
} else {
PlatformView::SetSemanticsEnabled(enabled);
}
}
// |shell:PlatformView|
void PlatformViewIOS::SetAccessibilityFeatures(int32_t flags) {
PlatformView::SetAccessibilityFeatures(flags);
}
// |PlatformView|
void PlatformViewIOS::UpdateSemantics(flutter::SemanticsNodeUpdates update,
flutter::CustomAccessibilityActionUpdates actions) {
FML_DCHECK(owner_controller_);
if (accessibility_bridge_) {
accessibility_bridge_.get()->UpdateSemantics(std::move(update), actions);
[[NSNotificationCenter defaultCenter] postNotificationName:FlutterSemanticsUpdateNotification
object:owner_controller_.get()];
}
}
// |PlatformView|
std::unique_ptr<VsyncWaiter> PlatformViewIOS::CreateVSyncWaiter() {
return std::make_unique<VsyncWaiterIOS>(task_runners_);
}
void PlatformViewIOS::OnPreEngineRestart() const {
if (accessibility_bridge_) {
accessibility_bridge_.get()->clearState();
}
if (!owner_controller_) {
return;
}
[owner_controller_.get() platformViewsController]->Reset();
[[owner_controller_.get() restorationPlugin] reset];
}
std::unique_ptr<std::vector<std::string>> PlatformViewIOS::ComputePlatformResolvedLocales(
const std::vector<std::string>& supported_locale_data) {
size_t localeDataLength = 3;
NSMutableArray<NSString*>* supported_locale_identifiers =
[NSMutableArray arrayWithCapacity:supported_locale_data.size() / localeDataLength];
for (size_t i = 0; i < supported_locale_data.size(); i += localeDataLength) {
NSDictionary<NSString*, NSString*>* dict = @{
NSLocaleLanguageCode : [NSString stringWithUTF8String:supported_locale_data[i].c_str()]
?: @"",
NSLocaleCountryCode : [NSString stringWithUTF8String:supported_locale_data[i + 1].c_str()]
?: @"",
NSLocaleScriptCode : [NSString stringWithUTF8String:supported_locale_data[i + 2].c_str()]
?: @""
};
[supported_locale_identifiers addObject:[NSLocale localeIdentifierFromComponents:dict]];
}
NSArray<NSString*>* result =
[NSBundle preferredLocalizationsFromArray:supported_locale_identifiers];
// Output format should be either empty or 3 strings for language, country, and script.
std::unique_ptr<std::vector<std::string>> out = std::make_unique<std::vector<std::string>>();
if (result != nullptr && [result count] > 0) {
NSLocale* locale = [NSLocale localeWithLocaleIdentifier:[result firstObject]];
NSString* languageCode = [locale languageCode];
out->emplace_back(languageCode == nullptr ? "" : languageCode.UTF8String);
NSString* countryCode = [locale countryCode];
out->emplace_back(countryCode == nullptr ? "" : countryCode.UTF8String);
NSString* scriptCode = [locale scriptCode];
out->emplace_back(scriptCode == nullptr ? "" : scriptCode.UTF8String);
}
return out;
}
PlatformViewIOS::ScopedObserver::ScopedObserver() {}
PlatformViewIOS::ScopedObserver::~ScopedObserver() {
if (observer_) {
[[NSNotificationCenter defaultCenter] removeObserver:observer_];
[observer_ release];
}
}
void PlatformViewIOS::ScopedObserver::reset(id<NSObject> observer) {
if (observer != observer_) {
if (observer_) {
[[NSNotificationCenter defaultCenter] removeObserver:observer_];
[observer_ release];
}
observer_ = observer;
}
}
} // namespace flutter
| engine/shell/platform/darwin/ios/platform_view_ios.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/platform_view_ios.mm",
"repo_id": "engine",
"token_count": 4151
} | 380 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#include "flutter/testing/autoreleasepool_test.h"
#include "flutter/testing/testing.h"
namespace flutter::testing {
namespace {
class AccessibilityBridgeMacSpy : public AccessibilityBridgeMac {
public:
using AccessibilityBridgeMac::OnAccessibilityEvent;
AccessibilityBridgeMacSpy(__weak FlutterEngine* flutter_engine,
__weak FlutterViewController* view_controller)
: AccessibilityBridgeMac(flutter_engine, view_controller) {}
std::unordered_map<std::string, gfx::NativeViewAccessible> actual_notifications;
private:
void DispatchMacOSNotification(gfx::NativeViewAccessible native_node,
NSAccessibilityNotificationName mac_notification) override {
actual_notifications[[mac_notification UTF8String]] = native_node;
}
};
} // namespace
} // namespace flutter::testing
@interface AccessibilityBridgeTestViewController : FlutterViewController
- (std::shared_ptr<flutter::AccessibilityBridgeMac>)createAccessibilityBridgeWithEngine:
(nonnull FlutterEngine*)engine;
@end
@implementation AccessibilityBridgeTestViewController
- (std::shared_ptr<flutter::AccessibilityBridgeMac>)createAccessibilityBridgeWithEngine:
(nonnull FlutterEngine*)engine {
return std::make_shared<flutter::testing::AccessibilityBridgeMacSpy>(engine, self);
}
@end
namespace flutter::testing {
namespace {
// Returns an engine configured for the text fixture resource configuration.
FlutterViewController* CreateTestViewController() {
NSString* fixtures = @(testing::GetFixturesPath());
FlutterDartProject* project = [[FlutterDartProject alloc]
initWithAssetsPath:fixtures
ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
return [[AccessibilityBridgeTestViewController alloc] initWithProject:project];
}
// Test fixture that instantiates and re-uses a single NSWindow across multiple tests.
//
// Works around: http://www.openradar.me/FB13291861
class AccessibilityBridgeMacWindowTest : public AutoreleasePoolTest {
public:
AccessibilityBridgeMacWindowTest() {
if (!gWindow_) {
gWindow_ = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600)
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
}
}
NSWindow* GetWindow() const { return gWindow_; }
private:
static NSWindow* gWindow_;
FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridgeMacWindowTest);
};
NSWindow* AccessibilityBridgeMacWindowTest::gWindow_ = nil;
// Test-specific name for AutoreleasePoolTest fixture.
using AccessibilityBridgeMacTest = AutoreleasePoolTest;
} // namespace
TEST_F(AccessibilityBridgeMacWindowTest, SendsAccessibilityCreateNotificationFlutterViewWindow) {
FlutterViewController* viewController = CreateTestViewController();
FlutterEngine* engine = viewController.engine;
NSWindow* expectedTarget = GetWindow();
expectedTarget.contentView = viewController.view;
// Setting up bridge so that the AccessibilityBridgeMacDelegateSpy
// can query semantics information from.
engine.semanticsEnabled = YES;
auto bridge = std::static_pointer_cast<AccessibilityBridgeMacSpy>(
viewController.accessibilityBridge.lock());
FlutterSemanticsNode2 root;
root.id = 0;
root.flags = static_cast<FlutterSemanticsFlag>(0);
root.actions = static_cast<FlutterSemanticsAction>(0);
root.text_selection_base = -1;
root.text_selection_extent = -1;
root.label = "root";
root.hint = "";
root.value = "";
root.increased_value = "";
root.decreased_value = "";
root.tooltip = "";
root.child_count = 0;
root.custom_accessibility_actions_count = 0;
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
auto platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
// Creates a targeted event.
ui::AXTree tree;
ui::AXNode ax_node(&tree, nullptr, 0, 0);
ui::AXNodeData node_data;
node_data.id = 0;
ax_node.SetData(node_data);
std::vector<ui::AXEventIntent> intent;
ui::AXEventGenerator::EventParams event_params(ui::AXEventGenerator::Event::CHILDREN_CHANGED,
ax::mojom::EventFrom::kNone, intent);
ui::AXEventGenerator::TargetedEvent targeted_event(&ax_node, event_params);
bridge->OnAccessibilityEvent(targeted_event);
ASSERT_EQ(bridge->actual_notifications.size(), 1u);
auto target = bridge->actual_notifications.find([NSAccessibilityCreatedNotification UTF8String]);
ASSERT_NE(target, bridge->actual_notifications.end());
EXPECT_EQ(target->second, expectedTarget);
[engine shutDownEngine];
}
// Flutter used to assume that the accessibility root had ID 0.
// In a multi-view world, each view has its own accessibility root
// with a globally unique node ID.
//
// node1
// |
// node2
TEST_F(AccessibilityBridgeMacWindowTest, NonZeroRootNodeId) {
FlutterViewController* viewController = CreateTestViewController();
FlutterEngine* engine = viewController.engine;
NSWindow* expectedTarget = GetWindow();
expectedTarget.contentView = viewController.view;
// Setting up bridge so that the AccessibilityBridgeMacDelegateSpy
// can query semantics information from.
engine.semanticsEnabled = YES;
auto bridge = std::static_pointer_cast<AccessibilityBridgeMacSpy>(
viewController.accessibilityBridge.lock());
FlutterSemanticsNode2 node1;
std::vector<int32_t> node1_children{2};
node1.id = 1;
node1.flags = static_cast<FlutterSemanticsFlag>(0);
node1.actions = static_cast<FlutterSemanticsAction>(0);
node1.text_selection_base = -1;
node1.text_selection_extent = -1;
node1.label = "node1";
node1.hint = "";
node1.value = "";
node1.increased_value = "";
node1.decreased_value = "";
node1.tooltip = "";
node1.child_count = node1_children.size();
node1.children_in_traversal_order = node1_children.data();
node1.children_in_hit_test_order = node1_children.data();
node1.custom_accessibility_actions_count = 0;
FlutterSemanticsNode2 node2;
node2.id = 2;
node2.flags = static_cast<FlutterSemanticsFlag>(0);
node2.actions = static_cast<FlutterSemanticsAction>(0);
node2.text_selection_base = -1;
node2.text_selection_extent = -1;
node2.label = "node2";
node2.hint = "";
node2.value = "";
node2.increased_value = "";
node2.decreased_value = "";
node2.tooltip = "";
node2.child_count = 0;
node2.custom_accessibility_actions_count = 0;
bridge->AddFlutterSemanticsNodeUpdate(node1);
bridge->AddFlutterSemanticsNodeUpdate(node2);
bridge->CommitUpdates();
// Look up the root node delegate.
auto root_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock();
ASSERT_TRUE(root_delegate);
ASSERT_EQ(root_delegate->GetChildCount(), 1);
// Look up the child node delegate.
auto child_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(2).lock();
ASSERT_TRUE(child_delegate);
ASSERT_EQ(child_delegate->GetChildCount(), 0);
// Ensure a node with ID 0 does not exist.
auto invalid_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
ASSERT_FALSE(invalid_delegate);
[engine shutDownEngine];
}
TEST_F(AccessibilityBridgeMacTest, DoesNotSendAccessibilityCreateNotificationWhenHeadless) {
FlutterViewController* viewController = CreateTestViewController();
FlutterEngine* engine = viewController.engine;
// Setting up bridge so that the AccessibilityBridgeMacDelegateSpy
// can query semantics information from.
engine.semanticsEnabled = YES;
auto bridge = std::static_pointer_cast<AccessibilityBridgeMacSpy>(
viewController.accessibilityBridge.lock());
FlutterSemanticsNode2 root;
root.id = 0;
root.flags = static_cast<FlutterSemanticsFlag>(0);
root.actions = static_cast<FlutterSemanticsAction>(0);
root.text_selection_base = -1;
root.text_selection_extent = -1;
root.label = "root";
root.hint = "";
root.value = "";
root.increased_value = "";
root.decreased_value = "";
root.tooltip = "";
root.child_count = 0;
root.custom_accessibility_actions_count = 0;
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
auto platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
// Creates a targeted event.
ui::AXTree tree;
ui::AXNode ax_node(&tree, nullptr, 0, 0);
ui::AXNodeData node_data;
node_data.id = 0;
ax_node.SetData(node_data);
std::vector<ui::AXEventIntent> intent;
ui::AXEventGenerator::EventParams event_params(ui::AXEventGenerator::Event::CHILDREN_CHANGED,
ax::mojom::EventFrom::kNone, intent);
ui::AXEventGenerator::TargetedEvent targeted_event(&ax_node, event_params);
bridge->OnAccessibilityEvent(targeted_event);
// Does not send any notification if the engine is headless.
EXPECT_EQ(bridge->actual_notifications.size(), 0u);
[engine shutDownEngine];
}
TEST_F(AccessibilityBridgeMacTest, DoesNotSendAccessibilityCreateNotificationWhenNoWindow) {
FlutterViewController* viewController = CreateTestViewController();
FlutterEngine* engine = viewController.engine;
// Setting up bridge so that the AccessibilityBridgeMacDelegateSpy
// can query semantics information from.
engine.semanticsEnabled = YES;
auto bridge = std::static_pointer_cast<AccessibilityBridgeMacSpy>(
viewController.accessibilityBridge.lock());
FlutterSemanticsNode2 root;
root.id = 0;
root.flags = static_cast<FlutterSemanticsFlag>(0);
root.actions = static_cast<FlutterSemanticsAction>(0);
root.text_selection_base = -1;
root.text_selection_extent = -1;
root.label = "root";
root.hint = "";
root.value = "";
root.increased_value = "";
root.decreased_value = "";
root.tooltip = "";
root.child_count = 0;
root.custom_accessibility_actions_count = 0;
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
auto platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
// Creates a targeted event.
ui::AXTree tree;
ui::AXNode ax_node(&tree, nullptr, 0, 0);
ui::AXNodeData node_data;
node_data.id = 0;
ax_node.SetData(node_data);
std::vector<ui::AXEventIntent> intent;
ui::AXEventGenerator::EventParams event_params(ui::AXEventGenerator::Event::CHILDREN_CHANGED,
ax::mojom::EventFrom::kNone, intent);
ui::AXEventGenerator::TargetedEvent targeted_event(&ax_node, event_params);
bridge->OnAccessibilityEvent(targeted_event);
// Does not send any notification if the flutter view is not attached to a NSWindow.
EXPECT_EQ(bridge->actual_notifications.size(), 0u);
[engine shutDownEngine];
}
} // namespace flutter::testing
| engine/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacTest.mm",
"repo_id": "engine",
"token_count": 3913
} | 381 |
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDISPLAYLINK_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDISPLAYLINK_H_
#import <AppKit/AppKit.h>
@protocol FlutterDisplayLinkDelegate <NSObject>
- (void)onDisplayLink:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp;
@end
/// Provides notifications of display refresh.
///
/// Internally FlutterDisplayLink will use at most one CVDisplayLink per
/// screen shared for all views belonging to that screen. This is necessary
/// because each CVDisplayLink comes with its own thread.
@interface FlutterDisplayLink : NSObject
/// Creates new instance tied to provided NSView. FlutterDisplayLink
/// will track view display changes transparently to synchronize
/// update with display refresh.
/// This function must be called on the main thread.
+ (instancetype)displayLinkWithView:(NSView*)view;
/// Delegate must be set on main thread. Delegate method will be called on
/// on display link thread.
@property(nonatomic, weak) id<FlutterDisplayLinkDelegate> delegate;
/// Pauses and resumes the display link. May be called from any thread.
@property(readwrite) BOOL paused;
/// Returns the nominal refresh period of the display to which the view
/// currently belongs (in seconds). If view does not belong to any display,
/// returns 0. Can be called from any thread.
@property(readonly) CFTimeInterval nominalOutputRefreshPeriod;
/// Invalidates the display link. Must be called on the main thread.
- (void)invalidate;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDISPLAYLINK_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h",
"repo_id": "engine",
"token_count": 478
} | 382 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h"
#include <cctype>
#include <map>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h"
// Turn on this flag to print complete layout data when switching IMEs. The data
// is used in unit tests.
// #define DEBUG_PRINT_LAYOUT
namespace {
using flutter::LayoutClue;
using flutter::LayoutGoal;
#ifdef DEBUG_PRINT_LAYOUT
// Prints layout entries that will be parsed by `MockLayoutData`.
NSString* debugFormatLayoutData(NSString* debugLayoutData,
uint16_t keyCode,
LayoutClue clue1,
LayoutClue clue2) {
return [NSString
stringWithFormat:@" %@%@0x%d%04x, 0x%d%04x,", debugLayoutData,
keyCode % 4 == 0 ? [NSString stringWithFormat:@"\n/* 0x%02x */ ", keyCode]
: @" ",
clue1.isDeadKey, clue1.character, clue2.isDeadKey, clue2.character];
}
#endif
// Someohow this pointer type must be defined as a single type for the compiler
// to compile the function pointer type (due to _Nullable).
typedef NSResponder* _NSResponderPtr;
typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
bool isEascii(const LayoutClue& clue) {
return clue.character < 256 && !clue.isDeadKey;
}
typedef void (^VoidBlock)();
// Someohow this pointer type must be defined as a single type for the compiler
// to compile the function pointer type (due to _Nullable).
typedef NSResponder* _NSResponderPtr;
typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
} // namespace
@interface FlutterKeyboardManager ()
/**
* The text input plugin set by initialization.
*/
@property(nonatomic, weak) id<FlutterKeyboardViewDelegate> viewDelegate;
/**
* The primary responders added by addPrimaryResponder.
*/
@property(nonatomic) NSMutableArray<id<FlutterKeyPrimaryResponder>>* primaryResponders;
@property(nonatomic) NSMutableArray<NSEvent*>* pendingEvents;
@property(nonatomic) BOOL processingEvent;
@property(nonatomic) NSMutableDictionary<NSNumber*, NSNumber*>* layoutMap;
@property(nonatomic, nullable) NSEvent* eventBeingDispatched;
/**
* Add a primary responder, which asynchronously decides whether to handle an
* event.
*/
- (void)addPrimaryResponder:(nonnull id<FlutterKeyPrimaryResponder>)responder;
/**
* Start processing the next event if not started already.
*
* This function might initiate an async process, whose callback calls this
* function again.
*/
- (void)processNextEvent;
/**
* Implement how to process an event.
*
* The `onFinish` must be called eventually, either during this function or
* asynchronously later, otherwise the event queue will be stuck.
*
* This function is called by processNextEvent.
*/
- (void)performProcessEvent:(NSEvent*)event onFinish:(nonnull VoidBlock)onFinish;
/**
* Dispatch an event that's not hadled by the responders to text input plugin,
* and potentially to the next responder.
*/
- (void)dispatchTextEvent:(nonnull NSEvent*)pendingEvent;
/**
* Clears the current layout and build a new one based on the current layout.
*/
- (void)buildLayout;
@end
@implementation FlutterKeyboardManager {
NextResponderProvider _getNextResponder;
}
- (nonnull instancetype)initWithViewDelegate:(nonnull id<FlutterKeyboardViewDelegate>)viewDelegate {
self = [super init];
if (self != nil) {
_processingEvent = FALSE;
_viewDelegate = viewDelegate;
FlutterMethodChannel* keyboardChannel =
[FlutterMethodChannel methodChannelWithName:@"flutter/keyboard"
binaryMessenger:[_viewDelegate getBinaryMessenger]
codec:[FlutterStandardMethodCodec sharedInstance]];
[keyboardChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[self handleKeyboardMethodCall:call result:result];
}];
_primaryResponders = [[NSMutableArray alloc] init];
__weak __typeof__(self) weakSelf = self;
[self addPrimaryResponder:[[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:^(const FlutterKeyEvent& event,
FlutterKeyEventCallback callback,
void* userData) {
__strong __typeof__(weakSelf) strongSelf = weakSelf;
[strongSelf.viewDelegate sendKeyEvent:event
callback:callback
userData:userData];
}]];
[self
addPrimaryResponder:[[FlutterChannelKeyResponder alloc]
initWithChannel:[FlutterBasicMessageChannel
messageChannelWithName:@"flutter/keyevent"
binaryMessenger:[_viewDelegate
getBinaryMessenger]
codec:[FlutterJSONMessageCodec
sharedInstance]]]];
_pendingEvents = [[NSMutableArray alloc] init];
_layoutMap = [NSMutableDictionary<NSNumber*, NSNumber*> dictionary];
[self buildLayout];
for (id<FlutterKeyPrimaryResponder> responder in _primaryResponders) {
responder.layoutMap = _layoutMap;
}
[_viewDelegate subscribeToKeyboardLayoutChange:^() {
[weakSelf buildLayout];
}];
}
return self;
}
- (void)handleKeyboardMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([[call method] isEqualToString:@"getKeyboardState"]) {
result([self getPressedState]);
} else {
result(FlutterMethodNotImplemented);
}
}
- (void)addPrimaryResponder:(nonnull id<FlutterKeyPrimaryResponder>)responder {
[_primaryResponders addObject:responder];
}
- (void)handleEvent:(nonnull NSEvent*)event {
// The `handleEvent` does not process the event immediately, but instead put
// events into a queue. Events are processed one by one by `processNextEvent`.
// Be sure to add a handling method in propagateKeyEvent when allowing more
// event types here.
if (event.type != NSEventTypeKeyDown && event.type != NSEventTypeKeyUp &&
event.type != NSEventTypeFlagsChanged) {
return;
}
[_pendingEvents addObject:event];
[self processNextEvent];
}
- (BOOL)isDispatchingKeyEvent:(NSEvent*)event {
return _eventBeingDispatched == event;
}
#pragma mark - Private
- (void)processNextEvent {
@synchronized(self) {
if (_processingEvent || [_pendingEvents count] == 0) {
return;
}
_processingEvent = TRUE;
}
NSEvent* pendingEvent = [_pendingEvents firstObject];
[_pendingEvents removeObjectAtIndex:0];
__weak __typeof__(self) weakSelf = self;
VoidBlock onFinish = ^() {
weakSelf.processingEvent = FALSE;
[weakSelf processNextEvent];
};
[self performProcessEvent:pendingEvent onFinish:onFinish];
}
- (void)performProcessEvent:(NSEvent*)event onFinish:(VoidBlock)onFinish {
// Having no primary responders require extra logic, but Flutter hard-codes
// all primary responders, so this is a situation that Flutter will never
// encounter.
NSAssert([_primaryResponders count] >= 0, @"At least one primary responder must be added.");
__weak __typeof__(self) weakSelf = self;
__block int unreplied = [_primaryResponders count];
__block BOOL anyHandled = false;
FlutterAsyncKeyCallback replyCallback = ^(BOOL handled) {
unreplied -= 1;
NSAssert(unreplied >= 0, @"More primary responders replied than possible.");
anyHandled = anyHandled || handled;
if (unreplied == 0) {
if (!anyHandled) {
[weakSelf dispatchTextEvent:event];
}
onFinish();
}
};
for (id<FlutterKeyPrimaryResponder> responder in _primaryResponders) {
[responder handleEvent:event callback:replyCallback];
}
}
- (void)dispatchTextEvent:(NSEvent*)event {
if ([_viewDelegate onTextInputKeyEvent:event]) {
return;
}
NSResponder* nextResponder = _viewDelegate.nextResponder;
if (nextResponder == nil) {
return;
}
NSAssert(_eventBeingDispatched == nil, @"An event is already being dispached.");
_eventBeingDispatched = event;
switch (event.type) {
case NSEventTypeKeyDown:
if ([nextResponder respondsToSelector:@selector(keyDown:)]) {
[nextResponder keyDown:event];
}
break;
case NSEventTypeKeyUp:
if ([nextResponder respondsToSelector:@selector(keyUp:)]) {
[nextResponder keyUp:event];
}
break;
case NSEventTypeFlagsChanged:
if ([nextResponder respondsToSelector:@selector(flagsChanged:)]) {
[nextResponder flagsChanged:event];
}
break;
default:
NSAssert(false, @"Unexpected key event type (got %lu).", event.type);
}
NSAssert(_eventBeingDispatched != nil, @"_eventBeingDispatched was cleared unexpectedly.");
_eventBeingDispatched = nil;
}
- (void)buildLayout {
[_layoutMap removeAllObjects];
std::map<uint32_t, LayoutGoal> mandatoryGoalsByChar;
std::map<uint32_t, LayoutGoal> usLayoutGoalsByKeyCode;
for (const LayoutGoal& goal : flutter::kLayoutGoals) {
if (goal.mandatory) {
mandatoryGoalsByChar[goal.keyChar] = goal;
} else {
usLayoutGoalsByKeyCode[goal.keyCode] = goal;
}
}
// Derive key mapping for each key code based on their layout clues.
// Key code 0x00 - 0x32 are typewriter keys (letters, digits, and symbols.)
// See keyCodeToPhysicalKey.
const uint16_t kMaxKeyCode = 0x32;
#ifdef DEBUG_PRINT_LAYOUT
NSString* debugLayoutData = @"";
#endif
for (uint16_t keyCode = 0; keyCode <= kMaxKeyCode; keyCode += 1) {
std::vector<LayoutClue> thisKeyClues = {
[_viewDelegate lookUpLayoutForKeyCode:keyCode shift:false],
[_viewDelegate lookUpLayoutForKeyCode:keyCode shift:true]};
#ifdef DEBUG_PRINT_LAYOUT
debugLayoutData =
debugFormatLayoutData(debugLayoutData, keyCode, thisKeyClues[0], thisKeyClues[1]);
#endif
// The logical key should be the first available clue from below:
//
// - Mandatory goal, if it matches any clue. This ensures that all alnum
// keys can be found somewhere.
// - US layout, if neither clue of the key is EASCII. This ensures that
// there are no non-latin logical keys.
// - Derived on the fly from keyCode & characters.
for (const LayoutClue& clue : thisKeyClues) {
uint32_t keyChar = clue.isDeadKey ? 0 : clue.character;
auto matchingGoal = mandatoryGoalsByChar.find(keyChar);
if (matchingGoal != mandatoryGoalsByChar.end()) {
// Found a key that produces a mandatory char. Use it.
NSAssert(_layoutMap[@(keyCode)] == nil, @"Attempting to assign an assigned key code.");
_layoutMap[@(keyCode)] = @(keyChar);
mandatoryGoalsByChar.erase(matchingGoal);
break;
}
}
bool hasAnyEascii = isEascii(thisKeyClues[0]) || isEascii(thisKeyClues[1]);
// See if any produced char meets the requirement as a logical key.
auto foundUsLayoutGoal = usLayoutGoalsByKeyCode.find(keyCode);
if (foundUsLayoutGoal != usLayoutGoalsByKeyCode.end() && _layoutMap[@(keyCode)] == nil &&
!hasAnyEascii) {
_layoutMap[@(keyCode)] = @(foundUsLayoutGoal->second.keyChar);
}
}
#ifdef DEBUG_PRINT_LAYOUT
NSLog(@"%@", debugLayoutData);
#endif
// Ensure all mandatory goals are assigned.
for (auto mandatoryGoalIter : mandatoryGoalsByChar) {
const LayoutGoal& goal = mandatoryGoalIter.second;
_layoutMap[@(goal.keyCode)] = @(goal.keyChar);
}
}
- (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags
timestamp:(NSTimeInterval)timestamp {
for (id<FlutterKeyPrimaryResponder> responder in _primaryResponders) {
[responder syncModifiersIfNeeded:modifierFlags timestamp:timestamp];
}
}
/**
* Returns the keyboard pressed state.
*
* Returns the keyboard pressed state. The dictionary contains one entry per
* pressed keys, mapping from the logical key to the physical key.
*/
- (nonnull NSDictionary*)getPressedState {
// The embedder responder is the first element in _primaryResponders.
FlutterEmbedderKeyResponder* embedderResponder =
(FlutterEmbedderKeyResponder*)_primaryResponders[0];
return [embedderResponder getPressedState];
}
@end
| engine/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm",
"repo_id": "engine",
"token_count": 5134
} | 383 |
// Copyright 2013 The Flutter 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/fml/logging.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h"
@implementation FlutterPlatformViewController {
// NSDictionary maps platform view type identifiers to FlutterPlatformViewFactories.
NSMutableDictionary<NSString*, NSObject<FlutterPlatformViewFactory>*>* _platformViewFactories;
// Map from platform view id to the underlying NSView.
std::map<int, NSView*> _platformViews;
// View ids that are going to be disposed on the next present call.
std::unordered_set<int64_t> _platformViewsToDispose;
}
- (instancetype)init {
self = [super init];
if (self) {
_platformViewFactories = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)onCreateWithViewIdentifier:(int64_t)viewId
viewType:(nonnull NSString*)viewType
arguments:(nullable id)args
result:(nonnull FlutterResult)result {
if (_platformViews.count(viewId) != 0) {
result([FlutterError errorWithCode:@"recreating_view"
message:@"trying to create an already created view"
details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]);
return;
}
NSObject<FlutterPlatformViewFactory>* factory = _platformViewFactories[viewType];
if (!factory) {
result([FlutterError
errorWithCode:@"unregistered_view_type"
message:[NSString stringWithFormat:@"A UIKitView widget is trying to create a "
@"PlatformView with an unregistered type: < %@ >",
viewType]
details:@"If you are the author of the PlatformView, make sure `registerViewFactory` "
@"is invoked.\n"
@"See: "
@"https://docs.flutter.dev/development/platform-integration/"
@"platform-views#on-the-platform-side-1 for more details.\n"
@"If you are not the author of the PlatformView, make sure to call "
@"`GeneratedPluginRegistrant.register`."]);
return;
}
NSView* platform_view = [factory createWithViewIdentifier:viewId arguments:args];
// Flutter compositing requires CALayer-backed platform views.
// Force the platform view to be backed by a CALayer.
[platform_view setWantsLayer:YES];
_platformViews[viewId] = platform_view;
result(nil);
}
- (void)onDisposeWithViewID:(int64_t)viewId result:(nonnull FlutterResult)result {
if (_platformViews.count(viewId) == 0) {
result([FlutterError errorWithCode:@"unknown_view"
message:@"trying to dispose an unknown"
details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]);
return;
}
// The following disposePlatformViews call will dispose the views.
_platformViewsToDispose.insert(viewId);
result(nil);
}
- (void)registerViewFactory:(nonnull NSObject<FlutterPlatformViewFactory>*)factory
withId:(nonnull NSString*)factoryId {
_platformViewFactories[factoryId] = factory;
}
- (nullable NSView*)platformViewWithID:(int64_t)viewId {
if (_platformViews.count(viewId)) {
return _platformViews[viewId];
} else {
return nil;
}
}
- (void)handleMethodCall:(nonnull FlutterMethodCall*)call result:(nonnull FlutterResult)result {
if ([[call method] isEqualToString:@"create"]) {
NSMutableDictionary<NSString*, id>* args = [call arguments];
if ([args objectForKey:@"id"]) {
int64_t viewId = [args[@"id"] longLongValue];
NSString* viewType = [NSString stringWithUTF8String:([args[@"viewType"] UTF8String])];
id creationArgs = nil;
NSObject<FlutterPlatformViewFactory>* factory = _platformViewFactories[viewType];
if ([factory respondsToSelector:@selector(createArgsCodec)]) {
NSObject<FlutterMessageCodec>* codec = [factory createArgsCodec];
if (codec != nil && args[@"params"] != nil) {
FlutterStandardTypedData* creationArgsData = args[@"params"];
creationArgs = [codec decode:creationArgsData.data];
}
}
[self onCreateWithViewIdentifier:viewId
viewType:viewType
arguments:creationArgs
result:result];
} else {
result([FlutterError errorWithCode:@"unknown_view"
message:@"'id' argument must be passed to create a platform view."
details:[NSString stringWithFormat:@"'id' not specified."]]);
}
} else if ([[call method] isEqualToString:@"dispose"]) {
NSNumber* arg = [call arguments];
int64_t viewId = [arg longLongValue];
[self onDisposeWithViewID:viewId result:result];
} else if ([[call method] isEqualToString:@"acceptGesture"]) {
[self handleAcceptGesture:call result:result];
} else if ([[call method] isEqualToString:@"rejectGesture"]) {
[self handleRejectGesture:call result:result];
} else {
result(FlutterMethodNotImplemented);
}
}
- (void)handleAcceptGesture:(FlutterMethodCall*)call result:(FlutterResult)result {
NSDictionary<NSString*, id>* args = [call arguments];
NSAssert(args && args[@"id"], @"id argument is required");
int64_t viewId = [args[@"id"] longLongValue];
if (_platformViews.count(viewId) == 0) {
result([FlutterError errorWithCode:@"unknown_view"
message:@"trying to set gesture state for an unknown view"
details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]);
return;
}
// TODO(cbracken): Implement. https://github.com/flutter/flutter/issues/124492
result(nil);
}
- (void)handleRejectGesture:(FlutterMethodCall*)call result:(FlutterResult)result {
NSDictionary<NSString*, id>* args = [call arguments];
NSAssert(args && args[@"id"], @"id argument is required");
int64_t viewId = [args[@"id"] longLongValue];
if (_platformViews.count(viewId) == 0) {
result([FlutterError errorWithCode:@"unknown_view"
message:@"trying to set gesture state for an unknown view"
details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]);
return;
}
// TODO(cbracken): Implement. https://github.com/flutter/flutter/issues/124492
result(nil);
}
- (void)disposePlatformViews {
if (_platformViewsToDispose.empty()) {
return;
}
FML_DCHECK([[NSThread currentThread] isMainThread])
<< "Must be on the main thread to handle disposing platform views";
for (int64_t viewId : _platformViewsToDispose) {
NSView* view = _platformViews[viewId];
[view removeFromSuperview];
_platformViews.erase(viewId);
}
_platformViewsToDispose.clear();
}
@end
| engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.mm",
"repo_id": "engine",
"token_count": 2917
} | 384 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
@implementation FlutterTextureRegistrar {
__weak id<FlutterTextureRegistrarDelegate> _delegate;
__weak FlutterEngine* _flutterEngine;
// A mapping of textureID to internal FlutterExternalTexture wrapper.
NSMutableDictionary<NSNumber*, FlutterExternalTexture*>* _textures;
}
- (instancetype)initWithDelegate:(id<FlutterTextureRegistrarDelegate>)delegate
engine:(FlutterEngine*)engine {
if (self = [super init]) {
_delegate = delegate;
_flutterEngine = engine;
_textures = [[NSMutableDictionary alloc] init];
}
return self;
}
- (int64_t)registerTexture:(id<FlutterTexture>)texture {
FlutterExternalTexture* externalTexture = [_delegate onRegisterTexture:texture];
int64_t textureID = [externalTexture textureID];
BOOL success = [_flutterEngine registerTextureWithID:textureID];
if (success) {
_textures[@(textureID)] = externalTexture;
return textureID;
} else {
NSLog(@"Unable to register the texture with id: %lld.", textureID);
return 0;
}
}
- (void)textureFrameAvailable:(int64_t)textureID {
BOOL success = [_flutterEngine markTextureFrameAvailable:textureID];
if (!success) {
NSLog(@"Unable to mark texture with id %lld as available.", textureID);
}
}
- (void)unregisterTexture:(int64_t)textureID {
bool success = [_flutterEngine unregisterTextureWithID:textureID];
if (success) {
[_textures removeObjectForKey:@(textureID)];
} else {
NSLog(@"Unable to unregister texture with id: %lld.", textureID);
}
}
- (FlutterExternalTexture*)getTextureWithID:(int64_t)textureID {
return _textures[@(textureID)];
}
@end
| engine/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.mm",
"repo_id": "engine",
"token_count": 671
} | 385 |
// Copyright 2013 The Flutter 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_FLUTTERVIEWCONTROLLER_INTERNAL_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h"
#include <memory>
#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardViewDelegate.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
@interface FlutterViewController () <FlutterKeyboardViewDelegate>
/**
* The identifier for this view controller.
*
* The ID is assigned by FlutterEngine when the view controller is attached.
*
* If the view controller is unattached (see FlutterViewController#attached),
* reading this property throws an assertion.
*/
@property(nonatomic, readonly) FlutterViewId viewId;
// The FlutterView for this view controller.
@property(nonatomic, readonly, nullable) FlutterView* flutterView;
/**
* The text input plugin that handles text editing state for text fields.
*/
@property(nonatomic, readonly, nonnull) FlutterTextInputPlugin* textInputPlugin;
@property(nonatomic, readonly) std::weak_ptr<flutter::AccessibilityBridgeMac> accessibilityBridge;
/**
* Returns YES if provided event is being currently redispatched by keyboard manager.
*/
- (BOOL)isDispatchingKeyEvent:(nonnull NSEvent*)event;
/**
* Set up the controller with `engine` and `id`, and other engine-level classes.
*
* This method is called by FlutterEngine. A view controller must be set up
* before being used, and must be set up only once until detachFromEngine:.
*/
- (void)setUpWithEngine:(nonnull FlutterEngine*)engine
viewId:(FlutterViewId)viewId
threadSynchronizer:(nonnull FlutterThreadSynchronizer*)threadSynchronizer;
/**
* Reset the `engine` and `id` of this controller.
*
* This method is called by FlutterEngine.
*/
- (void)detachFromEngine;
/**
* Called by the associated FlutterEngine when FlutterEngine#semanticsEnabled
* has changed.
*/
- (void)notifySemanticsEnabledChanged;
/**
* Notify from the framework that the semantics for this view needs to be
* updated.
*/
- (void)updateSemantics:(nonnull const FlutterSemanticsUpdate2*)update;
@end
// Private methods made visible for testing
@interface FlutterViewController (TestMethods)
- (void)onAccessibilityStatusChanged:(BOOL)enabled;
/* Creates an accessibility bridge with the provided parameters.
*
* By default this method calls AccessibilityBridgeMac's initializer. Exposing
* this method allows unit tests to override.
*/
- (std::shared_ptr<flutter::AccessibilityBridgeMac>)createAccessibilityBridgeWithEngine:
(nonnull FlutterEngine*)engine;
- (nonnull FlutterView*)createFlutterViewWithMTLDevice:(nonnull id<MTLDevice>)device
commandQueue:(nonnull id<MTLCommandQueue>)commandQueue;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h",
"repo_id": "engine",
"token_count": 1051
} | 386 |
framework module FlutterEmbedder {
umbrella header "FlutterEmbedder.h"
export *
module * { export * }
}
| engine/shell/platform/embedder/assets/embedder.modulemap/0 | {
"file_path": "engine/shell/platform/embedder/assets/embedder.modulemap",
"repo_id": "engine",
"token_count": 36
} | 387 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_H_
#include <map>
#include <memory>
#include <unordered_map>
#include "flutter/flow/embedded_views.h"
#include "flutter/fml/hash_combine.h"
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/embedder/embedder_external_view.h"
#include "flutter/shell/platform/embedder/embedder_render_target_cache.h"
namespace flutter {
//------------------------------------------------------------------------------
/// @brief The external view embedder used by the generic embedder API.
/// This class acts a proxy between the rasterizer and the embedder
/// when the rasterizer is rendering into multiple layers. It asks
/// the embedder for the render targets for the various layers the
/// rasterizer is rendering into, recycles the render targets as
/// necessary and converts rasterizer specific metadata into an
/// embedder friendly format so that it can present the layers
/// on-screen.
///
class EmbedderExternalViewEmbedder final : public ExternalViewEmbedder {
public:
using CreateRenderTargetCallback =
std::function<std::unique_ptr<EmbedderRenderTarget>(
GrDirectContext* context,
const std::shared_ptr<impeller::AiksContext>& aiks_context,
const FlutterBackingStoreConfig& config)>;
using PresentCallback =
std::function<bool(FlutterViewId view_id,
const std::vector<const FlutterLayer*>& layers)>;
using SurfaceTransformationCallback = std::function<SkMatrix(void)>;
//----------------------------------------------------------------------------
/// @brief Creates an external view embedder used by the generic embedder
/// API.
///
/// @param[in] avoid_backing_store_cache If set, create_render_target_callback
/// will beinvoked every frame for every
/// engine composited layer. The result
/// will not cached.
///
/// @param[in] create_render_target_callback
/// The render target callback used to
/// request the render target for a layer.
/// @param[in] present_callback The callback used to forward a
/// collection of layers (backed by
/// fulfilled render targets) to the
/// embedder for presentation.
///
EmbedderExternalViewEmbedder(
bool avoid_backing_store_cache,
const CreateRenderTargetCallback& create_render_target_callback,
const PresentCallback& present_callback);
//----------------------------------------------------------------------------
/// @brief Collects the external view embedder.
///
~EmbedderExternalViewEmbedder() override;
//----------------------------------------------------------------------------
/// @brief Sets the surface transformation callback used by the external
/// view embedder to ask the platform for the per frame root
/// surface transformation.
///
/// @param[in] surface_transformation_callback The surface transformation
/// callback
///
void SetSurfaceTransformationCallback(
SurfaceTransformationCallback surface_transformation_callback);
private:
// |ExternalViewEmbedder|
void CancelFrame() override;
// |ExternalViewEmbedder|
void BeginFrame(GrDirectContext* context,
const fml::RefPtr<fml::RasterThreadMerger>&
raster_thread_merger) override;
// |ExternalViewEmbedder|
void PrepareFlutterView(int64_t flutter_view_id,
SkISize frame_size,
double device_pixel_ratio) override;
// |ExternalViewEmbedder|
void PrerollCompositeEmbeddedView(
int64_t view_id,
std::unique_ptr<EmbeddedViewParams> params) override;
// |ExternalViewEmbedder|
DlCanvas* CompositeEmbeddedView(int64_t view_id) override;
// |ExternalViewEmbedder|
void SubmitFlutterView(
GrDirectContext* context,
const std::shared_ptr<impeller::AiksContext>& aiks_context,
std::unique_ptr<SurfaceFrame> frame) override;
// |ExternalViewEmbedder|
DlCanvas* GetRootCanvas() override;
private:
const bool avoid_backing_store_cache_;
const CreateRenderTargetCallback create_render_target_callback_;
const PresentCallback present_callback_;
SurfaceTransformationCallback surface_transformation_callback_;
SkISize pending_frame_size_ = SkISize::Make(0, 0);
double pending_device_pixel_ratio_ = 1.0;
SkMatrix pending_surface_transformation_;
EmbedderExternalView::PendingViews pending_views_;
std::vector<EmbedderExternalView::ViewIdentifier> composition_order_;
EmbedderRenderTargetCache render_target_cache_;
void Reset();
SkMatrix GetSurfaceTransformation() const;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderExternalViewEmbedder);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_H_
| engine/shell/platform/embedder/embedder_external_view_embedder.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_external_view_embedder.h",
"repo_id": "engine",
"token_count": 2070
} | 388 |
// Copyright 2013 The Flutter 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_SEMANTICS_UPDATE_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SEMANTICS_UPDATE_H_
#include "flutter/lib/ui/semantics/custom_accessibility_action.h"
#include "flutter/lib/ui/semantics/semantics_node.h"
#include "flutter/shell/platform/embedder/embedder.h"
namespace flutter {
// A semantic update, used by the embedder API's v1 and v2 semantic update
// callbacks.
class EmbedderSemanticsUpdate {
public:
EmbedderSemanticsUpdate(const SemanticsNodeUpdates& nodes,
const CustomAccessibilityActionUpdates& actions);
~EmbedderSemanticsUpdate();
// Get the semantic update. The pointer is only valid while
// |EmbedderSemanticsUpdate| exists.
FlutterSemanticsUpdate* get() { return &update_; }
private:
FlutterSemanticsUpdate update_;
std::vector<FlutterSemanticsNode> nodes_;
std::vector<FlutterSemanticsCustomAction> actions_;
// Translates engine semantic nodes to embedder semantic nodes.
void AddNode(const SemanticsNode& node);
// Translates engine semantic custom actions to embedder semantic custom
// actions.
void AddAction(const CustomAccessibilityAction& action);
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderSemanticsUpdate);
};
// A semantic update, used by the embedder API's v3 semantic update callback.
//
// This holds temporary embedder-specific objects that are translated from
// the engine's internal representation and passed back to the semantics
// update callback. Once the callback finishes, this object is destroyed
// and the temporary embedder-specific objects are automatically cleaned up.
class EmbedderSemanticsUpdate2 {
public:
EmbedderSemanticsUpdate2(const SemanticsNodeUpdates& nodes,
const CustomAccessibilityActionUpdates& actions);
~EmbedderSemanticsUpdate2();
// Get the semantic update. The pointer is only valid while
// |EmbedderSemanticsUpdate2| exists.
FlutterSemanticsUpdate2* get() { return &update_; }
private:
// These fields hold temporary embedder-specific objects that
// must remain valid for the duration of the semantics update callback.
// They are automatically cleaned up when |EmbedderSemanticsUpdate2| is
// destroyed.
FlutterSemanticsUpdate2 update_;
std::vector<FlutterSemanticsNode2> nodes_;
std::vector<FlutterSemanticsNode2*> node_pointers_;
std::vector<FlutterSemanticsCustomAction2> actions_;
std::vector<FlutterSemanticsCustomAction2*> action_pointers_;
std::vector<std::unique_ptr<std::vector<const FlutterStringAttribute*>>>
node_string_attributes_;
std::vector<std::unique_ptr<FlutterStringAttribute>> string_attributes_;
std::vector<std::unique_ptr<FlutterLocaleStringAttribute>> locale_attributes_;
std::unique_ptr<FlutterSpellOutStringAttribute> spell_out_attribute_;
// Translates engine semantic nodes to embedder semantic nodes.
void AddNode(const SemanticsNode& node);
// Translates engine semantic custom actions to embedder semantic custom
// actions.
void AddAction(const CustomAccessibilityAction& action);
// A helper struct for |CreateStringAttributes|.
struct EmbedderStringAttributes {
// The number of string attribute pointers in |attributes|.
size_t count;
// An array of string attribute pointers.
const FlutterStringAttribute** attributes;
};
// Translates engine string attributes to embedder string attributes.
EmbedderStringAttributes CreateStringAttributes(
const StringAttributes& attribute);
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderSemanticsUpdate2);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SEMANTICS_UPDATE_H_
| engine/shell/platform/embedder/embedder_semantics_update.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_semantics_update.h",
"repo_id": "engine",
"token_count": 1154
} | 389 |
// Copyright 2013 The Flutter 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_task_runner.h"
#include "flutter/fml/message_loop_impl.h"
#include "flutter/fml/message_loop_task_queues.h"
namespace flutter {
EmbedderTaskRunner::EmbedderTaskRunner(DispatchTable table,
size_t embedder_identifier)
: TaskRunner(nullptr /* loop implemenation*/),
embedder_identifier_(embedder_identifier),
dispatch_table_(std::move(table)),
placeholder_id_(
fml::MessageLoopTaskQueues::GetInstance()->CreateTaskQueue()) {
FML_DCHECK(dispatch_table_.post_task_callback);
FML_DCHECK(dispatch_table_.runs_task_on_current_thread_callback);
}
EmbedderTaskRunner::~EmbedderTaskRunner() = default;
size_t EmbedderTaskRunner::GetEmbedderIdentifier() const {
return embedder_identifier_;
}
void EmbedderTaskRunner::PostTask(const fml::closure& task) {
PostTaskForTime(task, fml::TimePoint::Now());
}
void EmbedderTaskRunner::PostTaskForTime(const fml::closure& task,
fml::TimePoint target_time) {
if (!task) {
return;
}
uint64_t baton = 0;
{
// Release the lock before the jump via the dispatch table.
std::scoped_lock lock(tasks_mutex_);
baton = ++last_baton_;
pending_tasks_[baton] = task;
}
dispatch_table_.post_task_callback(this, baton, target_time);
}
void EmbedderTaskRunner::PostDelayedTask(const fml::closure& task,
fml::TimeDelta delay) {
PostTaskForTime(task, fml::TimePoint::Now() + delay);
}
bool EmbedderTaskRunner::RunsTasksOnCurrentThread() {
return dispatch_table_.runs_task_on_current_thread_callback();
}
bool EmbedderTaskRunner::PostTask(uint64_t baton) {
fml::closure task;
{
std::scoped_lock lock(tasks_mutex_);
auto found = pending_tasks_.find(baton);
if (found == pending_tasks_.end()) {
FML_LOG(ERROR) << "Embedder attempted to post an unknown task.";
return false;
}
task = found->second;
pending_tasks_.erase(found);
// Let go of the tasks mutex befor executing the task.
}
FML_DCHECK(task);
task();
return true;
}
// |fml::TaskRunner|
fml::TaskQueueId EmbedderTaskRunner::GetTaskQueueId() {
return placeholder_id_;
}
} // namespace flutter
| engine/shell/platform/embedder/embedder_task_runner.cc/0 | {
"file_path": "engine/shell/platform/embedder/embedder_task_runner.cc",
"repo_id": "engine",
"token_count": 958
} | 390 |
// Copyright 2013 The Flutter 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_TEST_UTILS_KEY_CODES_G_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_KEY_CODES_G_H_
#include <cinttypes>
// 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/key_codes_cc.tmpl
// instead.
//
// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information.
// This file contains keyboard constants to be used in unit tests. They should
// not be used in production code.
namespace flutter {
namespace testing {
namespace keycodes {
constexpr uint64_t kPhysicalHyper = 0x00000010;
constexpr uint64_t kPhysicalSuperKey = 0x00000011;
constexpr uint64_t kPhysicalFn = 0x00000012;
constexpr uint64_t kPhysicalFnLock = 0x00000013;
constexpr uint64_t kPhysicalSuspend = 0x00000014;
constexpr uint64_t kPhysicalResume = 0x00000015;
constexpr uint64_t kPhysicalTurbo = 0x00000016;
constexpr uint64_t kPhysicalPrivacyScreenToggle = 0x00000017;
constexpr uint64_t kPhysicalMicrophoneMuteToggle = 0x00000018;
constexpr uint64_t kPhysicalSleep = 0x00010082;
constexpr uint64_t kPhysicalWakeUp = 0x00010083;
constexpr uint64_t kPhysicalDisplayToggleIntExt = 0x000100b5;
constexpr uint64_t kPhysicalGameButton1 = 0x0005ff01;
constexpr uint64_t kPhysicalGameButton2 = 0x0005ff02;
constexpr uint64_t kPhysicalGameButton3 = 0x0005ff03;
constexpr uint64_t kPhysicalGameButton4 = 0x0005ff04;
constexpr uint64_t kPhysicalGameButton5 = 0x0005ff05;
constexpr uint64_t kPhysicalGameButton6 = 0x0005ff06;
constexpr uint64_t kPhysicalGameButton7 = 0x0005ff07;
constexpr uint64_t kPhysicalGameButton8 = 0x0005ff08;
constexpr uint64_t kPhysicalGameButton9 = 0x0005ff09;
constexpr uint64_t kPhysicalGameButton10 = 0x0005ff0a;
constexpr uint64_t kPhysicalGameButton11 = 0x0005ff0b;
constexpr uint64_t kPhysicalGameButton12 = 0x0005ff0c;
constexpr uint64_t kPhysicalGameButton13 = 0x0005ff0d;
constexpr uint64_t kPhysicalGameButton14 = 0x0005ff0e;
constexpr uint64_t kPhysicalGameButton15 = 0x0005ff0f;
constexpr uint64_t kPhysicalGameButton16 = 0x0005ff10;
constexpr uint64_t kPhysicalGameButtonA = 0x0005ff11;
constexpr uint64_t kPhysicalGameButtonB = 0x0005ff12;
constexpr uint64_t kPhysicalGameButtonC = 0x0005ff13;
constexpr uint64_t kPhysicalGameButtonLeft1 = 0x0005ff14;
constexpr uint64_t kPhysicalGameButtonLeft2 = 0x0005ff15;
constexpr uint64_t kPhysicalGameButtonMode = 0x0005ff16;
constexpr uint64_t kPhysicalGameButtonRight1 = 0x0005ff17;
constexpr uint64_t kPhysicalGameButtonRight2 = 0x0005ff18;
constexpr uint64_t kPhysicalGameButtonSelect = 0x0005ff19;
constexpr uint64_t kPhysicalGameButtonStart = 0x0005ff1a;
constexpr uint64_t kPhysicalGameButtonThumbLeft = 0x0005ff1b;
constexpr uint64_t kPhysicalGameButtonThumbRight = 0x0005ff1c;
constexpr uint64_t kPhysicalGameButtonX = 0x0005ff1d;
constexpr uint64_t kPhysicalGameButtonY = 0x0005ff1e;
constexpr uint64_t kPhysicalGameButtonZ = 0x0005ff1f;
constexpr uint64_t kPhysicalUsbReserved = 0x00070000;
constexpr uint64_t kPhysicalUsbErrorRollOver = 0x00070001;
constexpr uint64_t kPhysicalUsbPostFail = 0x00070002;
constexpr uint64_t kPhysicalUsbErrorUndefined = 0x00070003;
constexpr uint64_t kPhysicalKeyA = 0x00070004;
constexpr uint64_t kPhysicalKeyB = 0x00070005;
constexpr uint64_t kPhysicalKeyC = 0x00070006;
constexpr uint64_t kPhysicalKeyD = 0x00070007;
constexpr uint64_t kPhysicalKeyE = 0x00070008;
constexpr uint64_t kPhysicalKeyF = 0x00070009;
constexpr uint64_t kPhysicalKeyG = 0x0007000a;
constexpr uint64_t kPhysicalKeyH = 0x0007000b;
constexpr uint64_t kPhysicalKeyI = 0x0007000c;
constexpr uint64_t kPhysicalKeyJ = 0x0007000d;
constexpr uint64_t kPhysicalKeyK = 0x0007000e;
constexpr uint64_t kPhysicalKeyL = 0x0007000f;
constexpr uint64_t kPhysicalKeyM = 0x00070010;
constexpr uint64_t kPhysicalKeyN = 0x00070011;
constexpr uint64_t kPhysicalKeyO = 0x00070012;
constexpr uint64_t kPhysicalKeyP = 0x00070013;
constexpr uint64_t kPhysicalKeyQ = 0x00070014;
constexpr uint64_t kPhysicalKeyR = 0x00070015;
constexpr uint64_t kPhysicalKeyS = 0x00070016;
constexpr uint64_t kPhysicalKeyT = 0x00070017;
constexpr uint64_t kPhysicalKeyU = 0x00070018;
constexpr uint64_t kPhysicalKeyV = 0x00070019;
constexpr uint64_t kPhysicalKeyW = 0x0007001a;
constexpr uint64_t kPhysicalKeyX = 0x0007001b;
constexpr uint64_t kPhysicalKeyY = 0x0007001c;
constexpr uint64_t kPhysicalKeyZ = 0x0007001d;
constexpr uint64_t kPhysicalDigit1 = 0x0007001e;
constexpr uint64_t kPhysicalDigit2 = 0x0007001f;
constexpr uint64_t kPhysicalDigit3 = 0x00070020;
constexpr uint64_t kPhysicalDigit4 = 0x00070021;
constexpr uint64_t kPhysicalDigit5 = 0x00070022;
constexpr uint64_t kPhysicalDigit6 = 0x00070023;
constexpr uint64_t kPhysicalDigit7 = 0x00070024;
constexpr uint64_t kPhysicalDigit8 = 0x00070025;
constexpr uint64_t kPhysicalDigit9 = 0x00070026;
constexpr uint64_t kPhysicalDigit0 = 0x00070027;
constexpr uint64_t kPhysicalEnter = 0x00070028;
constexpr uint64_t kPhysicalEscape = 0x00070029;
constexpr uint64_t kPhysicalBackspace = 0x0007002a;
constexpr uint64_t kPhysicalTab = 0x0007002b;
constexpr uint64_t kPhysicalSpace = 0x0007002c;
constexpr uint64_t kPhysicalMinus = 0x0007002d;
constexpr uint64_t kPhysicalEqual = 0x0007002e;
constexpr uint64_t kPhysicalBracketLeft = 0x0007002f;
constexpr uint64_t kPhysicalBracketRight = 0x00070030;
constexpr uint64_t kPhysicalBackslash = 0x00070031;
constexpr uint64_t kPhysicalSemicolon = 0x00070033;
constexpr uint64_t kPhysicalQuote = 0x00070034;
constexpr uint64_t kPhysicalBackquote = 0x00070035;
constexpr uint64_t kPhysicalComma = 0x00070036;
constexpr uint64_t kPhysicalPeriod = 0x00070037;
constexpr uint64_t kPhysicalSlash = 0x00070038;
constexpr uint64_t kPhysicalCapsLock = 0x00070039;
constexpr uint64_t kPhysicalF1 = 0x0007003a;
constexpr uint64_t kPhysicalF2 = 0x0007003b;
constexpr uint64_t kPhysicalF3 = 0x0007003c;
constexpr uint64_t kPhysicalF4 = 0x0007003d;
constexpr uint64_t kPhysicalF5 = 0x0007003e;
constexpr uint64_t kPhysicalF6 = 0x0007003f;
constexpr uint64_t kPhysicalF7 = 0x00070040;
constexpr uint64_t kPhysicalF8 = 0x00070041;
constexpr uint64_t kPhysicalF9 = 0x00070042;
constexpr uint64_t kPhysicalF10 = 0x00070043;
constexpr uint64_t kPhysicalF11 = 0x00070044;
constexpr uint64_t kPhysicalF12 = 0x00070045;
constexpr uint64_t kPhysicalPrintScreen = 0x00070046;
constexpr uint64_t kPhysicalScrollLock = 0x00070047;
constexpr uint64_t kPhysicalPause = 0x00070048;
constexpr uint64_t kPhysicalInsert = 0x00070049;
constexpr uint64_t kPhysicalHome = 0x0007004a;
constexpr uint64_t kPhysicalPageUp = 0x0007004b;
constexpr uint64_t kPhysicalDelete = 0x0007004c;
constexpr uint64_t kPhysicalEnd = 0x0007004d;
constexpr uint64_t kPhysicalPageDown = 0x0007004e;
constexpr uint64_t kPhysicalArrowRight = 0x0007004f;
constexpr uint64_t kPhysicalArrowLeft = 0x00070050;
constexpr uint64_t kPhysicalArrowDown = 0x00070051;
constexpr uint64_t kPhysicalArrowUp = 0x00070052;
constexpr uint64_t kPhysicalNumLock = 0x00070053;
constexpr uint64_t kPhysicalNumpadDivide = 0x00070054;
constexpr uint64_t kPhysicalNumpadMultiply = 0x00070055;
constexpr uint64_t kPhysicalNumpadSubtract = 0x00070056;
constexpr uint64_t kPhysicalNumpadAdd = 0x00070057;
constexpr uint64_t kPhysicalNumpadEnter = 0x00070058;
constexpr uint64_t kPhysicalNumpad1 = 0x00070059;
constexpr uint64_t kPhysicalNumpad2 = 0x0007005a;
constexpr uint64_t kPhysicalNumpad3 = 0x0007005b;
constexpr uint64_t kPhysicalNumpad4 = 0x0007005c;
constexpr uint64_t kPhysicalNumpad5 = 0x0007005d;
constexpr uint64_t kPhysicalNumpad6 = 0x0007005e;
constexpr uint64_t kPhysicalNumpad7 = 0x0007005f;
constexpr uint64_t kPhysicalNumpad8 = 0x00070060;
constexpr uint64_t kPhysicalNumpad9 = 0x00070061;
constexpr uint64_t kPhysicalNumpad0 = 0x00070062;
constexpr uint64_t kPhysicalNumpadDecimal = 0x00070063;
constexpr uint64_t kPhysicalIntlBackslash = 0x00070064;
constexpr uint64_t kPhysicalContextMenu = 0x00070065;
constexpr uint64_t kPhysicalPower = 0x00070066;
constexpr uint64_t kPhysicalNumpadEqual = 0x00070067;
constexpr uint64_t kPhysicalF13 = 0x00070068;
constexpr uint64_t kPhysicalF14 = 0x00070069;
constexpr uint64_t kPhysicalF15 = 0x0007006a;
constexpr uint64_t kPhysicalF16 = 0x0007006b;
constexpr uint64_t kPhysicalF17 = 0x0007006c;
constexpr uint64_t kPhysicalF18 = 0x0007006d;
constexpr uint64_t kPhysicalF19 = 0x0007006e;
constexpr uint64_t kPhysicalF20 = 0x0007006f;
constexpr uint64_t kPhysicalF21 = 0x00070070;
constexpr uint64_t kPhysicalF22 = 0x00070071;
constexpr uint64_t kPhysicalF23 = 0x00070072;
constexpr uint64_t kPhysicalF24 = 0x00070073;
constexpr uint64_t kPhysicalOpen = 0x00070074;
constexpr uint64_t kPhysicalHelp = 0x00070075;
constexpr uint64_t kPhysicalSelect = 0x00070077;
constexpr uint64_t kPhysicalAgain = 0x00070079;
constexpr uint64_t kPhysicalUndo = 0x0007007a;
constexpr uint64_t kPhysicalCut = 0x0007007b;
constexpr uint64_t kPhysicalCopy = 0x0007007c;
constexpr uint64_t kPhysicalPaste = 0x0007007d;
constexpr uint64_t kPhysicalFind = 0x0007007e;
constexpr uint64_t kPhysicalAudioVolumeMute = 0x0007007f;
constexpr uint64_t kPhysicalAudioVolumeUp = 0x00070080;
constexpr uint64_t kPhysicalAudioVolumeDown = 0x00070081;
constexpr uint64_t kPhysicalNumpadComma = 0x00070085;
constexpr uint64_t kPhysicalIntlRo = 0x00070087;
constexpr uint64_t kPhysicalKanaMode = 0x00070088;
constexpr uint64_t kPhysicalIntlYen = 0x00070089;
constexpr uint64_t kPhysicalConvert = 0x0007008a;
constexpr uint64_t kPhysicalNonConvert = 0x0007008b;
constexpr uint64_t kPhysicalLang1 = 0x00070090;
constexpr uint64_t kPhysicalLang2 = 0x00070091;
constexpr uint64_t kPhysicalLang3 = 0x00070092;
constexpr uint64_t kPhysicalLang4 = 0x00070093;
constexpr uint64_t kPhysicalLang5 = 0x00070094;
constexpr uint64_t kPhysicalAbort = 0x0007009b;
constexpr uint64_t kPhysicalProps = 0x000700a3;
constexpr uint64_t kPhysicalNumpadParenLeft = 0x000700b6;
constexpr uint64_t kPhysicalNumpadParenRight = 0x000700b7;
constexpr uint64_t kPhysicalNumpadBackspace = 0x000700bb;
constexpr uint64_t kPhysicalNumpadMemoryStore = 0x000700d0;
constexpr uint64_t kPhysicalNumpadMemoryRecall = 0x000700d1;
constexpr uint64_t kPhysicalNumpadMemoryClear = 0x000700d2;
constexpr uint64_t kPhysicalNumpadMemoryAdd = 0x000700d3;
constexpr uint64_t kPhysicalNumpadMemorySubtract = 0x000700d4;
constexpr uint64_t kPhysicalNumpadSignChange = 0x000700d7;
constexpr uint64_t kPhysicalNumpadClear = 0x000700d8;
constexpr uint64_t kPhysicalNumpadClearEntry = 0x000700d9;
constexpr uint64_t kPhysicalControlLeft = 0x000700e0;
constexpr uint64_t kPhysicalShiftLeft = 0x000700e1;
constexpr uint64_t kPhysicalAltLeft = 0x000700e2;
constexpr uint64_t kPhysicalMetaLeft = 0x000700e3;
constexpr uint64_t kPhysicalControlRight = 0x000700e4;
constexpr uint64_t kPhysicalShiftRight = 0x000700e5;
constexpr uint64_t kPhysicalAltRight = 0x000700e6;
constexpr uint64_t kPhysicalMetaRight = 0x000700e7;
constexpr uint64_t kPhysicalInfo = 0x000c0060;
constexpr uint64_t kPhysicalClosedCaptionToggle = 0x000c0061;
constexpr uint64_t kPhysicalBrightnessUp = 0x000c006f;
constexpr uint64_t kPhysicalBrightnessDown = 0x000c0070;
constexpr uint64_t kPhysicalBrightnessToggle = 0x000c0072;
constexpr uint64_t kPhysicalBrightnessMinimum = 0x000c0073;
constexpr uint64_t kPhysicalBrightnessMaximum = 0x000c0074;
constexpr uint64_t kPhysicalBrightnessAuto = 0x000c0075;
constexpr uint64_t kPhysicalKbdIllumUp = 0x000c0079;
constexpr uint64_t kPhysicalKbdIllumDown = 0x000c007a;
constexpr uint64_t kPhysicalMediaLast = 0x000c0083;
constexpr uint64_t kPhysicalLaunchPhone = 0x000c008c;
constexpr uint64_t kPhysicalProgramGuide = 0x000c008d;
constexpr uint64_t kPhysicalExit = 0x000c0094;
constexpr uint64_t kPhysicalChannelUp = 0x000c009c;
constexpr uint64_t kPhysicalChannelDown = 0x000c009d;
constexpr uint64_t kPhysicalMediaPlay = 0x000c00b0;
constexpr uint64_t kPhysicalMediaPause = 0x000c00b1;
constexpr uint64_t kPhysicalMediaRecord = 0x000c00b2;
constexpr uint64_t kPhysicalMediaFastForward = 0x000c00b3;
constexpr uint64_t kPhysicalMediaRewind = 0x000c00b4;
constexpr uint64_t kPhysicalMediaTrackNext = 0x000c00b5;
constexpr uint64_t kPhysicalMediaTrackPrevious = 0x000c00b6;
constexpr uint64_t kPhysicalMediaStop = 0x000c00b7;
constexpr uint64_t kPhysicalEject = 0x000c00b8;
constexpr uint64_t kPhysicalMediaPlayPause = 0x000c00cd;
constexpr uint64_t kPhysicalSpeechInputToggle = 0x000c00cf;
constexpr uint64_t kPhysicalBassBoost = 0x000c00e5;
constexpr uint64_t kPhysicalMediaSelect = 0x000c0183;
constexpr uint64_t kPhysicalLaunchWordProcessor = 0x000c0184;
constexpr uint64_t kPhysicalLaunchSpreadsheet = 0x000c0186;
constexpr uint64_t kPhysicalLaunchMail = 0x000c018a;
constexpr uint64_t kPhysicalLaunchContacts = 0x000c018d;
constexpr uint64_t kPhysicalLaunchCalendar = 0x000c018e;
constexpr uint64_t kPhysicalLaunchApp2 = 0x000c0192;
constexpr uint64_t kPhysicalLaunchApp1 = 0x000c0194;
constexpr uint64_t kPhysicalLaunchInternetBrowser = 0x000c0196;
constexpr uint64_t kPhysicalLogOff = 0x000c019c;
constexpr uint64_t kPhysicalLockScreen = 0x000c019e;
constexpr uint64_t kPhysicalLaunchControlPanel = 0x000c019f;
constexpr uint64_t kPhysicalSelectTask = 0x000c01a2;
constexpr uint64_t kPhysicalLaunchDocuments = 0x000c01a7;
constexpr uint64_t kPhysicalSpellCheck = 0x000c01ab;
constexpr uint64_t kPhysicalLaunchKeyboardLayout = 0x000c01ae;
constexpr uint64_t kPhysicalLaunchScreenSaver = 0x000c01b1;
constexpr uint64_t kPhysicalLaunchAudioBrowser = 0x000c01b7;
constexpr uint64_t kPhysicalLaunchAssistant = 0x000c01cb;
constexpr uint64_t kPhysicalNewKey = 0x000c0201;
constexpr uint64_t kPhysicalClose = 0x000c0203;
constexpr uint64_t kPhysicalSave = 0x000c0207;
constexpr uint64_t kPhysicalPrint = 0x000c0208;
constexpr uint64_t kPhysicalBrowserSearch = 0x000c0221;
constexpr uint64_t kPhysicalBrowserHome = 0x000c0223;
constexpr uint64_t kPhysicalBrowserBack = 0x000c0224;
constexpr uint64_t kPhysicalBrowserForward = 0x000c0225;
constexpr uint64_t kPhysicalBrowserStop = 0x000c0226;
constexpr uint64_t kPhysicalBrowserRefresh = 0x000c0227;
constexpr uint64_t kPhysicalBrowserFavorites = 0x000c022a;
constexpr uint64_t kPhysicalZoomIn = 0x000c022d;
constexpr uint64_t kPhysicalZoomOut = 0x000c022e;
constexpr uint64_t kPhysicalZoomToggle = 0x000c0232;
constexpr uint64_t kPhysicalRedo = 0x000c0279;
constexpr uint64_t kPhysicalMailReply = 0x000c0289;
constexpr uint64_t kPhysicalMailForward = 0x000c028b;
constexpr uint64_t kPhysicalMailSend = 0x000c028c;
constexpr uint64_t kPhysicalKeyboardLayoutSelect = 0x000c029d;
constexpr uint64_t kPhysicalShowAllWindows = 0x000c029f;
constexpr uint64_t kLogicalSpace = 0x00000000020;
constexpr uint64_t kLogicalExclamation = 0x00000000021;
constexpr uint64_t kLogicalQuote = 0x00000000022;
constexpr uint64_t kLogicalNumberSign = 0x00000000023;
constexpr uint64_t kLogicalDollar = 0x00000000024;
constexpr uint64_t kLogicalPercent = 0x00000000025;
constexpr uint64_t kLogicalAmpersand = 0x00000000026;
constexpr uint64_t kLogicalQuoteSingle = 0x00000000027;
constexpr uint64_t kLogicalParenthesisLeft = 0x00000000028;
constexpr uint64_t kLogicalParenthesisRight = 0x00000000029;
constexpr uint64_t kLogicalAsterisk = 0x0000000002a;
constexpr uint64_t kLogicalAdd = 0x0000000002b;
constexpr uint64_t kLogicalComma = 0x0000000002c;
constexpr uint64_t kLogicalMinus = 0x0000000002d;
constexpr uint64_t kLogicalPeriod = 0x0000000002e;
constexpr uint64_t kLogicalSlash = 0x0000000002f;
constexpr uint64_t kLogicalDigit0 = 0x00000000030;
constexpr uint64_t kLogicalDigit1 = 0x00000000031;
constexpr uint64_t kLogicalDigit2 = 0x00000000032;
constexpr uint64_t kLogicalDigit3 = 0x00000000033;
constexpr uint64_t kLogicalDigit4 = 0x00000000034;
constexpr uint64_t kLogicalDigit5 = 0x00000000035;
constexpr uint64_t kLogicalDigit6 = 0x00000000036;
constexpr uint64_t kLogicalDigit7 = 0x00000000037;
constexpr uint64_t kLogicalDigit8 = 0x00000000038;
constexpr uint64_t kLogicalDigit9 = 0x00000000039;
constexpr uint64_t kLogicalColon = 0x0000000003a;
constexpr uint64_t kLogicalSemicolon = 0x0000000003b;
constexpr uint64_t kLogicalLess = 0x0000000003c;
constexpr uint64_t kLogicalEqual = 0x0000000003d;
constexpr uint64_t kLogicalGreater = 0x0000000003e;
constexpr uint64_t kLogicalQuestion = 0x0000000003f;
constexpr uint64_t kLogicalAt = 0x00000000040;
constexpr uint64_t kLogicalBracketLeft = 0x0000000005b;
constexpr uint64_t kLogicalBackslash = 0x0000000005c;
constexpr uint64_t kLogicalBracketRight = 0x0000000005d;
constexpr uint64_t kLogicalCaret = 0x0000000005e;
constexpr uint64_t kLogicalUnderscore = 0x0000000005f;
constexpr uint64_t kLogicalBackquote = 0x00000000060;
constexpr uint64_t kLogicalKeyA = 0x00000000061;
constexpr uint64_t kLogicalKeyB = 0x00000000062;
constexpr uint64_t kLogicalKeyC = 0x00000000063;
constexpr uint64_t kLogicalKeyD = 0x00000000064;
constexpr uint64_t kLogicalKeyE = 0x00000000065;
constexpr uint64_t kLogicalKeyF = 0x00000000066;
constexpr uint64_t kLogicalKeyG = 0x00000000067;
constexpr uint64_t kLogicalKeyH = 0x00000000068;
constexpr uint64_t kLogicalKeyI = 0x00000000069;
constexpr uint64_t kLogicalKeyJ = 0x0000000006a;
constexpr uint64_t kLogicalKeyK = 0x0000000006b;
constexpr uint64_t kLogicalKeyL = 0x0000000006c;
constexpr uint64_t kLogicalKeyM = 0x0000000006d;
constexpr uint64_t kLogicalKeyN = 0x0000000006e;
constexpr uint64_t kLogicalKeyO = 0x0000000006f;
constexpr uint64_t kLogicalKeyP = 0x00000000070;
constexpr uint64_t kLogicalKeyQ = 0x00000000071;
constexpr uint64_t kLogicalKeyR = 0x00000000072;
constexpr uint64_t kLogicalKeyS = 0x00000000073;
constexpr uint64_t kLogicalKeyT = 0x00000000074;
constexpr uint64_t kLogicalKeyU = 0x00000000075;
constexpr uint64_t kLogicalKeyV = 0x00000000076;
constexpr uint64_t kLogicalKeyW = 0x00000000077;
constexpr uint64_t kLogicalKeyX = 0x00000000078;
constexpr uint64_t kLogicalKeyY = 0x00000000079;
constexpr uint64_t kLogicalKeyZ = 0x0000000007a;
constexpr uint64_t kLogicalBraceLeft = 0x0000000007b;
constexpr uint64_t kLogicalBar = 0x0000000007c;
constexpr uint64_t kLogicalBraceRight = 0x0000000007d;
constexpr uint64_t kLogicalTilde = 0x0000000007e;
constexpr uint64_t kLogicalUnidentified = 0x00100000001;
constexpr uint64_t kLogicalBackspace = 0x00100000008;
constexpr uint64_t kLogicalTab = 0x00100000009;
constexpr uint64_t kLogicalEnter = 0x0010000000d;
constexpr uint64_t kLogicalEscape = 0x0010000001b;
constexpr uint64_t kLogicalDelete = 0x0010000007f;
constexpr uint64_t kLogicalAccel = 0x00100000101;
constexpr uint64_t kLogicalAltGraph = 0x00100000103;
constexpr uint64_t kLogicalCapsLock = 0x00100000104;
constexpr uint64_t kLogicalFn = 0x00100000106;
constexpr uint64_t kLogicalFnLock = 0x00100000107;
constexpr uint64_t kLogicalHyper = 0x00100000108;
constexpr uint64_t kLogicalNumLock = 0x0010000010a;
constexpr uint64_t kLogicalScrollLock = 0x0010000010c;
constexpr uint64_t kLogicalSuperKey = 0x0010000010e;
constexpr uint64_t kLogicalSymbol = 0x0010000010f;
constexpr uint64_t kLogicalSymbolLock = 0x00100000110;
constexpr uint64_t kLogicalShiftLevel5 = 0x00100000111;
constexpr uint64_t kLogicalArrowDown = 0x00100000301;
constexpr uint64_t kLogicalArrowLeft = 0x00100000302;
constexpr uint64_t kLogicalArrowRight = 0x00100000303;
constexpr uint64_t kLogicalArrowUp = 0x00100000304;
constexpr uint64_t kLogicalEnd = 0x00100000305;
constexpr uint64_t kLogicalHome = 0x00100000306;
constexpr uint64_t kLogicalPageDown = 0x00100000307;
constexpr uint64_t kLogicalPageUp = 0x00100000308;
constexpr uint64_t kLogicalClear = 0x00100000401;
constexpr uint64_t kLogicalCopy = 0x00100000402;
constexpr uint64_t kLogicalCrSel = 0x00100000403;
constexpr uint64_t kLogicalCut = 0x00100000404;
constexpr uint64_t kLogicalEraseEof = 0x00100000405;
constexpr uint64_t kLogicalExSel = 0x00100000406;
constexpr uint64_t kLogicalInsert = 0x00100000407;
constexpr uint64_t kLogicalPaste = 0x00100000408;
constexpr uint64_t kLogicalRedo = 0x00100000409;
constexpr uint64_t kLogicalUndo = 0x0010000040a;
constexpr uint64_t kLogicalAccept = 0x00100000501;
constexpr uint64_t kLogicalAgain = 0x00100000502;
constexpr uint64_t kLogicalAttn = 0x00100000503;
constexpr uint64_t kLogicalCancel = 0x00100000504;
constexpr uint64_t kLogicalContextMenu = 0x00100000505;
constexpr uint64_t kLogicalExecute = 0x00100000506;
constexpr uint64_t kLogicalFind = 0x00100000507;
constexpr uint64_t kLogicalHelp = 0x00100000508;
constexpr uint64_t kLogicalPause = 0x00100000509;
constexpr uint64_t kLogicalPlay = 0x0010000050a;
constexpr uint64_t kLogicalProps = 0x0010000050b;
constexpr uint64_t kLogicalSelect = 0x0010000050c;
constexpr uint64_t kLogicalZoomIn = 0x0010000050d;
constexpr uint64_t kLogicalZoomOut = 0x0010000050e;
constexpr uint64_t kLogicalBrightnessDown = 0x00100000601;
constexpr uint64_t kLogicalBrightnessUp = 0x00100000602;
constexpr uint64_t kLogicalCamera = 0x00100000603;
constexpr uint64_t kLogicalEject = 0x00100000604;
constexpr uint64_t kLogicalLogOff = 0x00100000605;
constexpr uint64_t kLogicalPower = 0x00100000606;
constexpr uint64_t kLogicalPowerOff = 0x00100000607;
constexpr uint64_t kLogicalPrintScreen = 0x00100000608;
constexpr uint64_t kLogicalHibernate = 0x00100000609;
constexpr uint64_t kLogicalStandby = 0x0010000060a;
constexpr uint64_t kLogicalWakeUp = 0x0010000060b;
constexpr uint64_t kLogicalAllCandidates = 0x00100000701;
constexpr uint64_t kLogicalAlphanumeric = 0x00100000702;
constexpr uint64_t kLogicalCodeInput = 0x00100000703;
constexpr uint64_t kLogicalCompose = 0x00100000704;
constexpr uint64_t kLogicalConvert = 0x00100000705;
constexpr uint64_t kLogicalFinalMode = 0x00100000706;
constexpr uint64_t kLogicalGroupFirst = 0x00100000707;
constexpr uint64_t kLogicalGroupLast = 0x00100000708;
constexpr uint64_t kLogicalGroupNext = 0x00100000709;
constexpr uint64_t kLogicalGroupPrevious = 0x0010000070a;
constexpr uint64_t kLogicalModeChange = 0x0010000070b;
constexpr uint64_t kLogicalNextCandidate = 0x0010000070c;
constexpr uint64_t kLogicalNonConvert = 0x0010000070d;
constexpr uint64_t kLogicalPreviousCandidate = 0x0010000070e;
constexpr uint64_t kLogicalProcess = 0x0010000070f;
constexpr uint64_t kLogicalSingleCandidate = 0x00100000710;
constexpr uint64_t kLogicalHangulMode = 0x00100000711;
constexpr uint64_t kLogicalHanjaMode = 0x00100000712;
constexpr uint64_t kLogicalJunjaMode = 0x00100000713;
constexpr uint64_t kLogicalEisu = 0x00100000714;
constexpr uint64_t kLogicalHankaku = 0x00100000715;
constexpr uint64_t kLogicalHiragana = 0x00100000716;
constexpr uint64_t kLogicalHiraganaKatakana = 0x00100000717;
constexpr uint64_t kLogicalKanaMode = 0x00100000718;
constexpr uint64_t kLogicalKanjiMode = 0x00100000719;
constexpr uint64_t kLogicalKatakana = 0x0010000071a;
constexpr uint64_t kLogicalRomaji = 0x0010000071b;
constexpr uint64_t kLogicalZenkaku = 0x0010000071c;
constexpr uint64_t kLogicalZenkakuHankaku = 0x0010000071d;
constexpr uint64_t kLogicalF1 = 0x00100000801;
constexpr uint64_t kLogicalF2 = 0x00100000802;
constexpr uint64_t kLogicalF3 = 0x00100000803;
constexpr uint64_t kLogicalF4 = 0x00100000804;
constexpr uint64_t kLogicalF5 = 0x00100000805;
constexpr uint64_t kLogicalF6 = 0x00100000806;
constexpr uint64_t kLogicalF7 = 0x00100000807;
constexpr uint64_t kLogicalF8 = 0x00100000808;
constexpr uint64_t kLogicalF9 = 0x00100000809;
constexpr uint64_t kLogicalF10 = 0x0010000080a;
constexpr uint64_t kLogicalF11 = 0x0010000080b;
constexpr uint64_t kLogicalF12 = 0x0010000080c;
constexpr uint64_t kLogicalF13 = 0x0010000080d;
constexpr uint64_t kLogicalF14 = 0x0010000080e;
constexpr uint64_t kLogicalF15 = 0x0010000080f;
constexpr uint64_t kLogicalF16 = 0x00100000810;
constexpr uint64_t kLogicalF17 = 0x00100000811;
constexpr uint64_t kLogicalF18 = 0x00100000812;
constexpr uint64_t kLogicalF19 = 0x00100000813;
constexpr uint64_t kLogicalF20 = 0x00100000814;
constexpr uint64_t kLogicalF21 = 0x00100000815;
constexpr uint64_t kLogicalF22 = 0x00100000816;
constexpr uint64_t kLogicalF23 = 0x00100000817;
constexpr uint64_t kLogicalF24 = 0x00100000818;
constexpr uint64_t kLogicalSoft1 = 0x00100000901;
constexpr uint64_t kLogicalSoft2 = 0x00100000902;
constexpr uint64_t kLogicalSoft3 = 0x00100000903;
constexpr uint64_t kLogicalSoft4 = 0x00100000904;
constexpr uint64_t kLogicalSoft5 = 0x00100000905;
constexpr uint64_t kLogicalSoft6 = 0x00100000906;
constexpr uint64_t kLogicalSoft7 = 0x00100000907;
constexpr uint64_t kLogicalSoft8 = 0x00100000908;
constexpr uint64_t kLogicalClose = 0x00100000a01;
constexpr uint64_t kLogicalMailForward = 0x00100000a02;
constexpr uint64_t kLogicalMailReply = 0x00100000a03;
constexpr uint64_t kLogicalMailSend = 0x00100000a04;
constexpr uint64_t kLogicalMediaPlayPause = 0x00100000a05;
constexpr uint64_t kLogicalMediaStop = 0x00100000a07;
constexpr uint64_t kLogicalMediaTrackNext = 0x00100000a08;
constexpr uint64_t kLogicalMediaTrackPrevious = 0x00100000a09;
constexpr uint64_t kLogicalNewKey = 0x00100000a0a;
constexpr uint64_t kLogicalOpen = 0x00100000a0b;
constexpr uint64_t kLogicalPrint = 0x00100000a0c;
constexpr uint64_t kLogicalSave = 0x00100000a0d;
constexpr uint64_t kLogicalSpellCheck = 0x00100000a0e;
constexpr uint64_t kLogicalAudioVolumeDown = 0x00100000a0f;
constexpr uint64_t kLogicalAudioVolumeUp = 0x00100000a10;
constexpr uint64_t kLogicalAudioVolumeMute = 0x00100000a11;
constexpr uint64_t kLogicalLaunchApplication2 = 0x00100000b01;
constexpr uint64_t kLogicalLaunchCalendar = 0x00100000b02;
constexpr uint64_t kLogicalLaunchMail = 0x00100000b03;
constexpr uint64_t kLogicalLaunchMediaPlayer = 0x00100000b04;
constexpr uint64_t kLogicalLaunchMusicPlayer = 0x00100000b05;
constexpr uint64_t kLogicalLaunchApplication1 = 0x00100000b06;
constexpr uint64_t kLogicalLaunchScreenSaver = 0x00100000b07;
constexpr uint64_t kLogicalLaunchSpreadsheet = 0x00100000b08;
constexpr uint64_t kLogicalLaunchWebBrowser = 0x00100000b09;
constexpr uint64_t kLogicalLaunchWebCam = 0x00100000b0a;
constexpr uint64_t kLogicalLaunchWordProcessor = 0x00100000b0b;
constexpr uint64_t kLogicalLaunchContacts = 0x00100000b0c;
constexpr uint64_t kLogicalLaunchPhone = 0x00100000b0d;
constexpr uint64_t kLogicalLaunchAssistant = 0x00100000b0e;
constexpr uint64_t kLogicalLaunchControlPanel = 0x00100000b0f;
constexpr uint64_t kLogicalBrowserBack = 0x00100000c01;
constexpr uint64_t kLogicalBrowserFavorites = 0x00100000c02;
constexpr uint64_t kLogicalBrowserForward = 0x00100000c03;
constexpr uint64_t kLogicalBrowserHome = 0x00100000c04;
constexpr uint64_t kLogicalBrowserRefresh = 0x00100000c05;
constexpr uint64_t kLogicalBrowserSearch = 0x00100000c06;
constexpr uint64_t kLogicalBrowserStop = 0x00100000c07;
constexpr uint64_t kLogicalAudioBalanceLeft = 0x00100000d01;
constexpr uint64_t kLogicalAudioBalanceRight = 0x00100000d02;
constexpr uint64_t kLogicalAudioBassBoostDown = 0x00100000d03;
constexpr uint64_t kLogicalAudioBassBoostUp = 0x00100000d04;
constexpr uint64_t kLogicalAudioFaderFront = 0x00100000d05;
constexpr uint64_t kLogicalAudioFaderRear = 0x00100000d06;
constexpr uint64_t kLogicalAudioSurroundModeNext = 0x00100000d07;
constexpr uint64_t kLogicalAvrInput = 0x00100000d08;
constexpr uint64_t kLogicalAvrPower = 0x00100000d09;
constexpr uint64_t kLogicalChannelDown = 0x00100000d0a;
constexpr uint64_t kLogicalChannelUp = 0x00100000d0b;
constexpr uint64_t kLogicalColorF0Red = 0x00100000d0c;
constexpr uint64_t kLogicalColorF1Green = 0x00100000d0d;
constexpr uint64_t kLogicalColorF2Yellow = 0x00100000d0e;
constexpr uint64_t kLogicalColorF3Blue = 0x00100000d0f;
constexpr uint64_t kLogicalColorF4Grey = 0x00100000d10;
constexpr uint64_t kLogicalColorF5Brown = 0x00100000d11;
constexpr uint64_t kLogicalClosedCaptionToggle = 0x00100000d12;
constexpr uint64_t kLogicalDimmer = 0x00100000d13;
constexpr uint64_t kLogicalDisplaySwap = 0x00100000d14;
constexpr uint64_t kLogicalExit = 0x00100000d15;
constexpr uint64_t kLogicalFavoriteClear0 = 0x00100000d16;
constexpr uint64_t kLogicalFavoriteClear1 = 0x00100000d17;
constexpr uint64_t kLogicalFavoriteClear2 = 0x00100000d18;
constexpr uint64_t kLogicalFavoriteClear3 = 0x00100000d19;
constexpr uint64_t kLogicalFavoriteRecall0 = 0x00100000d1a;
constexpr uint64_t kLogicalFavoriteRecall1 = 0x00100000d1b;
constexpr uint64_t kLogicalFavoriteRecall2 = 0x00100000d1c;
constexpr uint64_t kLogicalFavoriteRecall3 = 0x00100000d1d;
constexpr uint64_t kLogicalFavoriteStore0 = 0x00100000d1e;
constexpr uint64_t kLogicalFavoriteStore1 = 0x00100000d1f;
constexpr uint64_t kLogicalFavoriteStore2 = 0x00100000d20;
constexpr uint64_t kLogicalFavoriteStore3 = 0x00100000d21;
constexpr uint64_t kLogicalGuide = 0x00100000d22;
constexpr uint64_t kLogicalGuideNextDay = 0x00100000d23;
constexpr uint64_t kLogicalGuidePreviousDay = 0x00100000d24;
constexpr uint64_t kLogicalInfo = 0x00100000d25;
constexpr uint64_t kLogicalInstantReplay = 0x00100000d26;
constexpr uint64_t kLogicalLink = 0x00100000d27;
constexpr uint64_t kLogicalListProgram = 0x00100000d28;
constexpr uint64_t kLogicalLiveContent = 0x00100000d29;
constexpr uint64_t kLogicalLock = 0x00100000d2a;
constexpr uint64_t kLogicalMediaApps = 0x00100000d2b;
constexpr uint64_t kLogicalMediaFastForward = 0x00100000d2c;
constexpr uint64_t kLogicalMediaLast = 0x00100000d2d;
constexpr uint64_t kLogicalMediaPause = 0x00100000d2e;
constexpr uint64_t kLogicalMediaPlay = 0x00100000d2f;
constexpr uint64_t kLogicalMediaRecord = 0x00100000d30;
constexpr uint64_t kLogicalMediaRewind = 0x00100000d31;
constexpr uint64_t kLogicalMediaSkip = 0x00100000d32;
constexpr uint64_t kLogicalNextFavoriteChannel = 0x00100000d33;
constexpr uint64_t kLogicalNextUserProfile = 0x00100000d34;
constexpr uint64_t kLogicalOnDemand = 0x00100000d35;
constexpr uint64_t kLogicalPInPDown = 0x00100000d36;
constexpr uint64_t kLogicalPInPMove = 0x00100000d37;
constexpr uint64_t kLogicalPInPToggle = 0x00100000d38;
constexpr uint64_t kLogicalPInPUp = 0x00100000d39;
constexpr uint64_t kLogicalPlaySpeedDown = 0x00100000d3a;
constexpr uint64_t kLogicalPlaySpeedReset = 0x00100000d3b;
constexpr uint64_t kLogicalPlaySpeedUp = 0x00100000d3c;
constexpr uint64_t kLogicalRandomToggle = 0x00100000d3d;
constexpr uint64_t kLogicalRcLowBattery = 0x00100000d3e;
constexpr uint64_t kLogicalRecordSpeedNext = 0x00100000d3f;
constexpr uint64_t kLogicalRfBypass = 0x00100000d40;
constexpr uint64_t kLogicalScanChannelsToggle = 0x00100000d41;
constexpr uint64_t kLogicalScreenModeNext = 0x00100000d42;
constexpr uint64_t kLogicalSettings = 0x00100000d43;
constexpr uint64_t kLogicalSplitScreenToggle = 0x00100000d44;
constexpr uint64_t kLogicalStbInput = 0x00100000d45;
constexpr uint64_t kLogicalStbPower = 0x00100000d46;
constexpr uint64_t kLogicalSubtitle = 0x00100000d47;
constexpr uint64_t kLogicalTeletext = 0x00100000d48;
constexpr uint64_t kLogicalTv = 0x00100000d49;
constexpr uint64_t kLogicalTvInput = 0x00100000d4a;
constexpr uint64_t kLogicalTvPower = 0x00100000d4b;
constexpr uint64_t kLogicalVideoModeNext = 0x00100000d4c;
constexpr uint64_t kLogicalWink = 0x00100000d4d;
constexpr uint64_t kLogicalZoomToggle = 0x00100000d4e;
constexpr uint64_t kLogicalDvr = 0x00100000d4f;
constexpr uint64_t kLogicalMediaAudioTrack = 0x00100000d50;
constexpr uint64_t kLogicalMediaSkipBackward = 0x00100000d51;
constexpr uint64_t kLogicalMediaSkipForward = 0x00100000d52;
constexpr uint64_t kLogicalMediaStepBackward = 0x00100000d53;
constexpr uint64_t kLogicalMediaStepForward = 0x00100000d54;
constexpr uint64_t kLogicalMediaTopMenu = 0x00100000d55;
constexpr uint64_t kLogicalNavigateIn = 0x00100000d56;
constexpr uint64_t kLogicalNavigateNext = 0x00100000d57;
constexpr uint64_t kLogicalNavigateOut = 0x00100000d58;
constexpr uint64_t kLogicalNavigatePrevious = 0x00100000d59;
constexpr uint64_t kLogicalPairing = 0x00100000d5a;
constexpr uint64_t kLogicalMediaClose = 0x00100000d5b;
constexpr uint64_t kLogicalAudioBassBoostToggle = 0x00100000e02;
constexpr uint64_t kLogicalAudioTrebleDown = 0x00100000e04;
constexpr uint64_t kLogicalAudioTrebleUp = 0x00100000e05;
constexpr uint64_t kLogicalMicrophoneToggle = 0x00100000e06;
constexpr uint64_t kLogicalMicrophoneVolumeDown = 0x00100000e07;
constexpr uint64_t kLogicalMicrophoneVolumeUp = 0x00100000e08;
constexpr uint64_t kLogicalMicrophoneVolumeMute = 0x00100000e09;
constexpr uint64_t kLogicalSpeechCorrectionList = 0x00100000f01;
constexpr uint64_t kLogicalSpeechInputToggle = 0x00100000f02;
constexpr uint64_t kLogicalAppSwitch = 0x00100001001;
constexpr uint64_t kLogicalCall = 0x00100001002;
constexpr uint64_t kLogicalCameraFocus = 0x00100001003;
constexpr uint64_t kLogicalEndCall = 0x00100001004;
constexpr uint64_t kLogicalGoBack = 0x00100001005;
constexpr uint64_t kLogicalGoHome = 0x00100001006;
constexpr uint64_t kLogicalHeadsetHook = 0x00100001007;
constexpr uint64_t kLogicalLastNumberRedial = 0x00100001008;
constexpr uint64_t kLogicalNotification = 0x00100001009;
constexpr uint64_t kLogicalMannerMode = 0x0010000100a;
constexpr uint64_t kLogicalVoiceDial = 0x0010000100b;
constexpr uint64_t kLogicalTv3DMode = 0x00100001101;
constexpr uint64_t kLogicalTvAntennaCable = 0x00100001102;
constexpr uint64_t kLogicalTvAudioDescription = 0x00100001103;
constexpr uint64_t kLogicalTvAudioDescriptionMixDown = 0x00100001104;
constexpr uint64_t kLogicalTvAudioDescriptionMixUp = 0x00100001105;
constexpr uint64_t kLogicalTvContentsMenu = 0x00100001106;
constexpr uint64_t kLogicalTvDataService = 0x00100001107;
constexpr uint64_t kLogicalTvInputComponent1 = 0x00100001108;
constexpr uint64_t kLogicalTvInputComponent2 = 0x00100001109;
constexpr uint64_t kLogicalTvInputComposite1 = 0x0010000110a;
constexpr uint64_t kLogicalTvInputComposite2 = 0x0010000110b;
constexpr uint64_t kLogicalTvInputHDMI1 = 0x0010000110c;
constexpr uint64_t kLogicalTvInputHDMI2 = 0x0010000110d;
constexpr uint64_t kLogicalTvInputHDMI3 = 0x0010000110e;
constexpr uint64_t kLogicalTvInputHDMI4 = 0x0010000110f;
constexpr uint64_t kLogicalTvInputVGA1 = 0x00100001110;
constexpr uint64_t kLogicalTvMediaContext = 0x00100001111;
constexpr uint64_t kLogicalTvNetwork = 0x00100001112;
constexpr uint64_t kLogicalTvNumberEntry = 0x00100001113;
constexpr uint64_t kLogicalTvRadioService = 0x00100001114;
constexpr uint64_t kLogicalTvSatellite = 0x00100001115;
constexpr uint64_t kLogicalTvSatelliteBS = 0x00100001116;
constexpr uint64_t kLogicalTvSatelliteCS = 0x00100001117;
constexpr uint64_t kLogicalTvSatelliteToggle = 0x00100001118;
constexpr uint64_t kLogicalTvTerrestrialAnalog = 0x00100001119;
constexpr uint64_t kLogicalTvTerrestrialDigital = 0x0010000111a;
constexpr uint64_t kLogicalTvTimer = 0x0010000111b;
constexpr uint64_t kLogicalKey11 = 0x00100001201;
constexpr uint64_t kLogicalKey12 = 0x00100001202;
constexpr uint64_t kLogicalSuspend = 0x00200000000;
constexpr uint64_t kLogicalResume = 0x00200000001;
constexpr uint64_t kLogicalSleep = 0x00200000002;
constexpr uint64_t kLogicalAbort = 0x00200000003;
constexpr uint64_t kLogicalLang1 = 0x00200000010;
constexpr uint64_t kLogicalLang2 = 0x00200000011;
constexpr uint64_t kLogicalLang3 = 0x00200000012;
constexpr uint64_t kLogicalLang4 = 0x00200000013;
constexpr uint64_t kLogicalLang5 = 0x00200000014;
constexpr uint64_t kLogicalIntlBackslash = 0x00200000020;
constexpr uint64_t kLogicalIntlRo = 0x00200000021;
constexpr uint64_t kLogicalIntlYen = 0x00200000022;
constexpr uint64_t kLogicalControlLeft = 0x00200000100;
constexpr uint64_t kLogicalControlRight = 0x00200000101;
constexpr uint64_t kLogicalShiftLeft = 0x00200000102;
constexpr uint64_t kLogicalShiftRight = 0x00200000103;
constexpr uint64_t kLogicalAltLeft = 0x00200000104;
constexpr uint64_t kLogicalAltRight = 0x00200000105;
constexpr uint64_t kLogicalMetaLeft = 0x00200000106;
constexpr uint64_t kLogicalMetaRight = 0x00200000107;
constexpr uint64_t kLogicalControl = 0x002000001f0;
constexpr uint64_t kLogicalShift = 0x002000001f2;
constexpr uint64_t kLogicalAlt = 0x002000001f4;
constexpr uint64_t kLogicalMeta = 0x002000001f6;
constexpr uint64_t kLogicalNumpadEnter = 0x0020000020d;
constexpr uint64_t kLogicalNumpadParenLeft = 0x00200000228;
constexpr uint64_t kLogicalNumpadParenRight = 0x00200000229;
constexpr uint64_t kLogicalNumpadMultiply = 0x0020000022a;
constexpr uint64_t kLogicalNumpadAdd = 0x0020000022b;
constexpr uint64_t kLogicalNumpadComma = 0x0020000022c;
constexpr uint64_t kLogicalNumpadSubtract = 0x0020000022d;
constexpr uint64_t kLogicalNumpadDecimal = 0x0020000022e;
constexpr uint64_t kLogicalNumpadDivide = 0x0020000022f;
constexpr uint64_t kLogicalNumpad0 = 0x00200000230;
constexpr uint64_t kLogicalNumpad1 = 0x00200000231;
constexpr uint64_t kLogicalNumpad2 = 0x00200000232;
constexpr uint64_t kLogicalNumpad3 = 0x00200000233;
constexpr uint64_t kLogicalNumpad4 = 0x00200000234;
constexpr uint64_t kLogicalNumpad5 = 0x00200000235;
constexpr uint64_t kLogicalNumpad6 = 0x00200000236;
constexpr uint64_t kLogicalNumpad7 = 0x00200000237;
constexpr uint64_t kLogicalNumpad8 = 0x00200000238;
constexpr uint64_t kLogicalNumpad9 = 0x00200000239;
constexpr uint64_t kLogicalNumpadEqual = 0x0020000023d;
constexpr uint64_t kLogicalGameButton1 = 0x00200000301;
constexpr uint64_t kLogicalGameButton2 = 0x00200000302;
constexpr uint64_t kLogicalGameButton3 = 0x00200000303;
constexpr uint64_t kLogicalGameButton4 = 0x00200000304;
constexpr uint64_t kLogicalGameButton5 = 0x00200000305;
constexpr uint64_t kLogicalGameButton6 = 0x00200000306;
constexpr uint64_t kLogicalGameButton7 = 0x00200000307;
constexpr uint64_t kLogicalGameButton8 = 0x00200000308;
constexpr uint64_t kLogicalGameButton9 = 0x00200000309;
constexpr uint64_t kLogicalGameButton10 = 0x0020000030a;
constexpr uint64_t kLogicalGameButton11 = 0x0020000030b;
constexpr uint64_t kLogicalGameButton12 = 0x0020000030c;
constexpr uint64_t kLogicalGameButton13 = 0x0020000030d;
constexpr uint64_t kLogicalGameButton14 = 0x0020000030e;
constexpr uint64_t kLogicalGameButton15 = 0x0020000030f;
constexpr uint64_t kLogicalGameButton16 = 0x00200000310;
constexpr uint64_t kLogicalGameButtonA = 0x00200000311;
constexpr uint64_t kLogicalGameButtonB = 0x00200000312;
constexpr uint64_t kLogicalGameButtonC = 0x00200000313;
constexpr uint64_t kLogicalGameButtonLeft1 = 0x00200000314;
constexpr uint64_t kLogicalGameButtonLeft2 = 0x00200000315;
constexpr uint64_t kLogicalGameButtonMode = 0x00200000316;
constexpr uint64_t kLogicalGameButtonRight1 = 0x00200000317;
constexpr uint64_t kLogicalGameButtonRight2 = 0x00200000318;
constexpr uint64_t kLogicalGameButtonSelect = 0x00200000319;
constexpr uint64_t kLogicalGameButtonStart = 0x0020000031a;
constexpr uint64_t kLogicalGameButtonThumbLeft = 0x0020000031b;
constexpr uint64_t kLogicalGameButtonThumbRight = 0x0020000031c;
constexpr uint64_t kLogicalGameButtonX = 0x0020000031d;
constexpr uint64_t kLogicalGameButtonY = 0x0020000031e;
constexpr uint64_t kLogicalGameButtonZ = 0x0020000031f;
} // namespace keycodes
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_KEY_CODES_G_H_
| engine/shell/platform/embedder/test_utils/key_codes.g.h/0 | {
"file_path": "engine/shell/platform/embedder/test_utils/key_codes.g.h",
"repo_id": "engine",
"token_count": 14927
} | 391 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.h"
#include <utility>
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/embedder/tests/embedder_assertions.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h"
namespace flutter {
namespace testing {
EmbedderTestCompositorGL::EmbedderTestCompositorGL(
SkISize surface_size,
sk_sp<GrDirectContext> context)
: EmbedderTestCompositor(surface_size, std::move(context)) {}
EmbedderTestCompositorGL::~EmbedderTestCompositorGL() = default;
bool EmbedderTestCompositorGL::UpdateOffscrenComposition(
const FlutterLayer** layers,
size_t layers_count) {
last_composition_ = nullptr;
const auto image_info = SkImageInfo::MakeN32Premul(surface_size_);
auto surface =
SkSurfaces::RenderTarget(context_.get(), // context
skgpu::Budgeted::kNo, // budgeted
image_info, // image info
1, // sample count
kTopLeft_GrSurfaceOrigin, // surface origin
nullptr, // surface properties
false // create mipmaps
);
if (!surface) {
FML_LOG(ERROR) << "Could not update the off-screen composition.";
return false;
}
auto canvas = surface->getCanvas();
// This has to be transparent because we are going to be compositing this
// sub-hierarchy onto the on-screen surface.
canvas->clear(SK_ColorTRANSPARENT);
for (size_t i = 0; i < layers_count; ++i) {
const auto* layer = layers[i];
sk_sp<SkImage> platform_rendered_contents;
sk_sp<SkImage> layer_image;
SkIPoint canvas_offset = SkIPoint::Make(0, 0);
switch (layer->type) {
case kFlutterLayerContentTypeBackingStore:
layer_image =
reinterpret_cast<SkSurface*>(layer->backing_store->user_data)
->makeImageSnapshot();
break;
case kFlutterLayerContentTypePlatformView:
layer_image =
platform_view_renderer_callback_
? platform_view_renderer_callback_(*layer, context_.get())
: nullptr;
canvas_offset = SkIPoint::Make(layer->offset.x, layer->offset.y);
break;
};
// If the layer is not a platform view but the engine did not specify an
// image for the backing store, it is an error.
if (!layer_image && layer->type != kFlutterLayerContentTypePlatformView) {
FML_LOG(ERROR) << "Could not snapshot layer in test compositor: "
<< *layer;
return false;
}
// The test could have just specified no contents to be rendered in place of
// a platform view. This is not an error.
if (layer_image) {
// The image rendered by Flutter already has the correct offset and
// transformation applied. The layers offset is meant for the platform.
canvas->drawImage(layer_image.get(), canvas_offset.x(),
canvas_offset.y());
}
}
last_composition_ = surface->makeImageSnapshot();
if (!last_composition_) {
FML_LOG(ERROR) << "Could not update the contents of the sub-composition.";
return false;
}
if (next_scene_callback_) {
auto last_composition_snapshot = last_composition_->makeRasterImage();
FML_CHECK(last_composition_snapshot);
auto callback = next_scene_callback_;
next_scene_callback_ = nullptr;
callback(std::move(last_composition_snapshot));
}
return true;
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/embedder/tests/embedder_test_compositor_gl.cc/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_test_compositor_gl.cc",
"repo_id": "engine",
"token_count": 1595
} | 392 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.h"
#include <memory>
#include <utility>
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/embedder/tests/embedder_test_compositor_vulkan.h"
#include "flutter/testing/test_vulkan_context.h"
#include "flutter/testing/test_vulkan_surface.h"
#include "flutter/vulkan/procs/vulkan_proc_table.h"
#include "flutter/vulkan/vulkan_device.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace flutter {
namespace testing {
EmbedderTestContextVulkan::EmbedderTestContextVulkan(std::string assets_path)
: EmbedderTestContext(std::move(assets_path)), surface_() {
vulkan_context_ = fml::MakeRefCounted<TestVulkanContext>();
}
EmbedderTestContextVulkan::~EmbedderTestContextVulkan() {}
void EmbedderTestContextVulkan::SetupSurface(SkISize surface_size) {
FML_CHECK(surface_size_.isEmpty());
surface_size_ = surface_size;
surface_ = TestVulkanSurface::Create(*vulkan_context_, surface_size_);
}
size_t EmbedderTestContextVulkan::GetSurfacePresentCount() const {
return present_count_;
}
VkImage EmbedderTestContextVulkan::GetNextImage(const SkISize& size) {
return surface_->GetImage();
}
bool EmbedderTestContextVulkan::PresentImage(VkImage image) {
FireRootSurfacePresentCallbackIfPresent(
[&]() { return surface_->GetSurfaceSnapshot(); });
present_count_++;
return true;
}
EmbedderTestContextType EmbedderTestContextVulkan::GetContextType() const {
return EmbedderTestContextType::kVulkanContext;
}
void EmbedderTestContextVulkan::SetupCompositor() {
FML_CHECK(!compositor_) << "Already set up a compositor in this context.";
FML_CHECK(surface_)
<< "Set up the Vulkan surface before setting up a compositor.";
compositor_ = std::make_unique<EmbedderTestCompositorVulkan>(
surface_size_, vulkan_context_->GetGrDirectContext());
}
void* EmbedderTestContextVulkan::InstanceProcAddr(
void* user_data,
FlutterVulkanInstanceHandle instance,
const char* name) {
auto proc_addr = reinterpret_cast<EmbedderTestContextVulkan*>(user_data)
->vulkan_context_->vk_->GetInstanceProcAddr(
reinterpret_cast<VkInstance>(instance), name);
return reinterpret_cast<void*>(proc_addr);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/embedder/tests/embedder_test_context_vulkan.cc/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_test_context_vulkan.cc",
"repo_id": "engine",
"token_count": 879
} | 393 |
// Copyright 2013 The Flutter 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_FUCHSIA_SDK_EXT_FUCHSIA_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_FUCHSIA_SDK_EXT_FUCHSIA_H_
#include <lib/zx/channel.h>
#include <lib/zx/eventpair.h>
#include <optional>
namespace fuchsia {
namespace dart {
/// Initializes Dart bindings for the Fuchsia application model.
void Initialize(zx::channel directory_request,
std::optional<zx::eventpair> view_ref);
} // namespace dart
} // namespace fuchsia
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_FUCHSIA_SDK_EXT_FUCHSIA_H_
| engine/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h",
"repo_id": "engine",
"token_count": 290
} | 394 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_DISPOSITION_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_DISPOSITION_H_
#include <zircon/syscalls.h>
#include <vector>
#include "flutter/fml/memory/ref_counted.h"
#include "handle.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"
namespace zircon {
namespace dart {
/**
* HandleDisposition is the native peer of a Dart object (HandleDisposition
* in dart:zircon) that holds a Handle and additional properties.
*/
class HandleDisposition : public fml::RefCountedThreadSafe<HandleDisposition>,
public tonic::DartWrappable {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_REF_COUNTED_THREAD_SAFE(HandleDisposition);
FML_FRIEND_MAKE_REF_COUNTED(HandleDisposition);
public:
static void RegisterNatives(tonic::DartLibraryNatives* natives);
static fml::RefPtr<HandleDisposition> create(zx_handle_op_t operation,
fml::RefPtr<dart::Handle> handle,
zx_obj_type_t type,
zx_rights_t rights);
zx_handle_op_t operation() const { return operation_; }
fml::RefPtr<dart::Handle> handle() const { return handle_; }
zx_obj_type_t type() const { return type_; }
zx_rights_t rights() const { return rights_; }
zx_status_t result() const { return result_; }
void set_result(zx_status_t result) { result_ = result; }
private:
explicit HandleDisposition(zx_handle_op_t operation,
fml::RefPtr<dart::Handle> handle,
zx_obj_type_t type,
zx_rights_t rights,
zx_status_t result)
: operation_(operation),
handle_(handle),
type_(type),
rights_(rights),
result_(result) {}
void RetainDartWrappableReference() const override { AddRef(); }
void ReleaseDartWrappableReference() const override { Release(); }
const zx_handle_op_t operation_;
const fml::RefPtr<dart::Handle> handle_;
const zx_obj_type_t type_;
const zx_rights_t rights_;
zx_status_t result_;
};
} // namespace dart
} // namespace zircon
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_DISPOSITION_H_
| engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.h/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.h",
"repo_id": "engine",
"token_count": 1142
} | 395 |
#include "dart_dl.h"
#include "flutter/fml/logging.h"
#include "include/dart_api_dl.h"
int zircon_dart_dl_initialize(void* initialize_api_dl_data) {
if (Dart_InitializeApiDL(initialize_api_dl_data) != 0) {
FML_LOG(ERROR) << "Failed to initialise Dart VM API";
return -1;
}
// Check symbols used are present
if (Dart_NewFinalizableHandle_DL == NULL) {
FML_LOG(ERROR) << "Unable to find Dart API finalizer symbols.";
return -1;
}
return 1;
}
| engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.cc",
"repo_id": "engine",
"token_count": 191
} | 396 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "dart_runner.h"
#include <lib/async-loop/loop.h>
#include <lib/async/default.h>
#include <lib/vfs/cpp/pseudo_dir.h>
#include <sys/stat.h>
#include <zircon/status.h>
#include <zircon/syscalls.h>
#include <cerrno>
#include <memory>
#include <thread>
#include <utility>
#include "dart_component_controller.h"
#include "flutter/fml/command_line.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "runtime/dart/utils/inlines.h"
#include "runtime/dart/utils/vmservice_object.h"
#include "service_isolate.h"
#include "third_party/dart/runtime/include/bin/dart_io_api.h"
#include "third_party/tonic/dart_microtask_queue.h"
#include "third_party/tonic/dart_state.h"
#if defined(AOT_RUNTIME)
extern "C" uint8_t _kDartVmSnapshotData[];
extern "C" uint8_t _kDartVmSnapshotInstructions[];
#endif
namespace dart_runner {
namespace {
const char* kDartVMArgs[] = {
// clang-format off
"--timeline_recorder=systrace",
"--timeline_streams=Compiler,Dart,Debugger,Embedder,GC,Isolate,VM",
#if defined(AOT_RUNTIME)
"--precompilation",
#else
"--enable_mirrors=false",
#endif
// No asserts in debug or release product.
// No asserts in release with flutter_profile=true (non-product)
// Yes asserts in non-product debug.
#if !defined(DART_PRODUCT) && (!defined(FLUTTER_PROFILE) || !defined(NDEBUG))
"--enable_asserts",
#endif
};
Dart_Isolate IsolateGroupCreateCallback(const char* uri,
const char* name,
const char* package_root,
const char* package_config,
Dart_IsolateFlags* flags,
void* callback_data,
char** error) {
if (std::string(uri) == DART_VM_SERVICE_ISOLATE_NAME) {
#if defined(DART_PRODUCT)
*error = strdup("The service isolate is not implemented in product mode");
return NULL;
#else
return CreateServiceIsolate(uri, flags, error);
#endif
}
*error = strdup("Isolate spawning is not implemented in dart_runner");
return NULL;
}
void IsolateShutdownCallback(void* isolate_group_data, void* isolate_data) {
// The service isolate (and maybe later the kernel isolate) doesn't have an
// async loop.
auto dispatcher = async_get_default_dispatcher();
auto loop = async_loop_from_dispatcher(dispatcher);
if (loop) {
tonic::DartMicrotaskQueue* queue =
tonic::DartMicrotaskQueue::GetForCurrentThread();
if (queue) {
queue->Destroy();
}
async_loop_quit(loop);
}
auto state =
static_cast<std::shared_ptr<tonic::DartState>*>(isolate_group_data);
state->get()->SetIsShuttingDown();
}
void IsolateGroupCleanupCallback(void* isolate_group_data) {
delete static_cast<std::shared_ptr<tonic::DartState>*>(isolate_group_data);
}
// Runs the application for a Dart component.
void RunApplication(
DartRunner* runner,
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller) {
const int64_t start = Dart_TimelineGetMicros();
DartComponentController app(std::move(start_info), runner_incoming_services,
std::move(controller));
const bool success = app.SetUp();
const int64_t end = Dart_TimelineGetMicros();
Dart_RecordTimelineEvent(
"DartComponentController::SetUp", start, end, 0, nullptr,
Dart_Timeline_Event_Duration, 0, NULL, NULL);
if (success) {
app.Run();
}
if (Dart_CurrentIsolate()) {
Dart_ShutdownIsolate();
}
}
void RunTestApplication(
DartRunner* runner,
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller,
fit::function<void(std::shared_ptr<DartTestComponentController>)>
component_created_callback,
fit::function<void(DartTestComponentController*)> done_callback) {
const int64_t start = Dart_TimelineGetMicros();
auto test_component = std::make_shared<DartTestComponentController>(
std::move(start_info), runner_incoming_services, std::move(controller),
std::move(done_callback));
component_created_callback(test_component);
// Start up the dart isolate and serve the suite protocol.
test_component->SetUp();
const int64_t end = Dart_TimelineGetMicros();
Dart_RecordTimelineEvent(
"DartTestComponentController::SetUp", start, end, 0, nullptr,
Dart_Timeline_Event_Duration, 0, NULL, NULL);
}
bool EntropySource(uint8_t* buffer, intptr_t count) {
zx_cprng_draw(buffer, count);
return true;
}
} // namespace
// "args" are how the component specifies arguments to the runner.
constexpr char kArgsKey[] = "args";
/// Parses the |args| field from the "program" field to determine
/// if a test component is being executed.
bool IsTestProgram(const fuchsia::data::Dictionary& program_metadata) {
for (const auto& entry : program_metadata.entries()) {
if (entry.key.compare(kArgsKey) != 0 || entry.value == nullptr) {
continue;
}
auto args = entry.value->str_vec();
// fml::CommandLine expects the first argument to be the name of the
// program, so we prepend a dummy argument so we can use fml::CommandLine to
// parse the arguments for us.
std::vector<std::string> command_line_args = {""};
command_line_args.insert(command_line_args.end(), args.begin(), args.end());
fml::CommandLine parsed_args = fml::CommandLineFromIterators(
command_line_args.begin(), command_line_args.end());
std::string is_test_str;
return parsed_args.GetOptionValue("is_test", &is_test_str) &&
is_test_str == "true";
}
return false;
}
DartRunner::DartRunner(sys::ComponentContext* context) : context_(context) {
context_->outgoing()
->AddPublicService<fuchsia::component::runner::ComponentRunner>(
[this](fidl::InterfaceRequest<
fuchsia::component::runner::ComponentRunner> request) {
component_runner_bindings_.AddBinding(this, std::move(request));
});
#if !defined(DART_PRODUCT)
// The VM service isolate uses the process-wide namespace. It writes the
// vm service protocol port under /tmp. The VMServiceObject exposes that
// port number to The Hub.
context_->outgoing()->debug_dir()->AddEntry(
dart_utils::VMServiceObject::kPortDirName,
std::make_unique<dart_utils::VMServiceObject>());
#endif // !defined(DART_PRODUCT)
dart::bin::BootstrapDartIo();
char* error =
Dart_SetVMFlags(dart_utils::ArraySize(kDartVMArgs), kDartVMArgs);
if (error) {
FML_LOG(FATAL) << "Dart_SetVMFlags failed: " << error;
}
Dart_InitializeParams params = {};
params.version = DART_INITIALIZE_PARAMS_CURRENT_VERSION;
#if defined(AOT_RUNTIME)
params.vm_snapshot_data = ::_kDartVmSnapshotData;
params.vm_snapshot_instructions = ::_kDartVmSnapshotInstructions;
#else
if (!dart_utils::MappedResource::LoadFromNamespace(
nullptr, "/pkg/data/vm_snapshot_data.bin", vm_snapshot_data_)) {
FML_LOG(FATAL) << "Failed to load vm snapshot data";
}
params.vm_snapshot_data = vm_snapshot_data_.address();
#endif
params.create_group = IsolateGroupCreateCallback;
params.shutdown_isolate = IsolateShutdownCallback;
params.cleanup_group = IsolateGroupCleanupCallback;
params.entropy_source = EntropySource;
#if !defined(DART_PRODUCT)
params.get_service_assets = GetVMServiceAssetsArchiveCallback;
#endif
error = Dart_Initialize(¶ms);
if (error)
FML_LOG(FATAL) << "Dart_Initialize failed: " << error;
}
DartRunner::~DartRunner() {
char* error = Dart_Cleanup();
if (error)
FML_LOG(FATAL) << "Dart_Cleanup failed: " << error;
}
void DartRunner::Start(
fuchsia::component::runner::ComponentStartInfo start_info,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller) {
// Parse the program field of the component's cml and check if it is a test
// component. If so, serve the |fuchsia.test.Suite| protocol from the
// component's outgoing directory, via DartTestComponentController.
if (IsTestProgram(start_info.program())) {
std::string url_copy = start_info.resolved_url();
TRACE_EVENT1("dart", "Start", "url", url_copy.c_str());
std::thread thread(
RunTestApplication, this, std::move(start_info), context_->svc(),
std::move(controller),
// component_created_callback
[this](std::shared_ptr<DartTestComponentController> ptr) {
test_components_.emplace(ptr.get(), std::move(ptr));
},
// done_callback
[this](DartTestComponentController* ptr) {
auto it = test_components_.find(ptr);
if (it != test_components_.end()) {
test_components_.erase(it);
}
});
thread.detach();
} else {
std::string url_copy = start_info.resolved_url();
TRACE_EVENT1("dart", "Start", "url", url_copy.c_str());
std::thread thread(RunApplication, this, std::move(start_info),
context_->svc(), std::move(controller));
thread.detach();
}
}
} // namespace dart_runner
| engine/shell/platform/fuchsia/dart_runner/dart_runner.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/dart_runner.cc",
"repo_id": "engine",
"token_count": 3674
} | 397 |
# dart_echo_server
Contains the Echo servers for the integration tests. There are currently two outputs:
- `dart-aot-echo-server`
- `dart-jit-echo-server`
The outputs run with their respective Dart runners and are consumed by their respective integration test.
| engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/README.md/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/README.md",
"repo_id": "engine",
"token_count": 69
} | 398 |
// Copyright 2013 The Flutter 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_ACCESSIBILITY_BRIDGE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ACCESSIBILITY_BRIDGE_H_
// Work around symbol conflicts with ICU.
#undef TRUE
#undef FALSE
#include <fuchsia/accessibility/semantics/cpp/fidl.h>
#include <fuchsia/ui/gfx/cpp/fidl.h>
#include <lib/fidl/cpp/binding_set.h>
#include <lib/inspect/component/cpp/component.h>
#include <zircon/types.h>
#include <memory>
#include <optional>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/lib/ui/semantics/semantics_node.h"
namespace flutter_runner {
// Accessibility bridge.
//
// This class intermediates accessibility-related calls between Fuchsia and
// Flutter. It serves to resolve the impedance mismatch between Flutter's
// platform-agnostic accessibility APIs and Fuchsia's APIs and behaviour.
//
// This bridge performs the following functions, among others:
//
// * Translates Flutter's semantics node updates to events Fuchsia requires
// (e.g. Flutter only sends updates for changed nodes, but Fuchsia requires
// the entire flattened subtree to be sent when a node changes.
class AccessibilityBridge
: public fuchsia::accessibility::semantics::SemanticListener {
public:
using SetSemanticsEnabledCallback = std::function<void(bool)>;
using DispatchSemanticsActionCallback =
std::function<void(int32_t, flutter::SemanticsAction)>;
// TODO(MI4-2531, FIDL-718): Remove this. We shouldn't be worried about
// batching messages at this level.
// FIDL may encode a C++ struct as larger than the sizeof the C++ struct.
// This is to make sure we don't send updates that are too large.
static constexpr uint32_t kMaxMessageSize = ZX_CHANNEL_MAX_MSG_BYTES / 2;
static_assert(fuchsia::accessibility::semantics::MAX_LABEL_SIZE <
kMaxMessageSize - 1);
// Flutter uses signed 32 bit integers for node IDs, while Fuchsia uses
// unsigned 32 bit integers. A change in the size on either one would break
// casts and size tracking logic in the implementation.
static constexpr size_t kNodeIdSize = sizeof(flutter::SemanticsNode::id);
static_assert(
kNodeIdSize ==
sizeof(fuchsia::accessibility::semantics::Node().node_id()),
"flutter::SemanticsNode::id and "
"fuchsia::accessibility::semantics::Node::node_id differ in size.");
// Maximum number of node ids to be deleted through the Semantics API.
static constexpr size_t kMaxDeletionsPerUpdate =
kMaxMessageSize / kNodeIdSize;
AccessibilityBridge(
SetSemanticsEnabledCallback set_semantics_enabled_callback,
DispatchSemanticsActionCallback dispatch_semantics_action_callback,
fuchsia::accessibility::semantics::SemanticsManagerHandle
semantics_manager,
fuchsia::ui::views::ViewRef view_ref,
inspect::Node inspect_node);
// Returns true if accessible navigation is enabled.
bool GetSemanticsEnabled() const;
// Enables Flutter accessibility navigation features.
//
// Once enabled, any semantics updates in the Flutter application will
// trigger |FuchsiaAccessibility::DispatchAccessibilityEvent| callbacks
// to send events back to the Fuchsia SemanticsManager.
void SetSemanticsEnabled(bool enabled);
// Adds a semantics node update to the buffer of node updates to apply.
void AddSemanticsNodeUpdate(const flutter::SemanticsNodeUpdates update,
float view_pixel_ratio);
// Requests a message announcement from the accessibility TTS system.
void RequestAnnounce(const std::string message);
// Notifies the bridge of a 'hover move' touch exploration event.
zx_status_t OnHoverMove(double x, double y);
// |fuchsia::accessibility::semantics::SemanticListener|
void HitTest(
fuchsia::math::PointF local_point,
fuchsia::accessibility::semantics::SemanticListener::HitTestCallback
callback) override;
// |fuchsia::accessibility::semantics::SemanticListener|
void OnAccessibilityActionRequested(
uint32_t node_id,
fuchsia::accessibility::semantics::Action action,
fuchsia::accessibility::semantics::SemanticListener::
OnAccessibilityActionRequestedCallback callback) override;
private:
// Fuchsia's default root semantic node id.
static constexpr int32_t kRootNodeId = 0;
// Represents an atomic semantic update to Fuchsia, which can contain deletes
// and updates of semantic nodes.
//
// An atomic update is a set of operations that take a semantic tree in a
// valid state to another valid state. Please check the semantics FIDL
// documentation for details.
struct FuchsiaAtomicUpdate {
FuchsiaAtomicUpdate() = default;
~FuchsiaAtomicUpdate() = default;
FuchsiaAtomicUpdate(FuchsiaAtomicUpdate&&) = default;
// Adds a node to be updated. |size| contains the
// size in bytes of the node to be updated.
void AddNodeUpdate(fuchsia::accessibility::semantics::Node node,
size_t size);
// Adds a node to be deleted.
void AddNodeDeletion(uint32_t id);
std::vector<std::pair<fuchsia::accessibility::semantics::Node, size_t>>
updates;
std::vector<uint32_t> deletions;
};
// Holds a flutter semantic node and some extra info.
// In particular, it adds a screen_rect field to flutter::SemanticsNode.
struct SemanticsNode {
flutter::SemanticsNode data;
SkRect screen_rect;
};
fuchsia::accessibility::semantics::Node GetRootNodeUpdate(size_t& node_size);
// Derives the BoundingBox of a Flutter semantics node from its
// rect and elevation.
fuchsia::ui::gfx::BoundingBox GetNodeLocation(
const flutter::SemanticsNode& node) const;
// Gets mat4 transformation from a Flutter semantics node.
fuchsia::ui::gfx::mat4 GetNodeTransform(
const flutter::SemanticsNode& node) const;
// Converts a Flutter semantics node's transformation to a mat4.
fuchsia::ui::gfx::mat4 ConvertSkiaTransformToMat4(
const SkM44 transform) const;
// Derives the attributes for a Fuchsia semantics node from a Flutter
// semantics node.
fuchsia::accessibility::semantics::Attributes GetNodeAttributes(
const flutter::SemanticsNode& node,
size_t* added_size) const;
// Derives the states for a Fuchsia semantics node from a Flutter semantics
// node.
fuchsia::accessibility::semantics::States GetNodeStates(
const flutter::SemanticsNode& node,
size_t* additional_size) const;
// Derives the set of supported actions for a Fuchsia semantics node from
// a Flutter semantics node.
std::vector<fuchsia::accessibility::semantics::Action> GetNodeActions(
const flutter::SemanticsNode& node,
size_t* additional_size) const;
// Derives the role for a Fuchsia semantics node from a Flutter
// semantics node.
fuchsia::accessibility::semantics::Role GetNodeRole(
const flutter::SemanticsNode& node) const;
// Gets the set of reachable descendants from the given node id.
std::unordered_set<int32_t> GetDescendants(int32_t node_id) const;
// Removes internal references to any dangling nodes from previous
// updates, and adds the nodes to be deleted to the current |atomic_update|.
//
// The node ids to be deleted are only collected at this point, and will be
// committed in the next call to |Apply()|.
void PruneUnreachableNodes(FuchsiaAtomicUpdate* atomic_update);
// Updates the on-screen positions of accessibility elements,
// starting from the root element with an identity matrix.
//
// This should be called from Update.
void UpdateScreenRects();
// Updates the on-screen positions of accessibility elements, starting
// from node_id and using the specified transform.
//
// Update calls this via UpdateScreenRects().
void UpdateScreenRects(int32_t node_id,
SkM44 parent_transform,
std::unordered_set<int32_t>* visited_nodes);
// Traverses the semantics tree to find the node_id hit by the given x,y
// point.
//
// Assumes that SemanticsNode::screen_rect is up to date.
std::optional<int32_t> GetHitNode(int32_t node_id, float x, float y);
// Returns whether the node is considered focusable.
bool IsFocusable(const flutter::SemanticsNode& node) const;
// Converts a fuchsia::accessibility::semantics::Action to a
// flutter::SemanticsAction.
//
// The node_id parameter is used for printing warnings about unsupported
// action types.
std::optional<flutter::SemanticsAction> GetFlutterSemanticsAction(
fuchsia::accessibility::semantics::Action fuchsia_action,
uint32_t node_id);
// Applies the updates and deletions in |atomic_update|, sending them via
// |tree_ptr|.
void Apply(FuchsiaAtomicUpdate* atomic_update);
// |fuchsia::accessibility::semantics::SemanticListener|
void OnSemanticsModeChanged(bool enabled,
OnSemanticsModeChangedCallback callback) override;
#if !FLUTTER_RELEASE
// Fills the inspect tree with debug information about the semantic tree.
void FillInspectTree(int32_t flutter_node_id,
int32_t current_level,
inspect::Node inspect_node,
inspect::Inspector* inspector) const;
#endif // !FLUTTER_RELEASE
SetSemanticsEnabledCallback set_semantics_enabled_callback_;
DispatchSemanticsActionCallback dispatch_semantics_action_callback_;
flutter::SemanticsNode root_flutter_semantics_node_;
float last_seen_view_pixel_ratio_ = 1.f;
fidl::Binding<fuchsia::accessibility::semantics::SemanticListener> binding_;
fuchsia::accessibility::semantics::SemanticsManagerPtr
fuchsia_semantics_manager_;
fuchsia::accessibility::semantics::SemanticTreePtr tree_ptr_;
// This is the cache of all nodes we've sent to Fuchsia's SemanticsManager.
// Assists with pruning unreachable nodes and hit testing.
std::unordered_map<int32_t, SemanticsNode> nodes_;
bool semantics_enabled_;
// Queue of atomic updates to be sent to Fuchsia.
std::shared_ptr<std::queue<FuchsiaAtomicUpdate>> atomic_updates_;
// Node to publish inspect data.
inspect::Node inspect_node_;
#if !FLUTTER_RELEASE
// Inspect node to store a dump of the semantic tree. Note that this only gets
// computed if requested, so it does not use memory to store the dump unless
// an explicit request is made.
inspect::LazyNode inspect_node_tree_dump_;
#endif // !FLUTTER_RELEASE
FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ACCESSIBILITY_BRIDGE_H_
| engine/shell/platform/fuchsia/flutter/accessibility_bridge.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/accessibility_bridge.h",
"repo_id": "engine",
"token_count": 3529
} | 399 |
// Copyright 2013 The Flutter 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 "flatland_connection.h"
#include <zircon/status.h>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
namespace flutter_runner {
namespace {
// Helper function for traces.
double DeltaFromNowInNanoseconds(const fml::TimePoint& now,
const fml::TimePoint& time) {
return (time - now).ToNanoseconds();
}
} // namespace
FlatlandConnection::FlatlandConnection(
std::string debug_label,
fuchsia::ui::composition::FlatlandHandle flatland,
fml::closure error_callback,
on_frame_presented_event on_frame_presented_callback)
: flatland_(flatland.Bind()),
error_callback_(error_callback),
on_frame_presented_callback_(std::move(on_frame_presented_callback)) {
flatland_.set_error_handler([callback = error_callback_](zx_status_t status) {
FML_LOG(ERROR) << "Flatland disconnected: " << zx_status_get_string(status);
callback();
});
flatland_->SetDebugName(debug_label);
flatland_.events().OnError =
fit::bind_member(this, &FlatlandConnection::OnError);
flatland_.events().OnFramePresented =
fit::bind_member(this, &FlatlandConnection::OnFramePresented);
flatland_.events().OnNextFrameBegin =
fit::bind_member(this, &FlatlandConnection::OnNextFrameBegin);
}
FlatlandConnection::~FlatlandConnection() = default;
// This method is called from the raster thread.
void FlatlandConnection::Present() {
TRACE_DURATION("flutter", "FlatlandConnection::Present");
std::scoped_lock<std::mutex> lock(threadsafe_state_.mutex_);
if (threadsafe_state_.present_credits_ > 0) {
DoPresent();
} else {
present_waiting_for_credit_ = true;
}
}
// This method is called from the raster thread.
void FlatlandConnection::DoPresent() {
TRACE_DURATION("flutter", "FlatlandConnection::DoPresent");
TRACE_FLOW_BEGIN("gfx", "Flatland::Present", next_present_trace_id_);
++next_present_trace_id_;
FML_CHECK(threadsafe_state_.present_credits_ > 0);
--threadsafe_state_.present_credits_;
fuchsia::ui::composition::PresentArgs present_args;
present_args.set_requested_presentation_time(0);
present_args.set_acquire_fences(std::move(acquire_fences_));
present_args.set_release_fences(std::move(previous_present_release_fences_));
// Frame rate over latency.
present_args.set_unsquashable(true);
flatland_->Present(std::move(present_args));
// In Flatland, release fences apply to the content of the previous present.
// Keeping track of the old frame's release fences and swapping ensure we set
// the correct ones for VulkanSurface's interpretation.
previous_present_release_fences_.clear();
previous_present_release_fences_.swap(current_present_release_fences_);
acquire_fences_.clear();
}
// This method is called from the UI thread.
void FlatlandConnection::AwaitVsync(FireCallbackCallback callback) {
TRACE_DURATION("flutter", "FlatlandConnection::AwaitVsync");
std::scoped_lock<std::mutex> lock(threadsafe_state_.mutex_);
threadsafe_state_.pending_fire_callback_ = nullptr;
const auto now = fml::TimePoint::Now();
// Initial case.
if (MaybeRunInitialVsyncCallback(now, callback))
return;
// Throttle case.
if (threadsafe_state_.present_credits_ == 0) {
threadsafe_state_.pending_fire_callback_ = callback;
return;
}
// Regular case.
RunVsyncCallback(now, callback);
}
// This method is called from the UI thread.
void FlatlandConnection::AwaitVsyncForSecondaryCallback(
FireCallbackCallback callback) {
TRACE_DURATION("flutter",
"FlatlandConnection::AwaitVsyncForSecondaryCallback");
std::scoped_lock<std::mutex> lock(threadsafe_state_.mutex_);
const auto now = fml::TimePoint::Now();
// Initial case.
if (MaybeRunInitialVsyncCallback(now, callback))
return;
// Regular case.
RunVsyncCallback(now, callback);
}
// This method is called from the raster thread.
void FlatlandConnection::OnError(
fuchsia::ui::composition::FlatlandError error) {
FML_LOG(ERROR) << "Flatland error: " << static_cast<int>(error);
error_callback_();
}
// This method is called from the raster thread.
void FlatlandConnection::OnNextFrameBegin(
fuchsia::ui::composition::OnNextFrameBeginValues values) {
// Collect now before locking because this is an important timing information
// from Scenic.
const auto now = fml::TimePoint::Now();
std::scoped_lock<std::mutex> lock(threadsafe_state_.mutex_);
threadsafe_state_.first_feedback_received_ = true;
threadsafe_state_.present_credits_ += values.additional_present_credits();
TRACE_DURATION("flutter", "FlatlandConnection::OnNextFrameBegin",
"present_credits", threadsafe_state_.present_credits_);
if (present_waiting_for_credit_ && threadsafe_state_.present_credits_ > 0) {
DoPresent();
present_waiting_for_credit_ = false;
}
// Update vsync_interval_ by calculating the difference between the first two
// presentation times. Flatland always returns >1 presentation_infos, so this
// check is to guard against any changes to this assumption.
if (values.has_future_presentation_infos() &&
values.future_presentation_infos().size() > 1) {
threadsafe_state_.vsync_interval_ = fml::TimeDelta::FromNanoseconds(
values.future_presentation_infos().at(1).presentation_time() -
values.future_presentation_infos().at(0).presentation_time());
} else {
FML_LOG(WARNING)
<< "Flatland didn't send enough future_presentation_infos to update "
"vsync interval.";
}
// Update next_presentation_times_.
std::queue<fml::TimePoint> new_times;
for (const auto& info : values.future_presentation_infos()) {
new_times.emplace(fml::TimePoint::FromEpochDelta(
fml::TimeDelta::FromNanoseconds(info.presentation_time())));
}
threadsafe_state_.next_presentation_times_.swap(new_times);
// Update vsync_offset_.
// We use modulo here because Flatland may point to the following vsync if
// OnNextFrameBegin() is called after the current frame's latch point.
auto vsync_offset =
(fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromNanoseconds(
values.future_presentation_infos().front().presentation_time())) -
now) %
threadsafe_state_.vsync_interval_;
// Thread contention may result in OnNextFrameBegin() being called after the
// presentation time. Ignore these outliers.
if (vsync_offset > fml::TimeDelta::Zero()) {
threadsafe_state_.vsync_offset_ = vsync_offset;
}
// Throttle case.
if (threadsafe_state_.pending_fire_callback_ &&
threadsafe_state_.present_credits_ > 0) {
RunVsyncCallback(now, threadsafe_state_.pending_fire_callback_);
threadsafe_state_.pending_fire_callback_ = nullptr;
}
}
// This method is called from the raster thread.
void FlatlandConnection::OnFramePresented(
fuchsia::scenic::scheduling::FramePresentedInfo info) {
on_frame_presented_callback_(std::move(info));
}
// Parses and updates next_presentation_times_.
fml::TimePoint FlatlandConnection::GetNextPresentationTime(
const fml::TimePoint& now) {
const fml::TimePoint& cutoff =
now > threadsafe_state_.last_presentation_time_
? now
: threadsafe_state_.last_presentation_time_;
// Remove presentation times that may have been passed. This may happen after
// a long draw call.
while (!threadsafe_state_.next_presentation_times_.empty() &&
threadsafe_state_.next_presentation_times_.front() <= cutoff) {
threadsafe_state_.next_presentation_times_.pop();
}
// Calculate a presentation time based on
// |threadsafe_state_.last_presentation_time_| that is later than cutoff using
// |vsync_interval| increments if we don't have any future presentation times
// left.
if (threadsafe_state_.next_presentation_times_.empty()) {
auto result = threadsafe_state_.last_presentation_time_;
while (result <= cutoff) {
result = result + threadsafe_state_.vsync_interval_;
}
return result;
}
// Return the next presentation time in the queue for the regular case.
const auto result = threadsafe_state_.next_presentation_times_.front();
threadsafe_state_.next_presentation_times_.pop();
return result;
}
// This method is called from the UI thread.
bool FlatlandConnection::MaybeRunInitialVsyncCallback(
const fml::TimePoint& now,
FireCallbackCallback& callback) {
if (!threadsafe_state_.first_feedback_received_) {
TRACE_DURATION("flutter",
"FlatlandConnection::MaybeRunInitialVsyncCallback");
const auto frame_end = now + kInitialFlatlandVsyncOffset;
threadsafe_state_.last_presentation_time_ = frame_end;
callback(now, frame_end);
return true;
}
return false;
}
// This method may be called from the raster or UI thread, but it is safe
// because VsyncWaiter posts the vsync callback on UI thread.
void FlatlandConnection::RunVsyncCallback(const fml::TimePoint& now,
FireCallbackCallback& callback) {
const auto& frame_end = GetNextPresentationTime(now);
const auto& frame_start = frame_end - threadsafe_state_.vsync_offset_;
threadsafe_state_.last_presentation_time_ = frame_end;
TRACE_DURATION("flutter", "FlatlandConnection::RunVsyncCallback",
"frame_start_delta",
DeltaFromNowInNanoseconds(now, frame_start), "frame_end_delta",
DeltaFromNowInNanoseconds(now, frame_end));
callback(frame_start, frame_end);
}
// This method is called from the raster thread.
void FlatlandConnection::EnqueueAcquireFence(zx::event fence) {
acquire_fences_.push_back(std::move(fence));
}
// This method is called from the raster thread.
void FlatlandConnection::EnqueueReleaseFence(zx::event fence) {
current_present_release_fences_.push_back(std::move(fence));
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/flatland_connection.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/flatland_connection.cc",
"repo_id": "engine",
"token_count": 3441
} | 400 |
{
"comment:0": "NOTE: THIS FILE IS GENERATED. DO NOT EDIT.",
"comment:1": "Instead modify 'flutter/shell/platform/fuchsia/flutter/kernel/libraries.yaml' and follow the instructions therein.",
"flutter_runner": {
"include": [
{
"path": "../../../../../../third_party/dart/sdk/lib/libraries.json",
"target": "vm_common"
}
],
"libraries": {
"fuchsia.builtin": {
"uri": "../../dart_runner/embedder/builtin.dart"
},
"zircon": {
"uri": "../../dart-pkg/zircon/lib/zircon.dart"
},
"zircon_ffi": {
"uri": "../../dart-pkg/zircon_ffi/lib/zircon_ffi.dart"
},
"fuchsia": {
"uri": "../../dart-pkg/fuchsia/lib/fuchsia.dart"
},
"ui": {
"uri": "../../../../../lib/ui/ui.dart"
}
}
}
} | engine/shell/platform/fuchsia/flutter/kernel/libraries.json/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/kernel/libraries.json",
"repo_id": "engine",
"token_count": 422
} | 401 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_DELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_DELEGATE_H_
#include <fuchsia/ui/pointer/cpp/fidl.h>
#include <array>
#include <functional>
#include <optional>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "flutter/lib/ui/window/pointer_data.h"
namespace flutter_runner {
// Helper class for keying into a map.
struct IxnHasher {
std::size_t operator()(
const fuchsia::ui::pointer::TouchInteractionId& ixn) const {
return std::hash<uint32_t>()(ixn.device_id) ^
std::hash<uint32_t>()(ixn.pointer_id) ^
std::hash<uint32_t>()(ixn.interaction_id);
}
};
// Channel processors for fuchsia.ui.pointer.TouchSource and MouseSource
// protocols. It manages the channel state, collects touch and mouse events, and
// surfaces them to PlatformView as flutter::PointerData events for further
// processing and dispatch.
class PointerDelegate {
public:
PointerDelegate(fuchsia::ui::pointer::TouchSourceHandle touch_source,
fuchsia::ui::pointer::MouseSourceHandle mouse_source);
// This function collects Fuchsia's TouchPointerSample and MousePointerSample
// data and transforms them into flutter::PointerData structs. It then calls
// the supplied callback with a vector of flutter::PointerData, which (1) does
// last processing (applies metrics), and (2) packs these flutter::PointerData
// in a flutter::PointerDataPacket for transport to the Engine.
void WatchLoop(
std::function<void(std::vector<flutter::PointerData>)> callback);
private:
/***** TOUCH STATE *****/
// Channel for touch events from Scenic.
fuchsia::ui::pointer::TouchSourcePtr touch_source_;
// Receive touch events from Scenic. Must be copyable.
std::function<void(std::vector<fuchsia::ui::pointer::TouchEvent>)>
touch_responder_;
// Per-interaction buffer of touch events from Scenic. When an interaction
// starts with event.pointer_sample.phase == ADD, we allocate a buffer and
// store samples. When interaction ownership becomes
// event.interaction_result.status == GRANTED, we flush the buffer to client,
// delete the buffer, and all future events in this interaction are flushed
// direct to client. When interaction ownership becomes DENIED, we delete the
// buffer, and the client does not get any previous or future events in this
// interaction.
//
// There are three basic interaction forms that we need to handle, and the API
// guarantees we see only these three forms. S=sample, R(g)=result-granted,
// R(d)=result-denied, and + means packaged in the same table. Time flows from
// left to right. Samples start with ADD, and end in REMOVE or CANCEL. Each
// interaction receives just one ownership result.
// (1) Late grant. S S S R(g) S S S
// (1-a) Combo. S S S+R(g) S S S
// (2) Early grant. S+R(g) S S S S S
// (3) Late deny. S S S R(d)
// (3-a) Combo. S S S+R(d)
//
// This results in the following high-level algorithm to correctly deal with
// buffer allocation and deletion, and event flushing or event dropping based
// on ownership.
// if event.sample.phase == ADD && !event.result
// allocate buffer[event.sample.interaction]
// if buffer[event.sample.interaction]
// buffer[event.sample.interaction].push(event.sample)
// else
// flush_to_client(event.sample)
// if event.result
// if event.result == GRANTED
// flush_to_client(buffer[event.result.interaction])
// delete buffer[event.result.interaction]
std::unordered_map<fuchsia::ui::pointer::TouchInteractionId,
std::vector<flutter::PointerData>,
IxnHasher>
touch_buffer_;
// The fuchsia.ui.pointer.TouchSource protocol allows one in-flight
// hanging-get Watch() call to gather touch events, and the client is expected
// to respond with consumption intent on the following hanging-get Watch()
// call. Store responses here for the next call.
std::vector<fuchsia::ui::pointer::TouchResponse> touch_responses_;
// The fuchsia.ui.pointer.TouchSource protocol issues channel-global view
// parameters on connection and on change. Events must apply these view
// parameters to correctly map to logical view coordinates. The "nullopt"
// state represents the absence of view parameters, early in the protocol
// lifecycle.
std::optional<fuchsia::ui::pointer::ViewParameters> touch_view_parameters_;
/***** MOUSE STATE *****/
// Channel for mouse events from Scenic.
fuchsia::ui::pointer::MouseSourcePtr mouse_source_;
// Receive mouse events from Scenic. Must be copyable.
std::function<void(std::vector<fuchsia::ui::pointer::MouseEvent>)>
mouse_responder_;
// The set of mouse devices that are currently interacting with the UI.
// A mouse is considered flutter::PointerData::Change::kDown if any button is
// pressed. This set is used to correctly set the phase in
// flutter::PointerData.change, with this high-level algorithm:
// if !mouse_down[id] && !button then: change = kHover
// if !mouse_down[id] && button then: change = kDown; mouse_down.add(id)
// if mouse_down[id] && button then: change = kMove
// if mouse_down[id] && !button then: change = kUp; mouse_down.remove(id)
std::unordered_set</*mouse device ID*/ uint32_t> mouse_down_;
// For each mouse device, its device-specific information, such as mouse
// button priority order.
std::unordered_map</*mouse device ID*/ uint32_t,
fuchsia::ui::pointer::MouseDeviceInfo>
mouse_device_info_;
// The fuchsia.ui.pointer.MouseSource protocol issues channel-global view
// parameters on connection and on change. Events must apply these view
// parameters to correctly map to logical view coordinates. The "nullopt"
// state represents the absence of view parameters, early in the protocol
// lifecycle.
std::optional<fuchsia::ui::pointer::ViewParameters> mouse_view_parameters_;
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_DELEGATE_H_
| engine/shell/platform/fuchsia/flutter/pointer_delegate.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/pointer_delegate.h",
"repo_id": "engine",
"token_count": 2051
} | 402 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "software_surface_producer.h"
#include <lib/fdio/directory.h>
#include <lib/zx/process.h>
#include <algorithm> // For std::remove_if
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
namespace flutter_runner {
namespace {
std::string GetCurrentProcessName() {
char name[ZX_MAX_NAME_LEN];
zx_status_t status =
zx::process::self()->get_property(ZX_PROP_NAME, name, sizeof(name));
if (status != ZX_OK) {
FML_LOG(ERROR) << "Failed to get process name for sysmem; using \"\".";
return std::string();
}
return std::string(name);
}
zx_koid_t GetCurrentProcessId() {
zx_info_handle_basic_t info;
zx_status_t status = zx::process::self()->get_info(
ZX_INFO_HANDLE_BASIC, &info, sizeof(info), /*actual_count*/ nullptr,
/*avail_count*/ nullptr);
if (status != ZX_OK) {
FML_LOG(ERROR) << "Failed to get process ID for sysmem; using 0.";
return ZX_KOID_INVALID;
}
return info.koid;
}
} // namespace
SoftwareSurfaceProducer::SoftwareSurfaceProducer() {
zx_status_t status = fdio_service_connect(
"/svc/fuchsia.sysmem.Allocator",
sysmem_allocator_.NewRequest().TakeChannel().release());
sysmem_allocator_->SetDebugClientInfo(GetCurrentProcessName(),
GetCurrentProcessId());
FML_DCHECK(status == ZX_OK);
status = fdio_service_connect(
"/svc/fuchsia.ui.composition.Allocator",
flatland_allocator_.NewRequest().TakeChannel().release());
FML_DCHECK(status == ZX_OK);
valid_ = true;
}
SoftwareSurfaceProducer::~SoftwareSurfaceProducer() = default;
std::unique_ptr<SurfaceProducerSurface>
SoftwareSurfaceProducer::ProduceOffscreenSurface(const SkISize& size) {
FML_CHECK(valid_);
return CreateSurface(size);
}
std::unique_ptr<SurfaceProducerSurface> SoftwareSurfaceProducer::ProduceSurface(
const SkISize& size) {
TRACE_EVENT2("flutter", "SoftwareSurfacePool::ProduceSurface", "width",
size.width(), "height", size.height());
FML_CHECK(valid_);
std::unique_ptr<SurfaceProducerSurface> surface;
auto exact_match_it =
std::find_if(available_surfaces_.begin(), available_surfaces_.end(),
[&size](const auto& surface) {
return surface->IsValid() && surface->GetSize() == size;
});
if (exact_match_it != available_surfaces_.end()) {
TRACE_EVENT_INSTANT0("flutter", "Exact match found");
surface = std::move(*exact_match_it);
available_surfaces_.erase(exact_match_it);
} else {
surface = CreateSurface(size);
}
if (surface == nullptr) {
FML_LOG(ERROR) << "Could not acquire surface.";
return nullptr;
}
if (!surface->FlushSessionAcquireAndReleaseEvents()) {
FML_LOG(ERROR) << "Could not flush acquire/release events for buffer.";
return nullptr;
}
return surface;
}
void SoftwareSurfaceProducer::SubmitSurfaces(
std::vector<std::unique_ptr<SurfaceProducerSurface>> surfaces) {
TRACE_EVENT0("flutter", "SoftwareSurfaceProducer::SubmitSurfaces");
// Submit surface
for (auto& surface : surfaces) {
SubmitSurface(std::move(surface));
}
// Buffer management.
AgeAndCollectOldBuffers();
}
void SoftwareSurfaceProducer::SubmitSurface(
std::unique_ptr<SurfaceProducerSurface> surface) {
TRACE_EVENT0("flutter", "SoftwareSurfacePool::SubmitSurface");
FML_CHECK(valid_);
// This cast is safe because |SoftwareSurface| is the only implementation of
// |SurfaceProducerSurface| for Flutter on Fuchsia. Additionally, it is
// required, because we need to access |SoftwareSurface| specific information
// of the surface (such as the amount of memory it contains).
auto software_surface = std::unique_ptr<SoftwareSurface>(
static_cast<SoftwareSurface*>(surface.release()));
if (!software_surface) {
return;
}
uintptr_t surface_key = reinterpret_cast<uintptr_t>(software_surface.get());
auto insert_iterator = pending_surfaces_.insert(std::make_pair(
surface_key, // key
std::move(software_surface) // value
));
if (insert_iterator.second) {
insert_iterator.first->second->SignalWritesFinished(std::bind(
&SoftwareSurfaceProducer::RecyclePendingSurface, this, surface_key));
}
}
std::unique_ptr<SoftwareSurface> SoftwareSurfaceProducer::CreateSurface(
const SkISize& size) {
TRACE_EVENT2("flutter", "SoftwareSurfacePool::CreateSurface", "width",
size.width(), "height", size.height());
auto surface = std::make_unique<SoftwareSurface>(sysmem_allocator_,
flatland_allocator_, size);
if (!surface->IsValid()) {
FML_LOG(ERROR) << "Created surface is invalid.";
return nullptr;
}
trace_surfaces_created_++;
return surface;
}
void SoftwareSurfaceProducer::RecycleSurface(
std::unique_ptr<SoftwareSurface> surface) {
// The surface may have become invalid (for example if the fences could
// not be reset).
if (!surface->IsValid()) {
FML_LOG(ERROR) << "Attempted to recycle invalid surface.";
return;
}
TRACE_EVENT0("flutter", "SoftwareSurfacePool::RecycleSurface");
// Recycle the buffer by putting it in the list of available surfaces if we
// have not reached the maximum amount of cached surfaces.
if (available_surfaces_.size() < kMaxSurfaces) {
available_surfaces_.push_back(std::move(surface));
} else {
TRACE_EVENT_INSTANT0("flutter", "Too many surfaces in pool, dropping");
}
TraceStats();
}
void SoftwareSurfaceProducer::RecyclePendingSurface(uintptr_t surface_key) {
// Before we do anything, we must clear the surface from the collection of
// pending surfaces.
auto found_in_pending = pending_surfaces_.find(surface_key);
if (found_in_pending == pending_surfaces_.end()) {
FML_LOG(ERROR) << "Attempted to recycle a surface that wasn't pending.";
return;
}
// Grab a hold of the surface to recycle and clear the entry in the pending
// surfaces collection.
auto surface_to_recycle = std::move(found_in_pending->second);
pending_surfaces_.erase(found_in_pending);
RecycleSurface(std::move(surface_to_recycle));
}
void SoftwareSurfaceProducer::AgeAndCollectOldBuffers() {
TRACE_EVENT0("flutter", "SoftwareSurfacePool::AgeAndCollectOldBuffers");
// Remove all surfaces that are no longer valid or are too old.
size_t size_before = available_surfaces_.size();
available_surfaces_.erase(
std::remove_if(available_surfaces_.begin(), available_surfaces_.end(),
[&](auto& surface) {
return !surface->IsValid() ||
surface->AdvanceAndGetAge() >= kMaxSurfaceAge;
}),
available_surfaces_.end());
TRACE_EVENT1("flutter", "AgeAndCollect", "aged surfaces",
(size_before - available_surfaces_.size()));
TraceStats();
}
void SoftwareSurfaceProducer::TraceStats() {
// Resources held in cached buffers.
size_t cached_surfaces_bytes = 0;
for (const auto& surface : available_surfaces_) {
cached_surfaces_bytes += surface->GetAllocationSize();
}
TRACE_COUNTER("flutter", "SurfacePoolCounts", 0u, "CachedCount",
available_surfaces_.size(), //
"Created", trace_surfaces_created_, //
"Reused", trace_surfaces_reused_, //
"PendingInCompositor", pending_surfaces_.size(), //
"Retained", 0 //
);
TRACE_COUNTER("flutter", "SurfacePoolBytes", 0u, //
"CachedBytes", cached_surfaces_bytes, //
"RetainedBytes", 0 //
);
// Reset per present/frame stats.
trace_surfaces_created_ = 0;
trace_surfaces_reused_ = 0;
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/software_surface_producer.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/software_surface_producer.cc",
"repo_id": "engine",
"token_count": 3109
} | 403 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fake_flatland.h"
#include <zircon/types.h>
#include <algorithm> // For std::remove_if
#include <memory>
#include "flutter/fml/logging.h"
namespace flutter_runner::testing {
FakeFlatland::FakeFlatland()
: allocator_binding_(this),
flatland_binding_(this),
present_handler_([](auto args) {}) {}
FakeFlatland::~FakeFlatland() = default;
fuchsia::ui::composition::AllocatorHandle FakeFlatland::ConnectAllocator(
async_dispatcher_t* dispatcher) {
FML_CHECK(!allocator_binding_.is_bound());
fuchsia::ui::composition::AllocatorHandle allocator;
allocator_binding_.Bind(allocator.NewRequest(), dispatcher);
return allocator;
}
fuchsia::ui::composition::FlatlandHandle FakeFlatland::ConnectFlatland(
async_dispatcher_t* dispatcher) {
FML_CHECK(!flatland_binding_.is_bound());
fuchsia::ui::composition::FlatlandHandle flatland;
flatland_binding_.Bind(flatland.NewRequest(), dispatcher);
return flatland;
}
void FakeFlatland::Disconnect(fuchsia::ui::composition::FlatlandError error) {
flatland_binding_.events().OnError(std::move(error));
flatland_binding_.Unbind();
allocator_binding_
.Unbind(); // TODO(fxb/85619): Does the real Scenic unbind this when
// Flatland has an error? Or is it independent?
}
void FakeFlatland::SetPresentHandler(PresentHandler present_handler) {
present_handler_ =
present_handler ? std::move(present_handler) : [](auto args) {};
}
void FakeFlatland::FireOnNextFrameBeginEvent(
fuchsia::ui::composition::OnNextFrameBeginValues
on_next_frame_begin_values) {
flatland_binding_.events().OnNextFrameBegin(
std::move(on_next_frame_begin_values));
}
void FakeFlatland::FireOnFramePresentedEvent(
fuchsia::scenic::scheduling::FramePresentedInfo frame_presented_info) {
flatland_binding_.events().OnFramePresented(std::move(frame_presented_info));
}
void FakeFlatland::NotImplemented_(const std::string& name) {
FML_LOG(FATAL) << "FakeFlatland does not implement " << name;
}
void FakeFlatland::RegisterBufferCollection(
fuchsia::ui::composition::RegisterBufferCollectionArgs args,
RegisterBufferCollectionCallback callback) {
auto [export_token_koid, _] = GetKoids(args.export_token());
auto [__, emplace_binding_success] =
graph_bindings_.buffer_collections.emplace(
export_token_koid,
BufferCollectionBinding{
.export_token = std::move(*args.mutable_export_token()),
.sysmem_token =
std::move(*args.mutable_buffer_collection_token()),
.usage = args.usage(),
});
// TODO(fxb/85619): Disconnect the Allocator here
FML_CHECK(emplace_binding_success)
<< "FakeFlatland::RegisterBufferCollection: BufferCollection already "
"exists with koid "
<< export_token_koid;
}
void FakeFlatland::Present(fuchsia::ui::composition::PresentArgs args) {
// Each FIDL call between this `Present()` and the last one mutated the
// `pending_graph_` independently of the `current_graph_`. Only the
// `current_graph_` is visible externally in the test.
//
// `Present()` updates the current graph with a deep clone of the pending one.
current_graph_ = pending_graph_.Clone();
present_handler_(std::move(args));
}
void FakeFlatland::CreateView(
fuchsia::ui::views::ViewCreationToken token,
fidl::InterfaceRequest<fuchsia::ui::composition::ParentViewportWatcher>
parent_viewport_watcher) {
CreateView2(std::move(token), fuchsia::ui::views::ViewIdentityOnCreation{},
fuchsia::ui::composition::ViewBoundProtocols{},
std::move(parent_viewport_watcher));
}
void FakeFlatland::CreateView2(
fuchsia::ui::views::ViewCreationToken token,
fuchsia::ui::views::ViewIdentityOnCreation view_identity,
fuchsia::ui::composition::ViewBoundProtocols view_protocols,
fidl::InterfaceRequest<fuchsia::ui::composition::ParentViewportWatcher>
parent_viewport_watcher) {
// TODO(fxb/85619): Handle a 2nd CreateView call
FML_CHECK(!pending_graph_.view.has_value());
FML_CHECK(!graph_bindings_.viewport_watcher.has_value());
auto view_token_koids = GetKoids(token);
auto view_ref_koids = GetKoids(view_identity.view_ref);
auto view_ref_control_koids = GetKoids(view_identity.view_ref_control);
FML_CHECK(view_ref_koids.first == view_ref_control_koids.second);
FML_CHECK(view_ref_koids.second == view_ref_control_koids.first);
pending_graph_.view.emplace(FakeView{
.view_token = view_token_koids.first,
.view_ref = view_ref_koids.first,
.view_ref_control = view_ref_control_koids.first,
.view_ref_focused =
view_protocols.has_view_ref_focused()
? GetKoids(view_protocols.view_ref_focused()).first
: zx_koid_t{},
.focuser = view_protocols.has_view_focuser()
? GetKoids(view_protocols.view_focuser()).first
: zx_koid_t{},
.touch_source = view_protocols.has_touch_source()
? GetKoids(view_protocols.touch_source()).first
: zx_koid_t{},
.mouse_source = view_protocols.has_mouse_source()
? GetKoids(view_protocols.mouse_source()).first
: zx_koid_t{},
.parent_viewport_watcher = GetKoids(parent_viewport_watcher).first,
});
graph_bindings_.viewport_watcher.emplace(
view_token_koids.first,
ParentViewportWatcher(
std::move(token), std::move(view_identity), std::move(view_protocols),
std::move(parent_viewport_watcher), flatland_binding_.dispatcher()));
}
void FakeFlatland::CreateTransform(
fuchsia::ui::composition::TransformId transform_id) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::CreateTransform: TransformId 0 is invalid.";
return;
}
if (pending_graph_.transform_map.count(transform_id.value) != 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::CreateTransform: TransformId "
<< transform_id.value << " is already in use.";
return;
}
auto [emplaced_transform, emplace_success] =
pending_graph_.transform_map.emplace(
transform_id.value, std::make_shared<FakeTransform>(FakeTransform{
.id = transform_id,
}));
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(emplace_success)
<< "FakeFlatland::CreateTransform: Internal error (transform_map) adding "
"transform with id: "
<< transform_id.value;
auto [_, emplace_parent_success] = parents_map_.emplace(
transform_id.value,
std::make_pair(std::weak_ptr<FakeTransform>(),
std::weak_ptr(emplaced_transform->second)));
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(emplace_parent_success)
<< "FakeFlatland::CreateTransform: Internal error (parent_map) adding "
"transform with id: "
<< transform_id.value;
}
void FakeFlatland::SetTranslation(
fuchsia::ui::composition::TransformId transform_id,
fuchsia::math::Vec translation) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetTranslation: TransformId 0 is invalid.";
return;
}
auto found_transform = pending_graph_.transform_map.find(transform_id.value);
if (found_transform == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetTranslation: TransformId "
<< transform_id.value << " does not exist.";
return;
}
auto& transform = found_transform->second;
FML_CHECK(transform);
transform->translation = translation;
}
void FakeFlatland::SetScale(fuchsia::ui::composition::TransformId transform_id,
fuchsia::math::VecF scale) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetScale: TransformId 0 is invalid.";
return;
}
auto found_transform = pending_graph_.transform_map.find(transform_id.value);
if (found_transform == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetScale: TransformId "
<< transform_id.value << " does not exist.";
return;
}
if (scale.x == 0.f || scale.y == 0.f) {
FML_CHECK(false) << "SetScale failed, zero values not allowed (" << scale.x
<< ", " << scale.y << " ).";
return;
}
if (isinf(scale.x) || isinf(scale.y) || isnan(scale.x) || isnan(scale.y)) {
FML_CHECK(false) << "SetScale failed, invalid scale values (" << scale.x
<< ", " << scale.y << " ).";
return;
}
auto& transform = found_transform->second;
FML_CHECK(transform);
transform->scale = scale;
}
void FakeFlatland::SetOrientation(
fuchsia::ui::composition::TransformId transform_id,
fuchsia::ui::composition::Orientation orientation) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetOrientation: TransformId 0 is invalid.";
return;
}
auto found_transform = pending_graph_.transform_map.find(transform_id.value);
if (found_transform == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetOrientation: TransformId "
<< transform_id.value << " does not exist.";
return;
}
auto& transform = found_transform->second;
FML_CHECK(transform);
transform->orientation = orientation;
}
void FakeFlatland::SetOpacity(
fuchsia::ui::composition::TransformId transform_id,
float value) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetOpacity: TransformId 0 is invalid.";
return;
}
auto found_transform = pending_graph_.transform_map.find(transform_id.value);
if (found_transform == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetOpacity: TransformId "
<< transform_id.value << " does not exist.";
return;
}
if (value < 0.f || value > 1.f) {
FML_CHECK(false) << "FakeFlatland::SetOpacity: Invalid opacity value.";
}
auto& transform = found_transform->second;
FML_CHECK(transform);
transform->opacity = value;
}
void FakeFlatland::SetClipBoundary(
fuchsia::ui::composition::TransformId transform_id,
std::unique_ptr<fuchsia::math::Rect> bounds) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetClipBoundary: TransformId 0 is invalid.";
return;
}
auto found_transform = pending_graph_.transform_map.find(transform_id.value);
if (found_transform == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetClipBoundary: TransformId "
<< transform_id.value << " does not exist.";
return;
}
auto& transform = found_transform->second;
FML_CHECK(transform);
if (bounds == nullptr) {
transform->clip_bounds = std::nullopt;
return;
}
transform->clip_bounds = *bounds.get();
}
// TODO(fxbug.dev/89111): Re-enable once SDK rolls.
// void FakeFlatland::SetImageOpacity(
// fuchsia::ui::composition::ContentId content_id,
// float opacity) {
// if (content_id.value == 0) {
// // TODO(fxb/85619): Raise a FlatlandError here
// FML_CHECK(false)
// << "FakeFlatland::SetImageOpacity: ContentId 0 is invalid.";
// return;
// }
// auto found_content = pending_graph_.content_map.find(image_id.value);
// if (found_content == pending_graph_.content_map.end()) {
// // TODO(fxb/85619): Raise a FlatlandError here
// FML_CHECK(false) << "FakeFlatland::SetImageOpacity: ContentId "
// << image_id.value << " does not exist.";
// return;
// }
// auto& content = found_content->second;
// FML_CHECK(content);
// FakeImage* image = std::get_if<FakeImage>(content.get());
// if (image == nullptr) {
// // TODO(fxb/85619): Raise a FlatlandError here
// FML_CHECK(false) << "FakeFlatland::SetImageOpacity: ContentId "
// << image_id.value << " is not an Image.";
// return;
// }
// image->opacity = opacity;
// }
void FakeFlatland::AddChild(
fuchsia::ui::composition::TransformId parent_transform_id,
fuchsia::ui::composition::TransformId child_transform_id) {
if (parent_transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::AddChild: Parent TransformId 0 is invalid.";
return;
}
if (child_transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::AddChild: Child TransformId 0 is invalid.";
return;
}
auto found_parent =
pending_graph_.transform_map.find(parent_transform_id.value);
if (found_parent == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::AddChild: Parent TransformId "
<< parent_transform_id.value << " does not exist.";
return;
}
auto found_child =
pending_graph_.transform_map.find(child_transform_id.value);
if (found_child == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::AddChild: Child TransformId "
<< child_transform_id.value << " does not exist.";
return;
}
auto found_child_old_parent = parents_map_.find(child_transform_id.value);
if (found_child_old_parent == parents_map_.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::AddChild: Internal error - Child TransformId "
<< child_transform_id.value << " is not in parents_map.";
return;
}
if (found_child_old_parent->second.second.expired()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::AddChild: Internal error - Child TransformId "
<< child_transform_id.value << " is expired in parents_map.";
return;
}
auto& child = found_child->second;
auto& new_parent = found_parent->second;
new_parent->children.push_back(child);
if (auto old_parent = found_child_old_parent->second.first.lock()) {
old_parent->children.erase(std::remove_if(
old_parent->children.begin(), old_parent->children.end(),
[&child](const auto& transform) { return transform == child; }));
}
found_child_old_parent->second.first = std::weak_ptr(new_parent);
}
void FakeFlatland::RemoveChild(
fuchsia::ui::composition::TransformId parent_transform_id,
fuchsia::ui::composition::TransformId child_transform_id) {
if (parent_transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::RemoveChild: Parent TransformId 0 is invalid.";
return;
}
if (child_transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::RemoveChild: Child TransformId 0 is invalid.";
return;
}
auto found_child =
pending_graph_.transform_map.find(child_transform_id.value);
if (found_child == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::RemoveChild: Child TransformId "
<< child_transform_id.value << " does not exist.";
return;
}
auto found_parent =
pending_graph_.transform_map.find(parent_transform_id.value);
if (found_parent == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::RemoveChild: Parent TransformId "
<< parent_transform_id.value << " does not exist.";
return;
}
auto found_child_parent = parents_map_.find(child_transform_id.value);
if (found_child_parent == parents_map_.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::RemoveChild: Internal error - Child TransformId "
<< child_transform_id.value << " is not in parents_map.";
return;
}
if (found_child_parent->second.second.expired()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::RemoveChild: Internal error - Child TransformId "
<< child_transform_id.value << " is expired in parents_map.";
return;
}
if (found_child_parent->second.first.lock() != found_parent->second) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::RemoveChild: Internal error - Child TransformId "
<< child_transform_id.value << " is not a child of Parent TransformId "
<< parent_transform_id.value << ".";
return;
}
found_child_parent->second.first = std::weak_ptr<FakeTransform>();
found_parent->second->children.erase(std::remove_if(
found_parent->second->children.begin(),
found_parent->second->children.end(),
[child_to_remove = found_child->second](const auto& child) {
return child == child_to_remove;
}));
}
void FakeFlatland::SetContent(
fuchsia::ui::composition::TransformId transform_id,
fuchsia::ui::composition::ContentId content_id) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetContent: TransformId 0 is invalid.";
return;
}
auto found_transform = pending_graph_.transform_map.find(transform_id.value);
if (found_transform == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetContent: TransformId "
<< transform_id.value << " does not exist.";
return;
}
auto& transform = found_transform->second;
FML_CHECK(transform);
if (content_id.value == 0) {
transform->content.reset();
return;
}
auto found_content = pending_graph_.content_map.find(content_id.value);
if (found_content == pending_graph_.content_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetContent: ContentId "
<< content_id.value << " does not exist.";
return;
}
auto& content = found_content->second;
FML_CHECK(content);
transform->content = content;
}
void FakeFlatland::SetRootTransform(
fuchsia::ui::composition::TransformId transform_id) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetRootTransform: TransformId 0 is invalid.";
return;
}
auto found_new_root = pending_graph_.transform_map.find(transform_id.value);
if (found_new_root == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetRootTransform: TransformId "
<< transform_id.value << " does not exist.";
return;
}
pending_graph_.root_transform = found_new_root->second;
}
void FakeFlatland::CreateViewport(
fuchsia::ui::composition::ContentId viewport_id,
fuchsia::ui::views::ViewportCreationToken token,
fuchsia::ui::composition::ViewportProperties properties,
fidl::InterfaceRequest<fuchsia::ui::composition::ChildViewWatcher>
child_view_watcher) {
if (viewport_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::CreateViewport: ContentId 0 is invalid.";
return;
}
if (pending_graph_.content_map.count(viewport_id.value) != 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::CreateViewport: ContentId "
<< viewport_id.value << " is already in use.";
return;
}
auto viewport_token_koids = GetKoids(token.value);
auto [emplaced_viewport, emplace_success] =
pending_graph_.content_map.emplace(
viewport_id.value,
std::make_shared<FakeContent>(FakeViewport{
.id = viewport_id,
.viewport_properties = std::move(properties),
.viewport_token = viewport_token_koids.first,
.child_view_watcher = GetKoids(child_view_watcher).first,
}));
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(emplace_success)
<< "FakeFlatland::CreateViewport: Internal error (content_map) adding "
"viewport with id: "
<< viewport_id.value;
auto [_, emplace_binding_success] = graph_bindings_.view_watchers.emplace(
viewport_token_koids.first,
ChildViewWatcher(std::move(token), std::move(child_view_watcher),
flatland_binding_.dispatcher()));
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(emplace_binding_success)
<< "FakeFlatland::CreateViewport: Internal error (view_watcher) adding "
"viewport with id: "
<< viewport_id.value;
}
void FakeFlatland::CreateImage(
fuchsia::ui::composition::ContentId image_id,
fuchsia::ui::composition::BufferCollectionImportToken import_token,
uint32_t vmo_index,
fuchsia::ui::composition::ImageProperties properties) {
if (image_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::CreateImage: ContentId 0 is invalid.";
return;
}
if (pending_graph_.content_map.count(image_id.value) != 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::CreateImage: ContentId "
<< image_id.value << " is already in use.";
return;
}
auto import_token_koids = GetKoids(import_token);
auto [emplaced_image, emplace_success] = pending_graph_.content_map.emplace(
image_id.value, std::make_shared<FakeContent>(FakeImage{
.id = image_id,
.image_properties = std::move(properties),
.import_token = import_token_koids.first,
.vmo_index = vmo_index,
}));
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(emplace_success)
<< "FakeFlatland::CreateImage: Internal error (content_map) adding "
"image with id: "
<< image_id.value;
auto [_, emplace_binding_success] = graph_bindings_.images.emplace(
import_token_koids.first, ImageBinding{
.import_token = std::move(import_token),
});
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(emplace_binding_success)
<< "FakeFlatland::CreateImage: Internal error (images_binding) adding "
"viewport with id: "
<< image_id.value;
}
void FakeFlatland::SetImageSampleRegion(
fuchsia::ui::composition::ContentId image_id,
fuchsia::math::RectF rect) {
if (image_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetImageSampleRegion: ContentId 0 is invalid.";
return;
}
auto found_content = pending_graph_.content_map.find(image_id.value);
if (found_content == pending_graph_.content_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetImageSampleRegion: ContentId "
<< image_id.value << " does not exist.";
return;
}
auto& content = found_content->second;
FML_CHECK(content);
FakeImage* image = std::get_if<FakeImage>(content.get());
if (image == nullptr) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetImageSampleRegion: ContentId "
<< image_id.value << " is not an Image.";
return;
}
image->sample_region = rect;
}
void FakeFlatland::SetImageDestinationSize(
fuchsia::ui::composition::ContentId image_id,
fuchsia::math::SizeU size) {
if (image_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetImageDestinationSize: ContentId 0 is invalid.";
return;
}
auto found_content = pending_graph_.content_map.find(image_id.value);
if (found_content == pending_graph_.content_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetImageDestinationSize: ContentId "
<< image_id.value << " does not exist.";
return;
}
auto& content = found_content->second;
FML_CHECK(content);
FakeImage* image = std::get_if<FakeImage>(content.get());
if (image == nullptr) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetImageDestinationSize: ContentId "
<< image_id.value << " is not an Image.";
return;
}
image->destination_size = size;
}
void FakeFlatland::SetImageBlendingFunction(
fuchsia::ui::composition::ContentId image_id,
fuchsia::ui::composition::BlendMode blend_mode) {
if (image_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetImageDestinationSize: ContentId 0 is invalid.";
return;
}
auto found_content = pending_graph_.content_map.find(image_id.value);
if (found_content == pending_graph_.content_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetImageDestinationSize: ContentId "
<< image_id.value << " does not exist.";
return;
}
auto& content = found_content->second;
FML_CHECK(content);
FakeImage* image = std::get_if<FakeImage>(content.get());
if (image == nullptr) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetImageDestinationSize: ContentId "
<< image_id.value << " is not an Image.";
return;
}
image->blend_mode = blend_mode;
}
void FakeFlatland::SetViewportProperties(
fuchsia::ui::composition::ContentId viewport_id,
fuchsia::ui::composition::ViewportProperties properties) {
if (viewport_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetViewportProperties: ContentId 0 is invalid.";
return;
}
auto found_content = pending_graph_.content_map.find(viewport_id.value);
if (found_content == pending_graph_.content_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetViewportProperties: ContentId "
<< viewport_id.value << " does not exist.";
return;
}
auto& content = found_content->second;
FML_CHECK(content);
FakeViewport* viewport = std::get_if<FakeViewport>(content.get());
if (viewport == nullptr) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetViewportProperties: ContentId "
<< viewport_id.value << " is not a Viewport.";
return;
}
viewport->viewport_properties = std::move(properties);
}
void FakeFlatland::ReleaseTransform(
fuchsia::ui::composition::TransformId transform_id) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::ReleaseTransform: TransformId 0 is invalid.";
return;
}
size_t erased = pending_graph_.transform_map.erase(transform_id.value);
if (erased == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::ReleaseTransform: TransformId "
<< transform_id.value << " does not exist.";
}
size_t parents_erased = parents_map_.erase(transform_id.value);
if (parents_erased == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::ReleaseTransform: TransformId "
<< transform_id.value << " does not exist in parents_map.";
}
}
void FakeFlatland::ReleaseViewport(
fuchsia::ui::composition::ContentId viewport_id,
ReleaseViewportCallback callback) {
if (viewport_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::ReleaseViewport: ContentId 0 is invalid.";
return;
}
auto found_content = pending_graph_.content_map.find(viewport_id.value);
if (found_content == pending_graph_.content_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::ReleaseViewport: ContentId "
<< viewport_id.value << " does not exist.";
return;
}
auto& content = found_content->second;
FML_CHECK(content);
FakeViewport* viewport = std::get_if<FakeViewport>(content.get());
if (viewport == nullptr) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::ReleaseViewport: ContentId "
<< viewport_id.value << " is not a Viewport.";
return;
}
pending_graph_.content_map.erase(found_content);
}
void FakeFlatland::ReleaseImage(fuchsia::ui::composition::ContentId image_id) {
if (image_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::ReleaseImage: ContentId 0 is invalid.";
return;
}
auto found_content = pending_graph_.content_map.find(image_id.value);
if (found_content == pending_graph_.content_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::ReleaseImage: ContentId "
<< image_id.value << " does not exist.";
return;
}
auto& content = found_content->second;
FML_CHECK(content);
FakeImage* image = std::get_if<FakeImage>(content.get());
if (image == nullptr) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::ReleaseImage: ContentId "
<< image_id.value << " is not a Viewport.";
return;
}
pending_graph_.content_map.erase(found_content);
}
void FakeFlatland::SetHitRegions(
fuchsia::ui::composition::TransformId transform_id,
std::vector<fuchsia::ui::composition::HitRegion> regions) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetTranslation: TransformId 0 is invalid.";
return;
}
auto found_transform = pending_graph_.transform_map.find(transform_id.value);
if (found_transform == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetTranslation: TransformId "
<< transform_id.value << " does not exist.";
return;
}
auto& transform = found_transform->second;
FML_CHECK(transform);
transform->hit_regions = std::move(regions);
}
void FakeFlatland::SetInfiniteHitRegion(
fuchsia::ui::composition::TransformId transform_id,
fuchsia::ui::composition::HitTestInteraction hit_test) {
if (transform_id.value == 0) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false)
<< "FakeFlatland::SetTranslation: TransformId 0 is invalid.";
return;
}
auto found_transform = pending_graph_.transform_map.find(transform_id.value);
if (found_transform == pending_graph_.transform_map.end()) {
// TODO(fxb/85619): Raise a FlatlandError here
FML_CHECK(false) << "FakeFlatland::SetTranslation: TransformId "
<< transform_id.value << " does not exist.";
return;
}
auto& transform = found_transform->second;
ZX_ASSERT(transform);
transform->hit_regions = {kInfiniteHitRegion};
}
void FakeFlatland::Clear() {
parents_map_.clear();
pending_graph_.Clear();
}
void FakeFlatland::SetDebugName(std::string debug_name) {
debug_name_ = std::move(debug_name);
}
FakeFlatland::ParentViewportWatcher::ParentViewportWatcher(
fuchsia::ui::views::ViewCreationToken view_token,
fuchsia::ui::views::ViewIdentityOnCreation view_identity,
fuchsia::ui::composition::ViewBoundProtocols view_protocols,
fidl::InterfaceRequest<fuchsia::ui::composition::ParentViewportWatcher>
parent_viewport_watcher,
async_dispatcher_t* dispatcher)
: view_token(std::move(view_token)),
view_identity(std::move(view_identity)),
view_protocols(std::move(view_protocols)),
parent_viewport_watcher(this,
std::move(parent_viewport_watcher),
dispatcher) {}
FakeFlatland::ParentViewportWatcher::ParentViewportWatcher(
ParentViewportWatcher&& other)
: view_token(std::move(other.view_token)),
view_identity(std::move(other.view_identity)),
view_protocols(std::move(other.view_protocols)),
parent_viewport_watcher(this,
other.parent_viewport_watcher.Unbind(),
other.parent_viewport_watcher.dispatcher()) {}
FakeFlatland::ParentViewportWatcher::~ParentViewportWatcher() = default;
void FakeFlatland::ParentViewportWatcher::NotImplemented_(
const std::string& name) {
FML_LOG(FATAL) << "FakeFlatland::ParentViewportWatcher does not implement "
<< name;
}
void FakeFlatland::ParentViewportWatcher::GetLayout(
GetLayoutCallback callback) {
NotImplemented_("GetLayout");
}
void FakeFlatland::ParentViewportWatcher::GetStatus(
GetStatusCallback callback) {
NotImplemented_("GetStatus");
}
FakeFlatland::ChildViewWatcher::ChildViewWatcher(
fuchsia::ui::views::ViewportCreationToken viewport_token,
fidl::InterfaceRequest<fuchsia::ui::composition::ChildViewWatcher>
child_view_watcher,
async_dispatcher_t* dispatcher)
: viewport_token(std::move(viewport_token)),
child_view_watcher(this, std::move(child_view_watcher), dispatcher) {}
FakeFlatland::ChildViewWatcher::ChildViewWatcher(ChildViewWatcher&& other)
: viewport_token(std::move(other.viewport_token)),
child_view_watcher(this,
other.child_view_watcher.Unbind(),
other.child_view_watcher.dispatcher()) {}
FakeFlatland::ChildViewWatcher::~ChildViewWatcher() = default;
void FakeFlatland::ChildViewWatcher::NotImplemented_(const std::string& name) {
FML_LOG(FATAL) << "FakeFlatland::ChildViewWatcher does not implement "
<< name;
}
void FakeFlatland::ChildViewWatcher::GetStatus(GetStatusCallback callback) {
NotImplemented_("GetStatus");
}
} // namespace flutter_runner::testing
| engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.cc",
"repo_id": "engine",
"token_count": 13925
} | 404 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
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") {
testonly = true
package_name = "text-input-view"
sources = [ "text_input_view.dart" ]
deps = [ "//flutter/shell/platform/fuchsia/dart:args" ]
}
flutter_component("component") {
testonly = true
component_name = "text-input-view"
manifest = rebase_path("meta/text-input-view.cml")
main_package = "text-input-view"
main_dart = "text_input_view.dart"
deps = [ ":lib" ]
}
fuchsia_package("package") {
testonly = true
package_name = "text-input-view"
deps = [ ":component" ]
}
| engine/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/BUILD.gn/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/BUILD.gn",
"repo_id": "engine",
"token_count": 375
} | 405 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_fuchsia)
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
source_set("check_view") {
sources = [
"check_view.cc",
"check_view.h",
]
deps = [
"${fuchsia_sdk}/fidl/fuchsia.ui.observation.geometry",
"${fuchsia_sdk}/pkg/zx",
"//flutter/fml",
]
}
source_set("screenshot") {
sources = [
"screenshot.cc",
"screenshot.h",
]
deps = [
"${fuchsia_sdk}/fidl/fuchsia.logger",
"${fuchsia_sdk}/pkg/zx",
"//flutter/fml",
]
}
source_set("portable_ui_test") {
testonly = true
sources = [
"portable_ui_test.cc",
"portable_ui_test.h",
]
deps = [
":check_view",
"${fuchsia_sdk}/fidl/fuchsia.inspect",
"${fuchsia_sdk}/fidl/fuchsia.logger",
"${fuchsia_sdk}/fidl/fuchsia.tracing.provider",
"${fuchsia_sdk}/fidl/fuchsia.ui.app",
"${fuchsia_sdk}/fidl/fuchsia.ui.composition",
"${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton",
"${fuchsia_sdk}/fidl/fuchsia.ui.input",
"${fuchsia_sdk}/fidl/fuchsia.ui.observation.geometry",
"${fuchsia_sdk}/fidl/fuchsia.ui.test.input",
"${fuchsia_sdk}/fidl/fuchsia.ui.test.scene",
"${fuchsia_sdk}/pkg/async-loop-testing",
"${fuchsia_sdk}/pkg/sys_component_cpp_testing",
"//flutter/fml",
]
}
| engine/shell/platform/fuchsia/flutter/tests/integration/utils/BUILD.gn/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/utils/BUILD.gn",
"repo_id": "engine",
"token_count": 703
} | 406 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Text editing functionality delegated from |PlatformView|.
/// See |TextDelegate| for details.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TEXT_DELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TEXT_DELEGATE_H_
#include <memory>
#include <fuchsia/ui/input/cpp/fidl.h>
#include <fuchsia/ui/input3/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/fidl/cpp/binding.h>
#include "flutter/lib/ui/window/platform_message.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/platform/fuchsia/flutter/keyboard.h"
#include "logging.h"
namespace flutter_runner {
/// The channel name used for text editing platofrm messages.
constexpr char kTextInputChannel[] = "flutter/textinput";
/// The channel name used for key event platform messages.
constexpr char kKeyEventChannel[] = "flutter/keyevent";
/// TextDelegate handles keyboard inpout and text editing.
///
/// It mediates between Fuchsia's input and Flutter's platform messages. When it
/// is initialized, it contacts `fuchsia.ui.input.Keyboard` to register itself
/// as listener of key events.
///
/// Whenever a text editing request comes from the
/// Flutter app, it will activate Fuchsia's input method editor, and will send
/// text edit actions coming from the Fuchsia platform over to the Flutter app,
/// by converting FIDL messages (`fuchsia.ui.input.InputMethodEditorClient`
/// calls) to appropriate text editing Flutter platform messages.
///
/// For details refer to:
/// * Flutter side:
/// https://api.flutter.dev/javadoc/io/flutter/embedding/engine/systemchannels/TextInputChannel.html
/// * Fuchsia side: https://fuchsia.dev/reference/fidl/fuchsia.ui.input
class TextDelegate : public fuchsia::ui::input3::KeyboardListener,
public fuchsia::ui::input::InputMethodEditorClient {
public:
/// Creates a new TextDelegate.
///
/// Args:
/// view_ref: the reference to the app's view. Required for registration
/// with Fuchsia.
/// ime_service: a handle to Fuchsia's input method service.
/// keyboard: the keyboard listener, gets notified of key presses and
/// releases.
/// dispatch_callback: a function used to send a Flutter platform message.
TextDelegate(fuchsia::ui::views::ViewRef view_ref,
fuchsia::ui::input::ImeServiceHandle ime_service,
fuchsia::ui::input3::KeyboardHandle keyboard,
std::function<void(std::unique_ptr<flutter::PlatformMessage>)>
dispatch_callback);
/// |fuchsia.ui.input3.KeyboardListener|
/// Called by the embedder every time there is a key event to process.
void OnKeyEvent(fuchsia::ui::input3::KeyEvent key_event,
fuchsia::ui::input3::KeyboardListener::OnKeyEventCallback
callback) override;
/// |fuchsia::ui::input::InputMethodEditorClient|
/// Called by the embedder every time the edit state is updated.
void DidUpdateState(
fuchsia::ui::input::TextInputState state,
std::unique_ptr<fuchsia::ui::input::InputEvent> event) override;
/// |fuchsia::ui::input::InputMethodEditorClient|
/// Called by the embedder when the action key is pressed, and the requested
/// action is supplied to Flutter.
void OnAction(fuchsia::ui::input::InputMethodAction action) override;
/// Gets a new input method editor from the input connection. Run when both
/// Scenic has focus and Flutter has requested input with setClient.
void ActivateIme();
/// Detaches the input method editor connection, ending the edit session and
/// closing the onscreen keyboard. Call when input is no longer desired,
/// either because Scenic says we lost focus or when Flutter no longer has a
/// text field focused.
void DeactivateIme();
/// Channel handler for kTextInputChannel
bool HandleFlutterTextInputChannelPlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message);
/// Returns true if there is a text state (i.e. if some text editing is in
/// progress).
bool HasTextState() { return last_text_state_.has_value(); }
private:
// Activates the input method editor, assigning |action| to the "enter" key.
// This action will be reported by |OnAction| above when the "enter" key is
// pressed. Note that in the case of multi-line text editors, |OnAction| will
// never be called: instead, the text editor will insert a newline into the
// edited text.
void ActivateIme(fuchsia::ui::input::InputMethodAction action);
// Converts Fuchsia platform key codes into Flutter key codes.
Keyboard keyboard_translator_;
// A callback for sending a single Flutter platform message.
std::function<void(std::unique_ptr<flutter::PlatformMessage>)>
dispatch_callback_;
// TextDelegate server-side binding. Methods called when the text edit state
// is updated.
fidl::Binding<fuchsia::ui::input::InputMethodEditorClient> ime_client_;
// An interface for interacting with a text input control.
fuchsia::ui::input::InputMethodEditorPtr ime_;
// An interface for requesting the InputMethodEditor.
fuchsia::ui::input::ImeServicePtr text_sync_service_;
// The locally-unique identifier of the text input currently in use. Flutter
// usually uses only one at a time.
int current_text_input_client_ = 0;
// TextDelegate server side binding. Methods called when a key is pressed.
fidl::Binding<fuchsia::ui::input3::KeyboardListener>
keyboard_listener_binding_;
// The client-side stub for calling the Keyboard protocol.
fuchsia::ui::input3::KeyboardPtr keyboard_;
// last_text_state_ is the last state of the text input as reported by the IME
// or initialized by Flutter. We set it to null if Flutter doesn't want any
// input, since then there is no text input state at all.
// If nullptr, then no editing is in progress.
std::optional<fuchsia::ui::input::TextInputState> last_text_state_;
// The action that Flutter expects to happen when the user presses the "enter"
// key. For example, it could be `InputMethodAction::DONE` which would cause
// text editing to stop and the current text to be accepted.
// If set to std::nullopt, then no editing is in progress.
std::optional<fuchsia::ui::input::InputMethodAction> requested_text_action_;
FML_DISALLOW_COPY_AND_ASSIGN(TextDelegate);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TEXT_DELEGATE_H_
| engine/shell/platform/fuchsia/flutter/text_delegate.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/text_delegate.h",
"repo_id": "engine",
"token_count": 2074
} | 407 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_fuchsia)
import("//flutter/common/config.gni")
import("//flutter/testing/testing.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
config("utils_config") {
include_dirs = [ "../../.." ]
}
template("make_utils") {
source_set(target_name) {
sources = [
"$target_gen_dir/build_info.cc",
"build_info.h",
"files.cc",
"files.h",
"handle_exception.cc",
"handle_exception.h",
"inlines.h",
"logging.h",
"mapped_resource.cc",
"mapped_resource.h",
"root_inspect_node.cc",
"root_inspect_node.h",
"tempfs.cc",
"tempfs.h",
"vmo.cc",
"vmo.h",
"vmservice_object.cc",
"vmservice_object.h",
]
deps = invoker.deps + [
":generate_build_info_cc_file",
"${fuchsia_sdk}/fidl/fuchsia.feedback",
"${fuchsia_sdk}/fidl/fuchsia.mem",
"${fuchsia_sdk}/pkg/async-loop",
"${fuchsia_sdk}/pkg/async-loop-cpp",
"${fuchsia_sdk}/pkg/async-loop-default",
"${fuchsia_sdk}/pkg/fdio",
"${fuchsia_sdk}/pkg/sys_cpp",
"${fuchsia_sdk}/pkg/inspect_component_cpp",
"${fuchsia_sdk}/pkg/trace",
"${fuchsia_sdk}/pkg/vfs_cpp",
"${fuchsia_sdk}/pkg/zx",
"//flutter/fml",
"//flutter/third_party/tonic",
]
public_configs = [ ":utils_config" ]
}
}
action("generate_build_info_cc_file") {
inputs = [
"build_info_in.cc",
"//flutter/.git/logs/HEAD",
"//fuchsia/sdk/$host_os/meta/manifest.json",
"$dart_src/.git/logs/HEAD",
]
outputs = [ "$target_gen_dir/build_info.cc" ]
script = "//flutter/tools/fuchsia/make_build_info.py"
args = [
"--input",
rebase_path("build_info_in.cc", root_build_dir),
"--output",
rebase_path(outputs[0], root_build_dir),
"--buildroot",
rebase_path("//", root_build_dir),
]
}
make_utils("utils") {
deps = [ "$dart_src/runtime/bin:elf_loader" ]
}
test_fixtures("utils_fixtures") {
fixtures = []
}
executable("dart_utils_unittests") {
testonly = true
output_name = "dart_utils_unittests"
sources = [ "build_info_unittests.cc" ]
libs = [
# This is needed for //flutter/third_party/googletest for linking zircon
# symbols.
"${fuchsia_arch_root}/sysroot/lib/libzircon.so",
]
deps = [
":utils",
":utils_fixtures",
"$dart_src/runtime:libdart_jit",
"$dart_src/runtime/bin:dart_io_api",
"${fuchsia_sdk}/pkg/inspect_component_cpp",
"${fuchsia_sdk}/pkg/sys_cpp",
"//flutter/testing",
]
}
make_utils("utils_product") {
deps = [ "$dart_src/runtime/bin:elf_loader_product" ]
}
| engine/shell/platform/fuchsia/runtime/dart/utils/BUILD.gn/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/BUILD.gn",
"repo_id": "engine",
"token_count": 1429
} | 408 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_TEMPFS_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_TEMPFS_H_
#include <lib/fdio/namespace.h>
namespace dart_utils {
// Take the virtual filesystem mapped into the process-wide namespace for /tmp,
// and map it to /tmp in the given namespace.
void BindTemp(fdio_ns_t* ns);
} // namespace dart_utils
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_TEMPFS_H_
| engine/shell/platform/fuchsia/runtime/dart/utils/tempfs.h/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/tempfs.h",
"repo_id": "engine",
"token_count": 229
} | 409 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_GLFW_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_GLFW_H_
#include <flutter_glfw.h>
#include <memory>
#include "flutter_window.h"
#include "plugin_registrar.h"
namespace flutter {
// An extension to PluginRegistrar providing access to GLFW-shell-specific
// functionality.
class PluginRegistrarGlfw : public PluginRegistrar {
public:
// Creates a new PluginRegistrar. |core_registrar| and the messenger it
// provides must remain valid as long as this object exists.
explicit PluginRegistrarGlfw(FlutterDesktopPluginRegistrarRef core_registrar)
: PluginRegistrar(core_registrar) {
window_ = std::make_unique<FlutterWindow>(
FlutterDesktopPluginRegistrarGetWindow(core_registrar));
}
virtual ~PluginRegistrarGlfw() {
// Must be the first call.
ClearPlugins();
// Explicitly cleared to facilitate destruction order testing.
window_.reset();
}
// Prevent copying.
PluginRegistrarGlfw(PluginRegistrarGlfw const&) = delete;
PluginRegistrarGlfw& operator=(PluginRegistrarGlfw const&) = delete;
FlutterWindow* window() { return window_.get(); }
// Enables input blocking on the given channel name.
//
// If set, then the parent window should disable input callbacks
// while waiting for the handler for messages on that channel to run.
void EnableInputBlockingForChannel(const std::string& channel) {
FlutterDesktopPluginRegistrarEnableInputBlocking(registrar(),
channel.c_str());
}
private:
// The owned FlutterWindow, if any.
std::unique_ptr<FlutterWindow> window_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_GLFW_H_
| engine/shell/platform/glfw/client_wrapper/include/flutter/plugin_registrar_glfw.h/0 | {
"file_path": "engine/shell/platform/glfw/client_wrapper/include/flutter/plugin_registrar_glfw.h",
"repo_id": "engine",
"token_count": 720
} | 410 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_GLFW_PLATFORM_HANDLER_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_PLATFORM_HANDLER_H_
#include <GLFW/glfw3.h>
#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/glfw/public/flutter_glfw.h"
#include "rapidjson/document.h"
namespace flutter {
// Handler for internal system channels.
class PlatformHandler {
public:
explicit PlatformHandler(flutter::BinaryMessenger* messenger,
GLFWwindow* window);
private:
// 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_;
// A reference to the GLFW window, if any. Null in headless mode.
GLFWwindow* window_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_PLATFORM_HANDLER_H_
| engine/shell/platform/glfw/platform_handler.h/0 | {
"file_path": "engine/shell/platform/glfw/platform_handler.h",
"repo_id": "engine",
"token_count": 464
} | 411 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_BACKING_STORE_PROVIDER_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_BACKING_STORE_PROVIDER_H_
#include <gtk/gtk.h>
#include <cstdint>
G_BEGIN_DECLS
G_DECLARE_FINAL_TYPE(FlBackingStoreProvider,
fl_backing_store_provider,
FL,
BACKING_STORE_PROVIDER,
GObject)
/**
* FlBackingStoreProvider:
*
* #FlBackingStoreProvider creates framebuffers and their backing textures
* for embedder compositor.
*/
/**
* fl_backing_store_provider_new:
* @width: width of texture.
* @height: height of texture.
*
* Creates a new frame buffer. fl_renderer_make_current() must be called
* first.
*
* Returns: a new #FlBackingStoreProvider.
*/
FlBackingStoreProvider* fl_backing_store_provider_new(int width, int height);
/**
* fl_backing_store_provider_get_gl_framebuffer_id:
* @provider: an #FlBackingStoreProvider.
*
* Gets created framebuffer id.
*
* Returns: gl framebuffer id, 0 if creation failed.
*/
uint32_t fl_backing_store_provider_get_gl_framebuffer_id(
FlBackingStoreProvider* provider);
/**
* fl_backing_store_provider_get_gl_texture_id:
* @provider: an #FlBackingStoreProvider.
*
* Gets created texture id.
*
* Returns: gl texture id, 0 if creation failed.
*/
uint32_t fl_backing_store_provider_get_gl_texture_id(
FlBackingStoreProvider* provider);
/**
* fl_backing_store_provider_get_gl_target:
* @provider: an #FlBackingStoreProvider.
*
* Gets target texture (example GL_TEXTURE_2D or GL_TEXTURE_RECTANGLE).
*
* Returns: target texture.
*/
uint32_t fl_backing_store_provider_get_gl_target(
FlBackingStoreProvider* provider);
/**
* fl_backing_store_provider_get_gl_format:
* @provider: an #FlBackingStoreProvider.
*
* Gets texture format (example GL_RGBA8).
*
* Returns: texture format.
*/
uint32_t fl_backing_store_provider_get_gl_format(
FlBackingStoreProvider* provider);
/**
* fl_backing_store_provider_get_geometry:
* @provider: an #FlBackingStoreProvider.
*
* Gets geometry of framebuffer.
*
* Returns: geometry of backing store.
*/
GdkRectangle fl_backing_store_provider_get_geometry(
FlBackingStoreProvider* provider);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_BACKING_STORE_PROVIDER_H_
| engine/shell/platform/linux/fl_backing_store_provider.h/0 | {
"file_path": "engine/shell/platform/linux/fl_backing_store_provider.h",
"repo_id": "engine",
"token_count": 932
} | 412 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/fl_gnome_settings.h"
#include <gio/gio.h>
#include <glib.h>
static constexpr char kDesktopInterfaceSchema[] = "org.gnome.desktop.interface";
static constexpr char kDesktopTextScalingFactorKey[] = "text-scaling-factor";
static constexpr char kDesktopClockFormatKey[] = "clock-format";
static constexpr char kDesktopGtkThemeKey[] = "gtk-theme";
static constexpr char kClockFormat12Hour[] = "12h";
static constexpr char kGtkThemeDarkSuffix[] = "-dark";
static constexpr char kInterfaceSettings[] = "interface-settings";
struct _FlGnomeSettings {
GObject parent_instance;
GSettings* interface_settings;
};
enum { kProp0, kPropInterfaceSettings, kPropLast };
static void fl_gnome_settings_iface_init(FlSettingsInterface* iface);
G_DEFINE_TYPE_WITH_CODE(FlGnomeSettings,
fl_gnome_settings,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_settings_get_type(),
fl_gnome_settings_iface_init))
static FlClockFormat fl_gnome_settings_get_clock_format(FlSettings* settings) {
FlGnomeSettings* self = FL_GNOME_SETTINGS(settings);
FlClockFormat clock_format = FL_CLOCK_FORMAT_24H;
if (self->interface_settings != nullptr) {
g_autofree gchar* value =
g_settings_get_string(self->interface_settings, kDesktopClockFormatKey);
if (g_strcmp0(value, kClockFormat12Hour) == 0) {
clock_format = FL_CLOCK_FORMAT_12H;
}
}
return clock_format;
}
static FlColorScheme fl_gnome_settings_get_color_scheme(FlSettings* settings) {
FlGnomeSettings* self = FL_GNOME_SETTINGS(settings);
FlColorScheme color_scheme = FL_COLOR_SCHEME_LIGHT;
if (self->interface_settings != nullptr) {
// check whether org.gnome.desktop.interface.gtk-theme ends with "-dark"
g_autofree gchar* value =
g_settings_get_string(self->interface_settings, kDesktopGtkThemeKey);
if (g_str_has_suffix(value, kGtkThemeDarkSuffix)) {
color_scheme = FL_COLOR_SCHEME_DARK;
}
}
return color_scheme;
}
static gboolean fl_gnome_settings_get_enable_animations(FlSettings* settings) {
return true;
}
static gboolean fl_gnome_settings_get_high_contrast(FlSettings* settings) {
return false;
}
static gdouble fl_gnome_settings_get_text_scaling_factor(FlSettings* settings) {
FlGnomeSettings* self = FL_GNOME_SETTINGS(settings);
gdouble scaling_factor = 1.0;
if (self->interface_settings != nullptr) {
scaling_factor = g_settings_get_double(self->interface_settings,
kDesktopTextScalingFactorKey);
}
return scaling_factor;
}
static void fl_gnome_settings_set_interface_settings(FlGnomeSettings* self,
GSettings* settings) {
g_return_if_fail(G_IS_SETTINGS(settings));
g_signal_connect_object(settings, "changed::clock-format",
G_CALLBACK(fl_settings_emit_changed), self,
G_CONNECT_SWAPPED);
g_signal_connect_object(settings, "changed::gtk-theme",
G_CALLBACK(fl_settings_emit_changed), self,
G_CONNECT_SWAPPED);
g_signal_connect_object(settings, "changed::text-scaling-factor",
G_CALLBACK(fl_settings_emit_changed), self,
G_CONNECT_SWAPPED);
self->interface_settings = G_SETTINGS(g_object_ref(settings));
}
static void fl_gnome_settings_set_property(GObject* object,
guint prop_id,
const GValue* value,
GParamSpec* pspec) {
FlGnomeSettings* self = FL_GNOME_SETTINGS(object);
switch (prop_id) {
case kPropInterfaceSettings:
fl_gnome_settings_set_interface_settings(
self, G_SETTINGS(g_value_get_object(value)));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void fl_gnome_settings_dispose(GObject* object) {
FlGnomeSettings* self = FL_GNOME_SETTINGS(object);
g_clear_object(&self->interface_settings);
G_OBJECT_CLASS(fl_gnome_settings_parent_class)->dispose(object);
}
static void fl_gnome_settings_class_init(FlGnomeSettingsClass* klass) {
GObjectClass* object_class = G_OBJECT_CLASS(klass);
object_class->dispose = fl_gnome_settings_dispose;
object_class->set_property = fl_gnome_settings_set_property;
g_object_class_install_property(
object_class, kPropInterfaceSettings,
g_param_spec_object(
kInterfaceSettings, kInterfaceSettings, kDesktopInterfaceSchema,
g_settings_get_type(),
static_cast<GParamFlags>(G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
G_PARAM_STATIC_STRINGS)));
}
static void fl_gnome_settings_iface_init(FlSettingsInterface* iface) {
iface->get_clock_format = fl_gnome_settings_get_clock_format;
iface->get_color_scheme = fl_gnome_settings_get_color_scheme;
iface->get_enable_animations = fl_gnome_settings_get_enable_animations;
iface->get_high_contrast = fl_gnome_settings_get_high_contrast;
iface->get_text_scaling_factor = fl_gnome_settings_get_text_scaling_factor;
}
static void fl_gnome_settings_init(FlGnomeSettings* self) {}
static GSettings* create_settings(const gchar* schema_id) {
GSettings* settings = nullptr;
GSettingsSchemaSource* source = g_settings_schema_source_get_default();
if (source != nullptr) {
g_autoptr(GSettingsSchema) schema =
g_settings_schema_source_lookup(source, schema_id, TRUE);
if (schema != nullptr) {
settings = g_settings_new_full(schema, nullptr, nullptr);
}
}
return settings;
}
FlSettings* fl_gnome_settings_new() {
g_autoptr(GSettings) interface_settings =
create_settings(kDesktopInterfaceSchema);
return FL_SETTINGS(g_object_new(fl_gnome_settings_get_type(),
kInterfaceSettings, interface_settings,
nullptr));
}
| engine/shell/platform/linux/fl_gnome_settings.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_gnome_settings.cc",
"repo_id": "engine",
"token_count": 2670
} | 413 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/fl_key_responder.h"
G_DEFINE_INTERFACE(FlKeyResponder, fl_key_responder, G_TYPE_OBJECT)
static void fl_key_responder_default_init(FlKeyResponderInterface* iface) {}
void fl_key_responder_handle_event(FlKeyResponder* self,
FlKeyEvent* event,
FlKeyResponderAsyncCallback callback,
gpointer user_data,
uint64_t specified_logical_key) {
g_return_if_fail(FL_IS_KEY_RESPONDER(self));
g_return_if_fail(event != nullptr);
g_return_if_fail(callback != nullptr);
FL_KEY_RESPONDER_GET_IFACE(self)->handle_event(
self, event, specified_logical_key, callback, user_data);
}
| engine/shell/platform/linux/fl_key_responder.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_key_responder.cc",
"repo_id": "engine",
"token_count": 412
} | 414 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h"
#include <cstring>
#include "flutter/shell/platform/linux/fl_method_codec_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_message_codec.h"
#include "gtest/gtest.h"
G_DECLARE_FINAL_TYPE(FlTestMethodCodec,
fl_test_method_codec,
FL,
TEST_METHOD_CODEC,
FlMethodCodec)
// Implement the FlMethodCodec API for the following tests to check it works as
// expected.
struct _FlTestMethodCodec {
FlMethodCodec parent_instance;
};
G_DEFINE_TYPE(FlTestMethodCodec,
fl_test_method_codec,
fl_method_codec_get_type())
// Helper function to convert binary data to text.
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);
}
// Helper function to convert text to binary data.
static GBytes* text_to_message(const gchar* text) {
return g_bytes_new(text, strlen(text));
}
// Implements FlMethodCodec::encode_method_call.
static GBytes* fl_test_codec_encode_method_call(FlMethodCodec* codec,
const gchar* name,
FlValue* args,
GError** error) {
EXPECT_TRUE(FL_IS_TEST_METHOD_CODEC(codec));
g_autofree gchar* text = nullptr;
if (args == nullptr || fl_value_get_type(args) == FL_VALUE_TYPE_NULL) {
text = g_strdup_printf("%s()", name);
} else if (fl_value_get_type(args) == FL_VALUE_TYPE_INT) {
text = g_strdup_printf("%s(%" G_GINT64_FORMAT ")", name,
fl_value_get_int(args));
} else {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"ERROR");
return nullptr;
}
return text_to_message(text);
}
// Implements FlMethodCodec::decode_method_call.
static gboolean fl_test_codec_decode_method_call(FlMethodCodec* codec,
GBytes* message,
gchar** name,
FlValue** args,
GError** error) {
EXPECT_TRUE(FL_IS_TEST_METHOD_CODEC(codec));
g_autofree gchar* m = message_to_text(message);
if (strcmp(m, "error") == 0) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"ERROR");
return FALSE;
} else {
*name = g_strdup(m);
*args = fl_value_new_null();
return TRUE;
}
}
// Implements FlMethodCodec::encode_success_envelope.
static GBytes* fl_test_codec_encode_success_envelope(FlMethodCodec* codec,
FlValue* result,
GError** error) {
EXPECT_TRUE(FL_IS_TEST_METHOD_CODEC(codec));
g_autofree gchar* text = nullptr;
if (result == nullptr || fl_value_get_type(result) == FL_VALUE_TYPE_NULL) {
text = g_strdup("(null)");
} else if (fl_value_get_type(result) == FL_VALUE_TYPE_INT) {
text = g_strdup_printf("%" G_GINT64_FORMAT, fl_value_get_int(result));
} else {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"ERROR");
return nullptr;
}
return text_to_message(text);
}
// Implements FlMethodCodec::encode_error_envelope.
static GBytes* fl_test_codec_encode_error_envelope(FlMethodCodec* codec,
const gchar* code,
const gchar* message,
FlValue* details,
GError** error) {
EXPECT_TRUE(FL_IS_TEST_METHOD_CODEC(codec));
if (details != nullptr && fl_value_get_type(details) != FL_VALUE_TYPE_INT) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"ERROR");
return nullptr;
}
g_autofree gchar* text = nullptr;
if (message == nullptr) {
if (details == nullptr ||
fl_value_get_type(details) == FL_VALUE_TYPE_NULL) {
text = g_strdup_printf("Error_%s()", code);
} else {
text = g_strdup_printf("Error_%s(%" G_GINT64_FORMAT ")", code,
fl_value_get_int(details));
}
} else {
if (details == nullptr ||
fl_value_get_type(details) == FL_VALUE_TYPE_NULL) {
text = g_strdup_printf("Error_%s(%s)", code, message);
} else {
text = g_strdup_printf("Error_%s(%s,%" G_GINT64_FORMAT ")", code, message,
fl_value_get_int(details));
}
}
return text_to_message(text);
}
// Implements FlMethodCodec::decode_response.
static FlMethodResponse* fl_test_codec_decode_response(FlMethodCodec* codec,
GBytes* message,
GError** error) {
EXPECT_TRUE(FL_IS_TEST_METHOD_CODEC(codec));
g_autofree gchar* m = message_to_text(message);
if (strcmp(m, "codec-error") == 0) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"ERROR");
return nullptr;
} else if (strcmp(m, "error") == 0) {
g_autoptr(FlValue) details = fl_value_new_int(42);
return FL_METHOD_RESPONSE(
fl_method_error_response_new("code", "message", details));
} else {
g_autoptr(FlValue) result = fl_value_new_string(m);
return FL_METHOD_RESPONSE(fl_method_success_response_new(result));
}
}
static void fl_test_method_codec_class_init(FlTestMethodCodecClass* klass) {
FL_METHOD_CODEC_CLASS(klass)->encode_method_call =
fl_test_codec_encode_method_call;
FL_METHOD_CODEC_CLASS(klass)->decode_method_call =
fl_test_codec_decode_method_call;
FL_METHOD_CODEC_CLASS(klass)->encode_success_envelope =
fl_test_codec_encode_success_envelope;
FL_METHOD_CODEC_CLASS(klass)->encode_error_envelope =
fl_test_codec_encode_error_envelope;
FL_METHOD_CODEC_CLASS(klass)->decode_response = fl_test_codec_decode_response;
}
static void fl_test_method_codec_init(FlTestMethodCodec* self) {}
static FlTestMethodCodec* fl_test_method_codec_new() {
return FL_TEST_METHOD_CODEC(
g_object_new(fl_test_method_codec_get_type(), nullptr));
}
TEST(FlMethodCodecTest, EncodeMethodCall) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_method_call(
FL_METHOD_CODEC(codec), "foo", nullptr, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(message, nullptr);
g_autofree gchar* message_text = message_to_text(message);
EXPECT_STREQ(message_text, "foo()");
}
TEST(FlMethodCodecTest, EncodeMethodCallEmptyName) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_method_call(
FL_METHOD_CODEC(codec), "", nullptr, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(message, nullptr);
g_autofree gchar* message_text = message_to_text(message);
EXPECT_STREQ(message_text, "()");
}
TEST(FlMethodCodecTest, EncodeMethodCallArgs) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(FlValue) args = fl_value_new_int(42);
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_method_call(
FL_METHOD_CODEC(codec), "foo", args, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(message, nullptr);
g_autofree gchar* message_text = message_to_text(message);
EXPECT_STREQ(message_text, "foo(42)");
}
TEST(FlMethodCodecTest, EncodeMethodCallError) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(FlValue) args = fl_value_new_bool(FALSE);
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_method_call(
FL_METHOD_CODEC(codec), "foo", args, &error);
EXPECT_EQ(message, nullptr);
EXPECT_TRUE(g_error_matches(error, FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED));
}
TEST(FlMethodCodecTest, DecodeMethodCall) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(GBytes) message = text_to_message("foo");
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
g_autoptr(GError) error = nullptr;
gboolean result = fl_method_codec_decode_method_call(
FL_METHOD_CODEC(codec), message, &name, &args, &error);
EXPECT_EQ(error, nullptr);
EXPECT_TRUE(result);
EXPECT_STREQ(name, "foo");
ASSERT_EQ(fl_value_get_type(args), FL_VALUE_TYPE_NULL);
}
TEST(FlMethodCodecTest, EncodeSuccessEnvelope) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(FlValue) result = fl_value_new_int(42);
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_success_envelope(
FL_METHOD_CODEC(codec), result, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(message, nullptr);
g_autofree gchar* message_text = message_to_text(message);
EXPECT_STREQ(message_text, "42");
}
TEST(FlMethodCodecTest, EncodeSuccessEnvelopeEmpty) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_success_envelope(
FL_METHOD_CODEC(codec), nullptr, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(message, nullptr);
g_autofree gchar* message_text = message_to_text(message);
EXPECT_STREQ(message_text, "(null)");
}
TEST(FlMethodCodecTest, EncodeSuccessEnvelopeError) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(FlValue) result = fl_value_new_string("X");
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_success_envelope(
FL_METHOD_CODEC(codec), result, &error);
EXPECT_EQ(message, nullptr);
EXPECT_TRUE(g_error_matches(error, FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED));
}
TEST(FlMethodCodecTest, EncodeErrorEnvelopeNoMessageOrDetails) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_error_envelope(
FL_METHOD_CODEC(codec), "code", nullptr, nullptr, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(message, nullptr);
g_autofree gchar* message_text = message_to_text(message);
EXPECT_STREQ(message_text, "Error_code()");
}
TEST(FlMethodCodecTest, EncodeErrorEnvelopeMessage) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_error_envelope(
FL_METHOD_CODEC(codec), "code", "message", nullptr, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(message, nullptr);
g_autofree gchar* message_text = message_to_text(message);
EXPECT_STREQ(message_text, "Error_code(message)");
}
TEST(FlMethodCodecTest, EncodeErrorEnvelopeDetails) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(FlValue) details = fl_value_new_int(42);
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_error_envelope(
FL_METHOD_CODEC(codec), "code", nullptr, details, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(message, nullptr);
g_autofree gchar* message_text = message_to_text(message);
EXPECT_STREQ(message_text, "Error_code(42)");
}
TEST(FlMethodCodecTest, EncodeErrorEnvelopeMessageAndDetails) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(FlValue) details = fl_value_new_int(42);
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_error_envelope(
FL_METHOD_CODEC(codec), "code", "message", details, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(message, nullptr);
g_autofree gchar* message_text = message_to_text(message);
EXPECT_STREQ(message_text, "Error_code(message,42)");
}
TEST(FlMethodCodecTest, DecodeResponseSuccess) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(GBytes) message = text_to_message("echo");
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(response, nullptr);
ASSERT_TRUE(FL_IS_METHOD_SUCCESS_RESPONSE(response));
FlValue* result = fl_method_success_response_get_result(
FL_METHOD_SUCCESS_RESPONSE(response));
ASSERT_NE(result, nullptr);
ASSERT_EQ(fl_value_get_type(result), FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(result), "echo");
}
TEST(FlMethodCodecTest, DecodeResponseNotImplemented) {
g_autoptr(FlTestMethodCodec) codec = fl_test_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);
EXPECT_EQ(error, nullptr);
EXPECT_NE(response, nullptr);
ASSERT_TRUE(FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(response));
}
TEST(FlMethodCodecTest, DecodeResponseCodecError) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(GBytes) message = text_to_message("codec-error");
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
EXPECT_TRUE(g_error_matches(error, FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED));
EXPECT_EQ(response, nullptr);
}
TEST(FlMethodCodecTest, DecodeResponseError) {
g_autoptr(FlTestMethodCodec) codec = fl_test_method_codec_new();
g_autoptr(GBytes) message = text_to_message("error");
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(response, nullptr);
ASSERT_TRUE(FL_METHOD_ERROR_RESPONSE(response));
EXPECT_STREQ(
fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(response)),
"code");
EXPECT_STREQ(
fl_method_error_response_get_message(FL_METHOD_ERROR_RESPONSE(response)),
"message");
FlValue* details =
fl_method_error_response_get_details(FL_METHOD_ERROR_RESPONSE(response));
ASSERT_NE(details, nullptr);
ASSERT_EQ(fl_value_get_type(details), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(details), 42);
}
| engine/shell/platform/linux/fl_method_codec_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_method_codec_test.cc",
"repo_id": "engine",
"token_count": 6879
} | 415 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_RENDERER_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_RENDERER_H_
#include <gtk/gtk.h>
#include "flutter/shell/platform/linux/public/flutter_linux/fl_dart_project.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_view.h"
#include "flutter/shell/platform/embedder/embedder.h"
G_BEGIN_DECLS
/**
* FlRendererError:
* Errors for #FlRenderer objects to set on failures.
*/
typedef enum {
// NOLINTBEGIN(readability-identifier-naming)
FL_RENDERER_ERROR_FAILED,
// NOLINTEND(readability-identifier-naming)
} FlRendererError;
GQuark fl_renderer_error_quark(void) G_GNUC_CONST;
G_DECLARE_DERIVABLE_TYPE(FlRenderer, fl_renderer, FL, RENDERER, GObject)
/**
* FlRenderer:
*
* #FlRenderer is an abstract class that allows Flutter to draw pixels.
*/
struct _FlRendererClass {
GObjectClass parent_class;
/**
* Virtual method called when Flutter needs to make the OpenGL context
* current.
* @renderer: an #FlRenderer.
*/
void (*make_current)(FlRenderer* renderer);
/**
* Virtual method called when Flutter needs to make the OpenGL resource
* context current.
* @renderer: an #FlRenderer.
*/
void (*make_resource_current)(FlRenderer* renderer);
/**
* Virtual method called when Flutter needs to clear the OpenGL context.
* @renderer: an #FlRenderer.
*/
void (*clear_current)(FlRenderer* renderer);
/**
* Virtual method called when Flutter needs a backing store for a specific
* #FlutterLayer.
* @renderer: an #FlRenderer.
* @config: backing store config.
* @backing_store_out: saves created backing store.
*
* Returns %TRUE if successful.
*/
gboolean (*create_backing_store)(FlRenderer* renderer,
const FlutterBackingStoreConfig* config,
FlutterBackingStore* backing_store_out);
/**
* Virtual method called when Flutter wants to release the backing store.
* @renderer: an #FlRenderer.
* @backing_store: backing store to be released.
*
* Returns %TRUE if successful.
*/
gboolean (*collect_backing_store)(FlRenderer* renderer,
const FlutterBackingStore* backing_store);
};
/**
* fl_renderer_start:
* @renderer: an #FlRenderer.
* @view: the view Flutter is renderering to.
*
* Start the renderer.
*
* Returns: %TRUE if successfully started.
*/
gboolean fl_renderer_start(FlRenderer* renderer, FlView* view);
/**
* fl_renderer_get_proc_address:
* @renderer: an #FlRenderer.
* @name: a function name.
*
* Gets the rendering API function that matches the given name.
*
* Returns: a function pointer.
*/
void* fl_renderer_get_proc_address(FlRenderer* renderer, const char* name);
/**
* fl_renderer_make_current:
* @renderer: an #FlRenderer.
*
* Makes the rendering context current.
*/
void fl_renderer_make_current(FlRenderer* renderer);
/**
* fl_renderer_make_resource_current:
* @renderer: an #FlRenderer.
*
* Makes the resource rendering context current.
*/
void fl_renderer_make_resource_current(FlRenderer* renderer);
/**
* fl_renderer_clear_current:
* @renderer: an #FlRenderer.
*
* Clears the current rendering context.
*/
void fl_renderer_clear_current(FlRenderer* renderer);
/**
* fl_renderer_get_fbo:
* @renderer: an #FlRenderer.
*
* Gets the frame buffer object to render to.
*
* Returns: a frame buffer object index.
*/
guint32 fl_renderer_get_fbo(FlRenderer* renderer);
/**
* fl_renderer_create_backing_store:
* @renderer: an #FlRenderer.
* @config: backing store config.
* @backing_store_out: saves created backing store.
*
* Obtain a backing store for a specific #FlutterLayer.
*
* Returns %TRUE if successful.
*/
gboolean fl_renderer_create_backing_store(
FlRenderer* renderer,
const FlutterBackingStoreConfig* config,
FlutterBackingStore* backing_store_out);
/**
* fl_renderer_collect_backing_store:
* @renderer: an #FlRenderer.
* @backing_store: backing store to be released.
*
* A callback invoked by the engine to release the backing store. The
* embedder may collect any resources associated with the backing store.
*
* Returns %TRUE if successful.
*/
gboolean fl_renderer_collect_backing_store(
FlRenderer* renderer,
const FlutterBackingStore* backing_store);
/**
* fl_renderer_present_layers:
* @renderer: an #FlRenderer.
* @layers: layers to be composited.
* @layers_count: number of layers.
*
* Callback invoked by the engine to composite the contents of each layer
* onto the screen.
*
* Returns %TRUE if successful.
*/
gboolean fl_renderer_present_layers(FlRenderer* renderer,
const FlutterLayer** layers,
size_t layers_count);
/**
* fl_renderer_wait_for_frame:
* @renderer: an #FlRenderer.
* @target_width: width of frame being waited for
* @target_height: height of frame being waited for
*
* Holds the thread until frame with requested dimensions is presented.
* While waiting for frame Flutter platform and raster tasks are being
* processed.
*/
void fl_renderer_wait_for_frame(FlRenderer* renderer,
int target_width,
int target_height);
/**
* fl_renderer_setup:
* @renderer: an #FlRenderer.
*
* Creates OpenGL resources required before rendering. Requires an active OpenGL
* context.
*/
void fl_renderer_setup(FlRenderer* renderer);
/**
* fl_renderer_render:
* @renderer: an #FlRenderer.
* @width: width of the window in pixels.
* @height: height of the window in pixels.
*
* Performs OpenGL commands to render current Flutter view.
*/
void fl_renderer_render(FlRenderer* renderer, int width, int height);
/**
* fl_renderer_cleanup:
*
* Removes OpenGL resources used for rendering. Requires an active OpenGL
* context.
*/
void fl_renderer_cleanup(FlRenderer* renderer);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_RENDERER_H_
| engine/shell/platform/linux/fl_renderer.h/0 | {
"file_path": "engine/shell/platform/linux/fl_renderer.h",
"repo_id": "engine",
"token_count": 2256
} | 416 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_SETTINGS_PORTAL_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_SETTINGS_PORTAL_H_
#include "flutter/shell/platform/linux/fl_settings.h"
G_BEGIN_DECLS
G_DECLARE_FINAL_TYPE(FlSettingsPortal,
fl_settings_portal,
FL,
SETTINGS_PORTAL,
GObject);
/**
* FlSettingsPortal:
* #FlSettingsPortal reads settings from the XDG desktop portal.
*/
/**
* fl_settings_portal_new:
*
* Creates a new settings portal instance.
*
* Returns: a new #FlSettingsPortal.
*/
FlSettingsPortal* fl_settings_portal_new();
/**
* fl_settings_portal_new_with_values:
* @values: (nullable): a #GVariantDict.
*
* Creates a new settings portal instance with initial values for testing.
*
* Returns: a new #FlSettingsPortal.
*/
FlSettingsPortal* fl_settings_portal_new_with_values(GVariantDict* values);
/**
* fl_settings_portal_start:
* @portal: an #FlSettingsPortal.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
*
* Reads the current settings and starts monitoring for changes in the desktop
* portal settings.
*
* Returns: %TRUE on success, or %FALSE if the portal is not available.
*/
gboolean fl_settings_portal_start(FlSettingsPortal* portal, GError** error);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_SETTINGS_PORTAL_H_
| engine/shell/platform/linux/fl_settings_portal.h/0 | {
"file_path": "engine/shell/platform/linux/fl_settings_portal.h",
"repo_id": "engine",
"token_count": 592
} | 417 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_gl.h"
#include "flutter/shell/platform/linux/fl_texture_gl_private.h"
#include <epoxy/gl.h>
#include <gmodule.h>
#include <cstdio>
typedef struct {
int64_t id;
} FlTextureGLPrivate;
static void fl_texture_gl_texture_iface_init(FlTextureInterface* iface);
G_DEFINE_TYPE_WITH_CODE(FlTextureGL,
fl_texture_gl,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_texture_get_type(),
fl_texture_gl_texture_iface_init);
G_ADD_PRIVATE(FlTextureGL))
// Implements FlTexture::set_id
static void fl_texture_gl_set_id(FlTexture* texture, int64_t id) {
FlTextureGL* self = FL_TEXTURE_GL(texture);
FlTextureGLPrivate* priv = reinterpret_cast<FlTextureGLPrivate*>(
fl_texture_gl_get_instance_private(self));
priv->id = id;
}
// Implements FlTexture::set_id
static int64_t fl_texture_gl_get_id(FlTexture* texture) {
FlTextureGL* self = FL_TEXTURE_GL(texture);
FlTextureGLPrivate* priv = reinterpret_cast<FlTextureGLPrivate*>(
fl_texture_gl_get_instance_private(self));
return priv->id;
}
static void fl_texture_gl_texture_iface_init(FlTextureInterface* iface) {
iface->set_id = fl_texture_gl_set_id;
iface->get_id = fl_texture_gl_get_id;
}
static void fl_texture_gl_class_init(FlTextureGLClass* klass) {}
static void fl_texture_gl_init(FlTextureGL* self) {}
gboolean fl_texture_gl_populate(FlTextureGL* self,
uint32_t width,
uint32_t height,
FlutterOpenGLTexture* opengl_texture,
GError** error) {
uint32_t target = 0, name = 0;
if (!FL_TEXTURE_GL_GET_CLASS(self)->populate(self, &target, &name, &width,
&height, error)) {
return FALSE;
}
opengl_texture->target = target;
opengl_texture->name = name;
opengl_texture->format = GL_RGBA8;
opengl_texture->destruction_callback = nullptr;
opengl_texture->user_data = nullptr;
opengl_texture->width = width;
opengl_texture->height = height;
return TRUE;
}
| engine/shell/platform/linux/fl_texture_gl.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_texture_gl.cc",
"repo_id": "engine",
"token_count": 1073
} | 418 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_KEY_MAPPING_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_KEY_MAPPING_H_
#include <gdk/gdk.h>
#include <cinttypes>
#include <map>
#include <vector>
inline uint64_t gpointer_to_uint64(gpointer pointer) {
return pointer == nullptr ? 0 : reinterpret_cast<uint64_t>(pointer);
}
inline gpointer uint64_to_gpointer(uint64_t number) {
return reinterpret_cast<gpointer>(number);
}
// Maps XKB specific key code values to Flutter's physical key code values.
extern std::map<uint64_t, uint64_t> xkb_to_physical_key_map;
// Maps GDK keyval values to Flutter's logical key code values.
extern std::map<uint64_t, uint64_t> gtk_keyval_to_logical_key_map;
void initialize_modifier_bit_to_checked_keys(GHashTable* table);
void initialize_lock_bit_to_checked_keys(GHashTable* table);
// Mask for the 32-bit value portion of the key code.
extern const uint64_t kValueMask;
// The plane value for keys which have a Unicode representation.
extern const uint64_t kUnicodePlane;
// The plane value for the private keys defined by the GTK embedding.
extern const uint64_t kGtkPlane;
typedef struct {
// The key code for a key that prints `keyChar` in the US keyboard layout.
uint16_t keycode;
// The logical key for this key.
uint64_t logical_key;
// If the goal is mandatory, the keyboard manager will make sure to find a
// logical key for this character, falling back to the US keyboard layout.
bool mandatory;
} LayoutGoal;
// NOLINTNEXTLINE(readability-identifier-naming)
extern const std::vector<LayoutGoal> layout_goals;
#endif // FLUTTER_SHELL_PLATFORM_LINUX_KEY_MAPPING_H_
| engine/shell/platform/linux/key_mapping.h/0 | {
"file_path": "engine/shell/platform/linux/key_mapping.h",
"repo_id": "engine",
"token_count": 600
} | 419 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRAR_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRAR_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_texture_registrar.h"
#include "fl_view.h"
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_INTERFACE(FlPluginRegistrar,
fl_plugin_registrar,
FL,
PLUGIN_REGISTRAR,
GObject)
struct _FlPluginRegistrarInterface {
GTypeInterface parent_iface;
FlBinaryMessenger* (*get_messenger)(FlPluginRegistrar* registrar);
FlTextureRegistrar* (*get_texture_registrar)(FlPluginRegistrar* registrar);
FlView* (*get_view)(FlPluginRegistrar* registrar);
};
/**
* FlPluginRegistrar:
*
* #FlPluginRegistrar is used when registering new plugins.
*/
/**
* fl_plugin_registrar_get_messenger:
* @registrar: an #FlPluginRegistrar.
*
* Gets the messenger this plugin can communicate with.
*
* Returns: an #FlBinaryMessenger.
*/
FlBinaryMessenger* fl_plugin_registrar_get_messenger(
FlPluginRegistrar* registrar);
/**
* fl_plugin_registrar_get_texture_registrar:
* @registrar: an #FlPluginRegistrar.
*
* Gets the texture registrar this plugin can communicate with.
*
* Returns: an #FlTextureRegistrar.
*/
FlTextureRegistrar* fl_plugin_registrar_get_texture_registrar(
FlPluginRegistrar* registrar);
/**
* fl_plugin_registrar_get_view:
* @registrar: an #FlPluginRegistrar.
*
* Get the view that Flutter is rendering with.
*
* Returns: (allow-none): an #FlView or %NULL if running in headless mode.
*/
FlView* fl_plugin_registrar_get_view(FlPluginRegistrar* registrar);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRAR_H_
| engine/shell/platform/linux/public/flutter_linux/fl_plugin_registrar.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_plugin_registrar.h",
"repo_id": "engine",
"token_count": 848
} | 420 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SIGNAL_HANDLER_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SIGNAL_HANDLER_H_
#include <glib-object.h>
#include <glib.h>
#include "gmock/gmock.h"
// Expects a signal that has no arguments.
//
// MockSignalHandler timeout(timer, "timeout");
// EXPECT_SIGNAL(timeout).Times(3);
//
#define EXPECT_SIGNAL(mock) EXPECT_CALL(mock, Handler())
// Expects a signal that has 1 argument.
//
// MockSignalHandler1<int> name_changed(object, "name-changed");
// EXPECT_SIGNAL(name_changed, testing::StrEq("example"));
//
#define EXPECT_SIGNAL1(mock, a1) EXPECT_CALL(mock, Handler1(a1))
// Expects a signal that has 2 arguments.
//
// MockSignalHandler2<int, GObject*> child_added(parent, "children::add");
// EXPECT_SIGNAL2(child_added, testing::Eq(1), testing::A<GObject*>());
//
#define EXPECT_SIGNAL2(mock, a1, a2) EXPECT_CALL(mock, Handler2(a1, a2))
namespace flutter {
namespace testing {
class SignalHandler {
public:
SignalHandler(gpointer instance, const gchar* name, GCallback callback);
virtual ~SignalHandler();
private:
gulong id_ = 0;
gpointer instance_ = nullptr;
};
// A mock signal handler that has no arguments. Used with EXPECT_SIGNAL().
class MockSignalHandler : public SignalHandler {
public:
MockSignalHandler(gpointer instance, const gchar* name)
: SignalHandler(instance, name, G_CALLBACK(OnSignal)) {}
MOCK_METHOD(void, Handler, ());
private:
static void OnSignal(MockSignalHandler* mock) { mock->Handler(); }
};
// A mock signal handler that has 1 argument. Used with EXPECT_SIGNAL1().
template <typename A1>
class MockSignalHandler1 : public SignalHandler {
public:
MockSignalHandler1(gpointer instance, const gchar* name)
: SignalHandler(instance, name, G_CALLBACK(OnSignal1)) {}
MOCK_METHOD(void, Handler1, (A1 a1));
private:
static void OnSignal1(MockSignalHandler1* mock, A1 a1) { mock->Handler1(a1); }
};
// A mock signal handler that has 2 arguments. Used with EXPECT_SIGNAL2().
template <typename A1, typename A2>
class MockSignalHandler2 : public SignalHandler {
public:
MockSignalHandler2(gpointer instance, const gchar* name)
: SignalHandler(instance, name, G_CALLBACK(OnSignal2)) {}
MOCK_METHOD(void, Handler2, (A1 a1, A2 a2));
private:
static void OnSignal2(MockSignalHandler2* mock, A1 a1, A2 a2) {
mock->Handler2(a1, a2);
}
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SIGNAL_HANDLER_H_
| engine/shell/platform/linux/testing/mock_signal_handler.h/0 | {
"file_path": "engine/shell/platform/linux/testing/mock_signal_handler.h",
"repo_id": "engine",
"token_count": 957
} | 421 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.