text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { final DomElement hostElement = createDomHTMLDivElement(); late DomManager domManager; late ResourceManager resourceManager; setUp(() { domManager = DomManager(devicePixelRatio: 3); hostElement.appendChild(domManager.rootElement); resourceManager = ResourceManager(domManager); }); tearDown(() { hostElement.clearChildren(); }); test('prepends resources host as sibling to root element (webkit)', () { debugBrowserEngineOverride = BrowserEngine.webkit; // Resource host hasn't been inserted yet. expect( hostElement.children.map((DomElement e) => e.tagName.toLowerCase()), isNot(contains(ResourceManager.resourcesHostTagName.toLowerCase())), ); final List<DomElement> resources = <DomElement>[ createDomHTMLDivElement()..setAttribute('test-resource', 'r1'), createDomHTMLDivElement()..setAttribute('test-resource', 'r2'), createDomHTMLDivElement()..setAttribute('test-resource', 'r3'), ]; resources.forEach(resourceManager.addResource); final DomElement resourcesHost = hostElement.firstElementChild!; expect( resourcesHost.tagName.toLowerCase(), ResourceManager.resourcesHostTagName.toLowerCase(), ); // Make sure the resources were correctly inserted into the host. expect(resourcesHost.children, resources); debugBrowserEngineOverride = null; }); test('prepends resources host inside the shadow root (non-webkit)', () { debugBrowserEngineOverride = BrowserEngine.blink; // Resource host hasn't been inserted yet. expect( hostElement.children.map((DomElement e) => e.tagName.toLowerCase()), isNot(contains(ResourceManager.resourcesHostTagName.toLowerCase())), ); final List<DomElement> resources = <DomElement>[ createDomHTMLDivElement()..setAttribute('test-resource', 'r1'), createDomHTMLDivElement()..setAttribute('test-resource', 'r2'), createDomHTMLDivElement()..setAttribute('test-resource', 'r3'), ]; resources.forEach(resourceManager.addResource); final DomElement resourcesHost = domManager.renderingHost.firstElementChild!; expect( resourcesHost.tagName.toLowerCase(), ResourceManager.resourcesHostTagName.toLowerCase(), ); // Make sure the resources were correctly inserted into the host. expect(resourcesHost.children, resources); debugBrowserEngineOverride = null; }); test('can remove resource', () { final DomHTMLDivElement resource = createDomHTMLDivElement(); resourceManager.addResource(resource); final DomElement? resourceRoot = resource.parent; expect(resourceRoot, isNotNull); expect(resourceRoot!.childNodes.length, 1); resourceManager.removeResource(resource); expect(resourceRoot.childNodes.length, 0); }); }
engine/lib/web_ui/test/html/resource_manager_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/resource_manager_test.dart", "repo_id": "engine", "token_count": 989 }
320
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import '../../common/test_initialization.dart'; import '../paragraph/helper.dart'; import 'layout_service_helper.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests(withImplicitView: true); test('does not crash on empty spans', () { final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText(''); builder.pushStyle(EngineTextStyle.only(color: red)); builder.addText('Lorem ipsum'); builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText(''); }); expect(() => paragraph.layout(constrain(double.infinity)), returnsNormally); }); test('measures spans in the same line correctly', () { final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(fontSize: 12.0)); // 12.0 * 6 = 72.0 (with spaces) // 12.0 * 5 = 60.0 (without spaces) builder.addText('Lorem '); builder.pushStyle(EngineTextStyle.only(fontSize: 13.0)); // 13.0 * 6 = 78.0 (with spaces) // 13.0 * 5 = 65.0 (without spaces) builder.addText('ipsum '); builder.pushStyle(EngineTextStyle.only(fontSize: 11.0)); // 11.0 * 5 = 55.0 builder.addText('dolor'); })..layout(constrain(double.infinity)); expect(paragraph.maxIntrinsicWidth, 205.0); expect(paragraph.minIntrinsicWidth, 65.0); // "ipsum" expect(paragraph.width, double.infinity); expectLines(paragraph, <TestLine>[ l('Lorem ipsum dolor', 0, 17, hardBreak: true, width: 205.0, left: 0.0), ]); }); test('breaks lines correctly at the end of spans', () { final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) { builder.addText('Lorem '); builder.pushStyle(EngineTextStyle.only(fontSize: 15.0)); builder.addText('sit '); builder.pop(); builder.addText('.'); })..layout(constrain(60.0)); expect(paragraph.maxIntrinsicWidth, 130.0); expect(paragraph.minIntrinsicWidth, 50.0); // "Lorem" expect(paragraph.width, 60.0); expectLines(paragraph, <TestLine>[ l('Lorem ', 0, 6, hardBreak: false, width: 50.0, left: 0.0), l('sit ', 6, 10, hardBreak: false, width: 45.0, left: 0.0), l('.', 10, 11, hardBreak: true, width: 10.0, left: 0.0), ]); }); test('breaks lines correctly in the middle of spans', () { final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) { builder.addText('Lorem ipsum '); builder.pushStyle(EngineTextStyle.only(fontSize: 11.0)); builder.addText('sit dolor'); })..layout(constrain(100.0)); expect(paragraph.maxIntrinsicWidth, 219.0); expect(paragraph.minIntrinsicWidth, 55.0); // "dolor" expect(paragraph.width, 100.0); expectLines(paragraph, <TestLine>[ l('Lorem ', 0, 6, hardBreak: false, width: 50.0, left: 0.0), l('ipsum sit ', 6, 16, hardBreak: false, width: 93.0, left: 0.0), l('dolor', 16, 21, hardBreak: true, width: 55.0, left: 0.0), ]); }); test('handles space-only spans', () { final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: red)); builder.addText('Lorem '); builder.pop(); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText(' '); builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText(' '); builder.pushStyle(EngineTextStyle.only(color: black)); builder.addText('ipsum'); }); paragraph.layout(constrain(80.0)); expect(paragraph.maxIntrinsicWidth, 160.0); expect(paragraph.minIntrinsicWidth, 50.0); // "Lorem" or "ipsum" expect(paragraph.width, 80.0); expectLines(paragraph, <TestLine>[ l('Lorem ', 0, 11, hardBreak: false, width: 50.0, widthWithTrailingSpaces: 110.0, left: 0.0), l('ipsum', 11, 16, hardBreak: true, width: 50.0, left: 0.0), ]); }); test('should not break at span end if it is not a line break', () { final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: red)); builder.addText('Lorem'); builder.pop(); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText(' '); builder.pushStyle(EngineTextStyle.only(color: black)); builder.addText('ip'); builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText('su'); builder.pushStyle(EngineTextStyle.only(color: white)); builder.addText('m'); })..layout(constrain(50.0)); expect(paragraph.maxIntrinsicWidth, 110.0); expect(paragraph.minIntrinsicWidth, 50.0); // "Lorem" or "ipsum" expect(paragraph.width, 50.0); expectLines(paragraph, <TestLine>[ l('Lorem ', 0, 6, hardBreak: false, width: 50.0, left: 0.0), l('ipsum', 6, 11, hardBreak: true, width: 50.0, left: 0.0), ]); }); test('should handle placeholder-only paragraphs', () { final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Ahem', fontSize: 10, textAlign: ui.TextAlign.center, ); final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) { builder.addPlaceholder(300.0, 50.0, ui.PlaceholderAlignment.baseline, baseline: ui.TextBaseline.alphabetic); })..layout(constrain(500.0)); expect(paragraph.maxIntrinsicWidth, 300.0); expect(paragraph.minIntrinsicWidth, 300.0); expect(paragraph.height, 50.0); expectLines(paragraph, <TestLine>[ l(placeholderChar, 0, 1, hardBreak: true, width: 300.0, left: 100.0), ]); }); test('correct maxIntrinsicWidth when paragraph ends with placeholder', () { final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Ahem', fontSize: 10, textAlign: ui.TextAlign.center, ); final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) { builder.addText('abcd'); builder.addPlaceholder(300.0, 50.0, ui.PlaceholderAlignment.bottom); })..layout(constrain(400.0)); expect(paragraph.maxIntrinsicWidth, 340.0); expect(paragraph.minIntrinsicWidth, 300.0); expect(paragraph.height, 50.0); expectLines(paragraph, <TestLine>[ l('abcd$placeholderChar', 0, 5, hardBreak: true, width: 340.0, left: 30.0), ]); }); test('handles new line followed by a placeholder', () { final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Ahem', fontSize: 10, textAlign: ui.TextAlign.center, ); final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) { builder.addText('Lorem\n'); builder.addPlaceholder(300.0, 40.0, ui.PlaceholderAlignment.bottom); builder.addText('ipsum'); })..layout(constrain(300.0)); // The placeholder's width + "ipsum" expect(paragraph.maxIntrinsicWidth, 300.0 + 50.0); expect(paragraph.minIntrinsicWidth, 300.0); expect(paragraph.height, 10.0 + 40.0 + 10.0); expectLines(paragraph, <TestLine>[ l('Lorem', 0, 6, hardBreak: true, width: 50.0, height: 10.0, left: 125.0), l(placeholderChar, 6, 7, hardBreak: false, width: 300.0, height: 40.0, left: 0.0), l('ipsum', 7, 12, hardBreak: true, width: 50.0, height: 10.0, left: 125.0), ]); }); test('correctly force-breaks consecutive non-breakable spans', () { final CanvasParagraph paragraph = rich(ahemStyle, (ui.ParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(fontSize: 1)); builder.addText('A'); builder.pop(); // Back to fontSize: 10 builder.addText('A' * 20); builder.pushStyle(EngineTextStyle.only(fontSize: 1)); builder.addText('A'); }); paragraph.layout(constrain(200)); expect(paragraph.maxIntrinsicWidth, 200.0 + 2.0); expect(paragraph.height, 20.0); expectLines(paragraph, <TestLine>[ // 1x small "A" + 19x big "A" l('A' * 20, 0, 20, hardBreak: false, width: 1.0 + 190.0, height: 10.0), // 1x big "A" + 1x small "A" l('AA', 20, 22, hardBreak: true, width: 10.0 + 1.0, height: 10.0), ]); }); test('does not make prohibited line breaks', () { final CanvasParagraph paragraph = rich(ahemStyle, (ui.ParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('AAA B'); builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText('BB '); builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText('CC'); }); paragraph.layout(constrain(60)); expect(paragraph.maxIntrinsicWidth, 100.0); expectLines(paragraph, <TestLine>[ l('AAA ', 0, 4, hardBreak: false, width: 30.0), l('BBB CC', 4, 10, hardBreak: true, width: 60.0), ]); }); }
engine/lib/web_ui/test/html/text/layout_service_rich_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/text/layout_service_rich_test.dart", "repo_id": "engine", "token_count": 3662 }
321
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import '../common/fake_asset_manager.dart'; import '../common/test_initialization.dart'; import 'utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests(); late FakeAssetScope testScope; setUp(() { mockHttpFetchResponseFactory = null; testScope = fakeAssetManager.pushAssetScope(); }); tearDown(() { fakeAssetManager.popAssetScope(testScope); }); test('Loading valid font from data succeeds without family name (except in HTML renderer)', () async { final FlutterFontCollection collection = renderer.fontCollection; final ByteBuffer ahemData = await httpFetchByteBuffer('/assets/fonts/ahem.ttf'); expect( await collection.loadFontFromList(ahemData.asUint8List()), !isHtml, // HtmlFontCollection requires family name ); }); test('Loading valid font from data succeeds with family name', () async { final FlutterFontCollection collection = renderer.fontCollection; final ByteBuffer ahemData = await httpFetchByteBuffer('/assets/fonts/ahem.ttf'); expect( await collection.loadFontFromList(ahemData.asUint8List(), fontFamily: 'FamilyName'), true ); }); test('Loading invalid font from data returns false', () async { final FlutterFontCollection collection = renderer.fontCollection; final List<int> invalidFontData = utf8.encode('This is not valid font data'); expect( await collection.loadFontFromList(Uint8List.fromList(invalidFontData), fontFamily: 'FamilyName'), false ); }); test('Loading valid asset fonts succeds', () async { testScope.setAssetPassthrough(robotoVariableFontUrl); testScope.setAssetPassthrough(robotoTestFontUrl); testScope.setAssetPassthrough(ahemFontUrl); final FlutterFontCollection collection = renderer.fontCollection; final AssetFontsResult result = await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(robotoFontFamily, <FontAsset>[ FontAsset(robotoVariableFontUrl, <String, String>{}), FontAsset(robotoTestFontUrl, <String, String>{'weight': 'bold'}), ]), FontFamily(ahemFontFamily, <FontAsset>[ FontAsset(ahemFontUrl, <String, String>{}) ]), ])); expect(result.loadedFonts, <String>[ robotoVariableFontUrl, robotoTestFontUrl, ahemFontUrl, ]); expect(result.fontFailures, isEmpty); }); test('Loading asset fonts reports when font not found', () async { testScope.setAssetPassthrough(robotoVariableFontUrl); testScope.setAssetPassthrough(robotoTestFontUrl); const String invalidFontUrl = 'assets/invalid_font_url.ttf'; final FlutterFontCollection collection = renderer.fontCollection; final AssetFontsResult result = await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(robotoFontFamily, <FontAsset>[ FontAsset(robotoVariableFontUrl, <String, String>{}), FontAsset(robotoTestFontUrl, <String, String>{'weight': 'bold'}), ]), FontFamily(ahemFontFamily, <FontAsset>[ FontAsset(invalidFontUrl, <String, String>{}) ]), ])); expect(result.loadedFonts, <String>[ robotoVariableFontUrl, robotoTestFontUrl, ]); expect(result.fontFailures, hasLength(1)); if (isHtml) { // The HTML renderer doesn't have a way to differentiate 404's from other // download errors. expect(result.fontFailures[invalidFontUrl], isA<FontDownloadError>()); } else { expect(result.fontFailures[invalidFontUrl], isA<FontNotFoundError>()); } }); test('Loading asset fonts reports when a font has invalid data', () async { const String invalidFontUrl = 'assets/invalid_font_data.ttf'; testScope.setAssetPassthrough(robotoVariableFontUrl); testScope.setAssetPassthrough(robotoTestFontUrl); testScope.setAssetPassthrough(invalidFontUrl); mockHttpFetchResponseFactory = (String url) async { if (url == invalidFontUrl) { return MockHttpFetchResponse( url: url, status: 200, payload: MockHttpFetchPayload( byteBuffer: stringAsUtf8Data('this is invalid data').buffer ), ); } return null; }; final FlutterFontCollection collection = renderer.fontCollection; final AssetFontsResult result = await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(robotoFontFamily, <FontAsset>[ FontAsset(robotoVariableFontUrl, <String, String>{}), FontAsset(robotoTestFontUrl, <String, String>{'weight': 'bold'}), ]), FontFamily(ahemFontFamily, <FontAsset>[ FontAsset(invalidFontUrl, <String, String>{}) ]), ])); expect(result.loadedFonts, <String>[ robotoVariableFontUrl, robotoTestFontUrl, ]); expect(result.fontFailures, hasLength(1)); if (isHtml) { // The HTML renderer doesn't have a way to differentiate invalid data // from other download errors. expect(result.fontFailures[invalidFontUrl], isA<FontDownloadError>()); } else { expect(result.fontFailures[invalidFontUrl], isA<FontInvalidDataError>()); } }); test('Font manifest with numeric and string descriptor values parses correctly', () async { testScope.setAsset('FontManifest.json', stringAsUtf8Data(r''' [ { "family": "FakeFont", "fonts": [ { "asset": "fonts/FakeFont.ttf", "style": "italic", "weight": 400 } ] } ] ''')); final FontManifest manifest = await fetchFontManifest(fakeAssetManager); expect(manifest.families.length, 1); final FontFamily family = manifest.families.single; expect(family.name, 'FakeFont'); expect(family.fontAssets.length, 1); final FontAsset fontAsset = family.fontAssets.single; expect(fontAsset.asset, 'fonts/FakeFont.ttf'); expect(fontAsset.descriptors.length, 2); expect(fontAsset.descriptors['style'], 'italic'); expect(fontAsset.descriptors['weight'], '400'); }); }
engine/lib/web_ui/test/ui/font_collection_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/font_collection_test.dart", "repo_id": "engine", "token_count": 2326 }
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: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/rendering.dart'; import '../common/test_initialization.dart'; import 'utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); group('${ui.SceneBuilder}', () { const ui.Rect region = ui.Rect.fromLTWH(0, 0, 300, 300); test('Test offset layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); sceneBuilder.pushOffset(150, 150); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawCircle( ui.Offset.zero, 50, ui.Paint()..color = const ui.Color(0xFF00FF00) ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_centered_circle.png', region: region); }); test('Test transform layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); final Matrix4 transform = Matrix4.identity(); // The html renderer expects the top-level transform to just be a scaling // matrix for the device pixel ratio, so just push the identity matrix. sceneBuilder.pushTransform(transform.toFloat64()); transform.translate(150, 150); transform.rotate(kUnitZ, math.pi / 3); sceneBuilder.pushTransform(transform.toFloat64()); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawRRect( ui.RRect.fromRectAndRadius( ui.Rect.fromCircle(center: ui.Offset.zero, radius: 50), const ui.Radius.circular(10) ), ui.Paint()..color = const ui.Color(0xFF0000FF) ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_rotated_rounded_square.png', region: region); }); test('Test clipRect layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); sceneBuilder.pushClipRect(const ui.Rect.fromLTRB(0, 0, 150, 150)); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawCircle( const ui.Offset(150, 150), 50, ui.Paint()..color = const ui.Color(0xFFFF0000) ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_circle_clip_rect.png', region: region); }); test('Test clipRRect layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); sceneBuilder.pushClipRRect(ui.RRect.fromRectAndRadius( const ui.Rect.fromLTRB(0, 0, 150, 150), const ui.Radius.circular(25), ), clipBehavior: ui.Clip.antiAlias); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawCircle( const ui.Offset(150, 150), 50, ui.Paint()..color = const ui.Color(0xFFFF00FF) ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_circle_clip_rrect.png', region: region); }); test('Test clipPath layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); final ui.Path path = ui.Path(); path.addOval(ui.Rect.fromCircle(center: const ui.Offset(150, 150), radius: 60)); sceneBuilder.pushClipPath(path); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawRect( ui.Rect.fromCircle(center: const ui.Offset(150, 150), radius: 50), ui.Paint()..color = const ui.Color(0xFF00FFFF) ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_rectangle_clip_circular_path.png', region: region); }); test('Test opacity layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawRect( ui.Rect.fromCircle(center: const ui.Offset(150, 150), radius: 50), ui.Paint()..color = const ui.Color(0xFF00FF00) ); })); sceneBuilder.pushOpacity(0x7F, offset: const ui.Offset(150, 150)); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { final ui.Paint paint = ui.Paint()..color = const ui.Color(0xFFFF0000); canvas.drawCircle( const ui.Offset(-25, 0), 50, paint ); canvas.drawCircle( const ui.Offset(25, 0), 50, paint ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_opacity_circles_on_square.png', region: region); }); test('shader mask layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { final ui.Paint paint = ui.Paint()..color = const ui.Color(0xFFFF0000); canvas.drawCircle( const ui.Offset(125, 150), 50, paint ); canvas.drawCircle( const ui.Offset(175, 150), 50, paint ); })); final ui.Shader shader = ui.Gradient.linear( ui.Offset.zero, const ui.Offset(50, 50), <ui.Color>[ const ui.Color(0xFFFFFFFF), const ui.Color(0x00000000), ]); sceneBuilder.pushShaderMask( shader, const ui.Rect.fromLTRB(125, 125, 175, 175), ui.BlendMode.srcATop ); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawRect( ui.Rect.fromCircle(center: const ui.Offset(150, 150), radius: 50), ui.Paint()..color = const ui.Color(0xFF00FF00) ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_shader_mask.png', region: region); }, skip: isFirefox && isHtml); // https://github.com/flutter/flutter/issues/86623 test('backdrop filter layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { // Create a red and blue checkerboard pattern final ui.Paint redPaint = ui.Paint()..color = const ui.Color(0xFFFF0000); final ui.Paint bluePaint = ui.Paint()..color = const ui.Color(0xFF0000FF); for (double y = 0; y < 300; y += 10) { for (double x = 0; x < 300; x += 10) { final ui.Paint paint = ((x + y) % 20 == 0) ? redPaint : bluePaint; canvas.drawRect(ui.Rect.fromLTWH(x, y, 10, 10), paint); } } })); sceneBuilder.pushBackdropFilter(ui.ImageFilter.blur( sigmaX: 3.0, sigmaY: 3.0, )); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawCircle( const ui.Offset(150, 150), 50, ui.Paint()..color = const ui.Color(0xFF00FF00) ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_backdrop_filter.png', region: region); }); test('image filter layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); sceneBuilder.pushImageFilter(ui.ImageFilter.blur( sigmaX: 5.0, sigmaY: 5.0, )); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawCircle( const ui.Offset(150, 150), 50, ui.Paint()..color = const ui.Color(0xFF00FF00) ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_image_filter.png', region: region); }); test('color filter layer', () async { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); 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, ]); sceneBuilder.pushColorFilter(sepia); sceneBuilder.addPicture(ui.Offset.zero, drawPicture((ui.Canvas canvas) { canvas.drawCircle( const ui.Offset(150, 150), 50, ui.Paint()..color = const ui.Color(0xFF00FF00) ); })); await renderScene(sceneBuilder.build()); await matchGoldenFile('scene_builder_color_filter.png', region: region); }); }); } ui.Picture drawPicture(void Function(ui.Canvas) drawCommands) { final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); drawCommands(canvas); return recorder.endRecording(); }
engine/lib/web_ui/test/ui/scene_builder_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/scene_builder_test.dart", "repo_id": "engine", "token_count": 4023 }
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. #include "flutter/runtime/dart_plugin_registrant.h" #include <string> #include "flutter/fml/logging.h" #include "flutter/fml/trace_event.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/logging/dart_invoke.h" namespace flutter { const char* dart_plugin_registrant_library_override = nullptr; bool InvokeDartPluginRegistrantIfAvailable(Dart_Handle library_handle) { TRACE_EVENT0("flutter", "InvokeDartPluginRegistrantIfAvailable"); // The Dart plugin registrant is a static method with signature `void // register()` within the class `_PluginRegistrant` generated by the Flutter // tool. // // This method binds a plugin implementation to their platform // interface based on the configuration of the app's pubpec.yaml, and the // plugin's pubspec.yaml. // // Since this method may or may not be defined, check if the class is defined // in the default library before calling the method. Dart_Handle plugin_registrant = ::Dart_GetClass(library_handle, tonic::ToDart("_PluginRegistrant")); if (Dart_IsError(plugin_registrant)) { return false; } tonic::CheckAndHandleError( tonic::DartInvokeField(plugin_registrant, "register", {})); return true; } bool FindAndInvokeDartPluginRegistrant() { std::string library_name = dart_plugin_registrant_library_override == nullptr ? "package:flutter/src/dart_plugin_registrant.dart" : dart_plugin_registrant_library_override; Dart_Handle library = Dart_LookupLibrary(tonic::ToDart(library_name)); if (Dart_IsError(library)) { return false; } Dart_Handle registrant_file_uri = Dart_GetField(library, tonic::ToDart("dartPluginRegistrantLibrary")); if (Dart_IsError(registrant_file_uri)) { // TODO(gaaclarke): Find a way to remove this branch so the field is // required. I couldn't get it working with unit tests. return InvokeDartPluginRegistrantIfAvailable(library); } std::string registrant_file_uri_string = tonic::DartConverter<std::string>::FromDart(registrant_file_uri); if (registrant_file_uri_string.empty()) { return false; } Dart_Handle registrant_library = Dart_LookupLibrary(registrant_file_uri); return InvokeDartPluginRegistrantIfAvailable(registrant_library); } } // namespace flutter
engine/runtime/dart_plugin_registrant.cc/0
{ "file_path": "engine/runtime/dart_plugin_registrant.cc", "repo_id": "engine", "token_count": 848 }
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. #include "flutter/runtime/dart_vm_lifecycle.h" #include <mutex> #include <utility> namespace flutter { // We need to explicitly put the constructor and destructor of the DartVM in the // critical section. All accesses (not just const members) to the global VM // object weak pointer are behind this mutex. static std::mutex gVMMutex; static std::weak_ptr<DartVM> gVM; static std::shared_ptr<DartVM>* gVMLeak; // We are going to be modifying more than just the control blocks of the // following weak pointers (in the |Create| case where an old VM could not be // reused). Ideally, we would use |std::atomic<std::weak_ptr<T>>| specialization // but that is only available since C++20. We don't expect contention on these // locks so we just use one mutex for all. static std::mutex gVMDependentsMutex; static std::weak_ptr<const DartVMData> gVMData; static std::weak_ptr<ServiceProtocol> gVMServiceProtocol; static std::weak_ptr<IsolateNameServer> gVMIsolateNameServer; DartVMRef::DartVMRef(std::shared_ptr<DartVM> vm) : vm_(std::move(vm)) {} DartVMRef::DartVMRef(DartVMRef&& other) = default; DartVMRef::~DartVMRef() { if (!vm_) { // If there is no valid VM (possible via a move), there is no way that the // decrement on the shared pointer can cause a collection. Avoid acquiring // the lifecycle lock in this case. This is just working around a // pessimization and not required for correctness. return; } std::scoped_lock lifecycle_lock(gVMMutex); vm_.reset(); } DartVMRef DartVMRef::Create(const Settings& settings, fml::RefPtr<const DartSnapshot> vm_snapshot, fml::RefPtr<const DartSnapshot> isolate_snapshot) { std::scoped_lock lifecycle_lock(gVMMutex); if (!settings.leak_vm) { FML_CHECK(!gVMLeak) << "Launch settings indicated that the VM should shut down in the " "process when done but a previous launch asked the VM to leak in " "the same process. For proper VM shutdown, all VM launches must " "indicate that they should shut down when done."; } // If there is already a running VM in the process, grab a strong reference to // it. if (auto vm = gVM.lock()) { FML_DLOG(WARNING) << "Attempted to create a VM in a process where one was " "already running. Ignoring arguments for current VM " "create call and reusing the old VM."; // There was already a running VM in the process, return DartVMRef{std::move(vm)}; } std::scoped_lock dependents_lock(gVMDependentsMutex); gVMData.reset(); gVMServiceProtocol.reset(); gVMIsolateNameServer.reset(); gVM.reset(); // If there is no VM in the process. Initialize one, hold the weak reference // and pass a strong reference to the caller. auto isolate_name_server = std::make_shared<IsolateNameServer>(); auto vm = DartVM::Create(settings, // std::move(vm_snapshot), // std::move(isolate_snapshot), // isolate_name_server // ); if (!vm) { FML_LOG(ERROR) << "Could not create Dart VM instance."; return DartVMRef{nullptr}; } gVMData = vm->GetVMData(); gVMServiceProtocol = vm->GetServiceProtocol(); gVMIsolateNameServer = isolate_name_server; gVM = vm; if (settings.leak_vm) { gVMLeak = new std::shared_ptr<DartVM>(vm); } return DartVMRef{std::move(vm)}; } bool DartVMRef::IsInstanceRunning() { std::scoped_lock lock(gVMMutex); return !gVM.expired(); } std::shared_ptr<const DartVMData> DartVMRef::GetVMData() { std::scoped_lock lock(gVMDependentsMutex); return gVMData.lock(); } std::shared_ptr<ServiceProtocol> DartVMRef::GetServiceProtocol() { std::scoped_lock lock(gVMDependentsMutex); return gVMServiceProtocol.lock(); } std::shared_ptr<IsolateNameServer> DartVMRef::GetIsolateNameServer() { std::scoped_lock lock(gVMDependentsMutex); return gVMIsolateNameServer.lock(); } DartVM* DartVMRef::GetRunningVM() { std::scoped_lock lock(gVMMutex); auto vm = gVM.lock().get(); FML_CHECK(vm) << "Caller assumed VM would be running when it wasn't"; return vm; } } // namespace flutter
engine/runtime/dart_vm_lifecycle.cc/0
{ "file_path": "engine/runtime/dart_vm_lifecycle.cc", "repo_id": "engine", "token_count": 1649 }
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. #include "flutter/runtime/dart_vm.h" #include "flutter/runtime/dart_vm_lifecycle.h" #include "flutter/runtime/platform_isolate_manager.h" #include "flutter/testing/fixture_test.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { struct IsolateData { PlatformIsolateManager* mgr; Dart_Isolate isolate = nullptr; bool is_shutdown = false; bool was_registered = false; explicit IsolateData(PlatformIsolateManager* _mgr) : mgr(_mgr) {} }; // The IsolateDataMap is a map from Dart_Isolate to a *vector* of IsolateData, // because Dart_Isolates are frequently reused after shutdown, and we want the // IsolateData objects to live as long as the map itself. The last element of // the vector is always the currently active IsolateData, and the other elements // refer to isolates that have been shutdown. using IsolateDataMap = std::unordered_map<Dart_Isolate, std::vector<std::unique_ptr<IsolateData>>>; // Using a thread local isolate data map so that MultithreadedCreation test // can avoid using locks while creating isolates on multiple threads. A lock // would sync up the threads, so would defeat the purpose of the test. static thread_local std::unique_ptr<IsolateDataMap> isolate_data_map_; class PlatformIsolateManagerTest : public FixtureTest { public: PlatformIsolateManagerTest() {} void TestWithRootIsolate(const std::function<void()>& test) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate_configuration = IsolateConfiguration::InferFromSettings(settings); UIDartState::Context context(task_runners); context.advisory_script_uri = "main.dart"; context.advisory_script_entrypoint = "main"; auto weak_isolate = DartIsolate::CreateRunningRootIsolate( vm_data->GetSettings(), // settings vm_data->GetIsolateSnapshot(), // isolate snapshot nullptr, // platform configuration DartIsolate::Flags{}, // flags nullptr, // root_isolate_create_callback settings.isolate_create_callback, // isolate create callback settings.isolate_shutdown_callback, // isolate shutdown callback "main", // dart entrypoint std::nullopt, // dart entrypoint library {}, // dart entrypoint arguments std::move(isolate_configuration), // isolate configuration context // engine context ); root_isolate_ = weak_isolate.lock()->isolate(); ASSERT_TRUE(root_isolate_); test(); Dart_EnterIsolate(root_isolate_); Dart_ShutdownIsolate(); } Dart_Isolate CreateAndRegisterIsolate(PlatformIsolateManager* mgr) { if (isolate_data_map_.get() == nullptr) { isolate_data_map_.reset(new IsolateDataMap()); } IsolateData* isolate_data = new IsolateData(mgr); char* error = nullptr; Dart_Isolate isolate = Dart_CreateIsolateInGroup(root_isolate_, "TestIsolate", OnShutdown, nullptr, isolate_data, &error); isolate_data->isolate = isolate; EXPECT_TRUE(isolate); Dart_ExitIsolate(); (*isolate_data_map_.get())[isolate].push_back( std::unique_ptr<IsolateData>(isolate_data)); isolate_data->was_registered = mgr->RegisterPlatformIsolate(isolate); return isolate; } bool IsolateIsShutdown(Dart_Isolate isolate) { EXPECT_EQ(1u, isolate_data_map_.get()->count(isolate)); EXPECT_LT(0u, (*isolate_data_map_.get())[isolate].size()); return (*isolate_data_map_.get())[isolate].back()->is_shutdown; } bool IsolateWasRegistered(Dart_Isolate isolate) { EXPECT_EQ(1u, isolate_data_map_.get()->count(isolate)); EXPECT_LT(0u, (*isolate_data_map_.get())[isolate].size()); return (*isolate_data_map_.get())[isolate].back()->was_registered; } private: Dart_Isolate root_isolate_ = nullptr; static void OnShutdown(void*, void* raw_isolate_data) { IsolateData* isolate_data = reinterpret_cast<IsolateData*>(raw_isolate_data); EXPECT_TRUE(isolate_data->isolate); EXPECT_FALSE(isolate_data->is_shutdown); isolate_data->is_shutdown = true; if (isolate_data->was_registered) { isolate_data->mgr->RemovePlatformIsolate(isolate_data->isolate); } } FML_DISALLOW_COPY_AND_ASSIGN(PlatformIsolateManagerTest); }; TEST_F(PlatformIsolateManagerTest, OrdinaryFlow) { TestWithRootIsolate([this]() { PlatformIsolateManager mgr; EXPECT_FALSE(mgr.HasShutdown()); EXPECT_FALSE(mgr.HasShutdownMaybeFalseNegative()); Dart_Isolate isolateA = CreateAndRegisterIsolate(&mgr); ASSERT_TRUE(isolateA); EXPECT_FALSE(IsolateIsShutdown(isolateA)); EXPECT_TRUE(IsolateWasRegistered(isolateA)); EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateA)); Dart_Isolate isolateB = CreateAndRegisterIsolate(&mgr); ASSERT_TRUE(isolateB); EXPECT_FALSE(IsolateIsShutdown(isolateB)); EXPECT_TRUE(IsolateWasRegistered(isolateB)); EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateB)); mgr.ShutdownPlatformIsolates(); EXPECT_TRUE(mgr.HasShutdown()); EXPECT_TRUE(mgr.HasShutdownMaybeFalseNegative()); EXPECT_TRUE(IsolateIsShutdown(isolateA)); EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateA)); EXPECT_TRUE(IsolateIsShutdown(isolateB)); EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB)); }); } TEST_F(PlatformIsolateManagerTest, EarlyShutdown) { TestWithRootIsolate([this]() { PlatformIsolateManager mgr; EXPECT_FALSE(mgr.HasShutdown()); Dart_Isolate isolateA = CreateAndRegisterIsolate(&mgr); ASSERT_TRUE(isolateA); EXPECT_FALSE(IsolateIsShutdown(isolateA)); EXPECT_TRUE(IsolateWasRegistered(isolateA)); EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateA)); Dart_Isolate isolateB = CreateAndRegisterIsolate(&mgr); ASSERT_TRUE(isolateB); EXPECT_FALSE(IsolateIsShutdown(isolateB)); EXPECT_TRUE(IsolateWasRegistered(isolateB)); EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateB)); Dart_EnterIsolate(isolateA); Dart_ShutdownIsolate(); EXPECT_TRUE(IsolateIsShutdown(isolateA)); EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateA)); Dart_EnterIsolate(isolateB); Dart_ShutdownIsolate(); EXPECT_TRUE(IsolateIsShutdown(isolateB)); EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB)); mgr.ShutdownPlatformIsolates(); EXPECT_TRUE(mgr.HasShutdown()); EXPECT_TRUE(IsolateIsShutdown(isolateA)); EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateA)); EXPECT_TRUE(IsolateIsShutdown(isolateB)); EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB)); }); } TEST_F(PlatformIsolateManagerTest, RegistrationAfterShutdown) { TestWithRootIsolate([this]() { PlatformIsolateManager mgr; EXPECT_FALSE(mgr.HasShutdown()); Dart_Isolate isolateA = CreateAndRegisterIsolate(&mgr); ASSERT_TRUE(isolateA); EXPECT_FALSE(IsolateIsShutdown(isolateA)); EXPECT_TRUE(IsolateWasRegistered(isolateA)); EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateA)); mgr.ShutdownPlatformIsolates(); EXPECT_TRUE(mgr.HasShutdown()); EXPECT_TRUE(IsolateIsShutdown(isolateA)); EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateA)); Dart_Isolate isolateB = CreateAndRegisterIsolate(&mgr); ASSERT_TRUE(isolateB); EXPECT_FALSE(IsolateIsShutdown(isolateB)); EXPECT_FALSE(IsolateWasRegistered(isolateB)); EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB)); Dart_EnterIsolate(isolateB); Dart_ShutdownIsolate(); EXPECT_TRUE(IsolateIsShutdown(isolateB)); EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB)); }); } TEST_F(PlatformIsolateManagerTest, MultithreadedCreation) { // Try to generate race conditions by creating Isolates on multiple threads, // while shutting down the manager. TestWithRootIsolate([this]() { PlatformIsolateManager mgr; EXPECT_FALSE(mgr.HasShutdown()); std::atomic<bool> test_finished = false; std::vector<std::thread> threads; threads.reserve(10); for (int i = 0; i < 10; ++i) { threads.push_back(std::thread([this, &mgr, &test_finished]() { for (int j = 0; j < 100; ++j) { Dart_Isolate isolate = CreateAndRegisterIsolate(&mgr); ASSERT_TRUE(isolate); if (!IsolateWasRegistered(isolate)) { Dart_EnterIsolate(isolate); Dart_ShutdownIsolate(); } } while (!test_finished.load()) { // Wait for the test to finish, to avoid prematurely destroying thread // local isolate_data_map_. } })); } mgr.ShutdownPlatformIsolates(); EXPECT_TRUE(mgr.HasShutdown()); test_finished = true; for (auto& thread : threads) { thread.join(); } }); } } // namespace testing } // namespace flutter
engine/runtime/platform_isolate_manager_unittests.cc/0
{ "file_path": "engine/runtime/platform_isolate_manager_unittests.cc", "repo_id": "engine", "token_count": 3840 }
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. #include "flutter/shell/common/animator.h" #include "flutter/common/constants.h" #include "flutter/flow/frame_timings.h" #include "flutter/fml/time/time_point.h" #include "flutter/fml/trace_event.h" #include "third_party/dart/runtime/include/dart_tools_api.h" namespace flutter { namespace { // Wait 51 milliseconds (which is 1 more milliseconds than 3 frames at 60hz) // before notifying the engine that we are idle. See comments in |BeginFrame| // for further discussion on why this is necessary. constexpr fml::TimeDelta kNotifyIdleTaskWaitTime = fml::TimeDelta::FromMilliseconds(51); } // namespace Animator::Animator(Delegate& delegate, const TaskRunners& task_runners, std::unique_ptr<VsyncWaiter> waiter) : delegate_(delegate), task_runners_(task_runners), waiter_(std::move(waiter)), #if SHELL_ENABLE_METAL layer_tree_pipeline_(std::make_shared<FramePipeline>(2)), #else // SHELL_ENABLE_METAL // TODO(dnfield): We should remove this logic and set the pipeline depth // back to 2 in this case. See // https://github.com/flutter/engine/pull/9132 for discussion. layer_tree_pipeline_(std::make_shared<FramePipeline>( task_runners.GetPlatformTaskRunner() == task_runners.GetRasterTaskRunner() ? 1 : 2)), #endif // SHELL_ENABLE_METAL pending_frame_semaphore_(1), weak_factory_(this) { } Animator::~Animator() = default; void Animator::EnqueueTraceFlowId(uint64_t trace_flow_id) { fml::TaskRunner::RunNowOrPostTask( task_runners_.GetUITaskRunner(), [self = weak_factory_.GetWeakPtr(), trace_flow_id] { if (!self) { return; } self->trace_flow_ids_.push_back(trace_flow_id); self->ScheduleMaybeClearTraceFlowIds(); }); } void Animator::BeginFrame( std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) { TRACE_EVENT_ASYNC_END0("flutter", "Frame Request Pending", frame_request_number_); // Clear layer trees rendered out of a frame. Only Animator::Render called // within a frame is used. layer_trees_tasks_.clear(); frame_request_number_++; frame_timings_recorder_ = std::move(frame_timings_recorder); frame_timings_recorder_->RecordBuildStart(fml::TimePoint::Now()); size_t flow_id_count = trace_flow_ids_.size(); std::unique_ptr<uint64_t[]> flow_ids = std::make_unique<uint64_t[]>(flow_id_count); for (size_t i = 0; i < flow_id_count; ++i) { flow_ids.get()[i] = trace_flow_ids_.at(i); } TRACE_EVENT_WITH_FRAME_NUMBER(frame_timings_recorder_, "flutter", "Animator::BeginFrame", flow_id_count, flow_ids.get()); while (!trace_flow_ids_.empty()) { uint64_t trace_flow_id = trace_flow_ids_.front(); TRACE_FLOW_END("flutter", "PointerEvent", trace_flow_id); trace_flow_ids_.pop_front(); } frame_scheduled_ = false; regenerate_layer_trees_ = false; pending_frame_semaphore_.Signal(); if (!producer_continuation_) { // We may already have a valid pipeline continuation in case a previous // begin frame did not result in an Animator::Render. Simply reuse that // instead of asking the pipeline for a fresh continuation. producer_continuation_ = layer_tree_pipeline_->Produce(); if (!producer_continuation_) { // If we still don't have valid continuation, the pipeline is currently // full because the consumer is being too slow. Try again at the next // frame interval. TRACE_EVENT0("flutter", "PipelineFull"); RequestFrame(); return; } } // We have acquired a valid continuation from the pipeline and are ready // to service potential frame. FML_DCHECK(producer_continuation_); const fml::TimePoint frame_target_time = frame_timings_recorder_->GetVsyncTargetTime(); dart_frame_deadline_ = frame_target_time.ToEpochDelta(); uint64_t frame_number = frame_timings_recorder_->GetFrameNumber(); delegate_.OnAnimatorBeginFrame(frame_target_time, frame_number); } void Animator::EndFrame() { if (frame_timings_recorder_ == nullptr) { // `EndFrame` has been called in this frame. This happens if the engine has // called `OnAllViewsRendered` and then the end of the vsync task calls // `EndFrame` again. return; } if (!layer_trees_tasks_.empty()) { // The build is completed in OnAnimatorBeginFrame. frame_timings_recorder_->RecordBuildEnd(fml::TimePoint::Now()); delegate_.OnAnimatorUpdateLatestFrameTargetTime( frame_timings_recorder_->GetVsyncTargetTime()); // Commit the pending continuation. std::vector<std::unique_ptr<LayerTreeTask>> layer_tree_task_list; layer_tree_task_list.reserve(layer_trees_tasks_.size()); for (auto& [view_id, layer_tree_task] : layer_trees_tasks_) { layer_tree_task_list.push_back(std::move(layer_tree_task)); } layer_trees_tasks_.clear(); PipelineProduceResult result = producer_continuation_.Complete( std::make_unique<FrameItem>(std::move(layer_tree_task_list), std::move(frame_timings_recorder_))); if (!result.success) { FML_DLOG(INFO) << "Failed to commit to the pipeline"; } else if (!result.is_first_item) { // Do nothing. It has been successfully pushed to the pipeline but not as // the first item. Eventually the 'Rasterizer' will consume it, so we // don't need to notify the delegate. } else { delegate_.OnAnimatorDraw(layer_tree_pipeline_); } } frame_timings_recorder_ = nullptr; if (!frame_scheduled_ && has_rendered_) { // Wait a tad more than 3 60hz frames before reporting a big idle period. // This is a heuristic that is meant to avoid giving false positives to the // VM when we are about to schedule a frame in the next vsync, the idea // being that if there have been three vsyncs with no frames it's a good // time to start doing GC work. task_runners_.GetUITaskRunner()->PostDelayedTask( [self = weak_factory_.GetWeakPtr()]() { if (!self) { return; } // If there's a frame scheduled, bail. // If there's no frame scheduled, but we're not yet past the last // vsync deadline, bail. if (!self->frame_scheduled_) { auto now = fml::TimeDelta::FromMicroseconds(Dart_TimelineGetMicros()); if (now > self->dart_frame_deadline_) { TRACE_EVENT0("flutter", "BeginFrame idle callback"); self->delegate_.OnAnimatorNotifyIdle( now + fml::TimeDelta::FromMilliseconds(100)); } } }, kNotifyIdleTaskWaitTime); } FML_DCHECK(layer_trees_tasks_.empty()); FML_DCHECK(frame_timings_recorder_ == nullptr); } void Animator::Render(int64_t view_id, std::unique_ptr<flutter::LayerTree> layer_tree, float device_pixel_ratio) { has_rendered_ = true; if (!frame_timings_recorder_) { // Framework can directly call render with a built scene. A major reason is // to render warm up frames. frame_timings_recorder_ = std::make_unique<FrameTimingsRecorder>(); const fml::TimePoint placeholder_time = fml::TimePoint::Now(); frame_timings_recorder_->RecordVsync(placeholder_time, placeholder_time); frame_timings_recorder_->RecordBuildStart(placeholder_time); } TRACE_EVENT_WITH_FRAME_NUMBER(frame_timings_recorder_, "flutter", "Animator::Render", /*flow_id_count=*/0, /*flow_ids=*/nullptr); // Only inserts if the view ID has not been rendered before, ignoring // duplicate Render calls. layer_trees_tasks_.try_emplace( view_id, std::make_unique<LayerTreeTask>(view_id, std::move(layer_tree), device_pixel_ratio)); } const std::weak_ptr<VsyncWaiter> Animator::GetVsyncWaiter() const { std::weak_ptr<VsyncWaiter> weak = waiter_; return weak; } bool Animator::CanReuseLastLayerTrees() { return !regenerate_layer_trees_; } void Animator::DrawLastLayerTrees( std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) { // This method is very cheap, but this makes it explicitly clear in trace // files. TRACE_EVENT0("flutter", "Animator::DrawLastLayerTrees"); pending_frame_semaphore_.Signal(); // In this case BeginFrame doesn't get called, we need to // adjust frame timings to update build start and end times, // given that the frame doesn't get built in this case, we // will use Now() for both start and end times as an indication. const auto now = fml::TimePoint::Now(); frame_timings_recorder->RecordBuildStart(now); frame_timings_recorder->RecordBuildEnd(now); delegate_.OnAnimatorDrawLastLayerTrees(std::move(frame_timings_recorder)); } void Animator::RequestFrame(bool regenerate_layer_trees) { if (regenerate_layer_trees) { // This event will be closed by BeginFrame. BeginFrame will only be called // if regenerating the layer trees. If a frame has been requested to update // an external texture, this will be false and no BeginFrame call will // happen. TRACE_EVENT_ASYNC_BEGIN0("flutter", "Frame Request Pending", frame_request_number_); regenerate_layer_trees_ = true; } if (!pending_frame_semaphore_.TryWait()) { // Multiple calls to Animator::RequestFrame will still result in a // single request to the VsyncWaiter. return; } // The AwaitVSync is going to call us back at the next VSync. However, we want // to be reasonably certain that the UI thread is not in the middle of a // particularly expensive callout. We post the AwaitVSync to run right after // an idle. This does NOT provide a guarantee that the UI thread has not // started an expensive operation right after posting this message however. // To support that, we need edge triggered wakes on VSync. task_runners_.GetUITaskRunner()->PostTask( [self = weak_factory_.GetWeakPtr()]() { if (!self) { return; } self->AwaitVSync(); }); frame_scheduled_ = true; } void Animator::AwaitVSync() { waiter_->AsyncWaitForVsync( [self = weak_factory_.GetWeakPtr()]( std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) { if (self) { if (self->CanReuseLastLayerTrees()) { self->DrawLastLayerTrees(std::move(frame_timings_recorder)); } else { self->BeginFrame(std::move(frame_timings_recorder)); self->EndFrame(); } } }); if (has_rendered_) { delegate_.OnAnimatorNotifyIdle(dart_frame_deadline_); } } void Animator::OnAllViewsRendered() { if (!layer_trees_tasks_.empty()) { EndFrame(); } } void Animator::ScheduleSecondaryVsyncCallback(uintptr_t id, const fml::closure& callback) { waiter_->ScheduleSecondaryCallback(id, callback); } void Animator::ScheduleMaybeClearTraceFlowIds() { waiter_->ScheduleSecondaryCallback( reinterpret_cast<uintptr_t>(this), [self = weak_factory_.GetWeakPtr()] { if (!self) { return; } if (!self->frame_scheduled_ && !self->trace_flow_ids_.empty()) { size_t flow_id_count = self->trace_flow_ids_.size(); std::unique_ptr<uint64_t[]> flow_ids = std::make_unique<uint64_t[]>(flow_id_count); for (size_t i = 0; i < flow_id_count; ++i) { flow_ids.get()[i] = self->trace_flow_ids_.at(i); } TRACE_EVENT0_WITH_FLOW_IDS( "flutter", "Animator::ScheduleMaybeClearTraceFlowIds - callback", flow_id_count, flow_ids.get()); while (!self->trace_flow_ids_.empty()) { auto flow_id = self->trace_flow_ids_.front(); TRACE_FLOW_END("flutter", "PointerEvent", flow_id); self->trace_flow_ids_.pop_front(); } } }); } } // namespace flutter
engine/shell/common/animator.cc/0
{ "file_path": "engine/shell/common/animator.cc", "repo_id": "engine", "token_count": 4942 }
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. #include "flutter/display_list/display_list.h" #include "flutter/display_list/dl_builder.h" #include "flutter/display_list/testing/dl_test_snippets.h" #include "flutter/shell/common/dl_op_spy.h" #include "flutter/testing/testing.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkFont.h" #include "third_party/skia/include/core/SkRSXform.h" namespace flutter { namespace testing { // The following macros demonstrate that the DlOpSpy class is equivalent // to DisplayList::affects_transparent_surface() now that DisplayListBuilder // implements operation culling. // See https://github.com/flutter/flutter/issues/125403 #define ASSERT_DID_DRAW(spy, dl) \ do { \ ASSERT_TRUE(spy.did_draw()); \ ASSERT_TRUE(dl->modifies_transparent_black()); \ } while (0) #define ASSERT_NO_DRAW(spy, dl) \ do { \ ASSERT_FALSE(spy.did_draw()); \ ASSERT_FALSE(dl->modifies_transparent_black()); \ } while (0) TEST(DlOpSpy, DidDrawIsFalseByDefault) { DlOpSpy dl_op_spy; ASSERT_FALSE(dl_op_spy.did_draw()); } TEST(DlOpSpy, EmptyDisplayList) { DisplayListBuilder builder; sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } TEST(DlOpSpy, SetColor) { { // No Color set. DisplayListBuilder builder; DlPaint paint; builder.DrawRect(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // Set transparent color. DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawRect(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } { // Set black color. DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawRect(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, SetColorSource) { { // Set null source DisplayListBuilder builder; DlPaint paint; paint.setColorSource(nullptr); builder.DrawRect(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // Set transparent color. DisplayListBuilder builder; DlPaint paint; auto color = DlColor::kTransparent(); DlColorColorSource color_source_transparent(color); paint.setColorSource(color_source_transparent.shared()); builder.DrawRect(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } { // Set black color. DisplayListBuilder builder; DlPaint paint; auto color = DlColor::kBlack(); DlColorColorSource color_source_transparent(color); paint.setColorSource(color_source_transparent.shared()); builder.DrawRect(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawColor) { { // Black color source. DisplayListBuilder builder; auto color = DlColor::kBlack(); builder.DrawColor(color, DlBlendMode::kSrc); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // Transparent color with kSrc. DisplayListBuilder builder; auto color = DlColor::kTransparent(); builder.DrawColor(color, DlBlendMode::kSrc); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } { // Transparent color with kSrcOver. DisplayListBuilder builder; auto color = DlColor::kTransparent(); builder.DrawColor(color, DlBlendMode::kSrcOver); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawPaint) { { // Transparent color in paint. DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawPaint(paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } { // black color in paint. DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawPaint(paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawLine) { { // black DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawLine(SkPoint::Make(0, 1), SkPoint::Make(1, 2), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawLine(SkPoint::Make(0, 1), SkPoint::Make(1, 2), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawRect) { { // black DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawRect(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawRect(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawOval) { { // black DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawOval(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawOval(SkRect::MakeWH(5, 5), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawCircle) { { // black DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawCircle(SkPoint::Make(5, 5), 1.0, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawCircle(SkPoint::Make(5, 5), 1.0, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawRRect) { { // black DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawRRect(SkRRect::MakeRect(SkRect::MakeWH(5, 5)), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawRRect(SkRRect::MakeRect(SkRect::MakeWH(5, 5)), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawPath) { { // black line DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); paint.setDrawStyle(DlDrawStyle::kStroke); builder.DrawPath(SkPath::Line(SkPoint::Make(0, 1), SkPoint::Make(1, 1)), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // triangle DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); SkPath path; path.moveTo({0, 0}); path.lineTo({1, 0}); path.lineTo({0, 1}); builder.DrawPath(path, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent line DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); paint.setDrawStyle(DlDrawStyle::kStroke); builder.DrawPath(SkPath::Line(SkPoint::Make(0, 1), SkPoint::Make(1, 1)), paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawArc) { { // black DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawArc(SkRect::MakeWH(5, 5), 0, 1, true, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawArc(SkRect::MakeWH(5, 5), 0, 1, true, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawPoints) { { // black DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); const SkPoint points[] = {SkPoint::Make(5, 4)}; builder.DrawPoints(DlCanvas::PointMode::kPoints, 1, points, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); const SkPoint points[] = {SkPoint::Make(5, 4)}; builder.DrawPoints(DlCanvas::PointMode::kPoints, 1, points, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawVertices) { { // black DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); const SkPoint vertices[] = { SkPoint::Make(5, 5), SkPoint::Make(5, 15), SkPoint::Make(15, 5), }; const SkPoint texture_coordinates[] = { SkPoint::Make(5, 5), SkPoint::Make(15, 5), SkPoint::Make(5, 15), }; const DlColor colors[] = { DlColor::kBlack(), DlColor::kRed(), DlColor::kGreen(), }; auto dl_vertices = DlVertices::Make(DlVertexMode::kTriangles, 3, vertices, texture_coordinates, colors, 0); builder.DrawVertices(dl_vertices.get(), DlBlendMode::kSrc, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); const SkPoint vertices[] = { SkPoint::Make(5, 5), SkPoint::Make(5, 15), SkPoint::Make(15, 5), }; const SkPoint texture_coordinates[] = { SkPoint::Make(5, 5), SkPoint::Make(15, 5), SkPoint::Make(5, 15), }; const DlColor colors[] = { DlColor::kBlack(), DlColor::kRed(), DlColor::kGreen(), }; auto dl_vertices = DlVertices::Make(DlVertexMode::kTriangles, 3, vertices, texture_coordinates, colors, 0); builder.DrawVertices(dl_vertices.get(), DlBlendMode::kSrc, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, Images) { { // DrawImage DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); SkImageInfo info = SkImageInfo::Make(50, 50, SkColorType::kRGBA_8888_SkColorType, SkAlphaType::kPremul_SkAlphaType); SkBitmap bitmap; bitmap.allocPixels(info, 0); auto sk_image = SkImages::RasterFromBitmap(bitmap); builder.DrawImage(DlImage::Make(sk_image), SkPoint::Make(5, 5), DlImageSampling::kLinear); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // DrawImageRect DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); SkImageInfo info = SkImageInfo::Make(50, 50, SkColorType::kRGBA_8888_SkColorType, SkAlphaType::kPremul_SkAlphaType); SkBitmap bitmap; bitmap.allocPixels(info, 0); auto sk_image = SkImages::RasterFromBitmap(bitmap); builder.DrawImageRect(DlImage::Make(sk_image), SkRect::MakeWH(5, 5), SkRect::MakeWH(5, 5), DlImageSampling::kLinear); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // DrawImageNine DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); SkImageInfo info = SkImageInfo::Make(50, 50, SkColorType::kRGBA_8888_SkColorType, SkAlphaType::kPremul_SkAlphaType); SkBitmap bitmap; bitmap.allocPixels(info, 0); auto sk_image = SkImages::RasterFromBitmap(bitmap); builder.DrawImageNine(DlImage::Make(sk_image), SkIRect::MakeWH(5, 5), SkRect::MakeWH(5, 5), DlFilterMode::kLinear); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // DrawAtlas DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); SkImageInfo info = SkImageInfo::Make(50, 50, SkColorType::kRGBA_8888_SkColorType, SkAlphaType::kPremul_SkAlphaType); SkBitmap bitmap; bitmap.allocPixels(info, 0); auto sk_image = SkImages::RasterFromBitmap(bitmap); const SkRSXform xform[] = {SkRSXform::Make(1, 0, 0, 0)}; const SkRect tex[] = {SkRect::MakeXYWH(10, 10, 10, 10)}; SkRect cull_rect = SkRect::MakeWH(5, 5); builder.DrawAtlas(DlImage::Make(sk_image), xform, tex, nullptr, 1, DlBlendMode::kSrc, DlImageSampling::kLinear, &cull_rect); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawDisplayList) { { // Recursive Transparent DisplayList DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawPaint(paint); sk_sp<DisplayList> dl = builder.Build(); DisplayListBuilder builder_parent; DlPaint paint_parent(DlColor::kTransparent()); builder_parent.DrawPaint(paint_parent); builder_parent.DrawDisplayList(dl, 1); sk_sp<DisplayList> dl2 = builder_parent.Build(); DlOpSpy dl_op_spy; dl2->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl2); } { // Sub non-transparent DisplayList, DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawPaint(paint); sk_sp<DisplayList> dl = builder.Build(); DisplayListBuilder builder_parent; DlPaint paint_parent(DlColor::kTransparent()); builder_parent.DrawPaint(paint_parent); builder_parent.DrawDisplayList(dl, 1); sk_sp<DisplayList> dl2 = builder_parent.Build(); DlOpSpy dl_op_spy; dl2->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl2); } { // Sub non-transparent DisplayList, 0 opacity DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); builder.DrawPaint(paint); sk_sp<DisplayList> dl = builder.Build(); DisplayListBuilder builder_parent; DlPaint paint_parent(DlColor::kTransparent()); builder_parent.DrawPaint(paint_parent); builder_parent.DrawDisplayList(dl, 0); sk_sp<DisplayList> dl2 = builder_parent.Build(); DlOpSpy dl_op_spy; dl2->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl2); } { // Parent non-transparent DisplayList DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); builder.DrawPaint(paint); sk_sp<DisplayList> dl = builder.Build(); DisplayListBuilder builder_parent; DlPaint paint_parent(DlColor::kBlack()); builder_parent.DrawPaint(paint_parent); builder_parent.DrawDisplayList(dl, 0); sk_sp<DisplayList> dl2 = builder_parent.Build(); DlOpSpy dl_op_spy; dl2->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl2); } } TEST(DlOpSpy, DrawTextBlob) { { // Non-transparent color. DisplayListBuilder builder; DlPaint paint(DlColor::kBlack()); std::string string = "xx"; SkFont font = CreateTestFontOfSize(12); auto text_blob = SkTextBlob::MakeFromString(string.c_str(), font); builder.DrawTextBlob(text_blob, 1, 1, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent color. DisplayListBuilder builder; DlPaint paint(DlColor::kTransparent()); std::string string = "xx"; SkFont font = CreateTestFontOfSize(12); auto text_blob = SkTextBlob::MakeFromString(string.c_str(), font); builder.DrawTextBlob(text_blob, 1, 1, paint); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } TEST(DlOpSpy, DrawShadow) { { // valid shadow DisplayListBuilder builder; DlPaint paint; DlColor color = DlColor::kBlack(); SkPath path = SkPath::Line(SkPoint::Make(0, 1), SkPoint::Make(1, 1)); builder.DrawShadow(path, color, 1, false, 1); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_DID_DRAW(dl_op_spy, dl); } { // transparent color DisplayListBuilder builder; DlPaint paint; DlColor color = DlColor::kTransparent(); SkPath path = SkPath::Line(SkPoint::Make(0, 1), SkPoint::Make(1, 1)); builder.DrawShadow(path, color, 1, false, 1); sk_sp<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); } } } // namespace testing } // namespace flutter
engine/shell/common/dl_op_spy_unittests.cc/0
{ "file_path": "engine/shell/common/dl_op_spy_unittests.cc", "repo_id": "engine", "token_count": 8764 }
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. #include "flutter/shell/common/pointer_data_dispatcher.h" #include "flutter/fml/trace_event.h" namespace flutter { PointerDataDispatcher::~PointerDataDispatcher() = default; DefaultPointerDataDispatcher::~DefaultPointerDataDispatcher() = default; SmoothPointerDataDispatcher::SmoothPointerDataDispatcher(Delegate& delegate) : DefaultPointerDataDispatcher(delegate), weak_factory_(this) {} SmoothPointerDataDispatcher::~SmoothPointerDataDispatcher() = default; void DefaultPointerDataDispatcher::DispatchPacket( std::unique_ptr<PointerDataPacket> packet, uint64_t trace_flow_id) { TRACE_EVENT0_WITH_FLOW_IDS("flutter", "DefaultPointerDataDispatcher::DispatchPacket", /*flow_id_count=*/1, &trace_flow_id); TRACE_FLOW_STEP("flutter", "PointerEvent", trace_flow_id); delegate_.DoDispatchPacket(std::move(packet), trace_flow_id); } void SmoothPointerDataDispatcher::DispatchPacket( std::unique_ptr<PointerDataPacket> packet, uint64_t trace_flow_id) { TRACE_EVENT0_WITH_FLOW_IDS("flutter", "SmoothPointerDataDispatcher::DispatchPacket", /*flow_id_count=*/1, &trace_flow_id); TRACE_FLOW_STEP("flutter", "PointerEvent", trace_flow_id); if (is_pointer_data_in_progress_) { if (pending_packet_ != nullptr) { DispatchPendingPacket(); } pending_packet_ = std::move(packet); pending_trace_flow_id_ = trace_flow_id; } else { FML_DCHECK(pending_packet_ == nullptr); DefaultPointerDataDispatcher::DispatchPacket(std::move(packet), trace_flow_id); } is_pointer_data_in_progress_ = true; ScheduleSecondaryVsyncCallback(); } void SmoothPointerDataDispatcher::ScheduleSecondaryVsyncCallback() { delegate_.ScheduleSecondaryVsyncCallback( reinterpret_cast<uintptr_t>(this), [dispatcher = weak_factory_.GetWeakPtr()]() { if (dispatcher && dispatcher->is_pointer_data_in_progress_) { if (dispatcher->pending_packet_ != nullptr) { dispatcher->DispatchPendingPacket(); } else { dispatcher->is_pointer_data_in_progress_ = false; } } }); } void SmoothPointerDataDispatcher::DispatchPendingPacket() { FML_DCHECK(pending_packet_ != nullptr); FML_DCHECK(is_pointer_data_in_progress_); DefaultPointerDataDispatcher::DispatchPacket(std::move(pending_packet_), pending_trace_flow_id_); pending_packet_ = nullptr; pending_trace_flow_id_ = -1; ScheduleSecondaryVsyncCallback(); } } // namespace flutter
engine/shell/common/pointer_data_dispatcher.cc/0
{ "file_path": "engine/shell/common/pointer_data_dispatcher.cc", "repo_id": "engine", "token_count": 1196 }
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. #include "flutter/shell/common/shell_io_manager.h" #include <utility> #include "flutter/fml/message_loop.h" #include "flutter/shell/common/context_options.h" #include "third_party/skia/include/gpu/ganesh/gl/GrGLDirectContext.h" #include "third_party/skia/include/gpu/gl/GrGLInterface.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" namespace flutter { sk_sp<GrDirectContext> ShellIOManager::CreateCompatibleResourceLoadingContext( GrBackendApi backend, const sk_sp<const GrGLInterface>& gl_interface) { #if SK_GL if (backend != GrBackendApi::kOpenGL) { return nullptr; } const auto options = MakeDefaultContextOptions(ContextType::kResource); if (auto context = GrDirectContexts::MakeGL(gl_interface, options)) { // Do not cache textures created by the image decoder. These textures // should be deleted when they are no longer referenced by an SkImage. context->setResourceCacheLimit(0); return context; } #endif // SK_GL return nullptr; } ShellIOManager::ShellIOManager( sk_sp<GrDirectContext> resource_context, std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch, fml::RefPtr<fml::TaskRunner> unref_queue_task_runner, std::shared_ptr<impeller::Context> impeller_context, fml::TimeDelta unref_queue_drain_delay) : resource_context_(std::move(resource_context)), resource_context_weak_factory_( resource_context_ ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>( resource_context_.get()) : nullptr), unref_queue_(fml::MakeRefCounted<flutter::SkiaUnrefQueue>( std::move(unref_queue_task_runner), unref_queue_drain_delay, resource_context_, /*drain_immediate=*/!!impeller_context)), is_gpu_disabled_sync_switch_(std::move(is_gpu_disabled_sync_switch)), impeller_context_(std::move(impeller_context)), weak_factory_(this) { if (!resource_context_) { #ifndef OS_FUCHSIA FML_DLOG(WARNING) << "The IO manager was initialized without a resource " "context. Async texture uploads will be disabled. " "Expect performance degradation."; #endif // OS_FUCHSIA } } ShellIOManager::~ShellIOManager() { // Last chance to drain the IO queue as the platform side reference to the // underlying OpenGL context may be going away. is_gpu_disabled_sync_switch_->Execute( fml::SyncSwitch::Handlers().SetIfFalse([&] { unref_queue_->Drain(); })); } void ShellIOManager::NotifyResourceContextAvailable( sk_sp<GrDirectContext> resource_context) { // The resource context needs to survive as long as we have Dart objects // referencing. We shouldn't ever need to replace it if we have one - unless // we've somehow shut down the Dart VM and started a new one fresh. if (!resource_context_) { UpdateResourceContext(std::move(resource_context)); } } void ShellIOManager::UpdateResourceContext( sk_sp<GrDirectContext> resource_context) { resource_context_ = std::move(resource_context); resource_context_weak_factory_ = resource_context_ ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>( resource_context_.get()) : nullptr; unref_queue_->UpdateResourceContext(resource_context_); } fml::WeakPtr<ShellIOManager> ShellIOManager::GetWeakPtr() { return weak_factory_.GetWeakPtr(); } // |IOManager| fml::WeakPtr<GrDirectContext> ShellIOManager::GetResourceContext() const { return resource_context_weak_factory_ ? resource_context_weak_factory_->GetWeakPtr() : fml::WeakPtr<GrDirectContext>(); } // |IOManager| fml::RefPtr<flutter::SkiaUnrefQueue> ShellIOManager::GetSkiaUnrefQueue() const { return unref_queue_; } // |IOManager| fml::WeakPtr<IOManager> ShellIOManager::GetWeakIOManager() const { return weak_factory_.GetWeakPtr(); } // |IOManager| std::shared_ptr<const fml::SyncSwitch> ShellIOManager::GetIsGpuDisabledSyncSwitch() { return is_gpu_disabled_sync_switch_; } // |IOManager| std::shared_ptr<impeller::Context> ShellIOManager::GetImpellerContext() const { return impeller_context_; } } // namespace flutter
engine/shell/common/shell_io_manager.cc/0
{ "file_path": "engine/shell/common/shell_io_manager.cc", "repo_id": "engine", "token_count": 1641 }
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. #include "flutter/shell/common/skia_event_tracer_impl.h" #define TRACE_EVENT_HIDE_MACROS #include <map> #include <set> #include <vector> #include "flutter/fml/logging.h" #include "flutter/fml/posix_wrappers.h" #include "flutter/fml/trace_event.h" #include "third_party/dart/runtime/include/dart_tools_api.h" #include "third_party/skia/include/utils/SkEventTracer.h" #include "third_party/skia/include/utils/SkTraceEventPhase.h" #if defined(OS_FUCHSIA) #include <algorithm> #include <cstring> #include <lib/trace-engine/context.h> #include <lib/trace-engine/instrumentation.h> // Skia's copy of these flags are defined in a private header, so, as is // commonly done with "trace_event_common.h" values, copy them inline here (see // https://cs.chromium.org/chromium/src/base/trace_event/common/trace_event_common.h?l=1102-1110&rcl=239b85aeb3a6c07b33b5f162cd0ae8128eabf44d). // // Type values for identifying types in the TraceValue union. #define TRACE_VALUE_TYPE_BOOL (static_cast<unsigned char>(1)) #define TRACE_VALUE_TYPE_UINT (static_cast<unsigned char>(2)) #define TRACE_VALUE_TYPE_INT (static_cast<unsigned char>(3)) #define TRACE_VALUE_TYPE_DOUBLE (static_cast<unsigned char>(4)) #define TRACE_VALUE_TYPE_POINTER (static_cast<unsigned char>(5)) #define TRACE_VALUE_TYPE_STRING (static_cast<unsigned char>(6)) #define TRACE_VALUE_TYPE_COPY_STRING (static_cast<unsigned char>(7)) #define TRACE_VALUE_TYPE_CONVERTABLE (static_cast<unsigned char>(8)) #endif // defined(OS_FUCHSIA) namespace flutter { namespace { // Skia prepends this string to the category names of its trace events. // Defined in Skia's src/core/SkTraceEvent.h. constexpr std::string_view kTraceCategoryPrefix = "disabled-by-default-"; // Category name used for shader compilation events. constexpr std::string_view kShaderCategoryName = "disabled-by-default-skia.shaders"; #if !defined(OS_FUCHSIA) // Argument name of the tag used by DevTools. constexpr char kDevtoolsTagArg[] = "devtoolsTag"; // DevtoolsTag value for shader events. constexpr char kShadersDevtoolsTag[] = "shaders"; #endif // !defined(OS_FUCHSIA) #if defined(OS_FUCHSIA) template <class T, class U> inline T BitCast(const U& u) { static_assert(sizeof(T) == sizeof(U)); T t; memcpy(&t, &u, sizeof(t)); return t; } #endif // defined(OS_FUCHSIA) } // namespace class FlutterEventTracer : public SkEventTracer { public: static constexpr const char* kSkiaTag = "skia"; static constexpr uint8_t kYes = 1; static constexpr uint8_t kNo = 0; FlutterEventTracer(bool enabled, const std::optional<std::vector<std::string>>& allowlist) : enabled_(enabled ? kYes : kNo) { if (allowlist.has_value()) { allowlist_.emplace(); for (const std::string& category : *allowlist) { allowlist_->insert(std::string(kTraceCategoryPrefix) + category); } } }; SkEventTracer::Handle addTraceEvent(char phase, const uint8_t* category_enabled_flag, const char* name, uint64_t id, int num_args, const char** p_arg_names, const uint8_t* p_arg_types, const uint64_t* p_arg_values, uint8_t flags) override { #if defined(OS_FUCHSIA) static trace_site_t trace_site; trace_string_ref_t category_ref; trace_context_t* trace_context = trace_acquire_context_for_category_cached( kSkiaTag, &trace_site, &category_ref); if (likely(!trace_context)) { return 0; } trace_ticks_t ticks = zx_ticks_get(); trace_thread_ref_t thread_ref; trace_context_register_current_thread(trace_context, &thread_ref); trace_string_ref_t name_ref; trace_context_register_string_literal(trace_context, name, &name_ref); constexpr int kMaxArgs = 2; trace_arg_t trace_args[kMaxArgs] = {}; FML_DCHECK(num_args >= 0); int num_trace_args = std::min(kMaxArgs, num_args); for (int i = 0; i < num_trace_args; i++) { const char* arg_name = p_arg_names[i]; const uint8_t arg_type = p_arg_types[i]; const uint64_t arg_value = p_arg_values[i]; trace_string_ref_t arg_name_string_ref = trace_context_make_registered_string_literal(trace_context, arg_name); trace_arg_value_t trace_arg_value; switch (arg_type) { case TRACE_VALUE_TYPE_BOOL: { trace_arg_value = trace_make_bool_arg_value(!!arg_value); break; } case TRACE_VALUE_TYPE_UINT: trace_arg_value = trace_make_uint64_arg_value(arg_value); break; case TRACE_VALUE_TYPE_INT: trace_arg_value = trace_make_int64_arg_value(BitCast<int64_t>(arg_value)); break; case TRACE_VALUE_TYPE_DOUBLE: trace_arg_value = trace_make_double_arg_value(BitCast<double>(arg_value)); break; case TRACE_VALUE_TYPE_POINTER: trace_arg_value = trace_make_pointer_arg_value(BitCast<uintptr_t>(arg_value)); break; case TRACE_VALUE_TYPE_STRING: { trace_string_ref_t arg_value_string_ref = trace_context_make_registered_string_literal( trace_context, reinterpret_cast<const char*>(arg_value)); trace_arg_value = trace_make_string_arg_value(arg_value_string_ref); break; } case TRACE_VALUE_TYPE_COPY_STRING: { const char* arg_value_as_cstring = reinterpret_cast<const char*>(arg_value); trace_string_ref_t arg_value_string_ref = trace_context_make_registered_string_copy( trace_context, arg_value_as_cstring, strlen(arg_value_as_cstring)); trace_arg_value = trace_make_string_arg_value(arg_value_string_ref); break; } case TRACE_VALUE_TYPE_CONVERTABLE: trace_arg_value = trace_make_null_arg_value(); break; default: trace_arg_value = trace_make_null_arg_value(); } trace_args[i] = trace_make_arg(arg_name_string_ref, trace_arg_value); } switch (phase) { case TRACE_EVENT_PHASE_BEGIN: case TRACE_EVENT_PHASE_COMPLETE: trace_context_write_duration_begin_event_record( trace_context, ticks, &thread_ref, &category_ref, &name_ref, trace_args, num_trace_args); break; case TRACE_EVENT_PHASE_END: trace_context_write_duration_end_event_record( trace_context, ticks, &thread_ref, &category_ref, &name_ref, trace_args, num_trace_args); break; case TRACE_EVENT_PHASE_INSTANT: trace_context_write_instant_event_record( trace_context, ticks, &thread_ref, &category_ref, &name_ref, TRACE_SCOPE_THREAD, trace_args, num_trace_args); break; case TRACE_EVENT_PHASE_ASYNC_BEGIN: trace_context_write_async_begin_event_record( trace_context, ticks, &thread_ref, &category_ref, &name_ref, id, trace_args, num_trace_args); break; case TRACE_EVENT_PHASE_ASYNC_END: trace_context_write_async_end_event_record( trace_context, ticks, &thread_ref, &category_ref, &name_ref, id, trace_args, num_trace_args); break; default: break; } trace_release_context(trace_context); #else // defined(OS_FUCHSIA) const char* devtoolsTag = nullptr; if (shaders_category_flag_ && category_enabled_flag == shaders_category_flag_) { devtoolsTag = kShadersDevtoolsTag; } switch (phase) { case TRACE_EVENT_PHASE_BEGIN: case TRACE_EVENT_PHASE_COMPLETE: if (devtoolsTag) { fml::tracing::TraceEvent1(kSkiaTag, name, /*flow_id_count=*/0, /*flow_ids=*/nullptr, kDevtoolsTagArg, devtoolsTag); } else { fml::tracing::TraceEvent0(kSkiaTag, name, /*flow_id_count=*/0, /*flow_ids=*/nullptr); } break; case TRACE_EVENT_PHASE_END: fml::tracing::TraceEventEnd(name); break; case TRACE_EVENT_PHASE_INSTANT: if (devtoolsTag) { fml::tracing::TraceEventInstant1(kSkiaTag, name, /*flow_id_count=*/0, /*flow_ids=*/nullptr, kDevtoolsTagArg, devtoolsTag); } else { fml::tracing::TraceEventInstant0(kSkiaTag, name, /*flow_id_count=*/0, /*flow_ids=*/nullptr); } break; case TRACE_EVENT_PHASE_ASYNC_BEGIN: if (devtoolsTag) { fml::tracing::TraceEventAsyncBegin1(kSkiaTag, name, id, /*flow_id_count=*/0, /*flow_ids=*/nullptr, kDevtoolsTagArg, devtoolsTag); } else { fml::tracing::TraceEventAsyncBegin0(kSkiaTag, name, id, /*flow_id_count=*/0, /*flow_ids=*/nullptr); } break; case TRACE_EVENT_PHASE_ASYNC_END: if (devtoolsTag) { fml::tracing::TraceEventAsyncEnd1(kSkiaTag, name, id, kDevtoolsTagArg, devtoolsTag); } else { fml::tracing::TraceEventAsyncEnd0(kSkiaTag, name, id); } break; default: break; } #endif // defined(OS_FUCHSIA) return 0; } void updateTraceEventDuration(const uint8_t* category_enabled_flag, const char* name, SkEventTracer::Handle handle) override { // This is only ever called from a scoped trace event so we will just end // the section. #if defined(OS_FUCHSIA) TRACE_DURATION_END(kSkiaTag, name); #else fml::tracing::TraceEventEnd(name); #endif } const uint8_t* getCategoryGroupEnabled(const char* name) override { // Skia will only use long-lived string literals as event names. std::lock_guard<std::mutex> lock(flag_map_mutex_); auto flag_it = category_flag_map_.find(name); if (flag_it == category_flag_map_.end()) { bool allowed; if (enabled_) { allowed = !allowlist_.has_value() || allowlist_->find(name) != allowlist_->end(); } else { allowed = false; } flag_it = category_flag_map_.insert(std::make_pair(name, allowed)).first; const uint8_t* flag = &flag_it->second; reverse_flag_map_.insert(std::make_pair(flag, name)); if (kShaderCategoryName == name) { shaders_category_flag_ = flag; } } return &flag_it->second; } const char* getCategoryGroupName( const uint8_t* category_enabled_flag) override { std::lock_guard<std::mutex> lock(flag_map_mutex_); auto reverse_it = reverse_flag_map_.find(category_enabled_flag); if (reverse_it != reverse_flag_map_.end()) { return reverse_it->second; } else { return kSkiaTag; } } private: uint8_t enabled_; std::optional<std::set<std::string>> allowlist_; std::mutex flag_map_mutex_; std::map<const char*, uint8_t> category_flag_map_; std::map<const uint8_t*, const char*> reverse_flag_map_; const uint8_t* shaders_category_flag_ = nullptr; FML_DISALLOW_COPY_AND_ASSIGN(FlutterEventTracer); }; void InitSkiaEventTracer( bool enabled, const std::optional<std::vector<std::string>>& allowlist) { auto tracer = new FlutterEventTracer(enabled, allowlist); // Initialize the binding to Skia's tracing events. Skia will // take ownership of and clean up the memory allocated here. SkEventTracer::SetInstance(tracer); } } // namespace flutter
engine/shell/common/skia_event_tracer_impl.cc/0
{ "file_path": "engine/shell/common/skia_event_tracer_impl.cc", "repo_id": "engine", "token_count": 5874 }
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. #include "variable_refresh_rate_display.h" #include "vsync_waiters_test.h" #include "gtest/gtest.h" namespace flutter { namespace testing { TEST(VariableRefreshRateDisplayTest, ReportCorrectInitialRefreshRate) { auto refresh_rate_reporter = std::make_shared<TestRefreshRateReporter>(60); auto display = flutter::VariableRefreshRateDisplay( 0, std::weak_ptr<TestRefreshRateReporter>(refresh_rate_reporter), 600, 800, 60); ASSERT_EQ(display.GetRefreshRate(), 60); } TEST(VariableRefreshRateDisplayTest, ReportCorrectRefreshRateWhenUpdated) { auto refresh_rate_reporter = std::make_shared<TestRefreshRateReporter>(60); auto display = flutter::VariableRefreshRateDisplay( 0, std::weak_ptr<TestRefreshRateReporter>(refresh_rate_reporter), 600, 800, 60); refresh_rate_reporter->UpdateRefreshRate(30); ASSERT_EQ(display.GetRefreshRate(), 30); } TEST(VariableRefreshRateDisplayTest, Report0IfReporterSharedPointerIsDestroyedAfterDisplayCreation) { auto refresh_rate_reporter = std::make_shared<TestRefreshRateReporter>(60); auto display = flutter::VariableRefreshRateDisplay( 0, std::weak_ptr<TestRefreshRateReporter>(refresh_rate_reporter), 600, 800, 60); refresh_rate_reporter.reset(); ASSERT_EQ(display.GetRefreshRate(), 0); } TEST(VariableRefreshRateDisplayTest, Report0IfReporterSharedPointerIsDestroyedBeforeDisplayCreation) { auto refresh_rate_reporter = std::make_shared<TestRefreshRateReporter>(60); refresh_rate_reporter.reset(); auto display = flutter::VariableRefreshRateDisplay( 0, std::weak_ptr<TestRefreshRateReporter>(refresh_rate_reporter), 600, 800, 60); ASSERT_EQ(display.GetRefreshRate(), 0); } } // namespace testing } // namespace flutter
engine/shell/common/variable_refresh_rate_display_unittests.cc/0
{ "file_path": "engine/shell/common/variable_refresh_rate_display_unittests.cc", "repo_id": "engine", "token_count": 655 }
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. #include "flutter/shell/gpu/gpu_surface_gl_skia.h" #include "flutter/common/graphics/persistent_cache.h" #include "flutter/fml/base32.h" #include "flutter/fml/logging.h" #include "flutter/fml/size.h" #include "flutter/fml/trace_event.h" #include "flutter/shell/common/context_options.h" #include "flutter/shell/gpu/gpu_surface_gl_delegate.h" #include "third_party/skia/include/core/SkAlphaType.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkColorType.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrContextOptions.h" #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" #include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" #include "third_party/skia/include/gpu/ganesh/gl/GrGLDirectContext.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" // These are common defines present on all OpenGL headers. However, we don't // want to perform GL header resolution on each platform we support. So just // define these upfront. It is unlikely we will need more. But, if we do, we can // add the same here. #define GPU_GL_RGBA8 0x8058 #define GPU_GL_RGBA4 0x8056 #define GPU_GL_RGB565 0x8D62 namespace flutter { // Default maximum number of bytes of GPU memory of budgeted resources in the // cache. // The shell will dynamically increase or decrease this cache based on the // viewport size, unless a user has specifically requested a size on the Skia // system channel. static const size_t kGrCacheMaxByteSize = 24 * (1 << 20); sk_sp<GrDirectContext> GPUSurfaceGLSkia::MakeGLContext( GPUSurfaceGLDelegate* delegate) { auto context_switch = delegate->GLContextMakeCurrent(); if (!context_switch->GetResult()) { FML_LOG(ERROR) << "Could not make the context current to set up the Gr context."; return nullptr; } const auto options = MakeDefaultContextOptions(ContextType::kRender, GrBackendApi::kOpenGL); auto context = GrDirectContexts::MakeGL(delegate->GetGLInterface(), options); if (!context) { FML_LOG(ERROR) << "Failed to set up Skia Gr context."; return nullptr; } context->setResourceCacheLimit(kGrCacheMaxByteSize); PersistentCache::GetCacheForProcess()->PrecompileKnownSkSLs(context.get()); return context; } GPUSurfaceGLSkia::GPUSurfaceGLSkia(GPUSurfaceGLDelegate* delegate, bool render_to_surface) : GPUSurfaceGLSkia(MakeGLContext(delegate), delegate, render_to_surface) { context_owner_ = true; } GPUSurfaceGLSkia::GPUSurfaceGLSkia(const sk_sp<GrDirectContext>& gr_context, GPUSurfaceGLDelegate* delegate, bool render_to_surface) : delegate_(delegate), context_(gr_context), render_to_surface_(render_to_surface), weak_factory_(this) { auto context_switch = delegate_->GLContextMakeCurrent(); if (!context_switch->GetResult()) { FML_LOG(ERROR) << "Could not make the context current to set up the Gr context."; return; } delegate_->GLContextClearCurrent(); valid_ = gr_context != nullptr; } GPUSurfaceGLSkia::~GPUSurfaceGLSkia() { if (!valid_) { return; } auto context_switch = delegate_->GLContextMakeCurrent(); if (!context_switch->GetResult()) { FML_LOG(ERROR) << "Could not make the context current to destroy the " "GrDirectContext resources."; return; } onscreen_surface_ = nullptr; fbo_id_ = 0; if (context_owner_) { context_->releaseResourcesAndAbandonContext(); } context_ = nullptr; delegate_->GLContextClearCurrent(); } // |Surface| bool GPUSurfaceGLSkia::IsValid() { return valid_; } static SkColorType FirstSupportedColorType(GrDirectContext* context, GrGLenum* format) { #define RETURN_IF_RENDERABLE(x, y) \ if (context->colorTypeSupportedAsSurface((x))) { \ *format = (y); \ return (x); \ } RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GPU_GL_RGBA8); RETURN_IF_RENDERABLE(kARGB_4444_SkColorType, GPU_GL_RGBA4); RETURN_IF_RENDERABLE(kRGB_565_SkColorType, GPU_GL_RGB565); return kUnknown_SkColorType; } static sk_sp<SkSurface> WrapOnscreenSurface(GrDirectContext* context, const SkISize& size, intptr_t fbo) { GrGLenum format = kUnknown_SkColorType; const SkColorType color_type = FirstSupportedColorType(context, &format); GrGLFramebufferInfo framebuffer_info = {}; framebuffer_info.fFBOID = static_cast<GrGLuint>(fbo); framebuffer_info.fFormat = format; auto render_target = GrBackendRenderTargets::MakeGL(size.width(), // width size.height(), // height 0, // sample count 0, // stencil bits framebuffer_info // framebuffer info ); sk_sp<SkColorSpace> colorspace = SkColorSpace::MakeSRGB(); SkSurfaceProps surface_props(0, kUnknown_SkPixelGeometry); return SkSurfaces::WrapBackendRenderTarget( context, // Gr context render_target, // render target GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin, // origin color_type, // color type colorspace, // colorspace &surface_props // surface properties ); } bool GPUSurfaceGLSkia::CreateOrUpdateSurfaces(const SkISize& size) { if (onscreen_surface_ != nullptr && size == SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height())) { // Surface size appears unchanged. So bail. return true; } // We need to do some updates. TRACE_EVENT0("flutter", "UpdateSurfacesSize"); // Either way, we need to get rid of previous surface. onscreen_surface_ = nullptr; fbo_id_ = 0; if (size.isEmpty()) { FML_LOG(ERROR) << "Cannot create surfaces of empty size."; return false; } sk_sp<SkSurface> onscreen_surface; GLFrameInfo frame_info = {static_cast<uint32_t>(size.width()), static_cast<uint32_t>(size.height())}; const GLFBOInfo fbo_info = delegate_->GLContextFBO(frame_info); onscreen_surface = WrapOnscreenSurface(context_.get(), // GL context size, // root surface size fbo_info.fbo_id // window FBO ID ); if (onscreen_surface == nullptr) { // If the onscreen surface could not be wrapped. There is absolutely no // point in moving forward. FML_LOG(ERROR) << "Could not wrap onscreen surface."; return false; } onscreen_surface_ = std::move(onscreen_surface); fbo_id_ = fbo_info.fbo_id; existing_damage_ = fbo_info.existing_damage; return true; } // |Surface| SkMatrix GPUSurfaceGLSkia::GetRootTransformation() const { return delegate_->GLContextSurfaceTransformation(); } // |Surface| std::unique_ptr<SurfaceFrame> GPUSurfaceGLSkia::AcquireFrame( const SkISize& size) { if (delegate_ == nullptr) { return nullptr; } auto context_switch = delegate_->GLContextMakeCurrent(); if (!context_switch->GetResult()) { FML_LOG(ERROR) << "Could not make the context current to acquire the frame."; return nullptr; } SurfaceFrame::FramebufferInfo framebuffer_info; // TODO(38466): Refactor GPU surface APIs take into account the fact that an // external view embedder may want to render to the root surface. if (!render_to_surface_) { framebuffer_info.supports_readback = true; return std::make_unique<SurfaceFrame>( nullptr, framebuffer_info, [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { return true; }, size); } const auto root_surface_transformation = GetRootTransformation(); sk_sp<SkSurface> surface = AcquireRenderSurface(size, root_surface_transformation); if (surface == nullptr) { return nullptr; } surface->getCanvas()->setMatrix(root_surface_transformation); SurfaceFrame::SubmitCallback submit_callback = [weak = weak_factory_.GetWeakPtr()](const SurfaceFrame& surface_frame, DlCanvas* canvas) { return weak ? weak->PresentSurface(surface_frame, canvas) : false; }; framebuffer_info = delegate_->GLContextFramebufferInfo(); if (!framebuffer_info.existing_damage.has_value()) { framebuffer_info.existing_damage = existing_damage_; } return std::make_unique<SurfaceFrame>(surface, framebuffer_info, submit_callback, size, std::move(context_switch)); } bool GPUSurfaceGLSkia::PresentSurface(const SurfaceFrame& frame, DlCanvas* canvas) { if (delegate_ == nullptr || canvas == nullptr || context_ == nullptr) { return false; } delegate_->GLContextSetDamageRegion(frame.submit_info().buffer_damage); { TRACE_EVENT0("flutter", "GrDirectContext::flushAndSubmit"); context_->flushAndSubmit(); } GLPresentInfo present_info = { .fbo_id = fbo_id_, .frame_damage = frame.submit_info().frame_damage, .presentation_time = frame.submit_info().presentation_time, .buffer_damage = frame.submit_info().buffer_damage, }; if (!delegate_->GLContextPresent(present_info)) { return false; } if (delegate_->GLContextFBOResetAfterPresent()) { auto current_size = SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height()); GLFrameInfo frame_info = {static_cast<uint32_t>(current_size.width()), static_cast<uint32_t>(current_size.height())}; // The FBO has changed, ask the delegate for the new FBO and do a surface // re-wrap. const GLFBOInfo fbo_info = delegate_->GLContextFBO(frame_info); auto new_onscreen_surface = WrapOnscreenSurface(context_.get(), // GL context current_size, // root surface size fbo_info.fbo_id // window FBO ID ); if (!new_onscreen_surface) { return false; } onscreen_surface_ = std::move(new_onscreen_surface); fbo_id_ = fbo_info.fbo_id; existing_damage_ = fbo_info.existing_damage; } return true; } sk_sp<SkSurface> GPUSurfaceGLSkia::AcquireRenderSurface( const SkISize& untransformed_size, const SkMatrix& root_surface_transformation) { const auto transformed_rect = root_surface_transformation.mapRect( SkRect::MakeWH(untransformed_size.width(), untransformed_size.height())); const auto transformed_size = SkISize::Make(transformed_rect.width(), transformed_rect.height()); if (!CreateOrUpdateSurfaces(transformed_size)) { return nullptr; } return onscreen_surface_; } // |Surface| GrDirectContext* GPUSurfaceGLSkia::GetContext() { return context_.get(); } // |Surface| std::unique_ptr<GLContextResult> GPUSurfaceGLSkia::MakeRenderContextCurrent() { return delegate_->GLContextMakeCurrent(); } // |Surface| bool GPUSurfaceGLSkia::ClearRenderContext() { return delegate_->GLContextClearCurrent(); } // |Surface| bool GPUSurfaceGLSkia::AllowsDrawingWhenGpuDisabled() const { return delegate_->AllowsDrawingWhenGpuDisabled(); } } // namespace flutter
engine/shell/gpu/gpu_surface_gl_skia.cc/0
{ "file_path": "engine/shell/gpu/gpu_surface_gl_skia.cc", "repo_id": "engine", "token_count": 4939 }
333
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_DELEGATE_H_ #define FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_DELEGATE_H_ #include "flutter/fml/memory/ref_ptr.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/vulkan/procs/vulkan_proc_table.h" #include "flutter/vulkan/vulkan_device.h" #include "flutter/vulkan/vulkan_image.h" #include "third_party/skia/include/core/SkSize.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief Interface implemented by all platform surfaces that can present /// a Vulkan backing store to the "screen". The GPU surface /// abstraction (which abstracts the client rendering API) uses this /// delegation pattern to tell the platform surface (which abstracts /// how backing stores fulfilled by the selected client rendering /// API end up on the "screen" on a particular platform) when the /// rasterizer needs to allocate and present the Vulkan backing /// store. /// /// @see |EmbedderSurfaceVulkan|. /// class GPUSurfaceVulkanDelegate { public: virtual ~GPUSurfaceVulkanDelegate(); /// @brief Obtain a reference to the Vulkan implementation's proc table. /// virtual const vulkan::VulkanProcTable& vk() = 0; /// @brief Called by the engine to fetch a VkImage for writing the next /// frame. /// virtual FlutterVulkanImage AcquireImage(const SkISize& size) = 0; /// @brief Called by the engine once a frame has been rendered to the image /// and it's ready to be bound for further reading/writing. /// virtual bool PresentImage(VkImage image, VkFormat format) = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_DELEGATE_H_
engine/shell/gpu/gpu_surface_vulkan_delegate.h/0
{ "file_path": "engine/shell/gpu/gpu_surface_vulkan_delegate.h", "repo_id": "engine", "token_count": 680 }
334
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/android_display.h" namespace flutter { AndroidDisplay::AndroidDisplay( std::shared_ptr<PlatformViewAndroidJNI> jni_facade) : Display(0, jni_facade->GetDisplayRefreshRate(), jni_facade->GetDisplayWidth(), jni_facade->GetDisplayHeight(), jni_facade->GetDisplayDensity()), jni_facade_(std::move(jni_facade)) {} double AndroidDisplay::GetRefreshRate() const { return jni_facade_->GetDisplayRefreshRate(); } double AndroidDisplay::GetWidth() const { return jni_facade_->GetDisplayWidth(); } double AndroidDisplay::GetHeight() const { return jni_facade_->GetDisplayHeight(); } double AndroidDisplay::GetDevicePixelRatio() const { return jni_facade_->GetDisplayDensity(); } } // namespace flutter
engine/shell/platform/android/android_display.cc/0
{ "file_path": "engine/shell/platform/android/android_display.cc", "repo_id": "engine", "token_count": 354 }
335
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/android_surface_software.h" #include <memory> #include <vector> #include "flutter/fml/logging.h" #include "flutter/fml/platform/android/jni_weak_ref.h" #include "flutter/fml/platform/android/scoped_java_ref.h" #include "flutter/fml/trace_event.h" #include "flutter/shell/platform/android/android_shell_holder.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { namespace { bool GetSkColorType(int32_t buffer_format, SkColorType* color_type, SkAlphaType* alpha_type) { switch (buffer_format) { case WINDOW_FORMAT_RGB_565: *color_type = kRGB_565_SkColorType; *alpha_type = kOpaque_SkAlphaType; return true; case WINDOW_FORMAT_RGBA_8888: *color_type = kRGBA_8888_SkColorType; *alpha_type = kPremul_SkAlphaType; return true; default: return false; } } } // anonymous namespace AndroidSurfaceSoftware::AndroidSurfaceSoftware() { GetSkColorType(WINDOW_FORMAT_RGBA_8888, &target_color_type_, &target_alpha_type_); } AndroidSurfaceSoftware::~AndroidSurfaceSoftware() = default; bool AndroidSurfaceSoftware::IsValid() const { return true; } bool AndroidSurfaceSoftware::ResourceContextMakeCurrent() { // Resource Context always not available on software backend. return false; } bool AndroidSurfaceSoftware::ResourceContextClearCurrent() { return false; } std::unique_ptr<Surface> AndroidSurfaceSoftware::CreateGPUSurface( // The software AndroidSurface neither uses any passed in Skia context // nor does it interact with the AndroidContext's raster Skia context. GrDirectContext* gr_context) { if (!IsValid()) { return nullptr; } auto surface = std::make_unique<GPUSurfaceSoftware>(this, true /* render to surface */); if (!surface->IsValid()) { return nullptr; } return surface; } sk_sp<SkSurface> AndroidSurfaceSoftware::AcquireBackingStore( const SkISize& size) { TRACE_EVENT0("flutter", "AndroidSurfaceSoftware::AcquireBackingStore"); if (!IsValid()) { return nullptr; } if (sk_surface_ != nullptr && SkISize::Make(sk_surface_->width(), sk_surface_->height()) == size) { // The old and new surface sizes are the same. Nothing to do here. return sk_surface_; } SkImageInfo image_info = SkImageInfo::Make(size.fWidth, size.fHeight, target_color_type_, target_alpha_type_, SkColorSpace::MakeSRGB()); sk_surface_ = SkSurfaces::Raster(image_info); return sk_surface_; } bool AndroidSurfaceSoftware::PresentBackingStore( sk_sp<SkSurface> backing_store) { TRACE_EVENT0("flutter", "AndroidSurfaceSoftware::PresentBackingStore"); if (!IsValid() || backing_store == nullptr) { return false; } SkPixmap pixmap; if (!backing_store->peekPixels(&pixmap)) { return false; } ANativeWindow_Buffer native_buffer; if (ANativeWindow_lock(native_window_->handle(), &native_buffer, nullptr)) { return false; } SkColorType color_type; SkAlphaType alpha_type; if (GetSkColorType(native_buffer.format, &color_type, &alpha_type)) { SkImageInfo native_image_info = SkImageInfo::Make( native_buffer.width, native_buffer.height, color_type, alpha_type); std::unique_ptr<SkCanvas> canvas = SkCanvas::MakeRasterDirect( native_image_info, native_buffer.bits, native_buffer.stride * SkColorTypeBytesPerPixel(color_type)); if (canvas) { SkBitmap bitmap; if (bitmap.installPixels(pixmap)) { canvas->drawImageRect( bitmap.asImage(), SkRect::MakeIWH(native_buffer.width, native_buffer.height), SkSamplingOptions()); } } } ANativeWindow_unlockAndPost(native_window_->handle()); return true; } void AndroidSurfaceSoftware::TeardownOnScreenContext() {} bool AndroidSurfaceSoftware::OnScreenSurfaceResize(const SkISize& size) { return true; } bool AndroidSurfaceSoftware::SetNativeWindow( fml::RefPtr<AndroidNativeWindow> window) { native_window_ = std::move(window); if (!(native_window_ && native_window_->IsValid())) { return false; } int32_t window_format = ANativeWindow_getFormat(native_window_->handle()); if (window_format < 0) { return false; } if (!GetSkColorType(window_format, &target_color_type_, &target_alpha_type_)) { return false; } return true; } } // namespace flutter
engine/shell/platform/android/android_surface_software.cc/0
{ "file_path": "engine/shell/platform/android/android_surface_software.cc", "repo_id": "engine", "token_count": 1788 }
336
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_SURFACE_POOL_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_SURFACE_POOL_H_ #include <mutex> #include "flutter/flow/surface.h" #include "flutter/shell/platform/android/context/android_context.h" #include "flutter/shell/platform/android/surface/android_surface.h" namespace flutter { //------------------------------------------------------------------------------ /// An Overlay layer represents an `android.view.View` in the C side. /// /// The `id` is used to uniquely identify the layer and recycle it between /// frames. /// struct OverlayLayer { OverlayLayer(int id, std::unique_ptr<AndroidSurface> android_surface, std::unique_ptr<Surface> surface); ~OverlayLayer(); // A unique id to identify the overlay when it gets recycled. const int id; // A GPU surface. const std::unique_ptr<AndroidSurface> android_surface; // A GPU surface. This may change when the overlay is recycled. std::unique_ptr<Surface> surface; // The `GrContext` that is currently used by the overlay surfaces. // We track this to know when the GrContext for the Flutter app has changed // so we can update the overlay with the new context. // // This may change when the overlay is recycled. intptr_t gr_context_key; }; class SurfacePool { public: SurfacePool(); ~SurfacePool(); // Gets a layer from the pool if available, or allocates a new one. // Finally, it marks the layer as used. That is, it increments // `available_layer_index_`. std::shared_ptr<OverlayLayer> GetLayer( GrDirectContext* gr_context, const AndroidContext& android_context, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade, const std::shared_ptr<AndroidSurfaceFactory>& surface_factory); // Gets the layers in the pool that aren't currently used. // This method doesn't mark the layers as unused. std::vector<std::shared_ptr<OverlayLayer>> GetUnusedLayers(); // Marks the layers in the pool as available for reuse. void RecycleLayers(); // Destroys all the layers in the pool. void DestroyLayers(const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade); // Sets the frame size used by the layers in the pool. // If the current layers in the pool have a different frame size, // then they are deallocated as soon as |GetLayer| is called. void SetFrameSize(SkISize frame_size); // Returns true if the current pool has layers in use. bool HasLayers(); private: // The index of the entry in the layers_ vector that determines the beginning // of the unused layers. For example, consider the following vector: // _____ // | 0 | // |---| // | 1 | <-- `available_layer_index_` // |---| // | 2 | // |---| // // This indicates that entries starting from 1 can be reused meanwhile the // entry at position 0 cannot be reused. size_t available_layer_index_ = 0; // The layers in the pool. std::vector<std::shared_ptr<OverlayLayer>> layers_; // The frame size of the layers in the pool. SkISize current_frame_size_; // The frame size to be used by future layers. SkISize requested_frame_size_; // Used to guard public methods. std::mutex mutex_; void DestroyLayersLocked( const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_SURFACE_POOL_H_
engine/shell/platform/android/external_view_embedder/surface_pool.h/0
{ "file_path": "engine/shell/platform/android/external_view_embedder/surface_pool.h", "repo_id": "engine", "token_count": 1151 }
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. // THIS FILE IS REPLACED WITH AN AUTO_GENERATED FILE (AND EXISTS JUST FOR IDE SUPPORT). // DO NOT EDIT THE VALUES HERE - SEE $flutter_root/tools/gen_android_buildconfig.py package io.flutter; public final class BuildConfig { private BuildConfig() { { } } public static final boolean DEBUG = false; public static final boolean PROFILE = false; public static final boolean RELEASE = false; public static final boolean JIT_RELEASE = false; }
engine/shell/platform/android/io/flutter/BuildConfig.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/BuildConfig.java", "repo_id": "engine", "token_count": 178 }
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. package io.flutter.embedding.android; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.FlutterEngine; /** * Provides a {@link io.flutter.embedding.engine.FlutterEngine} instance to be used by a {@code * FlutterActivity} or {@code FlutterFragment}. * * <p>{@link io.flutter.embedding.engine.FlutterEngine} instances require significant time to warm * up. Therefore, a developer might choose to hold onto an existing {@link * io.flutter.embedding.engine.FlutterEngine} and connect it to various {@link FlutterActivity}s * and/or {@code FlutterFragment}s. This interface facilitates providing a cached, pre-warmed {@link * io.flutter.embedding.engine.FlutterEngine}. */ public interface FlutterEngineProvider { /** * Returns the {@link io.flutter.embedding.engine.FlutterEngine} that should be used by a child * {@code FlutterFragment}. * * <p>This method may return a new {@link io.flutter.embedding.engine.FlutterEngine}, an existing, * cached {@link FlutterEngine}, or null to express that the {@code FlutterEngineProvider} would * like the {@code FlutterFragment} to provide its own {@code FlutterEngine} instance. * * @param context The current context. e.g. An activity. * @return The Flutter engine. */ @Nullable FlutterEngine provideFlutterEngine(@NonNull Context context); }
engine/shell/platform/android/io/flutter/embedding/android/FlutterEngineProvider.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/android/FlutterEngineProvider.java", "repo_id": "engine", "token_count": 477 }
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. package io.flutter.embedding.android; import android.app.Activity; import androidx.annotation.NonNull; import androidx.core.util.Consumer; import androidx.window.java.layout.WindowInfoTrackerCallbackAdapter; import androidx.window.layout.WindowLayoutInfo; import java.util.concurrent.Executor; /** Wraps {@link WindowInfoTrackerCallbackAdapter} in order to be able to mock it during testing. */ public class WindowInfoRepositoryCallbackAdapterWrapper { @NonNull final WindowInfoTrackerCallbackAdapter adapter; public WindowInfoRepositoryCallbackAdapterWrapper( @NonNull WindowInfoTrackerCallbackAdapter adapter) { this.adapter = adapter; } public void addWindowLayoutInfoListener( @NonNull Activity activity, @NonNull Executor executor, @NonNull Consumer<WindowLayoutInfo> consumer) { adapter.addWindowLayoutInfoListener(activity, executor, consumer); } public void removeWindowLayoutInfoListener(@NonNull Consumer<WindowLayoutInfo> consumer) { adapter.removeWindowLayoutInfoListener(consumer); } }
engine/shell/platform/android/io/flutter/embedding/android/WindowInfoRepositoryCallbackAdapterWrapper.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/android/WindowInfoRepositoryCallbackAdapterWrapper.java", "repo_id": "engine", "token_count": 338 }
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. package io.flutter.embedding.engine.loader; /** Encapsulates all the information that Flutter needs from application manifest. */ public final class FlutterApplicationInfo { private static final String DEFAULT_AOT_SHARED_LIBRARY_NAME = "libapp.so"; private static final String DEFAULT_VM_SNAPSHOT_DATA = "vm_snapshot_data"; private static final String DEFAULT_ISOLATE_SNAPSHOT_DATA = "isolate_snapshot_data"; private static final String DEFAULT_FLUTTER_ASSETS_DIR = "flutter_assets"; public final String aotSharedLibraryName; public final String vmSnapshotData; public final String isolateSnapshotData; public final String flutterAssetsDir; public final String domainNetworkPolicy; public final String nativeLibraryDir; final boolean automaticallyRegisterPlugins; public FlutterApplicationInfo( String aotSharedLibraryName, String vmSnapshotData, String isolateSnapshotData, String flutterAssetsDir, String domainNetworkPolicy, String nativeLibraryDir, boolean automaticallyRegisterPlugins) { this.aotSharedLibraryName = aotSharedLibraryName == null ? DEFAULT_AOT_SHARED_LIBRARY_NAME : aotSharedLibraryName; this.vmSnapshotData = vmSnapshotData == null ? DEFAULT_VM_SNAPSHOT_DATA : vmSnapshotData; this.isolateSnapshotData = isolateSnapshotData == null ? DEFAULT_ISOLATE_SNAPSHOT_DATA : isolateSnapshotData; this.flutterAssetsDir = flutterAssetsDir == null ? DEFAULT_FLUTTER_ASSETS_DIR : flutterAssetsDir; this.nativeLibraryDir = nativeLibraryDir; this.domainNetworkPolicy = domainNetworkPolicy == null ? "" : domainNetworkPolicy; this.automaticallyRegisterPlugins = automaticallyRegisterPlugins; } }
engine/shell/platform/android/io/flutter/embedding/engine/loader/FlutterApplicationInfo.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/loader/FlutterApplicationInfo.java", "repo_id": "engine", "token_count": 593 }
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. package io.flutter.embedding.engine.plugins.lifecycle; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.lifecycle.Lifecycle; /** * An {@code Object} that can be used to obtain a {@link Lifecycle} reference. * * <p><strong>DO NOT USE THIS CLASS IN AN APP OR A PLUGIN.</strong> * * <p>This class is used by the flutter_android_lifecycle package to provide access to a {@link * Lifecycle} in a way that makes it easier for Flutter and the Flutter plugin ecosystem to handle * breaking changes in Lifecycle libraries. */ @Keep public class HiddenLifecycleReference { @NonNull private final Lifecycle lifecycle; public HiddenLifecycleReference(@NonNull Lifecycle lifecycle) { this.lifecycle = lifecycle; } @NonNull public Lifecycle getLifecycle() { return lifecycle; } }
engine/shell/platform/android/io/flutter/embedding/engine/plugins/lifecycle/HiddenLifecycleReference.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/lifecycle/HiddenLifecycleReference.java", "repo_id": "engine", "token_count": 293 }
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. package io.flutter.embedding.engine.systemchannels; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import io.flutter.Log; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.StringCodec; import java.util.Locale; /** * A {@link BasicMessageChannel} that communicates lifecycle events to the framework. * * <p>The activity listens to the Android lifecycle events, in addition to the focus events for * windows, and this channel combines that information to decide if the application is the inactive, * resumed, paused, or detached state. */ public class LifecycleChannel { private static final String TAG = "LifecycleChannel"; private static final String CHANNEL_NAME = "flutter/lifecycle"; // This enum should match the Dart enum of the same name. // // HIDDEN isn't used on Android (it's synthesized in the Framework code). It's // only listed here so that apicheck_test.dart can make sure that the states here // match the Dart code. private enum AppLifecycleState { DETACHED, RESUMED, INACTIVE, HIDDEN, PAUSED, }; private AppLifecycleState lastAndroidState = null; private AppLifecycleState lastFlutterState = null; private boolean lastFocus = true; @NonNull private final BasicMessageChannel<String> channel; public LifecycleChannel(@NonNull DartExecutor dartExecutor) { this(new BasicMessageChannel<String>(dartExecutor, CHANNEL_NAME, StringCodec.INSTANCE)); } @VisibleForTesting public LifecycleChannel(@NonNull BasicMessageChannel<String> channel) { this.channel = channel; } // Here's the state table this implements: // // | Android State | Window focused | Flutter state | // |---------------|----------------|---------------| // | Resumed | true | resumed | // | Resumed | false | inactive | // | Paused | true | inactive | // | Paused | false | inactive | // | Stopped | true | paused | // | Stopped | false | paused | // | Detached | true | detached | // | Detached | false | detached | // // The hidden state isn't used on Android, it's synthesized in the Framework // code when transitioning between paused and inactive in either direction. private void sendState(AppLifecycleState state, boolean hasFocus) { if (lastAndroidState == state && hasFocus == lastFocus) { // No inputs changed, so Flutter state could not have changed. return; } if (state == null && lastAndroidState == null) { // If we're responding to a focus change before the state is set, just // keep the last reported focus state and don't send anything to the // framework. This could happen if focus events and lifecycle events are // delivered out of the expected order. lastFocus = hasFocus; return; } AppLifecycleState newState = null; switch (state) { case RESUMED: // Focus is only taken into account when the Android state is "Resumed". // In all other states, focus is ignored, because we can't know what order // Android lifecycle notifications and window focus notifications events // will arrive in, and those states don't send input events anyhow. newState = hasFocus ? AppLifecycleState.RESUMED : AppLifecycleState.INACTIVE; break; case INACTIVE: case HIDDEN: case PAUSED: case DETACHED: newState = state; break; } // Keep the last reported values for future updates. lastAndroidState = state; lastFocus = hasFocus; if (newState == lastFlutterState) { // No change in the resulting Flutter state, so don't report anything. return; } String message = "AppLifecycleState." + newState.name().toLowerCase(Locale.ROOT); Log.v(TAG, "Sending " + message + " message."); channel.send(message); lastFlutterState = newState; } // Called if at least one window in the app has focus, even if the focused // window doesn't contain a Flutter view. public void aWindowIsFocused() { sendState(lastAndroidState, true); } // Called if no windows in the app have focus. public void noWindowsAreFocused() { sendState(lastAndroidState, false); } public void appIsResumed() { sendState(AppLifecycleState.RESUMED, lastFocus); } public void appIsInactive() { sendState(AppLifecycleState.INACTIVE, lastFocus); } public void appIsPaused() { sendState(AppLifecycleState.PAUSED, lastFocus); } public void appIsDetached() { sendState(AppLifecycleState.DETACHED, lastFocus); } }
engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/LifecycleChannel.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/LifecycleChannel.java", "repo_id": "engine", "token_count": 1691 }
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. package io.flutter.plugin.common; import androidx.annotation.Nullable; import io.flutter.BuildConfig; import io.flutter.Log; /** * An implementation of {@link MethodChannel.Result} that writes error results to the Android log. */ public class ErrorLogResult implements MethodChannel.Result { private String tag; private int level; public ErrorLogResult(String tag) { this(tag, Log.WARN); } public ErrorLogResult(String tag, int level) { this.tag = tag; this.level = level; } @Override public void success(@Nullable Object result) {} @Override public void error( String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) { String details = (errorDetails != null) ? " details: " + errorDetails : ""; if (level >= Log.WARN || BuildConfig.DEBUG) { Log.println(level, tag, errorMessage + details); } } @Override public void notImplemented() { if (level >= Log.WARN || BuildConfig.DEBUG) { Log.println(level, tag, "method not implemented"); } } }
engine/shell/platform/android/io/flutter/plugin/common/ErrorLogResult.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/common/ErrorLogResult.java", "repo_id": "engine", "token_count": 380 }
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. package io.flutter.plugin.editing; import static io.flutter.Build.API_LEVELS; import android.annotation.TargetApi; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.DynamicLayout; import android.text.Editable; import android.text.InputType; import android.text.Layout; import android.text.Selection; import android.text.TextPaint; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.BaseInputConnection; import android.view.inputmethod.CursorAnchorInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputContentInfo; import android.view.inputmethod.InputMethodManager; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.view.inputmethod.InputConnectionCompat; import io.flutter.Log; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.systemchannels.TextInputChannel; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; public class InputConnectionAdaptor extends BaseInputConnection implements ListenableEditingState.EditingStateWatcher { private static final String TAG = "InputConnectionAdaptor"; public interface KeyboardDelegate { public boolean handleEvent(@NonNull KeyEvent keyEvent); } private final View mFlutterView; private final int mClient; private final TextInputChannel textInputChannel; private final ListenableEditingState mEditable; private final EditorInfo mEditorInfo; private ExtractedTextRequest mExtractRequest; private boolean mMonitorCursorUpdate = false; private CursorAnchorInfo.Builder mCursorAnchorInfoBuilder; private ExtractedText mExtractedText = new ExtractedText(); private InputMethodManager mImm; private final Layout mLayout; private FlutterTextUtils flutterTextUtils; private final KeyboardDelegate keyboardDelegate; private int batchEditNestDepth = 0; @SuppressWarnings("deprecation") public InputConnectionAdaptor( View view, int client, TextInputChannel textInputChannel, KeyboardDelegate keyboardDelegate, ListenableEditingState editable, EditorInfo editorInfo, FlutterJNI flutterJNI) { super(view, true); mFlutterView = view; mClient = client; this.textInputChannel = textInputChannel; mEditable = editable; mEditable.addEditingStateListener(this); mEditorInfo = editorInfo; this.keyboardDelegate = keyboardDelegate; this.flutterTextUtils = new FlutterTextUtils(flutterJNI); // We create a dummy Layout with max width so that the selection // shifting acts as if all text were in one line. mLayout = new DynamicLayout( mEditable, new TextPaint(), Integer.MAX_VALUE, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); mImm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); } public InputConnectionAdaptor( View view, int client, TextInputChannel textInputChannel, KeyboardDelegate keyboardDelegate, ListenableEditingState editable, EditorInfo editorInfo) { this(view, client, textInputChannel, keyboardDelegate, editable, editorInfo, new FlutterJNI()); } private ExtractedText getExtractedText(ExtractedTextRequest request) { mExtractedText.startOffset = 0; mExtractedText.partialStartOffset = -1; mExtractedText.partialEndOffset = -1; mExtractedText.selectionStart = mEditable.getSelectionStart(); mExtractedText.selectionEnd = mEditable.getSelectionEnd(); mExtractedText.text = request == null || (request.flags & GET_TEXT_WITH_STYLES) == 0 ? mEditable.toString() : mEditable; return mExtractedText; } private CursorAnchorInfo getCursorAnchorInfo() { if (mCursorAnchorInfoBuilder == null) { mCursorAnchorInfoBuilder = new CursorAnchorInfo.Builder(); } else { mCursorAnchorInfoBuilder.reset(); } mCursorAnchorInfoBuilder.setSelectionRange( mEditable.getSelectionStart(), mEditable.getSelectionEnd()); final int composingStart = mEditable.getComposingStart(); final int composingEnd = mEditable.getComposingEnd(); if (composingStart >= 0 && composingEnd > composingStart) { mCursorAnchorInfoBuilder.setComposingText( composingStart, mEditable.toString().subSequence(composingStart, composingEnd)); } else { mCursorAnchorInfoBuilder.setComposingText(-1, ""); } return mCursorAnchorInfoBuilder.build(); } @Override public Editable getEditable() { return mEditable; } @Override public boolean beginBatchEdit() { mEditable.beginBatchEdit(); batchEditNestDepth += 1; return super.beginBatchEdit(); } @Override public boolean endBatchEdit() { boolean result = super.endBatchEdit(); batchEditNestDepth -= 1; mEditable.endBatchEdit(); return result; } @Override public boolean commitText(CharSequence text, int newCursorPosition) { final boolean result = super.commitText(text, newCursorPosition); return result; } @Override public boolean deleteSurroundingText(int beforeLength, int afterLength) { if (mEditable.getSelectionStart() == -1) { return true; } final boolean result = super.deleteSurroundingText(beforeLength, afterLength); return result; } @Override public boolean deleteSurroundingTextInCodePoints(int beforeLength, int afterLength) { boolean result = super.deleteSurroundingTextInCodePoints(beforeLength, afterLength); return result; } @Override public boolean setComposingRegion(int start, int end) { final boolean result = super.setComposingRegion(start, end); return result; } @Override public boolean setComposingText(CharSequence text, int newCursorPosition) { boolean result; beginBatchEdit(); if (text.length() == 0) { result = super.commitText(text, newCursorPosition); } else { result = super.setComposingText(text, newCursorPosition); } endBatchEdit(); return result; } @Override public boolean finishComposingText() { final boolean result = super.finishComposingText(); return result; } // When there's not enough vertical screen space, the IME may enter fullscreen mode and this // method will be used to get (a portion of) the currently edited text. Samsung keyboard seems // to use this method instead of InputConnection#getText{Before,After}Cursor. // See https://github.com/flutter/engine/pull/17426. // TODO(garyq): Implement a more feature complete version of getExtractedText @Override public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { final boolean textMonitor = (flags & GET_EXTRACTED_TEXT_MONITOR) != 0; if (textMonitor == (mExtractRequest == null)) { Log.d(TAG, "The input method toggled text monitoring " + (textMonitor ? "on" : "off")); } // Enables text monitoring if the relevant flag is set. See // InputConnectionAdaptor#didChangeEditingState. mExtractRequest = textMonitor ? request : null; return getExtractedText(request); } @Override public boolean requestCursorUpdates(int cursorUpdateMode) { if ((cursorUpdateMode & CURSOR_UPDATE_IMMEDIATE) != 0) { mImm.updateCursorAnchorInfo(mFlutterView, getCursorAnchorInfo()); } final boolean updated = (cursorUpdateMode & CURSOR_UPDATE_MONITOR) != 0; if (updated != mMonitorCursorUpdate) { Log.d(TAG, "The input method toggled cursor monitoring " + (updated ? "on" : "off")); } // Enables cursor monitoring. See InputConnectionAdaptor#didChangeEditingState. mMonitorCursorUpdate = updated; return true; } @Override public boolean clearMetaKeyStates(int states) { boolean result = super.clearMetaKeyStates(states); return result; } @Override public void closeConnection() { super.closeConnection(); mEditable.removeEditingStateListener(this); for (; batchEditNestDepth > 0; batchEditNestDepth--) { endBatchEdit(); } } @Override public boolean setSelection(int start, int end) { beginBatchEdit(); boolean result = super.setSelection(start, end); endBatchEdit(); return result; } // Sanitizes the index to ensure the index is within the range of the // contents of editable. private static int clampIndexToEditable(int index, Editable editable) { int clamped = Math.max(0, Math.min(editable.length(), index)); if (clamped != index) { Log.d( "flutter", "Text selection index was clamped (" + index + "->" + clamped + ") to remain in bounds. This may not be your fault, as some keyboards may select outside of bounds."); } return clamped; } // This function is called both when hardware key events occur and aren't // handled by the framework, as well as when soft keyboard editing events // occur, and need a chance to be handled by the framework. @Override public boolean sendKeyEvent(KeyEvent event) { return keyboardDelegate.handleEvent(event); } public boolean handleKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) { return handleHorizontalMovement(true, event.isShiftPressed()); } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) { return handleHorizontalMovement(false, event.isShiftPressed()); } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) { return handleVerticalMovement(true, event.isShiftPressed()); } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) { return handleVerticalMovement(false, event.isShiftPressed()); // When the enter key is pressed on a non-multiline field, consider it a // submit instead of a newline. } else if ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER || event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_ENTER) && (InputType.TYPE_TEXT_FLAG_MULTI_LINE & mEditorInfo.inputType) == 0) { performEditorAction(mEditorInfo.imeOptions & EditorInfo.IME_MASK_ACTION); return true; } else { // Enter a character. final int selStart = Selection.getSelectionStart(mEditable); final int selEnd = Selection.getSelectionEnd(mEditable); final int character = event.getUnicodeChar(); if (selStart < 0 || selEnd < 0 || character == 0) { return false; } final int selMin = Math.min(selStart, selEnd); final int selMax = Math.max(selStart, selEnd); beginBatchEdit(); if (selMin != selMax) mEditable.delete(selMin, selMax); mEditable.insert(selMin, String.valueOf((char) character)); setSelection(selMin + 1, selMin + 1); endBatchEdit(); return true; } } return false; } private boolean handleHorizontalMovement(boolean isLeft, boolean isShiftPressed) { final int selStart = Selection.getSelectionStart(mEditable); final int selEnd = Selection.getSelectionEnd(mEditable); if (selStart < 0 || selEnd < 0) { return false; } final int newSelectionEnd = isLeft ? Math.max(flutterTextUtils.getOffsetBefore(mEditable, selEnd), 0) : Math.min(flutterTextUtils.getOffsetAfter(mEditable, selEnd), mEditable.length()); final boolean shouldCollapse = selStart == selEnd && !isShiftPressed; if (shouldCollapse) { setSelection(newSelectionEnd, newSelectionEnd); } else { setSelection(selStart, newSelectionEnd); } return true; }; private boolean handleVerticalMovement(boolean isUp, boolean isShiftPressed) { final int selStart = Selection.getSelectionStart(mEditable); final int selEnd = Selection.getSelectionEnd(mEditable); if (selStart < 0 || selEnd < 0) { return false; } final boolean shouldCollapse = selStart == selEnd && !isShiftPressed; beginBatchEdit(); if (shouldCollapse) { if (isUp) { Selection.moveUp(mEditable, mLayout); } else { Selection.moveDown(mEditable, mLayout); } final int newSelection = Selection.getSelectionStart(mEditable); setSelection(newSelection, newSelection); } else { if (isUp) { Selection.extendUp(mEditable, mLayout); } else { Selection.extendDown(mEditable, mLayout); } setSelection(Selection.getSelectionStart(mEditable), Selection.getSelectionEnd(mEditable)); } endBatchEdit(); return true; } @Override public boolean performContextMenuAction(int id) { beginBatchEdit(); final boolean result = doPerformContextMenuAction(id); endBatchEdit(); return result; } private boolean doPerformContextMenuAction(int id) { if (id == android.R.id.selectAll) { setSelection(0, mEditable.length()); return true; } else if (id == android.R.id.cut) { int selStart = Selection.getSelectionStart(mEditable); int selEnd = Selection.getSelectionEnd(mEditable); if (selStart != selEnd) { int selMin = Math.min(selStart, selEnd); int selMax = Math.max(selStart, selEnd); CharSequence textToCut = mEditable.subSequence(selMin, selMax); ClipboardManager clipboard = (ClipboardManager) mFlutterView.getContext().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("text label?", textToCut); clipboard.setPrimaryClip(clip); mEditable.delete(selMin, selMax); setSelection(selMin, selMin); } return true; } else if (id == android.R.id.copy) { int selStart = Selection.getSelectionStart(mEditable); int selEnd = Selection.getSelectionEnd(mEditable); if (selStart != selEnd) { CharSequence textToCopy = mEditable.subSequence(Math.min(selStart, selEnd), Math.max(selStart, selEnd)); ClipboardManager clipboard = (ClipboardManager) mFlutterView.getContext().getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setPrimaryClip(ClipData.newPlainText("text label?", textToCopy)); } return true; } else if (id == android.R.id.paste) { ClipboardManager clipboard = (ClipboardManager) mFlutterView.getContext().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = clipboard.getPrimaryClip(); if (clip != null) { CharSequence textToPaste = clip.getItemAt(0).coerceToText(mFlutterView.getContext()); int selStart = Math.max(0, Selection.getSelectionStart(mEditable)); int selEnd = Math.max(0, Selection.getSelectionEnd(mEditable)); int selMin = Math.min(selStart, selEnd); int selMax = Math.max(selStart, selEnd); if (selMin != selMax) mEditable.delete(selMin, selMax); mEditable.insert(selMin, textToPaste); int newSelStart = selMin + textToPaste.length(); setSelection(newSelStart, newSelStart); } return true; } return false; } @Override public boolean performPrivateCommand(String action, Bundle data) { textInputChannel.performPrivateCommand(mClient, action, data); return true; } @Override public boolean performEditorAction(int actionCode) { switch (actionCode) { case EditorInfo.IME_ACTION_NONE: textInputChannel.newline(mClient); break; case EditorInfo.IME_ACTION_UNSPECIFIED: textInputChannel.unspecifiedAction(mClient); break; case EditorInfo.IME_ACTION_GO: textInputChannel.go(mClient); break; case EditorInfo.IME_ACTION_SEARCH: textInputChannel.search(mClient); break; case EditorInfo.IME_ACTION_SEND: textInputChannel.send(mClient); break; case EditorInfo.IME_ACTION_NEXT: textInputChannel.next(mClient); break; case EditorInfo.IME_ACTION_PREVIOUS: textInputChannel.previous(mClient); break; default: case EditorInfo.IME_ACTION_DONE: textInputChannel.done(mClient); break; } return true; } @Override @TargetApi(API_LEVELS.API_25) @RequiresApi(API_LEVELS.API_25) public boolean commitContent(InputContentInfo inputContentInfo, int flags, Bundle opts) { // Ensure permission is granted. if (Build.VERSION.SDK_INT >= API_LEVELS.API_25 && (flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) { try { inputContentInfo.requestPermission(); } catch (Exception e) { return false; } } else { return false; } if (inputContentInfo.getDescription().getMimeTypeCount() > 0) { inputContentInfo.requestPermission(); final Uri uri = inputContentInfo.getContentUri(); final String mimeType = inputContentInfo.getDescription().getMimeType(0); Context context = mFlutterView.getContext(); if (uri != null) { InputStream is; try { // Extract byte data from the given URI. is = context.getContentResolver().openInputStream(uri); } catch (FileNotFoundException ex) { inputContentInfo.releasePermission(); return false; } if (is != null) { final byte[] data = this.readStreamFully(is, 64 * 1024); final Map<String, Object> obj = new HashMap<>(); obj.put("mimeType", mimeType); obj.put("data", data); obj.put("uri", uri.toString()); // Commit the content to the text input channel and release the permission. textInputChannel.commitContent(mClient, obj); inputContentInfo.releasePermission(); return true; } } inputContentInfo.releasePermission(); } return false; } private byte[] readStreamFully(InputStream is, int blocksize) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[blocksize]; while (true) { int len = -1; try { len = is.read(buffer); } catch (IOException ex) { } if (len == -1) break; baos.write(buffer, 0, len); } return baos.toByteArray(); } // -------- Start: ListenableEditingState watcher implementation ------- @Override public void didChangeEditingState( boolean textChanged, boolean selectionChanged, boolean composingRegionChanged) { // This method notifies the input method that the editing state has changed. // updateSelection is mandatory. updateExtractedText and updateCursorAnchorInfo // are on demand (if the input method set the correspoinding monitoring // flags). See getExtractedText and requestCursorUpdates. // Always send selection update. InputMethodManager#updateSelection skips // sending the message if none of the parameters have changed since the last // time we called it. mImm.updateSelection( mFlutterView, mEditable.getSelectionStart(), mEditable.getSelectionEnd(), mEditable.getComposingStart(), mEditable.getComposingEnd()); if (mExtractRequest != null) { mImm.updateExtractedText( mFlutterView, mExtractRequest.token, getExtractedText(mExtractRequest)); } if (mMonitorCursorUpdate) { final CursorAnchorInfo info = getCursorAnchorInfo(); mImm.updateCursorAnchorInfo(mFlutterView, info); } } // -------- End: ListenableEditingState watcher implementation ------- }
engine/shell/platform/android/io/flutter/plugin/editing/InputConnectionAdaptor.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/editing/InputConnectionAdaptor.java", "repo_id": "engine", "token_count": 7512 }
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.plugin.platform; import static io.flutter.Build.API_LEVELS; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.PorterDuff; import android.graphics.Rect; import android.view.MotionEvent; import android.view.Surface; import android.view.View; import android.view.ViewParent; import android.view.ViewTreeObserver; import android.view.accessibility.AccessibilityEvent; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.Log; import io.flutter.embedding.android.AndroidTouchProcessor; import io.flutter.util.ViewUtils; /** * Wraps a platform view to intercept gestures and project this view onto a {@link * PlatformViewRenderTarget}. * * <p>An Android platform view is composed by the engine using a {@code TextureLayer}. The view is * embeded to the Android view hierarchy like a normal view, but it's projected onto a {@link * PlatformViewRenderTarget}, so it can be efficiently composed by the engine. * * <p>Since the view is in the Android view hierarchy, keyboard and accessibility interactions * behave normally. */ @TargetApi(API_LEVELS.API_23) public class PlatformViewWrapper extends FrameLayout { private static final String TAG = "PlatformViewWrapper"; private int prevLeft; private int prevTop; private int left; private int top; private AndroidTouchProcessor touchProcessor; private PlatformViewRenderTarget renderTarget; private ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener; public PlatformViewWrapper(@NonNull Context context) { super(context); setWillNotDraw(false); } public PlatformViewWrapper( @NonNull Context context, @NonNull PlatformViewRenderTarget renderTarget) { this(context); this.renderTarget = renderTarget; } /** * Sets the touch processor that allows to intercept gestures. * * @param newTouchProcessor The touch processor. */ public void setTouchProcessor(@Nullable AndroidTouchProcessor newTouchProcessor) { touchProcessor = newTouchProcessor; } /** * Sets the layout parameters for this view. * * @param params The new parameters. */ public void setLayoutParams(@NonNull FrameLayout.LayoutParams params) { super.setLayoutParams(params); left = params.leftMargin; top = params.topMargin; } public void resizeRenderTarget(int width, int height) { if (renderTarget != null) { renderTarget.resize(width, height); } } public int getRenderTargetWidth() { if (renderTarget != null) { return renderTarget.getWidth(); } return 0; } public int getRenderTargetHeight() { if (renderTarget != null) { return renderTarget.getHeight(); } return 0; } /** Releases resources. */ public void release() { if (renderTarget != null) { renderTarget.release(); renderTarget = null; } } @Override public boolean onInterceptTouchEvent(@NonNull MotionEvent event) { return true; } @Override public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { final View embeddedView = getChildAt(0); if (embeddedView != null && embeddedView.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { return false; } // Forward the request only if the embedded view is in the Flutter accessibility tree. // The embedded view may be ignored when the framework doesn't populate a SemanticNode // for the current platform view. // See AccessibilityBridge for more. return super.requestSendAccessibilityEvent(child, event); } /** Used on Android O+, {@link invalidateChildInParent} used for previous versions. */ @SuppressLint("NewApi") @Override public void onDescendantInvalidated(@NonNull View child, @NonNull View target) { super.onDescendantInvalidated(child, target); invalidate(); } @Override public ViewParent invalidateChildInParent(int[] location, Rect dirty) { invalidate(); return super.invalidateChildInParent(location, dirty); } @Override @SuppressLint("NewApi") public void draw(Canvas canvas) { if (renderTarget == null) { super.draw(canvas); Log.e(TAG, "Platform view cannot be composed without a RenderTarget."); return; } final Surface targetSurface = renderTarget.getSurface(); final Canvas targetCanvas = targetSurface.lockHardwareCanvas(); if (targetCanvas == null) { // Cannot render right now. invalidate(); return; } try { // Fill the render target with transparent pixels. This is needed for platform views that // expect a transparent background. targetCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); // Override the canvas that this subtree of views will use to draw. super.draw(targetCanvas); } finally { renderTarget.scheduleFrame(); targetSurface.unlockCanvasAndPost(targetCanvas); } } @Override @SuppressLint("ClickableViewAccessibility") public boolean onTouchEvent(@NonNull MotionEvent event) { if (touchProcessor == null) { return super.onTouchEvent(event); } final Matrix screenMatrix = new Matrix(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: prevLeft = left; prevTop = top; screenMatrix.postTranslate(left, top); break; case MotionEvent.ACTION_MOVE: // While the view is dragged, use the left and top positions as // they were at the moment the touch event fired. screenMatrix.postTranslate(prevLeft, prevTop); prevLeft = left; prevTop = top; break; case MotionEvent.ACTION_UP: default: screenMatrix.postTranslate(left, top); break; } return touchProcessor.onTouchEvent(event, screenMatrix); } @VisibleForTesting public ViewTreeObserver.OnGlobalFocusChangeListener getActiveFocusListener() { return this.activeFocusListener; } public void setOnDescendantFocusChangeListener(@NonNull OnFocusChangeListener userFocusListener) { unsetOnDescendantFocusChangeListener(); final ViewTreeObserver observer = getViewTreeObserver(); if (observer.isAlive() && activeFocusListener == null) { activeFocusListener = new ViewTreeObserver.OnGlobalFocusChangeListener() { @Override public void onGlobalFocusChanged(View oldFocus, View newFocus) { userFocusListener.onFocusChange( PlatformViewWrapper.this, ViewUtils.childHasFocus(PlatformViewWrapper.this)); } }; observer.addOnGlobalFocusChangeListener(activeFocusListener); } } public void unsetOnDescendantFocusChangeListener() { final ViewTreeObserver observer = getViewTreeObserver(); if (observer.isAlive() && activeFocusListener != null) { final ViewTreeObserver.OnGlobalFocusChangeListener currFocusListener = activeFocusListener; activeFocusListener = null; observer.removeOnGlobalFocusChangeListener(currFocusListener); } } }
engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewWrapper.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewWrapper.java", "repo_id": "engine", "token_count": 2468 }
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.util; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.window.layout.WindowMetrics; import androidx.window.layout.WindowMetricsCalculator; public final class ViewUtils { public interface DisplayUpdater { /** Publishes display metrics to Dart code in Flutter. */ public void updateDisplayMetrics(float width, float height, float density); } /** * Calculates the maximum display metrics for the given context, and pushes the metric data to the * updater. */ public static void calculateMaximumDisplayMetrics( @Nullable Context context, @NonNull DisplayUpdater updater) { Activity activity = getActivity(context); if (activity != null) { WindowMetrics metrics = WindowMetricsCalculator.getOrCreate().computeMaximumWindowMetrics(activity); float width = metrics.getBounds().width(); float height = metrics.getBounds().height(); float density = context.getResources().getDisplayMetrics().density; updater.updateDisplayMetrics(width, height, density); } } /** * Retrieves the {@link Activity} from a given {@link Context}. * * <p>This method will recursively traverse up the context chain if it is a {@link ContextWrapper} * until it finds the first instance of the base context that is an {@link Activity}. */ @Nullable public static Activity getActivity(@Nullable Context context) { if (context == null) { return null; } if (context instanceof Activity) { return (Activity) context; } if (context instanceof ContextWrapper) { // Recurse up chain of base contexts until we find an Activity. return getActivity(((ContextWrapper) context).getBaseContext()); } return null; } /** * Determines if the current view or any descendant view has focus. * * @param root The root view. * @return True if the current view or any descendant view has focus. */ public static boolean childHasFocus(@Nullable View root) { return traverseHierarchy(root, (View view) -> view.hasFocus()); } /** * Returns true if the root or any child view is an instance of the given types. * * @param root The root view. * @param viewTypes The types of views. * @return true if any child view is an instance of any of the given types. */ public static boolean hasChildViewOfType(@Nullable View root, Class<? extends View>[] viewTypes) { return traverseHierarchy( root, (View view) -> { for (int i = 0; i < viewTypes.length; i++) { final Class<? extends View> viewType = viewTypes[i]; if (viewType.isInstance(view)) { return true; } } return false; }); } /** Allows to visit a view. */ public interface ViewVisitor { boolean run(@NonNull View view); } /** * Traverses the view hierarchy in pre-order and runs the visitor for each child view including * the root view. * * <p>If the visitor returns true, the traversal stops, and the method returns true. * * <p>If the visitor returns false, the traversal continues until all views are visited. * * @param root The root view. * @param visitor The visitor. * @return true if the visitor returned true for a given view. */ public static boolean traverseHierarchy(@Nullable View root, @NonNull ViewVisitor visitor) { if (root == null) { return false; } if (visitor.run(root)) { return true; } if (root instanceof ViewGroup) { final ViewGroup viewGroup = (ViewGroup) root; for (int idx = 0; idx < viewGroup.getChildCount(); idx++) { if (traverseHierarchy(viewGroup.getChildAt(idx), visitor)) { return true; } } } return false; } }
engine/shell/platform/android/io/flutter/util/ViewUtils.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/util/ViewUtils.java", "repo_id": "engine", "token_count": 1408 }
347
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/platform_message_handler_android.h" namespace flutter { PlatformMessageHandlerAndroid::PlatformMessageHandlerAndroid( const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) : jni_facade_(jni_facade) {} void PlatformMessageHandlerAndroid::InvokePlatformMessageResponseCallback( int response_id, std::unique_ptr<fml::Mapping> mapping) { // Called from any thread. if (!response_id) { return; } // TODO(gaaclarke): Move the jump to the ui thread here from // PlatformMessageResponseDart so we won't need to use a mutex anymore. fml::RefPtr<flutter::PlatformMessageResponse> message_response; { std::lock_guard lock(pending_responses_mutex_); auto it = pending_responses_.find(response_id); if (it == pending_responses_.end()) { return; } message_response = std::move(it->second); pending_responses_.erase(it); } message_response->Complete(std::move(mapping)); } void PlatformMessageHandlerAndroid::InvokePlatformMessageEmptyResponseCallback( int response_id) { // Called from any thread. if (!response_id) { return; } fml::RefPtr<flutter::PlatformMessageResponse> message_response; { std::lock_guard lock(pending_responses_mutex_); auto it = pending_responses_.find(response_id); if (it == pending_responses_.end()) { return; } message_response = std::move(it->second); pending_responses_.erase(it); } message_response->CompleteEmpty(); } // |PlatformView| void PlatformMessageHandlerAndroid::HandlePlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { // Called from any thread. int response_id = next_response_id_.fetch_add(1); if (auto response = message->response()) { std::lock_guard lock(pending_responses_mutex_); pending_responses_[response_id] = response; } // This call can re-enter in InvokePlatformMessageXxxResponseCallback. jni_facade_->FlutterViewHandlePlatformMessage(std::move(message), response_id); } } // namespace flutter
engine/shell/platform/android/platform_message_handler_android.cc/0
{ "file_path": "engine/shell/platform/android/platform_message_handler_android.cc", "repo_id": "engine", "token_count": 782 }
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. #include "flutter/shell/platform/android/surface/android_surface.h" #include "flutter/fml/logging.h" namespace flutter { AndroidSurface::AndroidSurface() = default; AndroidSurface::~AndroidSurface() = default; std::unique_ptr<Surface> AndroidSurface::CreateSnapshotSurface() { return nullptr; } std::shared_ptr<impeller::Context> AndroidSurface::GetImpellerContext() { return nullptr; } } // namespace flutter
engine/shell/platform/android/surface/android_surface.cc/0
{ "file_path": "engine/shell/platform/android/surface/android_surface.cc", "repo_id": "engine", "token_count": 182 }
349
package io.flutter.embedding.android; import static android.content.ComponentCallbacks2.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNotNull; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.View; import androidx.annotation.NonNull; import androidx.lifecycle.Lifecycle; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.FlutterInjector; import io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.Host; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterEngineCache; import io.flutter.embedding.engine.FlutterEngineGroup; import io.flutter.embedding.engine.FlutterEngineGroupCache; import io.flutter.embedding.engine.FlutterShellArgs; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.loader.FlutterLoader; import io.flutter.embedding.engine.plugins.activity.ActivityControlSurface; import io.flutter.embedding.engine.renderer.FlutterRenderer; import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener; import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; import io.flutter.embedding.engine.systemchannels.LifecycleChannel; import io.flutter.embedding.engine.systemchannels.LocalizationChannel; import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; import io.flutter.embedding.engine.systemchannels.NavigationChannel; import io.flutter.embedding.engine.systemchannels.SettingsChannel; import io.flutter.embedding.engine.systemchannels.SystemChannel; import io.flutter.embedding.engine.systemchannels.TextInputChannel; import io.flutter.plugin.localization.LocalizationPlugin; import io.flutter.plugin.platform.PlatformViewsController; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.Robolectric; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class FlutterActivityAndFragmentDelegateTest { private final Context ctx = ApplicationProvider.getApplicationContext(); private FlutterEngine mockFlutterEngine; private FlutterActivityAndFragmentDelegate.Host mockHost; private FlutterActivityAndFragmentDelegate.Host mockHost2; @SuppressWarnings("deprecation") // Robolectric.setupActivity // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 @Before public void setup() { FlutterInjector.reset(); // Create a mocked FlutterEngine for the various interactions required by the delegate // being tested. mockFlutterEngine = mockFlutterEngine(); // Create a mocked Host, which is required by the delegate being tested. mockHost = mock(FlutterActivityAndFragmentDelegate.Host.class); when(mockHost.getContext()).thenReturn(ctx); when(mockHost.getActivity()).thenReturn(Robolectric.setupActivity(Activity.class)); when(mockHost.getLifecycle()).thenReturn(mock(Lifecycle.class)); when(mockHost.getFlutterShellArgs()).thenReturn(new FlutterShellArgs(new String[] {})); when(mockHost.getDartEntrypointFunctionName()).thenReturn("main"); when(mockHost.getDartEntrypointArgs()).thenReturn(null); when(mockHost.getAppBundlePath()).thenReturn("/fake/path"); when(mockHost.getInitialRoute()).thenReturn("/"); when(mockHost.getRenderMode()).thenReturn(RenderMode.surface); when(mockHost.getTransparencyMode()).thenReturn(TransparencyMode.transparent); when(mockHost.provideFlutterEngine(any(Context.class))).thenReturn(mockFlutterEngine); when(mockHost.shouldAttachEngineToActivity()).thenReturn(true); when(mockHost.shouldHandleDeeplinking()).thenReturn(false); when(mockHost.shouldDestroyEngineWithHost()).thenReturn(true); when(mockHost.shouldDispatchAppLifecycleState()).thenReturn(true); when(mockHost.attachToEngineAutomatically()).thenReturn(true); mockHost2 = mock(FlutterActivityAndFragmentDelegate.Host.class); when(mockHost2.getContext()).thenReturn(ctx); when(mockHost2.getActivity()).thenReturn(Robolectric.setupActivity(Activity.class)); when(mockHost2.getLifecycle()).thenReturn(mock(Lifecycle.class)); when(mockHost2.getFlutterShellArgs()).thenReturn(new FlutterShellArgs(new String[] {})); when(mockHost2.getDartEntrypointFunctionName()).thenReturn("main"); when(mockHost2.getDartEntrypointArgs()).thenReturn(null); when(mockHost2.getAppBundlePath()).thenReturn("/fake/path"); when(mockHost2.getInitialRoute()).thenReturn("/"); when(mockHost2.getRenderMode()).thenReturn(RenderMode.surface); when(mockHost2.getTransparencyMode()).thenReturn(TransparencyMode.transparent); when(mockHost2.provideFlutterEngine(any(Context.class))).thenReturn(mockFlutterEngine); when(mockHost2.shouldAttachEngineToActivity()).thenReturn(true); when(mockHost2.shouldHandleDeeplinking()).thenReturn(false); when(mockHost2.shouldDestroyEngineWithHost()).thenReturn(true); when(mockHost2.shouldDispatchAppLifecycleState()).thenReturn(true); when(mockHost2.attachToEngineAutomatically()).thenReturn(true); } @Test public void itSendsLifecycleEventsToFlutter() { // ---- Test setup ---- // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // We're testing lifecycle behaviors, which require/expect that certain methods have already // been executed by the time they run. Therefore, we run those expected methods first. delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // --- Execute the behavior under test --- // By the time an Activity/Fragment is started, we don't expect any lifecycle messages // to have been sent to Flutter. delegate.onStart(); verify(mockFlutterEngine.getLifecycleChannel(), never()).aWindowIsFocused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).noWindowsAreFocused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsResumed(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); // When the Activity/Fragment is resumed, a resumed message should have been sent to Flutter. delegate.onResume(); verify(mockFlutterEngine.getLifecycleChannel(), never()).aWindowIsFocused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).noWindowsAreFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); // When the app loses focus because something else has it (e.g. notification // windowshade or app switcher), it should go to inactive. delegate.onWindowFocusChanged(false); verify(mockFlutterEngine.getLifecycleChannel(), never()).aWindowIsFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); // When the app regains focus, it should go to resumed again. delegate.onWindowFocusChanged(true); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).aWindowIsFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); // When the Activity/Fragment is paused, an inactive message should have been sent to Flutter. delegate.onPause(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).aWindowIsFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsInactive(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); // When the Activity/Fragment is stopped, a paused message should have been sent to Flutter. // Notice that Flutter uses the term "paused" in a different way, and at a different time // than the Android OS. delegate.onStop(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).aWindowIsFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsInactive(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsPaused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); // When activity detaches, a detached message should have been sent to Flutter. delegate.onDetach(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).aWindowIsFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsInactive(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsPaused(); verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsDetached(); } @Test public void itDoesNotSendsLifecycleEventsToFlutter() { // ---- Test setup ---- // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); when(mockHost.shouldDispatchAppLifecycleState()).thenReturn(false); // We're testing lifecycle behaviors, which require/expect that certain methods have already // been executed by the time they run. Therefore, we run those expected methods first. delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); delegate.onResume(); delegate.onWindowFocusChanged(false); delegate.onWindowFocusChanged(true); delegate.onPause(); delegate.onStop(); delegate.onDetach(); verify(mockFlutterEngine.getLifecycleChannel(), never()).aWindowIsFocused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).noWindowsAreFocused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsResumed(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); } @Test public void itDefersToTheHostToProvideFlutterEngine() { // ---- Test setup ---- // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is created in onAttach(). delegate.onAttach(ctx); // Verify that the host was asked to provide a FlutterEngine. verify(mockHost, times(1)).provideFlutterEngine(any(Context.class)); // Verify that the delegate's FlutterEngine is our mock FlutterEngine. assertEquals( "The delegate failed to use the host's FlutterEngine.", mockFlutterEngine, delegate.getFlutterEngine()); } @Test public void itUsesCachedEngineWhenProvided() { // ---- Test setup ---- // Place a FlutterEngine in the static cache. FlutterEngine cachedEngine = mockFlutterEngine(); FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); // Adjust fake host to request cached engine. when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is obtained in onAttach(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); delegate.onResume(); // --- Verify that the cached engine was used --- // Verify that the non-cached engine was not used. verify(mockFlutterEngine.getDartExecutor(), never()) .executeDartEntrypoint(any(DartExecutor.DartEntrypoint.class)); // We should never instruct a cached engine to execute Dart code - it should already be // executing it. verify(cachedEngine.getDartExecutor(), never()) .executeDartEntrypoint(any(DartExecutor.DartEntrypoint.class)); // If the cached engine is being used, it should have sent a resumed lifecycle event. verify(cachedEngine.getLifecycleChannel(), times(1)).appIsResumed(); } @Test(expected = IllegalStateException.class) public void itThrowsExceptionIfCachedEngineDoesNotExist() { // ---- Test setup ---- // Adjust fake host to request cached engine that does not exist. when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine existence is verified in onAttach() delegate.onAttach(ctx); // Expect IllegalStateException. } // Bug: b/271100292 @Test public void flutterEngineGroupGetsInitialRouteFromIntent() { // ---- Test setup ---- FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); Activity mockActivity = mock(Activity.class); Intent mockIntent = mock(Intent.class); when(mockFlutterLoader.findAppBundlePath()).thenReturn("default_flutter_assets/path"); FlutterInjector.setInstance( new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); FlutterEngineGroup flutterEngineGroup = mock(FlutterEngineGroup.class); FlutterEngineGroupCache.getInstance().put("my_flutter_engine_group", flutterEngineGroup); List<String> entryPointArgs = new ArrayList<>(); entryPointArgs.add("entrypoint-arg"); // Adjust fake host to request cached engine group. when(mockHost.getInitialRoute()).thenReturn(null); when(mockHost.getCachedEngineGroupId()).thenReturn("my_flutter_engine_group"); when(mockHost.provideFlutterEngine(any(Context.class))).thenReturn(null); when(mockHost.shouldAttachEngineToActivity()).thenReturn(false); when(mockHost.getDartEntrypointArgs()).thenReturn(entryPointArgs); when(mockHost.shouldHandleDeeplinking()).thenReturn(true); when(mockHost.getActivity()).thenReturn(mockActivity); when(mockActivity.getIntent()).thenReturn(mockIntent); when(mockIntent.getData()).thenReturn(Uri.parse("foo://example.com/initial_route")); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is obtained in onAttach(). delegate.onAttach(ctx); DartExecutor.DartEntrypoint entrypoint = new DartExecutor.DartEntrypoint("/fake/path", "main"); ArgumentCaptor<FlutterEngineGroup.Options> optionsCaptor = ArgumentCaptor.forClass(FlutterEngineGroup.Options.class); verify(flutterEngineGroup, times(1)).createAndRunEngine(optionsCaptor.capture()); assertEquals("foo://example.com/initial_route", optionsCaptor.getValue().getInitialRoute()); } @Test public void itUsesNewEngineInGroupWhenProvided() { // ---- Test setup ---- FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); when(mockFlutterLoader.findAppBundlePath()).thenReturn("default_flutter_assets/path"); FlutterInjector.setInstance( new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); FlutterEngineGroup flutterEngineGroup = mock(FlutterEngineGroup.class); FlutterEngineGroupCache.getInstance().put("my_flutter_engine_group", flutterEngineGroup); List<String> entryPointArgs = new ArrayList<>(); entryPointArgs.add("entrypoint-arg"); // Adjust fake host to request cached engine group. when(mockHost.getCachedEngineGroupId()).thenReturn("my_flutter_engine_group"); when(mockHost.provideFlutterEngine(any(Context.class))).thenReturn(null); when(mockHost.shouldAttachEngineToActivity()).thenReturn(false); when(mockHost.getDartEntrypointArgs()).thenReturn(entryPointArgs); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is obtained in onAttach(). delegate.onAttach(ctx); // If the engine in FlutterEngineGroup is being used, it should have sent a resumed lifecycle // event. // Note: "/fake/path" and "main" come from `setUp()`. DartExecutor.DartEntrypoint entrypoint = new DartExecutor.DartEntrypoint("/fake/path", "main"); ArgumentCaptor<FlutterEngineGroup.Options> optionsCaptor = ArgumentCaptor.forClass(FlutterEngineGroup.Options.class); verify(flutterEngineGroup, times(1)).createAndRunEngine(optionsCaptor.capture()); assertEquals(mockHost.getContext(), optionsCaptor.getValue().getContext()); assertEquals(entrypoint, optionsCaptor.getValue().getDartEntrypoint()); assertEquals(mockHost.getInitialRoute(), optionsCaptor.getValue().getInitialRoute()); assertNotNull(optionsCaptor.getValue().getDartEntrypointArgs()); assertEquals(1, optionsCaptor.getValue().getDartEntrypointArgs().size()); assertEquals("entrypoint-arg", optionsCaptor.getValue().getDartEntrypointArgs().get(0)); } @Test(expected = IllegalStateException.class) public void itThrowsExceptionIfNewEngineInGroupNotExist() { // ---- Test setup ---- FlutterEngineGroupCache.getInstance().clear(); // Adjust fake host to request cached engine group that does not exist. when(mockHost.getCachedEngineGroupId()).thenReturn("my_flutter_engine_group"); when(mockHost.getCachedEngineId()).thenReturn(null); when(mockHost.provideFlutterEngine(any(Context.class))).thenReturn(null); when(mockHost.shouldAttachEngineToActivity()).thenReturn(false); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine existence is verified in onAttach() delegate.onAttach(ctx); // Expect IllegalStateException. } @Test public void itGivesHostAnOpportunityToConfigureFlutterEngine() { // ---- Test setup ---- // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is created in onAttach(). delegate.onAttach(ctx); // Verify that the host was asked to configure our FlutterEngine. verify(mockHost, times(1)).configureFlutterEngine(mockFlutterEngine); } @Test public void itGivesHostAnOpportunityToConfigureFlutterSurfaceView() { // ---- Test setup ---- // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // Verify that the host was asked to configure a FlutterSurfaceView. verify(mockHost, times(1)).onFlutterSurfaceViewCreated(isNotNull()); } @SuppressWarnings("deprecation") // Robolectric.setupActivity // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 @Test public void itGivesHostAnOpportunityToConfigureFlutterTextureView() { // ---- Test setup ---- Host customMockHost = mock(Host.class); when(customMockHost.getContext()).thenReturn(ctx); when(customMockHost.getActivity()).thenReturn(Robolectric.setupActivity(Activity.class)); when(customMockHost.getLifecycle()).thenReturn(mock(Lifecycle.class)); when(customMockHost.getFlutterShellArgs()).thenReturn(new FlutterShellArgs(new String[] {})); when(customMockHost.getDartEntrypointFunctionName()).thenReturn("main"); when(customMockHost.getAppBundlePath()).thenReturn("/fake/path"); when(customMockHost.getInitialRoute()).thenReturn("/"); when(customMockHost.getRenderMode()).thenReturn(RenderMode.texture); when(customMockHost.getTransparencyMode()).thenReturn(TransparencyMode.transparent); when(customMockHost.provideFlutterEngine(any(Context.class))).thenReturn(mockFlutterEngine); when(customMockHost.shouldAttachEngineToActivity()).thenReturn(true); when(customMockHost.shouldDestroyEngineWithHost()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(customMockHost); // --- Execute the behavior under test --- delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, false); // Verify that the host was asked to configure a FlutterTextureView. verify(customMockHost, times(1)).onFlutterTextureViewCreated(isNotNull()); } @Test public void itGivesHostAnOpportunityToCleanUpFlutterEngine() { // ---- Test setup ---- // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is created in onAttach(). delegate.onAttach(ctx); delegate.onDetach(); // Verify that the host was asked to configure our FlutterEngine. verify(mockHost, times(1)).cleanUpFlutterEngine(mockFlutterEngine); } @Test public void itSendsInitialRouteToFlutter() { // ---- Test setup ---- // Set initial route on our fake Host. when(mockHost.getInitialRoute()).thenReturn("/my/route"); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The initial route is sent in onStart(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); // Verify that the navigation channel was given our initial route. verify(mockFlutterEngine.getNavigationChannel(), times(1)).setInitialRoute("/my/route"); } @Test public void itExecutesDartEntrypointProvidedByHost() { // ---- Test setup ---- // Set Dart entrypoint parameters on fake host. when(mockHost.getAppBundlePath()).thenReturn("/my/bundle/path"); when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint"); // Create the DartEntrypoint that we expect to be executed. DartExecutor.DartEntrypoint dartEntrypoint = new DartExecutor.DartEntrypoint("/my/bundle/path", "myEntrypoint"); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // Dart is executed in onStart(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); // Verify that the host's Dart entrypoint was used. verify(mockFlutterEngine.getDartExecutor(), times(1)) .executeDartEntrypoint(eq(dartEntrypoint), isNull()); } @Test public void itExecutesDartEntrypointWithArgsProvidedByHost() { // ---- Test setup ---- // Set Dart entrypoint parameters on fake host. when(mockHost.getAppBundlePath()).thenReturn("/my/bundle/path"); when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint"); List<String> dartEntrypointArgs = new ArrayList<String>(Arrays.asList("foo", "bar")); when(mockHost.getDartEntrypointArgs()).thenReturn(dartEntrypointArgs); // Create the DartEntrypoint that we expect to be executed DartExecutor.DartEntrypoint dartEntrypoint = new DartExecutor.DartEntrypoint("/my/bundle/path", "myEntrypoint"); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // Dart is executed in onStart(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); // Verify that the host's Dart entrypoint was used. verify(mockFlutterEngine.getDartExecutor(), times(1)) .executeDartEntrypoint(any(DartExecutor.DartEntrypoint.class), eq(dartEntrypointArgs)); } @Test public void itExecutesDartLibraryUriProvidedByHost() { when(mockHost.getAppBundlePath()).thenReturn("/my/bundle/path"); when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint"); when(mockHost.getDartEntrypointLibraryUri()).thenReturn("package:foo/bar.dart"); DartExecutor.DartEntrypoint expectedEntrypoint = new DartExecutor.DartEntrypoint("/my/bundle/path", "package:foo/bar.dart", "myEntrypoint"); FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); verify(mockFlutterEngine.getDartExecutor(), times(1)) .executeDartEntrypoint(eq(expectedEntrypoint), isNull()); } @Test public void itUsesDefaultFlutterLoaderAppBundlePathWhenUnspecified() { // ---- Test setup ---- FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); when(mockFlutterLoader.findAppBundlePath()).thenReturn("default_flutter_assets/path"); FlutterInjector.setInstance( new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); // Set Dart entrypoint parameters on fake host. when(mockHost.getAppBundlePath()).thenReturn(null); when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint"); // Create the DartEntrypoint that we expect to be executed. DartExecutor.DartEntrypoint dartEntrypoint = new DartExecutor.DartEntrypoint("default_flutter_assets/path", "myEntrypoint"); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // Dart is executed in onStart(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); // Verify that the host's Dart entrypoint was used. verify(mockFlutterEngine.getDartExecutor(), times(1)) .executeDartEntrypoint(eq(dartEntrypoint), isNull()); } // "Attaching" to the surrounding Activity refers to Flutter being able to control // system chrome and other Activity-level details. If Flutter is not attached to the // surrounding Activity, it cannot control those details. This includes plugins. @Test public void itAttachesFlutterToTheActivityIfDesired() { // ---- Test setup ---- // Declare that the host wants Flutter to attach to the surrounding Activity. when(mockHost.shouldAttachEngineToActivity()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // Flutter is attached to the surrounding Activity in onAttach. delegate.onAttach(ctx); // Verify that the ActivityControlSurface was told to attach to an Activity. verify(mockFlutterEngine.getActivityControlSurface(), times(1)) .attachToActivity(any(ExclusiveAppComponent.class), any(Lifecycle.class)); // Flutter is detached from the surrounding Activity in onDetach. delegate.onDetach(); // Verify that the ActivityControlSurface was told to detach from the Activity. verify(mockFlutterEngine.getActivityControlSurface(), times(1)).detachFromActivity(); } // "Attaching" to the surrounding Activity refers to Flutter being able to control // system chrome and other Activity-level details. If Flutter is not attached to the // surrounding Activity, it cannot control those details. This includes plugins. @Test public void itDoesNotAttachFlutterToTheActivityIfNotDesired() { // ---- Test setup ---- // Declare that the host does NOT want Flutter to attach to the surrounding Activity. when(mockHost.shouldAttachEngineToActivity()).thenReturn(false); // getActivity() returns null if the activity is not attached when(mockHost.getActivity()).thenReturn(null); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // Flutter is attached to the surrounding Activity in onAttach. delegate.onAttach(ctx); // Make sure all of the other lifecycle methods can run safely as well // without a valid Activity delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); delegate.onResume(); delegate.onPause(); delegate.onStop(); delegate.onDestroyView(); // Flutter is detached from the surrounding Activity in onDetach. delegate.onDetach(); // Verify that the ActivityControlSurface was NOT told to attach or detach to an Activity. verify(mockFlutterEngine.getActivityControlSurface(), never()) .attachToActivity(any(ExclusiveAppComponent.class), any(Lifecycle.class)); verify(mockFlutterEngine.getActivityControlSurface(), never()).detachFromActivity(); } @Test public void itSendsPopRouteMessageToFlutterWhenHardwareBackButtonIsPressed() { // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); // Emulate the host and inform our delegate that the back button was pressed. delegate.onBackPressed(); // Verify that the navigation channel tried to send a message to Flutter. verify(mockFlutterEngine.getNavigationChannel(), times(1)).popRoute(); } @Test public void itForwardsOnRequestPermissionsResultToFlutterEngine() { // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); // Emulate the host and call the method that we expect to be forwarded. delegate.onRequestPermissionsResult(0, new String[] {}, new int[] {}); // Verify that the call was forwarded to the engine. verify(mockFlutterEngine.getActivityControlSurface(), times(1)) .onRequestPermissionsResult(any(Integer.class), any(String[].class), any(int[].class)); } @Test public void itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinking() { Intent intent = FlutterActivity.createDefaultIntent(ctx); intent.setData(Uri.parse("http://myApp/custom/route?query=test")); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); when(mockHost.getActivity()).thenReturn(flutterActivity); when(mockHost.getInitialRoute()).thenReturn(null); when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // Emulate app start. delegate.onStart(); // Verify that the navigation channel was given the initial route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)) .setInitialRoute("http://myApp/custom/route?query=test"); } @Test public void itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinkingWithQueryParameterAndFragment() { Intent intent = FlutterActivity.createDefaultIntent(ctx); intent.setData(Uri.parse("http://myApp/custom/route?query=test#fragment")); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); when(mockHost.getActivity()).thenReturn(flutterActivity); when(mockHost.getInitialRoute()).thenReturn(null); when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // Emulate app start. delegate.onStart(); // Verify that the navigation channel was given the initial route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)) .setInitialRoute("http://myApp/custom/route?query=test#fragment"); } @Test public void itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinkingWithFragmentNoQueryParameter() { Intent intent = FlutterActivity.createDefaultIntent(ctx); intent.setData(Uri.parse("http://myApp/custom/route#fragment")); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); when(mockHost.getActivity()).thenReturn(flutterActivity); when(mockHost.getInitialRoute()).thenReturn(null); when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // Emulate app start. delegate.onStart(); // Verify that the navigation channel was given the initial route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)) .setInitialRoute("http://myApp/custom/route#fragment"); } @Test public void itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinkingNoQueryParameter() { Intent intent = FlutterActivity.createDefaultIntent(ctx); intent.setData(Uri.parse("http://myApp/custom/route")); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); when(mockHost.getActivity()).thenReturn(flutterActivity); when(mockHost.getInitialRoute()).thenReturn(null); when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // Emulate app start. delegate.onStart(); // Verify that the navigation channel was given the initial route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)) .setInitialRoute("http://myApp/custom/route"); } @Test public void itSendsdefaultInitialRouteOnStartIfNotDeepLinkingFromIntent() { // Creates an empty intent without launch uri. Intent intent = FlutterActivity.createDefaultIntent(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); when(mockHost.getActivity()).thenReturn(flutterActivity); when(mockHost.getInitialRoute()).thenReturn(null); when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // Emulate app start. delegate.onStart(); // Verify that the navigation channel was given the default initial route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)).setInitialRoute("/"); } @Test public void itSendsPushRouteInformationMessageWhenOnNewIntent() { when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); String expected = "http://myApp/custom/route?query=test"; Intent mockIntent = mock(Intent.class); when(mockIntent.getData()).thenReturn(Uri.parse(expected)); // Emulate the host and call the method that we expect to be forwarded. delegate.onNewIntent(mockIntent); // Verify that the navigation channel was given the push route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRouteInformation(expected); } @Test public void itDoesSendPushRouteInformationMessageWhenOnNewIntentIsNonHierarchicalUri() { when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); Intent mockIntent = mock(Intent.class); // mailto: URIs are non-hierarchical when(mockIntent.getData()).thenReturn(Uri.parse("mailto:[email protected]")); // Emulate the host and call the method delegate.onNewIntent(mockIntent); // Verify that the navigation channel was not given a push route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)) .pushRouteInformation("mailto:[email protected]"); } @Test public void itSendsPushRouteInformationMessageWhenOnNewIntentWithQueryParameterAndFragment() { when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); String expected = "http://myApp/custom/route?query=test#fragment"; Intent mockIntent = mock(Intent.class); when(mockIntent.getData()).thenReturn(Uri.parse(expected)); // Emulate the host and call the method that we expect to be forwarded. delegate.onNewIntent(mockIntent); // Verify that the navigation channel was given the push route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRouteInformation(expected); } @Test public void itSendsPushRouteInformationMessageWhenOnNewIntentWithFragmentNoQueryParameter() { when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); String expected = "http://myApp/custom/route#fragment"; Intent mockIntent = mock(Intent.class); when(mockIntent.getData()).thenReturn(Uri.parse(expected)); // Emulate the host and call the method that we expect to be forwarded. delegate.onNewIntent(mockIntent); // Verify that the navigation channel was given the push route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRouteInformation(expected); } @Test public void itSendsPushRouteInformationMessageWhenOnNewIntentNoQueryParameter() { when(mockHost.shouldHandleDeeplinking()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); String expected = "http://myApp/custom/route#fragment"; Intent mockIntent = mock(Intent.class); when(mockIntent.getData()).thenReturn(Uri.parse(expected)); // Emulate the host and call the method that we expect to be forwarded. delegate.onNewIntent(mockIntent); // Verify that the navigation channel was given the push route message. verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRouteInformation(expected); } @Test public void itForwardsOnNewIntentToFlutterEngine() { // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); // Emulate the host and call the method that we expect to be forwarded. delegate.onNewIntent(mock(Intent.class)); // Verify that the call was forwarded to the engine. verify(mockFlutterEngine.getActivityControlSurface(), times(1)).onNewIntent(any(Intent.class)); } @Test public void itForwardsOnActivityResultToFlutterEngine() { // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); // Emulate the host and call the method that we expect to be forwarded. delegate.onActivityResult(0, 0, null); // Verify that the call was forwarded to the engine. verify(mockFlutterEngine.getActivityControlSurface(), times(1)) .onActivityResult(any(Integer.class), any(Integer.class), /*intent=*/ isNull()); } @Test public void itForwardsOnUserLeaveHintToFlutterEngine() { // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); // Emulate the host and call the method that we expect to be forwarded. delegate.onUserLeaveHint(); // Verify that the call was forwarded to the engine. verify(mockFlutterEngine.getActivityControlSurface(), times(1)).onUserLeaveHint(); } @Test public void itNotifiesDartExecutorAndSendsMessageOverSystemChannelWhenToldToTrimMemory() { // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // The FlutterEngine is set up in onAttach(). delegate.onAttach(ctx); // Test assumes no frames have been displayed. verify(mockHost, times(0)).onFlutterUiDisplayed(); // Emulate the host and call the method that we expect to be forwarded. delegate.onTrimMemory(TRIM_MEMORY_RUNNING_MODERATE); delegate.onTrimMemory(TRIM_MEMORY_RUNNING_LOW); verify(mockFlutterEngine.getDartExecutor(), times(0)).notifyLowMemoryWarning(); verify(mockFlutterEngine.getSystemChannel(), times(0)).sendMemoryPressureWarning(); delegate.onTrimMemory(TRIM_MEMORY_RUNNING_CRITICAL); delegate.onTrimMemory(TRIM_MEMORY_BACKGROUND); delegate.onTrimMemory(TRIM_MEMORY_COMPLETE); delegate.onTrimMemory(TRIM_MEMORY_MODERATE); delegate.onTrimMemory(TRIM_MEMORY_UI_HIDDEN); verify(mockFlutterEngine.getDartExecutor(), times(0)).notifyLowMemoryWarning(); verify(mockFlutterEngine.getSystemChannel(), times(0)).sendMemoryPressureWarning(); verify(mockHost, times(0)).onFlutterUiDisplayed(); delegate.onCreateView(null, null, null, 0, false); final FlutterRenderer renderer = mockFlutterEngine.getRenderer(); ArgumentCaptor<FlutterUiDisplayListener> listenerCaptor = ArgumentCaptor.forClass(FlutterUiDisplayListener.class); // 2 times: once for engine attachment, once for view creation. verify(renderer, times(2)).addIsDisplayingFlutterUiListener(listenerCaptor.capture()); listenerCaptor.getValue().onFlutterUiDisplayed(); verify(mockHost, times(1)).onFlutterUiDisplayed(); delegate.onTrimMemory(TRIM_MEMORY_RUNNING_MODERATE); verify(mockFlutterEngine.getDartExecutor(), times(0)).notifyLowMemoryWarning(); verify(mockFlutterEngine.getSystemChannel(), times(0)).sendMemoryPressureWarning(); delegate.onTrimMemory(TRIM_MEMORY_RUNNING_LOW); delegate.onTrimMemory(TRIM_MEMORY_RUNNING_CRITICAL); delegate.onTrimMemory(TRIM_MEMORY_BACKGROUND); delegate.onTrimMemory(TRIM_MEMORY_COMPLETE); delegate.onTrimMemory(TRIM_MEMORY_MODERATE); delegate.onTrimMemory(TRIM_MEMORY_UI_HIDDEN); verify(mockFlutterEngine.getDartExecutor(), times(6)).notifyLowMemoryWarning(); verify(mockFlutterEngine.getSystemChannel(), times(6)).sendMemoryPressureWarning(); } @Test public void itDestroysItsOwnEngineIfHostRequestsIt() { // ---- Test setup ---- // Adjust fake host to request engine destruction. when(mockHost.shouldDestroyEngineWithHost()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // Push the delegate through all lifecycle methods all the way to destruction. delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); delegate.onResume(); delegate.onPause(); delegate.onStop(); delegate.onDestroyView(); delegate.onDetach(); // --- Verify that the cached engine was destroyed --- verify(mockFlutterEngine, times(1)).destroy(); } @Test public void itDoesNotDestroyItsOwnEngineWhenHostSaysNotTo() { // ---- Test setup ---- // Adjust fake host to request engine destruction. when(mockHost.shouldDestroyEngineWithHost()).thenReturn(false); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // Push the delegate through all lifecycle methods all the way to destruction. delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); delegate.onResume(); delegate.onPause(); delegate.onStop(); delegate.onDestroyView(); delegate.onDetach(); // --- Verify that the cached engine was destroyed --- verify(mockFlutterEngine, never()).destroy(); } @Test public void itDestroysCachedEngineWhenHostRequestsIt() { // ---- Test setup ---- // Place a FlutterEngine in the static cache. FlutterEngine cachedEngine = mockFlutterEngine(); FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); // Adjust fake host to request cached engine. when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); // Adjust fake host to request engine destruction. when(mockHost.shouldDestroyEngineWithHost()).thenReturn(true); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // Push the delegate through all lifecycle methods all the way to destruction. delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); delegate.onResume(); delegate.onPause(); delegate.onStop(); delegate.onDestroyView(); delegate.onDetach(); // --- Verify that the cached engine was destroyed --- verify(cachedEngine, times(1)).destroy(); assertNull(FlutterEngineCache.getInstance().get("my_flutter_engine")); } @Test public void itDoesNotDestroyCachedEngineWhenHostSaysNotTo() { // ---- Test setup ---- // Place a FlutterEngine in the static cache. FlutterEngine cachedEngine = mockFlutterEngine(); FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); // Adjust fake host to request cached engine. when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); // Adjust fake host to request engine retention. when(mockHost.shouldDestroyEngineWithHost()).thenReturn(false); // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- // Push the delegate through all lifecycle methods all the way to destruction. delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); delegate.onResume(); delegate.onPause(); delegate.onStop(); delegate.onDestroyView(); delegate.onDetach(); // --- Verify that the cached engine was NOT destroyed --- verify(cachedEngine, never()).destroy(); } @Test public void itDelaysFirstDrawWhenRequested() { // ---- Test setup ---- FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // We're testing lifecycle behaviors, which require/expect that certain methods have already // been executed by the time they run. Therefore, we run those expected methods first. delegate.onAttach(ctx); // --- Execute the behavior under test --- boolean shouldDelayFirstAndroidViewDraw = true; delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw); assertNotNull(delegate.activePreDrawListener); } @Test public void itDoesNotDelayFirstDrawWhenNotRequested() { // ---- Test setup ---- FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // We're testing lifecycle behaviors, which require/expect that certain methods have already // been executed by the time they run. Therefore, we run those expected methods first. delegate.onAttach(ctx); // --- Execute the behavior under test --- boolean shouldDelayFirstAndroidViewDraw = false; delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw); assertNull(delegate.activePreDrawListener); } @Test public void itThrowsWhenDelayingTheFirstDrawAndUsingATextureView() { // ---- Test setup ---- when(mockHost.getRenderMode()).thenReturn(RenderMode.texture); FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // We're testing lifecycle behaviors, which require/expect that certain methods have already // been executed by the time they run. Therefore, we run those expected methods first. delegate.onAttach(ctx); // --- Execute the behavior under test --- boolean shouldDelayFirstAndroidViewDraw = true; assertThrows( IllegalArgumentException.class, () -> { delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw); }); } @Test public void itChangesFlutterViewVisibilityWhenOnStartAndOnStop() { // ---- Test setup ---- // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); // --- Execute the behavior under test --- delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); delegate.onStart(); // Verify that the flutterView is visible. assertEquals(View.VISIBLE, delegate.flutterView.getVisibility()); delegate.onStop(); // Verify that the flutterView is gone. assertEquals(View.GONE, delegate.flutterView.getVisibility()); delegate.onStart(); // Verify that the flutterView is visible. assertEquals(View.VISIBLE, delegate.flutterView.getVisibility()); delegate.flutterView.setVisibility(View.INVISIBLE); delegate.onStop(); // Verify that the flutterView is gone. assertEquals(View.GONE, delegate.flutterView.getVisibility()); delegate.onStart(); // Verify that the flutterView is invisible. assertEquals(View.INVISIBLE, delegate.flutterView.getVisibility()); delegate.flutterView.setVisibility(View.GONE); delegate.onStop(); // Verify that the flutterView is gone. assertEquals(View.GONE, delegate.flutterView.getVisibility()); delegate.onStart(); // Verify that the flutterView is gone. assertEquals(View.GONE, delegate.flutterView.getVisibility()); } @Test public void flutterSurfaceViewVisibilityChangedWithFlutterView() { // ---- Test setup ---- // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // --- Execute the behavior under test --- // For `FlutterSurfaceView`, setting visibility to the current `FlutterView` will not take // effect since it is not in the view tree. So we need to make sure that when the visibility of // `FlutterView` changes, the `FlutterSurfaceView` changes at the same time // See https://github.com/flutter/flutter/issues/105203 assertEquals(FlutterSurfaceView.class, delegate.flutterView.renderSurface.getClass()); FlutterSurfaceView surfaceView = (FlutterSurfaceView) delegate.flutterView.renderSurface; // Verify that the `FlutterSurfaceView` is gone. delegate.flutterView.setVisibility(View.GONE); assertEquals(View.GONE, surfaceView.getVisibility()); // Verify that the `FlutterSurfaceView` is visible. delegate.flutterView.setVisibility(View.VISIBLE); assertEquals(View.VISIBLE, surfaceView.getVisibility()); // Verify that the `FlutterSurfaceView` is invisible. delegate.flutterView.setVisibility(View.INVISIBLE); assertEquals(View.INVISIBLE, surfaceView.getVisibility()); } @Test public void usesFlutterEngineGroup() { FlutterEngineGroup mockEngineGroup = mock(FlutterEngineGroup.class); when(mockEngineGroup.createAndRunEngine(any(FlutterEngineGroup.Options.class))) .thenReturn(mockFlutterEngine); FlutterActivityAndFragmentDelegate.Host host = mock(FlutterActivityAndFragmentDelegate.Host.class); when(mockHost.getContext()).thenReturn(ctx); FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost, mockEngineGroup); delegate.onAttach(ctx); FlutterEngine engineUnderTest = delegate.getFlutterEngine(); assertEquals(engineUnderTest, mockFlutterEngine); } @Test public void itDoesAttachFlutterViewToEngine() { // ---- Test setup ---- // Create the real object that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // --- Execute the behavior under test --- assertTrue(delegate.flutterView.isAttachedToFlutterEngine()); } @Test public void itDoesNotAttachFlutterViewToEngine() { // ---- Test setup ---- // Create the real object that we're testing. when(mockHost.attachToEngineAutomatically()).thenReturn(false); FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); delegate.onAttach(ctx); delegate.onCreateView(null, null, null, 0, true); // --- Execute the behavior under test --- assertFalse(delegate.flutterView.isAttachedToFlutterEngine()); } @Test public void itDoesNotDetachTwice() { FlutterEngine cachedEngine = mockFlutterEngine(); FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); // Engine is a cached singleton that isn't owned by either hosts. when(mockHost.shouldDestroyEngineWithHost()).thenReturn(false); when(mockHost2.shouldDestroyEngineWithHost()).thenReturn(false); // Adjust fake hosts to request cached engine. when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); when(mockHost2.getCachedEngineId()).thenReturn("my_flutter_engine"); // Create the real objects that we're testing. FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); FlutterActivityAndFragmentDelegate delegate2 = new FlutterActivityAndFragmentDelegate(mockHost2); // This test is written to recreate the following scenario: // 1. We have a FlutterFragment_A attached to a singleton cached engine. // 2. An intent arrives that spawns FlutterFragment_B. // 3. FlutterFragment_B starts and steals the engine from FlutterFragment_A while attaching. // Via a call to FlutterActivityAndFragmentDelegate.detachFromFlutterEngine(). // 4. FlutterFragment_A is forcibly detached from the engine. // 5. FlutterFragment_B is attached to the engine. // 6. FlutterFragment_A is detached from the engine. // Note that the second detach for FlutterFragment_A is done unconditionally when the Fragment // is being // torn down. // At this point the engine's life cycle channel receives a message (triggered by // FlutterFragment_A's second detach) // that indicates the app is detached. This breaks FlutterFragment_B. // Below is a sequence of calls that mimicks the calls that the above scenario would trigger // without // relying on an intent to trigger the behaviour. // FlutterFragment_A is attached to the engine. delegate.onAttach(ctx); // NOTE: The following two calls happen in a slightly different order in reality. That is, via, // a call to host.detachFromFlutterEngine, delegate2.onAttach ends up invoking // delegate.onDetach. // To keep this regression test simple, we call them directly. // Detach FlutterFragment_A. delegate.onDetach(); verify(cachedEngine.getLifecycleChannel(), times(1)).appIsDetached(); // Attaches to the engine FlutterFragment_B. delegate2.onAttach(ctx); delegate2.onResume(); verify(cachedEngine.getLifecycleChannel(), times(1)).appIsResumed(); verify(cachedEngine.getLifecycleChannel(), times(1)).appIsDetached(); // A second Detach of FlutterFragment_A happens when the Fragment is detached. delegate.onDetach(); // IMPORTANT: The bug we fixed would have resulted in the engine thinking the app // is detached twice instead of once. verify(cachedEngine.getLifecycleChannel(), times(1)).appIsDetached(); } /** * Creates a mock {@link io.flutter.embedding.engine.FlutterEngine}. * * <p>The heuristic for deciding what to mock in the given {@link * io.flutter.embedding.engine.FlutterEngine} is that we should mock the minimum number of * necessary methods and associated objects. Maintaining developers should add more mock behavior * as required for tests, but should avoid mocking things that are not required for the correct * execution of tests. */ @NonNull private FlutterEngine mockFlutterEngine() { // The use of SettingsChannel by the delegate requires some behavior of its own, so it is // explicitly mocked with some internal behavior. SettingsChannel fakeSettingsChannel = mock(SettingsChannel.class); SettingsChannel.MessageBuilder fakeMessageBuilder = mock(SettingsChannel.MessageBuilder.class); when(fakeMessageBuilder.setPlatformBrightness(any(SettingsChannel.PlatformBrightness.class))) .thenReturn(fakeMessageBuilder); when(fakeMessageBuilder.setTextScaleFactor(any(Float.class))).thenReturn(fakeMessageBuilder); when(fakeMessageBuilder.setDisplayMetrics(any())).thenReturn(fakeMessageBuilder); when(fakeMessageBuilder.setNativeSpellCheckServiceDefined(any(Boolean.class))) .thenReturn(fakeMessageBuilder); when(fakeMessageBuilder.setBrieflyShowPassword(any(Boolean.class))) .thenReturn(fakeMessageBuilder); when(fakeMessageBuilder.setUse24HourFormat(any(Boolean.class))).thenReturn(fakeMessageBuilder); when(fakeSettingsChannel.startMessage()).thenReturn(fakeMessageBuilder); // Mock FlutterEngine and all of its required direct calls. FlutterEngine engine = mock(FlutterEngine.class); when(engine.getAccessibilityChannel()).thenReturn(mock(AccessibilityChannel.class)); when(engine.getActivityControlSurface()).thenReturn(mock(ActivityControlSurface.class)); when(engine.getDartExecutor()).thenReturn(mock(DartExecutor.class)); when(engine.getLifecycleChannel()).thenReturn(mock(LifecycleChannel.class)); when(engine.getLocalizationChannel()).thenReturn(mock(LocalizationChannel.class)); when(engine.getLocalizationPlugin()).thenReturn(mock(LocalizationPlugin.class)); when(engine.getMouseCursorChannel()).thenReturn(mock(MouseCursorChannel.class)); when(engine.getNavigationChannel()).thenReturn(mock(NavigationChannel.class)); when(engine.getPlatformViewsController()).thenReturn(mock(PlatformViewsController.class)); FlutterRenderer renderer = mock(FlutterRenderer.class); when(engine.getRenderer()).thenReturn(renderer); when(engine.getSettingsChannel()).thenReturn(fakeSettingsChannel); when(engine.getSystemChannel()).thenReturn(mock(SystemChannel.class)); when(engine.getTextInputChannel()).thenReturn(mock(TextInputChannel.class)); return engine; } }
engine/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityAndFragmentDelegateTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityAndFragmentDelegateTest.java", "repo_id": "engine", "token_count": 20424 }
350
package test.io.flutter.embedding.engine; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import android.content.Intent; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.FlutterShellArgs; import java.util.Arrays; import java.util.HashSet; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class FlutterShellArgsTest { @Test public void itProcessesShellFlags() { // Setup the test. Intent intent = new Intent(); intent.putExtra("dart-flags", "--observe --no-hot --no-pub"); intent.putExtra("trace-skia-allowlist", "skia.a,skia.b"); // Execute the behavior under test. FlutterShellArgs args = FlutterShellArgs.fromIntent(intent); HashSet<String> argValues = new HashSet<String>(Arrays.asList(args.toArray())); // Verify results. assertEquals(2, argValues.size()); assertTrue(argValues.contains("--dart-flags=--observe --no-hot --no-pub")); assertTrue(argValues.contains("--trace-skia-allowlist=skia.a,skia.b")); } @Test public void itHandles4xMsaaFlag() { Intent intent = new Intent(); intent.putExtra("msaa-samples", 4); FlutterShellArgs args = FlutterShellArgs.fromIntent(intent); HashSet<String> argValues = new HashSet<String>(Arrays.asList(args.toArray())); assertEquals(1, argValues.size()); assertTrue(argValues.contains("--msaa-samples=4")); } @Test public void itHandles1xMsaaFlag() { Intent intent = new Intent(); intent.putExtra("msaa-samples", 1); FlutterShellArgs args = FlutterShellArgs.fromIntent(intent); HashSet<String> argValues = new HashSet<String>(Arrays.asList(args.toArray())); assertEquals(0, argValues.size()); } }
engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterShellArgsTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterShellArgsTest.java", "repo_id": "engine", "token_count": 675 }
351
package io.flutter.embedding.android; 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 androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.systemchannels.KeyboardChannel; 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.nio.ByteBuffer; import java.util.HashMap; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class KeyboardChannelTest { private static BinaryMessenger.BinaryReply sendToBinaryMessageHandler( BinaryMessenger.BinaryMessageHandler binaryMessageHandler, String method, Object args) { MethodCall methodCall = new MethodCall(method, args); ByteBuffer encodedMethodCall = StandardMethodCodec.INSTANCE.encodeMethodCall(methodCall); BinaryMessenger.BinaryReply reply = mock(BinaryMessenger.BinaryReply.class); binaryMessageHandler.onMessage((ByteBuffer) encodedMethodCall.flip(), reply); return reply; } @SuppressWarnings("deprecation") // setMessageHandler is deprecated. @Test public void respondsToGetKeyboardStateChannelMessage() { ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> binaryMessageHandlerCaptor = ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); DartExecutor mockBinaryMessenger = mock(DartExecutor.class); KeyboardChannel.KeyboardMethodHandler mockHandler = mock(KeyboardChannel.KeyboardMethodHandler.class); KeyboardChannel keyboardChannel = new KeyboardChannel(mockBinaryMessenger); verify(mockBinaryMessenger, times(1)) .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); BinaryMessenger.BinaryMessageHandler binaryMessageHandler = binaryMessageHandlerCaptor.getValue(); keyboardChannel.setKeyboardMethodHandler(mockHandler); sendToBinaryMessageHandler(binaryMessageHandler, "getKeyboardState", null); verify(mockHandler, times(1)).getKeyboardState(); } @Test public void repliesWhenNoKeyboardChannelHandler() { // Regression test for https://github.com/flutter/flutter/issues/122441#issuecomment-1582052616. KeyboardChannel keyboardChannel = new KeyboardChannel(mock(DartExecutor.class)); MethodCall methodCall = new MethodCall("getKeyboardState", null); MethodChannel.Result result = mock(MethodChannel.Result.class); keyboardChannel.parsingMethodHandler.onMethodCall(methodCall, result); verify(result).success(new HashMap()); } }
engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyboardChannelTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyboardChannelTest.java", "repo_id": "engine", "token_count": 902 }
352
package io.flutter.plugin.editing; import static io.flutter.Build.API_LEVELS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.AdditionalMatchers.gt; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.isNotNull; import static org.mockito.Mockito.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Insets; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.text.InputType; import android.text.Selection; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.KeyEvent; import android.view.View; import android.view.ViewStructure; import android.view.WindowInsets; import android.view.WindowInsetsAnimation; import android.view.autofill.AutofillManager; import android.view.autofill.AutofillValue; import android.view.inputmethod.CursorAnchorInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodSubtype; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.android.FlutterView; import io.flutter.embedding.android.KeyboardManager; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.loader.FlutterLoader; import io.flutter.embedding.engine.renderer.FlutterRenderer; import io.flutter.embedding.engine.systemchannels.TextInputChannel; import io.flutter.embedding.engine.systemchannels.TextInputChannel.TextEditState; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.JSONMethodCodec; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.platform.PlatformViewsController; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; 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.Robolectric; import org.robolectric.annotation.Config; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.shadow.api.Shadow; import org.robolectric.shadows.ShadowAutofillManager; import org.robolectric.shadows.ShadowBuild; import org.robolectric.shadows.ShadowInputMethodManager; @Config( manifest = Config.NONE, shadows = {TextInputPluginTest.TestImm.class, TextInputPluginTest.TestAfm.class}) @RunWith(AndroidJUnit4.class) public class TextInputPluginTest { private final Context ctx = ApplicationProvider.getApplicationContext(); @Mock FlutterJNI mockFlutterJni; @Mock FlutterLoader mockFlutterLoader; @Before public void setUp() { MockitoAnnotations.openMocks(this); when(mockFlutterJni.isAttached()).thenReturn(true); } // Verifies the method and arguments for a captured method call. private void verifyMethodCall(ByteBuffer buffer, String methodName, String[] expectedArgs) throws JSONException { buffer.rewind(); MethodCall methodCall = JSONMethodCodec.INSTANCE.decodeMethodCall(buffer); assertEquals(methodName, methodCall.method); if (expectedArgs != null) { JSONArray args = methodCall.arguments(); assertEquals(expectedArgs.length, args.length()); for (int i = 0; i < args.length(); i++) { assertEquals(expectedArgs[i], args.get(i).toString()); } } } private static void sendToBinaryMessageHandler( BinaryMessenger.BinaryMessageHandler binaryMessageHandler, String method, Object args) { MethodCall methodCall = new MethodCall(method, args); ByteBuffer encodedMethodCall = JSONMethodCodec.INSTANCE.encodeMethodCall(methodCall); binaryMessageHandler.onMessage( (ByteBuffer) encodedMethodCall.flip(), mock(BinaryMessenger.BinaryReply.class)); } @SuppressWarnings("deprecation") // DartExecutor.send is deprecated. @Test public void textInputPlugin_RequestsReattachOnCreation() throws JSONException { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); FlutterJNI mockFlutterJni = mock(FlutterJNI.class); DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJni, mock(AssetManager.class))); TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); ArgumentCaptor<String> channelCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<ByteBuffer> bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); assertEquals("flutter/textinput", channelCaptor.getValue()); verifyMethodCall(bufferCaptor.getValue(), "TextInputClient.requestExistingInputState", null); } @Test public void setTextInputEditingState_doesNotInvokeUpdateEditingState() { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, null, null, null)); textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("initial input from framework", 0, 0, -1, -1)); assertTrue(textInputPlugin.getEditable().toString().equals("initial input from framework")); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("more update from the framework", 1, 2, -1, -1)); assertTrue(textInputPlugin.getEditable().toString().equals("more update from the framework")); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); } @Test public void setTextInputEditingState_willNotThrowWithoutSetTextInputClient() { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); // Here's no textInputPlugin.setTextInputClient() textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("initial input from framework", 0, 0, -1, -1)); assertTrue(textInputPlugin.getEditable().toString().equals("initial input from framework")); } @Test public void setTextInputEditingState_doesNotInvokeUpdateEditingStateWithDeltas() { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, true, // Enable delta model. TextInputChannel.TextCapitalization.NONE, null, null, null, null, null, null)); textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("receiving initial input from framework", 0, 0, -1, -1)); assertTrue( textInputPlugin.getEditable().toString().equals("receiving initial input from framework")); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState( "receiving more updates from the framework", 1, 2, -1, -1)); assertTrue( textInputPlugin .getEditable() .toString() .equals("receiving more updates from the framework")); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); } @Test public void textEditingDelta_TestUpdateEditingValueWithDeltasIsNotInvokedWhenDeltaModelDisabled() throws NullPointerException { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); EditorInfo outAttrs = new EditorInfo(); outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); CharSequence newText = "I do not fear computers. I fear the lack of them."; // Change InputTarget to FRAMEWORK_CLIENT. textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, // Delta model is disabled. TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); InputConnection inputConnection = textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); inputConnection.beginBatchEdit(); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.setComposingText(newText, newText.length()); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); // Selection changes so this will trigger an update to the framework through // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners // of the editing state. inputConnection.setSelection(3, 4); assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.endBatchEdit(); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(2)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); } @Test public void textEditingDelta_TestUpdateEditingValueIsNotInvokedWhenDeltaModelEnabled() throws NullPointerException { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); EditorInfo outAttrs = new EditorInfo(); outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); CharSequence newText = "I do not fear computers. I fear the lack of them."; final TextEditingDelta expectedDelta = new TextEditingDelta("", 0, 0, newText, newText.length(), newText.length(), 0, 49); // Change InputTarget to FRAMEWORK_CLIENT. textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, true, // Enable delta model. TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); InputConnection inputConnection = textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); inputConnection.beginBatchEdit(); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.setComposingText(newText, newText.length()); final ArrayList<TextEditingDelta> actualDeltas = ((ListenableEditingState) textInputPlugin.getEditable()).extractBatchTextEditingDeltas(); assertEquals(2, actualDeltas.size()); final TextEditingDelta delta = actualDeltas.get(1); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); // Verify delta is what we expect. assertEquals(expectedDelta.getOldText(), delta.getOldText()); assertEquals(expectedDelta.getDeltaText(), delta.getDeltaText()); assertEquals(expectedDelta.getDeltaStart(), delta.getDeltaStart()); assertEquals(expectedDelta.getDeltaEnd(), delta.getDeltaEnd()); assertEquals(expectedDelta.getNewSelectionStart(), delta.getNewSelectionStart()); assertEquals(expectedDelta.getNewSelectionEnd(), delta.getNewSelectionEnd()); assertEquals(expectedDelta.getNewComposingStart(), delta.getNewComposingStart()); assertEquals(expectedDelta.getNewComposingEnd(), delta.getNewComposingEnd()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); // Selection changes so this will trigger an update to the framework through // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners // of the editing state. inputConnection.setSelection(3, 4); assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnection.endBatchEdit(); verify(textInputChannel, times(2)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); } @Test public void textEditingDelta_TestDeltaIsCreatedWhenComposingTextSetIsInserting() throws NullPointerException { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); EditorInfo outAttrs = new EditorInfo(); outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); CharSequence newText = "I do not fear computers. I fear the lack of them."; final TextEditingDelta expectedDelta = new TextEditingDelta("", 0, 0, newText, newText.length(), newText.length(), 0, 49); // Change InputTarget to FRAMEWORK_CLIENT. textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, true, // Enable delta model. TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); InputConnection inputConnection = textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); inputConnection.beginBatchEdit(); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.setComposingText(newText, newText.length()); final ArrayList<TextEditingDelta> actualDeltas = ((ListenableEditingState) textInputPlugin.getEditable()).extractBatchTextEditingDeltas(); assertEquals(2, actualDeltas.size()); final TextEditingDelta delta = actualDeltas.get(1); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); // Verify delta is what we expect. assertEquals(expectedDelta.getOldText(), delta.getOldText()); assertEquals(expectedDelta.getDeltaText(), delta.getDeltaText()); assertEquals(expectedDelta.getDeltaStart(), delta.getDeltaStart()); assertEquals(expectedDelta.getDeltaEnd(), delta.getDeltaEnd()); assertEquals(expectedDelta.getNewSelectionStart(), delta.getNewSelectionStart()); assertEquals(expectedDelta.getNewSelectionEnd(), delta.getNewSelectionEnd()); assertEquals(expectedDelta.getNewComposingStart(), delta.getNewComposingStart()); assertEquals(expectedDelta.getNewComposingEnd(), delta.getNewComposingEnd()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); // Selection changes so this will trigger an update to the framework through // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners // of the editing state. inputConnection.setSelection(3, 4); assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.endBatchEdit(); verify(textInputChannel, times(2)).updateEditingStateWithDeltas(anyInt(), any()); } @Test public void textEditingDelta_TestDeltaIsCreatedWhenComposingTextSetIsDeleting() throws NullPointerException { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); EditorInfo outAttrs = new EditorInfo(); outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); CharSequence newText = "I do not fear computers. I fear the lack of them."; final TextEditingDelta expectedDelta = new TextEditingDelta( newText, 0, 49, "I do not fear computers. I fear the lack of them", 48, 48, 0, 48); // Change InputTarget to FRAMEWORK_CLIENT. textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, true, // Enable delta model. TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState(newText.toString(), 49, 49, 0, 49)); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); InputConnection inputConnection = textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); inputConnection.beginBatchEdit(); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.setComposingText("I do not fear computers. I fear the lack of them", 48); final ArrayList<TextEditingDelta> actualDeltas = ((ListenableEditingState) textInputPlugin.getEditable()).extractBatchTextEditingDeltas(); final TextEditingDelta delta = actualDeltas.get(1); System.out.println(delta.getDeltaText()); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); // Verify delta is what we expect. assertEquals(expectedDelta.getOldText(), delta.getOldText()); assertEquals(expectedDelta.getDeltaText(), delta.getDeltaText()); assertEquals(expectedDelta.getDeltaStart(), delta.getDeltaStart()); assertEquals(expectedDelta.getDeltaEnd(), delta.getDeltaEnd()); assertEquals(expectedDelta.getNewSelectionStart(), delta.getNewSelectionStart()); assertEquals(expectedDelta.getNewSelectionEnd(), delta.getNewSelectionEnd()); assertEquals(expectedDelta.getNewComposingStart(), delta.getNewComposingStart()); assertEquals(expectedDelta.getNewComposingEnd(), delta.getNewComposingEnd()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); // Selection changes so this will trigger an update to the framework through // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners // of the editing state. inputConnection.setSelection(3, 4); assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.endBatchEdit(); verify(textInputChannel, times(2)).updateEditingStateWithDeltas(anyInt(), any()); } @Test public void textEditingDelta_TestDeltaIsCreatedWhenComposingTextSetIsReplacing() throws NullPointerException { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); EditorInfo outAttrs = new EditorInfo(); outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); CharSequence newText = "helfo"; final TextEditingDelta expectedDelta = new TextEditingDelta(newText, 0, 5, "hello", 5, 5, 0, 5); // Change InputTarget to FRAMEWORK_CLIENT. textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, true, // Enable delta model. TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState(newText.toString(), 5, 5, 0, 5)); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); InputConnection inputConnection = textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); inputConnection.beginBatchEdit(); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.setComposingText("hello", 5); final ArrayList<TextEditingDelta> actualDeltas = ((ListenableEditingState) textInputPlugin.getEditable()).extractBatchTextEditingDeltas(); final TextEditingDelta delta = actualDeltas.get(1); System.out.println(delta.getDeltaText()); verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); // Verify delta is what we expect. assertEquals(expectedDelta.getOldText(), delta.getOldText()); assertEquals(expectedDelta.getDeltaText(), delta.getDeltaText()); assertEquals(expectedDelta.getDeltaStart(), delta.getDeltaStart()); assertEquals(expectedDelta.getDeltaEnd(), delta.getDeltaEnd()); assertEquals(expectedDelta.getNewSelectionStart(), delta.getNewSelectionStart()); assertEquals(expectedDelta.getNewSelectionEnd(), delta.getNewSelectionEnd()); assertEquals(expectedDelta.getNewComposingStart(), delta.getNewComposingStart()); assertEquals(expectedDelta.getNewComposingEnd(), delta.getNewComposingEnd()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.endBatchEdit(); assertEquals( 0, ((ListenableEditingState) textInputPlugin.getEditable()) .extractBatchTextEditingDeltas() .size()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.beginBatchEdit(); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); // Selection changes so this will trigger an update to the framework through // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners // of the editing state. inputConnection.setSelection(3, 4); assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); inputConnection.endBatchEdit(); verify(textInputChannel, times(2)).updateEditingStateWithDeltas(anyInt(), any()); } @Test public void inputConnectionAdaptor_RepeatFilter() throws NullPointerException { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); EditorInfo outAttrs = new EditorInfo(); outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); // Change InputTarget to FRAMEWORK_CLIENT. textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); InputConnectionAdaptor inputConnectionAdaptor = (InputConnectionAdaptor) textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); inputConnectionAdaptor.beginBatchEdit(); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnectionAdaptor.setComposingText("I do not fear computers. I fear the lack of them.", 1); verify(textInputChannel, times(0)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnectionAdaptor.endBatchEdit(); verify(textInputChannel, times(1)) .updateEditingState( anyInt(), eq("I do not fear computers. I fear the lack of them."), eq(49), eq(49), eq(0), eq(49)); inputConnectionAdaptor.beginBatchEdit(); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnectionAdaptor.endBatchEdit(); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnectionAdaptor.beginBatchEdit(); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnectionAdaptor.setSelection(3, 4); assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); verify(textInputChannel, times(1)) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); inputConnectionAdaptor.endBatchEdit(); verify(textInputChannel, times(1)) .updateEditingState( anyInt(), eq("I do not fear computers. I fear the lack of them."), eq(3), eq(4), eq(0), eq(49)); } @Test public void setTextInputEditingState_doesNotRestartWhenTextIsIdentical() { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); // Move the cursor. assertEquals(1, testImm.getRestartCount(testView)); textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); // Verify that we haven't restarted the input. assertEquals(1, testImm.getRestartCount(testView)); } @Test public void setTextInputEditingState_alwaysSetEditableWhenDifferent() { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. With // changed text, we should // always set the Editable contents. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("hello", 0, 0, -1, -1)); assertEquals(1, testImm.getRestartCount(testView)); assertTrue(textInputPlugin.getEditable().toString().equals("hello")); // No pending restart, set Editable contents anyways. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("Shibuyawoo", 0, 0, -1, -1)); assertEquals(1, testImm.getRestartCount(testView)); assertTrue(textInputPlugin.getEditable().toString().equals("Shibuyawoo")); } // See https://github.com/flutter/flutter/issues/29341 and // https://github.com/flutter/flutter/issues/31512 // All modern Samsung keybords are affected including non-korean languages and thus // need the restart. // Update: many other keyboards need this too: // https://github.com/flutter/flutter/issues/78827 @SuppressWarnings("deprecation") // InputMethodSubtype @Test public void setTextInputEditingState_restartsIMEOnlyWhenFrameworkChangesComposingRegion() { // Initialize a TextInputPlugin that needs to be always restarted. InputMethodSubtype inputMethodSubtype = new InputMethodSubtype(0, 0, /*locale=*/ "en", "", "", false, false); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); assertEquals(1, testImm.getRestartCount(testView)); InputConnection connection = textInputPlugin.createInputConnection( testView, mock(KeyboardManager.class), new EditorInfo()); connection.setComposingText("POWERRRRR", 1); textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("UNLIMITED POWERRRRR", 0, 0, 10, 19)); // Does not restart since the composing text is not changed. assertEquals(1, testImm.getRestartCount(testView)); connection.finishComposingText(); // Does not restart since the composing text is committed by the IME. assertEquals(1, testImm.getRestartCount(testView)); // Does not restart since the composing text is changed by the IME. connection.setComposingText("POWERRRRR", 1); assertEquals(1, testImm.getRestartCount(testView)); // The framework tries to commit the composing region. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("POWERRRRR", 0, 0, -1, -1)); // Verify that we've restarted the input. assertEquals(2, testImm.getRestartCount(testView)); } @Test public void TextEditState_throwsOnInvalidStatesReceived() { // Index OOB: assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", 0, -9, -1, -1)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", -9, 0, -1, -1)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", 0, 1, -1, -1)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", 1, 0, -1, -1)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, 1, 5)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, 5, 1)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, 5, 5)); // Invalid Selections: assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", -1, -2, -1, -1)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", -2, -1, -1, -1)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", -9, -9, -1, -1)); // Invalid Composing Ranges: assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, -9, -1)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, -1, -9)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, -9, -9)); assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, 2, 1)); // Valid values (does not throw): // Nothing selected/composing: TextEditState state = new TextEditState("", -1, -1, -1, -1); assertEquals("", state.text); assertEquals(-1, state.selectionStart); assertEquals(-1, state.selectionEnd); assertEquals(-1, state.composingStart); assertEquals(-1, state.composingEnd); // Collapsed selection. state = new TextEditState("x", 0, 0, 0, 1); assertEquals(0, state.selectionStart); assertEquals(0, state.selectionEnd); // Reversed Selection. state = new TextEditState("REEEE", 4, 2, -1, -1); assertEquals(4, state.selectionStart); assertEquals(2, state.selectionEnd); // A collapsed selection and composing range. state = new TextEditState("text", 0, 0, 0, 0); assertEquals("text", state.text); assertEquals(0, state.selectionStart); assertEquals(0, state.selectionEnd); assertEquals(0, state.composingStart); assertEquals(0, state.composingEnd); } @Test public void setTextInputEditingState_nullInputMethodSubtype() { TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(null); View testView = new View(ctx); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); assertEquals(1, testImm.getRestartCount(testView)); } @Test public void clearTextInputClient_alwaysRestartsImm() { // Initialize a general TextInputPlugin. InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); View testView = new View(ctx); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); assertEquals(1, testImm.getRestartCount(testView)); // A restart is always forced when calling clearTextInputClient(). textInputPlugin.clearTextInputClient(); assertEquals(2, testImm.getRestartCount(testView)); } @Test public void destroy_clearTextInputMethodHandler() { View testView = new View(ctx); TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); verify(textInputChannel, times(1)).setTextInputMethodHandler(isNotNull()); textInputPlugin.destroy(); verify(textInputChannel, times(1)).setTextInputMethodHandler(isNull()); } @SuppressWarnings("deprecation") // DartExecutor.send is deprecated. private void verifyInputConnection(TextInputChannel.TextInputType textInputType) throws JSONException { TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); FlutterJNI mockFlutterJni = mock(FlutterJNI.class); View testView = new View(ctx); DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJni, mock(AssetManager.class))); TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(textInputType, false, false), null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); ArgumentCaptor<String> channelCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<ByteBuffer> bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); assertEquals("flutter/textinput", channelCaptor.getValue()); verifyMethodCall(bufferCaptor.getValue(), "TextInputClient.requestExistingInputState", null); InputConnectionAdaptor connection = (InputConnectionAdaptor) textInputPlugin.createInputConnection( testView, mock(KeyboardManager.class), new EditorInfo()); connection.handleKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); verify(dartExecutor, times(2)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); assertEquals("flutter/textinput", channelCaptor.getValue()); verifyMethodCall( bufferCaptor.getValue(), "TextInputClient.performAction", new String[] {"0", "TextInputAction.done"}); connection.handleKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)); connection.handleKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_NUMPAD_ENTER)); verify(dartExecutor, times(3)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); assertEquals("flutter/textinput", channelCaptor.getValue()); verifyMethodCall( bufferCaptor.getValue(), "TextInputClient.performAction", new String[] {"0", "TextInputAction.done"}); } @Test public void inputConnection_createsActionFromEnter() throws JSONException { verifyInputConnection(TextInputChannel.TextInputType.TEXT); } @Test public void inputConnection_respondsToKeyEvents_textInputTypeNone() throws JSONException { verifyInputConnection(TextInputChannel.TextInputType.NONE); } @SuppressWarnings("deprecation") // InputMethodSubtype @Test public void inputConnection_finishComposingTextUpdatesIMM() throws JSONException { ShadowBuild.setManufacturer("samsung"); InputMethodSubtype inputMethodSubtype = new InputMethodSubtype(0, 0, /*locale=*/ "en", "", "", false, false); Settings.Secure.putString( ctx.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD, "com.sec.android.inputmethod/.SamsungKeypad"); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setCurrentInputMethodSubtype(inputMethodSubtype); FlutterJNI mockFlutterJni = mock(FlutterJNI.class); View testView = new View(ctx); DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJni, mock(AssetManager.class))); TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), null, null, null, null, null)); // There's a pending restart since we initialized the text input client. Flush that now. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("text", 0, 0, -1, -1)); InputConnection connection = textInputPlugin.createInputConnection( testView, mock(KeyboardManager.class), new EditorInfo()); connection.requestCursorUpdates( InputConnection.CURSOR_UPDATE_MONITOR | InputConnection.CURSOR_UPDATE_IMMEDIATE); connection.finishComposingText(); assertEquals(-1, testImm.getLastCursorAnchorInfo().getComposingTextStart()); assertEquals(0, testImm.getLastCursorAnchorInfo().getComposingText().length()); } @Test public void inputConnection_textInputTypeNone() { View testView = new View(ctx); DartExecutor dartExecutor = mock(DartExecutor.class); TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.NONE, false, false), null, null, null, null, null)); InputConnection connection = textInputPlugin.createInputConnection( testView, mock(KeyboardManager.class), new EditorInfo()); assertNotNull(connection); } @Test public void showTextInput_textInputTypeNone() { TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); View testView = new View(ctx); DartExecutor dartExecutor = mock(DartExecutor.class); TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.NONE, false, false), null, null, null, null, null)); textInputPlugin.showTextInput(testView); assertEquals(testImm.isSoftInputVisible(), false); } @Test public void inputConnection_textInputTypeMultilineAndSuggestionsDisabled() { // Regression test for https://github.com/flutter/flutter/issues/71679. View testView = new View(ctx); DartExecutor dartExecutor = mock(DartExecutor.class); TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, false, // Disable suggestions. true, false, TextInputChannel.TextCapitalization.NONE, new TextInputChannel.InputType(TextInputChannel.TextInputType.MULTILINE, false, false), null, null, null, null, null)); EditorInfo editorInfo = new EditorInfo(); InputConnection connection = textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), editorInfo); assertEquals( editorInfo.inputType, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } // -------- Start: Autofill Tests ------- @Test public void autofill_enabledByDefault() { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } FlutterView testView = new FlutterView(ctx); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); final TextInputChannel.Configuration.Autofill autofill = new TextInputChannel.Configuration.Autofill( "1", new String[] {}, null, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final TextInputChannel.Configuration config = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill, null, null); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill, null, new TextInputChannel.Configuration[] {config})); final ViewStructure viewStructure = mock(ViewStructure.class); final ViewStructure[] children = {mock(ViewStructure.class), mock(ViewStructure.class)}; when(viewStructure.newChild(anyInt())) .thenAnswer(invocation -> children[(int) invocation.getArgument(0)]); textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); verify(viewStructure).newChild(0); verify(children[0]).setAutofillId(any(), eq("1".hashCode())); // The flutter application sends an empty hint list, don't set hints. verify(children[0], never()).setAutofillHints(aryEq(new String[] {})); verify(children[0]).setDimens(anyInt(), anyInt(), anyInt(), anyInt(), gt(0), gt(0)); } @Test public void autofill_canBeDisabled() { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } FlutterView testView = new FlutterView(ctx); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); final TextInputChannel.Configuration.Autofill autofill = new TextInputChannel.Configuration.Autofill( "1", new String[] {}, null, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final TextInputChannel.Configuration config = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, null, null, null); textInputPlugin.setTextInputClient(0, config); final ViewStructure viewStructure = mock(ViewStructure.class); textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); verify(viewStructure, times(0)).newChild(anyInt()); } @Test public void autofill_hintText() { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } FlutterView testView = new FlutterView(ctx); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); final TextInputChannel.Configuration.Autofill autofill = new TextInputChannel.Configuration.Autofill( "1", new String[] {}, "placeholder", new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final TextInputChannel.Configuration config = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill, null, null); textInputPlugin.setTextInputClient(0, config); final ViewStructure viewStructure = mock(ViewStructure.class); final ViewStructure[] children = {mock(ViewStructure.class), mock(ViewStructure.class)}; when(viewStructure.newChild(anyInt())) .thenAnswer(invocation -> children[(int) invocation.getArgument(0)]); textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); verify(children[0]).setHint("placeholder"); } @Config(minSdk = API_LEVELS.API_26) @SuppressWarnings("deprecation") @Test public void autofill_onProvideVirtualViewStructure() { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } FlutterView testView = getTestView(); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); final TextInputChannel.Configuration.Autofill autofill1 = new TextInputChannel.Configuration.Autofill( "1", new String[] {"HINT1"}, "placeholder1", new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final TextInputChannel.Configuration.Autofill autofill2 = new TextInputChannel.Configuration.Autofill( "2", new String[] {"HINT2", "EXTRA"}, null, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final TextInputChannel.Configuration config1 = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill1, null, null); final TextInputChannel.Configuration config2 = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill2, null, null); textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill1, null, new TextInputChannel.Configuration[] {config1, config2})); final ViewStructure viewStructure = mock(ViewStructure.class); final ViewStructure[] children = {mock(ViewStructure.class), mock(ViewStructure.class)}; when(viewStructure.newChild(anyInt())) .thenAnswer(invocation -> children[(int) invocation.getArgument(0)]); textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); verify(viewStructure).newChild(0); verify(viewStructure).newChild(1); verify(children[0]).setAutofillId(any(), eq("1".hashCode())); verify(children[0]).setAutofillHints(aryEq(new String[] {"HINT1"})); verify(children[0]).setDimens(anyInt(), anyInt(), anyInt(), anyInt(), gt(0), gt(0)); verify(children[0]).setHint("placeholder1"); verify(children[1]).setAutofillId(any(), eq("2".hashCode())); verify(children[1]).setAutofillHints(aryEq(new String[] {"HINT2", "EXTRA"})); verify(children[1]).setDimens(anyInt(), anyInt(), anyInt(), anyInt(), gt(0), gt(0)); verify(children[1], times(0)).setHint(any()); } @SuppressWarnings("deprecation") @Config(minSdk = API_LEVELS.API_26) @Test public void autofill_onProvideVirtualViewStructure_singular_textfield() { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } // Migrate to ActivityScenario by following https://github.com/robolectric/robolectric/pull/4736 FlutterView testView = getTestView(); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); final TextInputChannel.Configuration.Autofill autofill = new TextInputChannel.Configuration.Autofill( "1", new String[] {"HINT1"}, "placeholder", new TextInputChannel.TextEditState("", 0, 0, -1, -1)); // Autofill should still work without AutofillGroup. textInputPlugin.setTextInputClient( 0, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill, null, null)); final ViewStructure viewStructure = mock(ViewStructure.class); final ViewStructure[] children = {mock(ViewStructure.class)}; when(viewStructure.newChild(anyInt())) .thenAnswer(invocation -> children[(int) invocation.getArgument(0)]); textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); verify(viewStructure).newChild(0); verify(children[0]).setAutofillId(any(), eq("1".hashCode())); verify(children[0]).setAutofillHints(aryEq(new String[] {"HINT1"})); verify(children[0]).setHint("placeholder"); // Verifies that the child has a non-zero size. verify(children[0]).setDimens(anyInt(), anyInt(), anyInt(), anyInt(), gt(0), gt(0)); } @Config(minSdk = API_LEVELS.API_26) @Test public void autofill_testLifeCycle() { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } TestAfm testAfm = Shadow.extract(ctx.getSystemService(AutofillManager.class)); FlutterView testView = getTestView(); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); // Set up an autofill scenario with 2 fields. final TextInputChannel.Configuration.Autofill autofill1 = new TextInputChannel.Configuration.Autofill( "1", new String[] {"HINT1"}, "placeholder1", new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final TextInputChannel.Configuration.Autofill autofill2 = new TextInputChannel.Configuration.Autofill( "2", new String[] {"HINT2", "EXTRA"}, null, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final TextInputChannel.Configuration config1 = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill1, null, null); final TextInputChannel.Configuration config2 = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill2, null, null); // Set client. This should call notifyViewExited on the FlutterView if the previous client is // also eligible for autofill. final TextInputChannel.Configuration autofillConfiguration = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill1, null, new TextInputChannel.Configuration[] {config1, config2}); textInputPlugin.setTextInputClient(0, autofillConfiguration); // notifyViewExited should not be called as this is the first client we set. assertEquals(testAfm.empty, testAfm.exitId); // The framework updates the text, call notifyValueChanged. textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("new text", -1, -1, -1, -1)); assertEquals("new text", testAfm.changeString); assertEquals("1".hashCode(), testAfm.changeVirtualId); // The input method updates the text, call notifyValueChanged. testAfm.resetStates(); final KeyboardManager mockKeyboardManager = mock(KeyboardManager.class); InputConnectionAdaptor adaptor = new InputConnectionAdaptor( testView, 0, mock(TextInputChannel.class), mockKeyboardManager, (ListenableEditingState) textInputPlugin.getEditable(), new EditorInfo()); adaptor.commitText("input from IME ", 1); assertEquals("input from IME new text", testAfm.changeString); assertEquals("1".hashCode(), testAfm.changeVirtualId); // notifyViewExited should be called on the previous client. testAfm.resetStates(); textInputPlugin.setTextInputClient( 1, new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, null, null, null)); assertEquals("1".hashCode(), testAfm.exitId); // TextInputPlugin#clearTextInputClient calls notifyViewExited. testAfm.resetStates(); textInputPlugin.setTextInputClient(3, autofillConfiguration); assertEquals(testAfm.empty, testAfm.exitId); textInputPlugin.clearTextInputClient(); assertEquals("1".hashCode(), testAfm.exitId); // TextInputPlugin#destroy calls notifyViewExited. testAfm.resetStates(); textInputPlugin.setTextInputClient(4, autofillConfiguration); assertEquals(testAfm.empty, testAfm.exitId); textInputPlugin.destroy(); assertEquals("1".hashCode(), testAfm.exitId); } @Config(minSdk = API_LEVELS.API_26) @SuppressWarnings("deprecation") @Test public void autofill_testAutofillUpdatesTheFramework() { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } TestAfm testAfm = Shadow.extract(ctx.getSystemService(AutofillManager.class)); FlutterView testView = getTestView(); TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); // Set up an autofill scenario with 2 fields. final TextInputChannel.Configuration.Autofill autofill1 = new TextInputChannel.Configuration.Autofill( "1", new String[] {"HINT1"}, null, new TextInputChannel.TextEditState("field 1", 0, 0, -1, -1)); final TextInputChannel.Configuration.Autofill autofill2 = new TextInputChannel.Configuration.Autofill( "2", new String[] {"HINT2", "EXTRA"}, null, new TextInputChannel.TextEditState("field 2", 0, 0, -1, -1)); final TextInputChannel.Configuration config1 = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill1, null, null); final TextInputChannel.Configuration config2 = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill2, null, null); final TextInputChannel.Configuration autofillConfiguration = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill1, null, new TextInputChannel.Configuration[] {config1, config2}); textInputPlugin.setTextInputClient(0, autofillConfiguration); textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final SparseArray<AutofillValue> autofillValues = new SparseArray(); autofillValues.append("1".hashCode(), AutofillValue.forText("focused field")); autofillValues.append("2".hashCode(), AutofillValue.forText("unfocused field")); // Autofill both fields. textInputPlugin.autofill(autofillValues); // Verify the Editable has been updated. assertTrue(textInputPlugin.getEditable().toString().equals("focused field")); // The autofill value of the focused field is sent via updateEditingState. verify(textInputChannel, times(1)) .updateEditingState(anyInt(), eq("focused field"), eq(13), eq(13), eq(-1), eq(-1)); final ArgumentCaptor<HashMap> mapCaptor = ArgumentCaptor.forClass(HashMap.class); verify(textInputChannel, times(1)).updateEditingStateWithTag(anyInt(), mapCaptor.capture()); final TextInputChannel.TextEditState editState = (TextInputChannel.TextEditState) mapCaptor.getValue().get("2"); assertEquals(editState.text, "unfocused field"); } @Config(minSdk = API_LEVELS.API_26) @Test public void autofill_doesNotCrashAfterClearClientCall() { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } FlutterView testView = new FlutterView(ctx); TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); // Set up an autofill scenario with 2 fields. final TextInputChannel.Configuration.Autofill autofillConfig = new TextInputChannel.Configuration.Autofill( "1", new String[] {"HINT1"}, "placeholder1", new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final TextInputChannel.Configuration config = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofillConfig, null, null); textInputPlugin.setTextInputClient(0, config); textInputPlugin.setTextInputEditingState( testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); textInputPlugin.clearTextInputClient(); final SparseArray<AutofillValue> autofillValues = new SparseArray(); autofillValues.append("1".hashCode(), AutofillValue.forText("focused field")); autofillValues.append("2".hashCode(), AutofillValue.forText("unfocused field")); // Autofill both fields. textInputPlugin.autofill(autofillValues); verify(textInputChannel, never()).updateEditingStateWithTag(anyInt(), any()); verify(textInputChannel, never()) .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); } @Config(minSdk = API_LEVELS.API_26) @Test public void autofill_testSetTextIpnutClientUpdatesSideFields() { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } TestAfm testAfm = Shadow.extract(ctx.getSystemService(AutofillManager.class)); FlutterView testView = getTestView(); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); // Set up an autofill scenario with 2 fields. final TextInputChannel.Configuration.Autofill autofill1 = new TextInputChannel.Configuration.Autofill( "1", new String[] {"HINT1"}, "null", new TextInputChannel.TextEditState("", 0, 0, -1, -1)); final TextInputChannel.Configuration.Autofill autofill2 = new TextInputChannel.Configuration.Autofill( "2", new String[] {"HINT2", "EXTRA"}, "null", new TextInputChannel.TextEditState( "Unfocused fields need love like everything does", 0, 0, -1, -1)); final TextInputChannel.Configuration config1 = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill1, null, null); final TextInputChannel.Configuration config2 = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill2, null, null); final TextInputChannel.Configuration autofillConfiguration = new TextInputChannel.Configuration( false, false, true, true, false, TextInputChannel.TextCapitalization.NONE, null, null, null, autofill1, null, new TextInputChannel.Configuration[] {config1, config2}); textInputPlugin.setTextInputClient(0, autofillConfiguration); // notifyValueChanged should be called for unfocused fields. assertEquals("2".hashCode(), testAfm.changeVirtualId); assertEquals("Unfocused fields need love like everything does", testAfm.changeString); } // -------- End: Autofill Tests ------- @SuppressWarnings("deprecation") private FlutterView getTestView() { // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 return new FlutterView(Robolectric.setupActivity(Activity.class)); } @SuppressWarnings("deprecation") // setMessageHandler is deprecated. @Test public void respondsToInputChannelMessages() { ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> binaryMessageHandlerCaptor = ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); DartExecutor mockBinaryMessenger = mock(DartExecutor.class); TextInputChannel.TextInputMethodHandler mockHandler = mock(TextInputChannel.TextInputMethodHandler.class); TextInputChannel textInputChannel = new TextInputChannel(mockBinaryMessenger); textInputChannel.setTextInputMethodHandler(mockHandler); verify(mockBinaryMessenger, times(1)) .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); BinaryMessenger.BinaryMessageHandler binaryMessageHandler = binaryMessageHandlerCaptor.getValue(); sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.requestAutofill", null); verify(mockHandler, times(1)).requestAutofill(); sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.finishAutofillContext", true); verify(mockHandler, times(1)).finishAutofillContext(true); sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.finishAutofillContext", false); verify(mockHandler, times(1)).finishAutofillContext(false); } @SuppressWarnings("deprecation") // setMessageHandler is deprecated. @Test public void sendAppPrivateCommand_dataIsEmpty() throws JSONException { ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> binaryMessageHandlerCaptor = ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); DartExecutor mockBinaryMessenger = mock(DartExecutor.class); TextInputChannel textInputChannel = new TextInputChannel(mockBinaryMessenger); EventHandler mockEventHandler = mock(EventHandler.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setEventHandler(mockEventHandler); View testView = new View(ctx); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); verify(mockBinaryMessenger, times(1)) .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); JSONObject arguments = new JSONObject(); arguments.put("action", "actionCommand"); arguments.put("data", ""); BinaryMessenger.BinaryMessageHandler binaryMessageHandler = binaryMessageHandlerCaptor.getValue(); sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.sendAppPrivateCommand", arguments); verify(mockEventHandler, times(1)) .sendAppPrivateCommand(any(View.class), eq("actionCommand"), eq(null)); } @SuppressWarnings("deprecation") // setMessageHandler is deprecated. @Test public void sendAppPrivateCommand_hasData() throws JSONException { ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> binaryMessageHandlerCaptor = ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); DartExecutor mockBinaryMessenger = mock(DartExecutor.class); TextInputChannel textInputChannel = new TextInputChannel(mockBinaryMessenger); EventHandler mockEventHandler = mock(EventHandler.class); TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); testImm.setEventHandler(mockEventHandler); View testView = new View(ctx); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); verify(mockBinaryMessenger, times(1)) .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); JSONObject arguments = new JSONObject(); arguments.put("action", "actionCommand"); arguments.put("data", "actionData"); ArgumentCaptor<Bundle> bundleCaptor = ArgumentCaptor.forClass(Bundle.class); BinaryMessenger.BinaryMessageHandler binaryMessageHandler = binaryMessageHandlerCaptor.getValue(); sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.sendAppPrivateCommand", arguments); verify(mockEventHandler, times(1)) .sendAppPrivateCommand(any(View.class), eq("actionCommand"), bundleCaptor.capture()); assertEquals("actionData", bundleCaptor.getValue().getCharSequence("data")); } @Test @TargetApi(API_LEVELS.API_30) @Config(sdk = API_LEVELS.API_30) @SuppressWarnings("deprecation") // getWindowSystemUiVisibility, SYSTEM_UI_FLAG_LAYOUT_STABLE. // flutter#133074 tracks migration work. public void ime_windowInsetsSync_notLaidOutBehindNavigation_excludesNavigationBars() { FlutterView testView = spy(getTestView()); when(testView.getWindowSystemUiVisibility()).thenReturn(View.SYSTEM_UI_FLAG_LAYOUT_STABLE); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); ImeSyncDeferringInsetsCallback imeSyncCallback = textInputPlugin.getImeSyncCallback(); FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); testView.attachToFlutterEngine(flutterEngine); WindowInsetsAnimation animation = mock(WindowInsetsAnimation.class); when(animation.getTypeMask()).thenReturn(WindowInsets.Type.ime()); List<WindowInsetsAnimation> animationList = new ArrayList(); animationList.add(animation); ArgumentCaptor<FlutterRenderer.ViewportMetrics> viewportMetricsCaptor = ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); WindowInsets.Builder builder = new WindowInsets.Builder(); // Set the initial insets and verify that they were set and the bottom view inset is correct imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); // Call onPrepare and set the lastWindowInsets - these should be stored for the end of the // animation instead of being applied immediately imeSyncCallback.getAnimationCallback().onPrepare(animation); builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 100)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); // Call onStart and apply new insets - these should be ignored completely imeSyncCallback.getAnimationCallback().onStart(animation, null); builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 50)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); // Progress the animation and ensure that the navigation bar insets have been subtracted // from the IME insets builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 25)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 50)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(10, viewportMetricsCaptor.getValue().viewInsetBottom); // End the animation and ensure that the bottom insets match the lastWindowInsets that we set // during onPrepare imeSyncCallback.getAnimationCallback().onEnd(animation); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(100, viewportMetricsCaptor.getValue().viewInsetBottom); } @Test @TargetApi(API_LEVELS.API_30) @Config(sdk = API_LEVELS.API_30) @SuppressWarnings("deprecation") // getWindowSystemUiVisibility // flutter#133074 tracks migration work. public void ime_windowInsetsSync_laidOutBehindNavigation_includesNavigationBars() { FlutterView testView = spy(getTestView()); when(testView.getWindowSystemUiVisibility()) .thenReturn( View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); ImeSyncDeferringInsetsCallback imeSyncCallback = textInputPlugin.getImeSyncCallback(); FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); testView.attachToFlutterEngine(flutterEngine); WindowInsetsAnimation animation = mock(WindowInsetsAnimation.class); when(animation.getTypeMask()).thenReturn(WindowInsets.Type.ime()); List<WindowInsetsAnimation> animationList = new ArrayList(); animationList.add(animation); ArgumentCaptor<FlutterRenderer.ViewportMetrics> viewportMetricsCaptor = ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); WindowInsets.Builder builder = new WindowInsets.Builder(); // Set the initial insets and verify that they were set and the bottom view inset is correct imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); // Call onPrepare and set the lastWindowInsets - these should be stored for the end of the // animation instead of being applied immediately imeSyncCallback.getAnimationCallback().onPrepare(animation); builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 100)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); // Call onStart and apply new insets - these should be ignored completely imeSyncCallback.getAnimationCallback().onStart(animation, null); builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 50)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); // Progress the animation and ensure that the navigation bar insets have not been // subtracted from the IME insets builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 25)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(25, viewportMetricsCaptor.getValue().viewInsetBottom); builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 50)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(50, viewportMetricsCaptor.getValue().viewInsetBottom); // End the animation and ensure that the bottom insets match the lastWindowInsets that we set // during onPrepare imeSyncCallback.getAnimationCallback().onEnd(animation); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(100, viewportMetricsCaptor.getValue().viewInsetBottom); } @Test @TargetApi(API_LEVELS.API_30) @Config(sdk = API_LEVELS.API_30) @SuppressWarnings("deprecation") // getWindowSystemUiVisibility, SYSTEM_UI_FLAG_LAYOUT_STABLE // flutter#133074 tracks migration work. public void lastWindowInsets_updatedOnSecondOnProgressCall() { FlutterView testView = spy(getTestView()); when(testView.getWindowSystemUiVisibility()).thenReturn(View.SYSTEM_UI_FLAG_LAYOUT_STABLE); TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); TextInputPlugin textInputPlugin = new TextInputPlugin(testView, textInputChannel, mock(PlatformViewsController.class)); ImeSyncDeferringInsetsCallback imeSyncCallback = textInputPlugin.getImeSyncCallback(); FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); testView.attachToFlutterEngine(flutterEngine); WindowInsetsAnimation imeAnimation = mock(WindowInsetsAnimation.class); when(imeAnimation.getTypeMask()).thenReturn(WindowInsets.Type.ime()); WindowInsetsAnimation navigationBarAnimation = mock(WindowInsetsAnimation.class); when(navigationBarAnimation.getTypeMask()).thenReturn(WindowInsets.Type.navigationBars()); List<WindowInsetsAnimation> animationList = new ArrayList(); animationList.add(imeAnimation); animationList.add(navigationBarAnimation); ArgumentCaptor<FlutterRenderer.ViewportMetrics> viewportMetricsCaptor = ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); WindowInsets.Builder builder = new WindowInsets.Builder(); // Set the initial insets and verify that they were set and the bottom view padding is correct builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 1000)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 100)); imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(100, viewportMetricsCaptor.getValue().viewPaddingBottom); // Call onPrepare and set the lastWindowInsets - these should be stored for the end of the // animation instead of being applied immediately imeSyncCallback.getAnimationCallback().onPrepare(imeAnimation); builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 0)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 100)); imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(100, viewportMetricsCaptor.getValue().viewPaddingBottom); // Call onPrepare again and apply new insets - these should overrite lastWindowInsets imeSyncCallback.getAnimationCallback().onPrepare(navigationBarAnimation); builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 0)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(100, viewportMetricsCaptor.getValue().viewPaddingBottom); // Progress the animation and ensure that the navigation bar insets have not been // subtracted from the IME insets builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 500)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingBottom); builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 250)); builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingBottom); // End the animation and ensure that the bottom insets match the lastWindowInsets that we set // during onPrepare imeSyncCallback.getAnimationCallback().onEnd(imeAnimation); verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingBottom); } interface EventHandler { void sendAppPrivateCommand(View view, String action, Bundle data); } @Implements(InputMethodManager.class) public static class TestImm extends ShadowInputMethodManager { private InputMethodSubtype currentInputMethodSubtype; private SparseIntArray restartCounter = new SparseIntArray(); private CursorAnchorInfo cursorAnchorInfo; private ArrayList<Integer> selectionUpdateValues; private boolean trackSelection = false; private EventHandler handler; public TestImm() { selectionUpdateValues = new ArrayList<Integer>(); } @Implementation public InputMethodSubtype getCurrentInputMethodSubtype() { return currentInputMethodSubtype; } @Implementation public void restartInput(View view) { int count = restartCounter.get(view.hashCode(), /*defaultValue=*/ 0) + 1; restartCounter.put(view.hashCode(), count); } public void setCurrentInputMethodSubtype(InputMethodSubtype inputMethodSubtype) { this.currentInputMethodSubtype = inputMethodSubtype; } public int getRestartCount(View view) { return restartCounter.get(view.hashCode(), /*defaultValue=*/ 0); } public void setEventHandler(EventHandler eventHandler) { handler = eventHandler; } @Implementation public void sendAppPrivateCommand(View view, String action, Bundle data) { handler.sendAppPrivateCommand(view, action, data); } @Implementation public void updateCursorAnchorInfo(View view, CursorAnchorInfo cursorAnchorInfo) { this.cursorAnchorInfo = cursorAnchorInfo; } // We simply store the values to verify later. @Implementation public void updateSelection( View view, int selStart, int selEnd, int candidatesStart, int candidatesEnd) { if (trackSelection) { this.selectionUpdateValues.add(selStart); this.selectionUpdateValues.add(selEnd); this.selectionUpdateValues.add(candidatesStart); this.selectionUpdateValues.add(candidatesEnd); } } // only track values when enabled via this. public void setTrackSelection(boolean val) { trackSelection = val; } // Returns true if the last updateSelection call passed the following values. public ArrayList<Integer> getSelectionUpdateValues() { return selectionUpdateValues; } public CursorAnchorInfo getLastCursorAnchorInfo() { return cursorAnchorInfo; } } @Implements(AutofillManager.class) public static class TestAfm extends ShadowAutofillManager { public static int empty = -999; String finishState; int changeVirtualId = empty; String changeString; int enterId = empty; int exitId = empty; @Implementation public void cancel() { finishState = "cancel"; } public void commit() { finishState = "commit"; } public void notifyViewEntered(View view, int virtualId, Rect absBounds) { enterId = virtualId; } public void notifyViewExited(View view, int virtualId) { exitId = virtualId; } public void notifyValueChanged(View view, int virtualId, AutofillValue value) { if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { return; } changeVirtualId = virtualId; changeString = value.getTextValue().toString(); } public void resetStates() { finishState = null; changeVirtualId = empty; changeString = null; enterId = empty; exitId = empty; } } }
engine/shell/platform/android/test/io/flutter/plugin/editing/TextInputPluginTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/editing/TextInputPluginTest.java", "repo_id": "engine", "token_count": 38948 }
353
package io.flutter.util; // 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_java.tmpl // instead. // // See flutter/flutter:dev/tools/gen_keycodes/README.md for more information. /** * This class contains keyboard constants to be used in unit tests. They should not be used in * production code. */ public class KeyCodes { public static final long PHYSICAL_HYPER = 0x00000010L; public static final long PHYSICAL_SUPER_KEY = 0x00000011L; public static final long PHYSICAL_FN = 0x00000012L; public static final long PHYSICAL_FN_LOCK = 0x00000013L; public static final long PHYSICAL_SUSPEND = 0x00000014L; public static final long PHYSICAL_RESUME = 0x00000015L; public static final long PHYSICAL_TURBO = 0x00000016L; public static final long PHYSICAL_PRIVACY_SCREEN_TOGGLE = 0x00000017L; public static final long PHYSICAL_MICROPHONE_MUTE_TOGGLE = 0x00000018L; public static final long PHYSICAL_SLEEP = 0x00010082L; public static final long PHYSICAL_WAKE_UP = 0x00010083L; public static final long PHYSICAL_DISPLAY_TOGGLE_INT_EXT = 0x000100b5L; public static final long PHYSICAL_GAME_BUTTON1 = 0x0005ff01L; public static final long PHYSICAL_GAME_BUTTON2 = 0x0005ff02L; public static final long PHYSICAL_GAME_BUTTON3 = 0x0005ff03L; public static final long PHYSICAL_GAME_BUTTON4 = 0x0005ff04L; public static final long PHYSICAL_GAME_BUTTON5 = 0x0005ff05L; public static final long PHYSICAL_GAME_BUTTON6 = 0x0005ff06L; public static final long PHYSICAL_GAME_BUTTON7 = 0x0005ff07L; public static final long PHYSICAL_GAME_BUTTON8 = 0x0005ff08L; public static final long PHYSICAL_GAME_BUTTON9 = 0x0005ff09L; public static final long PHYSICAL_GAME_BUTTON10 = 0x0005ff0aL; public static final long PHYSICAL_GAME_BUTTON11 = 0x0005ff0bL; public static final long PHYSICAL_GAME_BUTTON12 = 0x0005ff0cL; public static final long PHYSICAL_GAME_BUTTON13 = 0x0005ff0dL; public static final long PHYSICAL_GAME_BUTTON14 = 0x0005ff0eL; public static final long PHYSICAL_GAME_BUTTON15 = 0x0005ff0fL; public static final long PHYSICAL_GAME_BUTTON16 = 0x0005ff10L; public static final long PHYSICAL_GAME_BUTTON_A = 0x0005ff11L; public static final long PHYSICAL_GAME_BUTTON_B = 0x0005ff12L; public static final long PHYSICAL_GAME_BUTTON_C = 0x0005ff13L; public static final long PHYSICAL_GAME_BUTTON_LEFT1 = 0x0005ff14L; public static final long PHYSICAL_GAME_BUTTON_LEFT2 = 0x0005ff15L; public static final long PHYSICAL_GAME_BUTTON_MODE = 0x0005ff16L; public static final long PHYSICAL_GAME_BUTTON_RIGHT1 = 0x0005ff17L; public static final long PHYSICAL_GAME_BUTTON_RIGHT2 = 0x0005ff18L; public static final long PHYSICAL_GAME_BUTTON_SELECT = 0x0005ff19L; public static final long PHYSICAL_GAME_BUTTON_START = 0x0005ff1aL; public static final long PHYSICAL_GAME_BUTTON_THUMB_LEFT = 0x0005ff1bL; public static final long PHYSICAL_GAME_BUTTON_THUMB_RIGHT = 0x0005ff1cL; public static final long PHYSICAL_GAME_BUTTON_X = 0x0005ff1dL; public static final long PHYSICAL_GAME_BUTTON_Y = 0x0005ff1eL; public static final long PHYSICAL_GAME_BUTTON_Z = 0x0005ff1fL; public static final long PHYSICAL_USB_RESERVED = 0x00070000L; public static final long PHYSICAL_USB_ERROR_ROLL_OVER = 0x00070001L; public static final long PHYSICAL_USB_POST_FAIL = 0x00070002L; public static final long PHYSICAL_USB_ERROR_UNDEFINED = 0x00070003L; public static final long PHYSICAL_KEY_A = 0x00070004L; public static final long PHYSICAL_KEY_B = 0x00070005L; public static final long PHYSICAL_KEY_C = 0x00070006L; public static final long PHYSICAL_KEY_D = 0x00070007L; public static final long PHYSICAL_KEY_E = 0x00070008L; public static final long PHYSICAL_KEY_F = 0x00070009L; public static final long PHYSICAL_KEY_G = 0x0007000aL; public static final long PHYSICAL_KEY_H = 0x0007000bL; public static final long PHYSICAL_KEY_I = 0x0007000cL; public static final long PHYSICAL_KEY_J = 0x0007000dL; public static final long PHYSICAL_KEY_K = 0x0007000eL; public static final long PHYSICAL_KEY_L = 0x0007000fL; public static final long PHYSICAL_KEY_M = 0x00070010L; public static final long PHYSICAL_KEY_N = 0x00070011L; public static final long PHYSICAL_KEY_O = 0x00070012L; public static final long PHYSICAL_KEY_P = 0x00070013L; public static final long PHYSICAL_KEY_Q = 0x00070014L; public static final long PHYSICAL_KEY_R = 0x00070015L; public static final long PHYSICAL_KEY_S = 0x00070016L; public static final long PHYSICAL_KEY_T = 0x00070017L; public static final long PHYSICAL_KEY_U = 0x00070018L; public static final long PHYSICAL_KEY_V = 0x00070019L; public static final long PHYSICAL_KEY_W = 0x0007001aL; public static final long PHYSICAL_KEY_X = 0x0007001bL; public static final long PHYSICAL_KEY_Y = 0x0007001cL; public static final long PHYSICAL_KEY_Z = 0x0007001dL; public static final long PHYSICAL_DIGIT1 = 0x0007001eL; public static final long PHYSICAL_DIGIT2 = 0x0007001fL; public static final long PHYSICAL_DIGIT3 = 0x00070020L; public static final long PHYSICAL_DIGIT4 = 0x00070021L; public static final long PHYSICAL_DIGIT5 = 0x00070022L; public static final long PHYSICAL_DIGIT6 = 0x00070023L; public static final long PHYSICAL_DIGIT7 = 0x00070024L; public static final long PHYSICAL_DIGIT8 = 0x00070025L; public static final long PHYSICAL_DIGIT9 = 0x00070026L; public static final long PHYSICAL_DIGIT0 = 0x00070027L; public static final long PHYSICAL_ENTER = 0x00070028L; public static final long PHYSICAL_ESCAPE = 0x00070029L; public static final long PHYSICAL_BACKSPACE = 0x0007002aL; public static final long PHYSICAL_TAB = 0x0007002bL; public static final long PHYSICAL_SPACE = 0x0007002cL; public static final long PHYSICAL_MINUS = 0x0007002dL; public static final long PHYSICAL_EQUAL = 0x0007002eL; public static final long PHYSICAL_BRACKET_LEFT = 0x0007002fL; public static final long PHYSICAL_BRACKET_RIGHT = 0x00070030L; public static final long PHYSICAL_BACKSLASH = 0x00070031L; public static final long PHYSICAL_SEMICOLON = 0x00070033L; public static final long PHYSICAL_QUOTE = 0x00070034L; public static final long PHYSICAL_BACKQUOTE = 0x00070035L; public static final long PHYSICAL_COMMA = 0x00070036L; public static final long PHYSICAL_PERIOD = 0x00070037L; public static final long PHYSICAL_SLASH = 0x00070038L; public static final long PHYSICAL_CAPS_LOCK = 0x00070039L; public static final long PHYSICAL_F1 = 0x0007003aL; public static final long PHYSICAL_F2 = 0x0007003bL; public static final long PHYSICAL_F3 = 0x0007003cL; public static final long PHYSICAL_F4 = 0x0007003dL; public static final long PHYSICAL_F5 = 0x0007003eL; public static final long PHYSICAL_F6 = 0x0007003fL; public static final long PHYSICAL_F7 = 0x00070040L; public static final long PHYSICAL_F8 = 0x00070041L; public static final long PHYSICAL_F9 = 0x00070042L; public static final long PHYSICAL_F10 = 0x00070043L; public static final long PHYSICAL_F11 = 0x00070044L; public static final long PHYSICAL_F12 = 0x00070045L; public static final long PHYSICAL_PRINT_SCREEN = 0x00070046L; public static final long PHYSICAL_SCROLL_LOCK = 0x00070047L; public static final long PHYSICAL_PAUSE = 0x00070048L; public static final long PHYSICAL_INSERT = 0x00070049L; public static final long PHYSICAL_HOME = 0x0007004aL; public static final long PHYSICAL_PAGE_UP = 0x0007004bL; public static final long PHYSICAL_DELETE = 0x0007004cL; public static final long PHYSICAL_END = 0x0007004dL; public static final long PHYSICAL_PAGE_DOWN = 0x0007004eL; public static final long PHYSICAL_ARROW_RIGHT = 0x0007004fL; public static final long PHYSICAL_ARROW_LEFT = 0x00070050L; public static final long PHYSICAL_ARROW_DOWN = 0x00070051L; public static final long PHYSICAL_ARROW_UP = 0x00070052L; public static final long PHYSICAL_NUM_LOCK = 0x00070053L; public static final long PHYSICAL_NUMPAD_DIVIDE = 0x00070054L; public static final long PHYSICAL_NUMPAD_MULTIPLY = 0x00070055L; public static final long PHYSICAL_NUMPAD_SUBTRACT = 0x00070056L; public static final long PHYSICAL_NUMPAD_ADD = 0x00070057L; public static final long PHYSICAL_NUMPAD_ENTER = 0x00070058L; public static final long PHYSICAL_NUMPAD1 = 0x00070059L; public static final long PHYSICAL_NUMPAD2 = 0x0007005aL; public static final long PHYSICAL_NUMPAD3 = 0x0007005bL; public static final long PHYSICAL_NUMPAD4 = 0x0007005cL; public static final long PHYSICAL_NUMPAD5 = 0x0007005dL; public static final long PHYSICAL_NUMPAD6 = 0x0007005eL; public static final long PHYSICAL_NUMPAD7 = 0x0007005fL; public static final long PHYSICAL_NUMPAD8 = 0x00070060L; public static final long PHYSICAL_NUMPAD9 = 0x00070061L; public static final long PHYSICAL_NUMPAD0 = 0x00070062L; public static final long PHYSICAL_NUMPAD_DECIMAL = 0x00070063L; public static final long PHYSICAL_INTL_BACKSLASH = 0x00070064L; public static final long PHYSICAL_CONTEXT_MENU = 0x00070065L; public static final long PHYSICAL_POWER = 0x00070066L; public static final long PHYSICAL_NUMPAD_EQUAL = 0x00070067L; public static final long PHYSICAL_F13 = 0x00070068L; public static final long PHYSICAL_F14 = 0x00070069L; public static final long PHYSICAL_F15 = 0x0007006aL; public static final long PHYSICAL_F16 = 0x0007006bL; public static final long PHYSICAL_F17 = 0x0007006cL; public static final long PHYSICAL_F18 = 0x0007006dL; public static final long PHYSICAL_F19 = 0x0007006eL; public static final long PHYSICAL_F20 = 0x0007006fL; public static final long PHYSICAL_F21 = 0x00070070L; public static final long PHYSICAL_F22 = 0x00070071L; public static final long PHYSICAL_F23 = 0x00070072L; public static final long PHYSICAL_F24 = 0x00070073L; public static final long PHYSICAL_OPEN = 0x00070074L; public static final long PHYSICAL_HELP = 0x00070075L; public static final long PHYSICAL_SELECT = 0x00070077L; public static final long PHYSICAL_AGAIN = 0x00070079L; public static final long PHYSICAL_UNDO = 0x0007007aL; public static final long PHYSICAL_CUT = 0x0007007bL; public static final long PHYSICAL_COPY = 0x0007007cL; public static final long PHYSICAL_PASTE = 0x0007007dL; public static final long PHYSICAL_FIND = 0x0007007eL; public static final long PHYSICAL_AUDIO_VOLUME_MUTE = 0x0007007fL; public static final long PHYSICAL_AUDIO_VOLUME_UP = 0x00070080L; public static final long PHYSICAL_AUDIO_VOLUME_DOWN = 0x00070081L; public static final long PHYSICAL_NUMPAD_COMMA = 0x00070085L; public static final long PHYSICAL_INTL_RO = 0x00070087L; public static final long PHYSICAL_KANA_MODE = 0x00070088L; public static final long PHYSICAL_INTL_YEN = 0x00070089L; public static final long PHYSICAL_CONVERT = 0x0007008aL; public static final long PHYSICAL_NON_CONVERT = 0x0007008bL; public static final long PHYSICAL_LANG1 = 0x00070090L; public static final long PHYSICAL_LANG2 = 0x00070091L; public static final long PHYSICAL_LANG3 = 0x00070092L; public static final long PHYSICAL_LANG4 = 0x00070093L; public static final long PHYSICAL_LANG5 = 0x00070094L; public static final long PHYSICAL_ABORT = 0x0007009bL; public static final long PHYSICAL_PROPS = 0x000700a3L; public static final long PHYSICAL_NUMPAD_PAREN_LEFT = 0x000700b6L; public static final long PHYSICAL_NUMPAD_PAREN_RIGHT = 0x000700b7L; public static final long PHYSICAL_NUMPAD_BACKSPACE = 0x000700bbL; public static final long PHYSICAL_NUMPAD_MEMORY_STORE = 0x000700d0L; public static final long PHYSICAL_NUMPAD_MEMORY_RECALL = 0x000700d1L; public static final long PHYSICAL_NUMPAD_MEMORY_CLEAR = 0x000700d2L; public static final long PHYSICAL_NUMPAD_MEMORY_ADD = 0x000700d3L; public static final long PHYSICAL_NUMPAD_MEMORY_SUBTRACT = 0x000700d4L; public static final long PHYSICAL_NUMPAD_SIGN_CHANGE = 0x000700d7L; public static final long PHYSICAL_NUMPAD_CLEAR = 0x000700d8L; public static final long PHYSICAL_NUMPAD_CLEAR_ENTRY = 0x000700d9L; public static final long PHYSICAL_CONTROL_LEFT = 0x000700e0L; public static final long PHYSICAL_SHIFT_LEFT = 0x000700e1L; public static final long PHYSICAL_ALT_LEFT = 0x000700e2L; public static final long PHYSICAL_META_LEFT = 0x000700e3L; public static final long PHYSICAL_CONTROL_RIGHT = 0x000700e4L; public static final long PHYSICAL_SHIFT_RIGHT = 0x000700e5L; public static final long PHYSICAL_ALT_RIGHT = 0x000700e6L; public static final long PHYSICAL_META_RIGHT = 0x000700e7L; public static final long PHYSICAL_INFO = 0x000c0060L; public static final long PHYSICAL_CLOSED_CAPTION_TOGGLE = 0x000c0061L; public static final long PHYSICAL_BRIGHTNESS_UP = 0x000c006fL; public static final long PHYSICAL_BRIGHTNESS_DOWN = 0x000c0070L; public static final long PHYSICAL_BRIGHTNESS_TOGGLE = 0x000c0072L; public static final long PHYSICAL_BRIGHTNESS_MINIMUM = 0x000c0073L; public static final long PHYSICAL_BRIGHTNESS_MAXIMUM = 0x000c0074L; public static final long PHYSICAL_BRIGHTNESS_AUTO = 0x000c0075L; public static final long PHYSICAL_KBD_ILLUM_UP = 0x000c0079L; public static final long PHYSICAL_KBD_ILLUM_DOWN = 0x000c007aL; public static final long PHYSICAL_MEDIA_LAST = 0x000c0083L; public static final long PHYSICAL_LAUNCH_PHONE = 0x000c008cL; public static final long PHYSICAL_PROGRAM_GUIDE = 0x000c008dL; public static final long PHYSICAL_EXIT = 0x000c0094L; public static final long PHYSICAL_CHANNEL_UP = 0x000c009cL; public static final long PHYSICAL_CHANNEL_DOWN = 0x000c009dL; public static final long PHYSICAL_MEDIA_PLAY = 0x000c00b0L; public static final long PHYSICAL_MEDIA_PAUSE = 0x000c00b1L; public static final long PHYSICAL_MEDIA_RECORD = 0x000c00b2L; public static final long PHYSICAL_MEDIA_FAST_FORWARD = 0x000c00b3L; public static final long PHYSICAL_MEDIA_REWIND = 0x000c00b4L; public static final long PHYSICAL_MEDIA_TRACK_NEXT = 0x000c00b5L; public static final long PHYSICAL_MEDIA_TRACK_PREVIOUS = 0x000c00b6L; public static final long PHYSICAL_MEDIA_STOP = 0x000c00b7L; public static final long PHYSICAL_EJECT = 0x000c00b8L; public static final long PHYSICAL_MEDIA_PLAY_PAUSE = 0x000c00cdL; public static final long PHYSICAL_SPEECH_INPUT_TOGGLE = 0x000c00cfL; public static final long PHYSICAL_BASS_BOOST = 0x000c00e5L; public static final long PHYSICAL_MEDIA_SELECT = 0x000c0183L; public static final long PHYSICAL_LAUNCH_WORD_PROCESSOR = 0x000c0184L; public static final long PHYSICAL_LAUNCH_SPREADSHEET = 0x000c0186L; public static final long PHYSICAL_LAUNCH_MAIL = 0x000c018aL; public static final long PHYSICAL_LAUNCH_CONTACTS = 0x000c018dL; public static final long PHYSICAL_LAUNCH_CALENDAR = 0x000c018eL; public static final long PHYSICAL_LAUNCH_APP2 = 0x000c0192L; public static final long PHYSICAL_LAUNCH_APP1 = 0x000c0194L; public static final long PHYSICAL_LAUNCH_INTERNET_BROWSER = 0x000c0196L; public static final long PHYSICAL_LOG_OFF = 0x000c019cL; public static final long PHYSICAL_LOCK_SCREEN = 0x000c019eL; public static final long PHYSICAL_LAUNCH_CONTROL_PANEL = 0x000c019fL; public static final long PHYSICAL_SELECT_TASK = 0x000c01a2L; public static final long PHYSICAL_LAUNCH_DOCUMENTS = 0x000c01a7L; public static final long PHYSICAL_SPELL_CHECK = 0x000c01abL; public static final long PHYSICAL_LAUNCH_KEYBOARD_LAYOUT = 0x000c01aeL; public static final long PHYSICAL_LAUNCH_SCREEN_SAVER = 0x000c01b1L; public static final long PHYSICAL_LAUNCH_AUDIO_BROWSER = 0x000c01b7L; public static final long PHYSICAL_LAUNCH_ASSISTANT = 0x000c01cbL; public static final long PHYSICAL_NEW_KEY = 0x000c0201L; public static final long PHYSICAL_CLOSE = 0x000c0203L; public static final long PHYSICAL_SAVE = 0x000c0207L; public static final long PHYSICAL_PRINT = 0x000c0208L; public static final long PHYSICAL_BROWSER_SEARCH = 0x000c0221L; public static final long PHYSICAL_BROWSER_HOME = 0x000c0223L; public static final long PHYSICAL_BROWSER_BACK = 0x000c0224L; public static final long PHYSICAL_BROWSER_FORWARD = 0x000c0225L; public static final long PHYSICAL_BROWSER_STOP = 0x000c0226L; public static final long PHYSICAL_BROWSER_REFRESH = 0x000c0227L; public static final long PHYSICAL_BROWSER_FAVORITES = 0x000c022aL; public static final long PHYSICAL_ZOOM_IN = 0x000c022dL; public static final long PHYSICAL_ZOOM_OUT = 0x000c022eL; public static final long PHYSICAL_ZOOM_TOGGLE = 0x000c0232L; public static final long PHYSICAL_REDO = 0x000c0279L; public static final long PHYSICAL_MAIL_REPLY = 0x000c0289L; public static final long PHYSICAL_MAIL_FORWARD = 0x000c028bL; public static final long PHYSICAL_MAIL_SEND = 0x000c028cL; public static final long PHYSICAL_KEYBOARD_LAYOUT_SELECT = 0x000c029dL; public static final long PHYSICAL_SHOW_ALL_WINDOWS = 0x000c029fL; public static final long LOGICAL_SPACE = 0x00000000020L; public static final long LOGICAL_EXCLAMATION = 0x00000000021L; public static final long LOGICAL_QUOTE = 0x00000000022L; public static final long LOGICAL_NUMBER_SIGN = 0x00000000023L; public static final long LOGICAL_DOLLAR = 0x00000000024L; public static final long LOGICAL_PERCENT = 0x00000000025L; public static final long LOGICAL_AMPERSAND = 0x00000000026L; public static final long LOGICAL_QUOTE_SINGLE = 0x00000000027L; public static final long LOGICAL_PARENTHESIS_LEFT = 0x00000000028L; public static final long LOGICAL_PARENTHESIS_RIGHT = 0x00000000029L; public static final long LOGICAL_ASTERISK = 0x0000000002aL; public static final long LOGICAL_ADD = 0x0000000002bL; public static final long LOGICAL_COMMA = 0x0000000002cL; public static final long LOGICAL_MINUS = 0x0000000002dL; public static final long LOGICAL_PERIOD = 0x0000000002eL; public static final long LOGICAL_SLASH = 0x0000000002fL; public static final long LOGICAL_DIGIT0 = 0x00000000030L; public static final long LOGICAL_DIGIT1 = 0x00000000031L; public static final long LOGICAL_DIGIT2 = 0x00000000032L; public static final long LOGICAL_DIGIT3 = 0x00000000033L; public static final long LOGICAL_DIGIT4 = 0x00000000034L; public static final long LOGICAL_DIGIT5 = 0x00000000035L; public static final long LOGICAL_DIGIT6 = 0x00000000036L; public static final long LOGICAL_DIGIT7 = 0x00000000037L; public static final long LOGICAL_DIGIT8 = 0x00000000038L; public static final long LOGICAL_DIGIT9 = 0x00000000039L; public static final long LOGICAL_COLON = 0x0000000003aL; public static final long LOGICAL_SEMICOLON = 0x0000000003bL; public static final long LOGICAL_LESS = 0x0000000003cL; public static final long LOGICAL_EQUAL = 0x0000000003dL; public static final long LOGICAL_GREATER = 0x0000000003eL; public static final long LOGICAL_QUESTION = 0x0000000003fL; public static final long LOGICAL_AT = 0x00000000040L; public static final long LOGICAL_BRACKET_LEFT = 0x0000000005bL; public static final long LOGICAL_BACKSLASH = 0x0000000005cL; public static final long LOGICAL_BRACKET_RIGHT = 0x0000000005dL; public static final long LOGICAL_CARET = 0x0000000005eL; public static final long LOGICAL_UNDERSCORE = 0x0000000005fL; public static final long LOGICAL_BACKQUOTE = 0x00000000060L; public static final long LOGICAL_KEY_A = 0x00000000061L; public static final long LOGICAL_KEY_B = 0x00000000062L; public static final long LOGICAL_KEY_C = 0x00000000063L; public static final long LOGICAL_KEY_D = 0x00000000064L; public static final long LOGICAL_KEY_E = 0x00000000065L; public static final long LOGICAL_KEY_F = 0x00000000066L; public static final long LOGICAL_KEY_G = 0x00000000067L; public static final long LOGICAL_KEY_H = 0x00000000068L; public static final long LOGICAL_KEY_I = 0x00000000069L; public static final long LOGICAL_KEY_J = 0x0000000006aL; public static final long LOGICAL_KEY_K = 0x0000000006bL; public static final long LOGICAL_KEY_L = 0x0000000006cL; public static final long LOGICAL_KEY_M = 0x0000000006dL; public static final long LOGICAL_KEY_N = 0x0000000006eL; public static final long LOGICAL_KEY_O = 0x0000000006fL; public static final long LOGICAL_KEY_P = 0x00000000070L; public static final long LOGICAL_KEY_Q = 0x00000000071L; public static final long LOGICAL_KEY_R = 0x00000000072L; public static final long LOGICAL_KEY_S = 0x00000000073L; public static final long LOGICAL_KEY_T = 0x00000000074L; public static final long LOGICAL_KEY_U = 0x00000000075L; public static final long LOGICAL_KEY_V = 0x00000000076L; public static final long LOGICAL_KEY_W = 0x00000000077L; public static final long LOGICAL_KEY_X = 0x00000000078L; public static final long LOGICAL_KEY_Y = 0x00000000079L; public static final long LOGICAL_KEY_Z = 0x0000000007aL; public static final long LOGICAL_BRACE_LEFT = 0x0000000007bL; public static final long LOGICAL_BAR = 0x0000000007cL; public static final long LOGICAL_BRACE_RIGHT = 0x0000000007dL; public static final long LOGICAL_TILDE = 0x0000000007eL; public static final long LOGICAL_UNIDENTIFIED = 0x00100000001L; public static final long LOGICAL_BACKSPACE = 0x00100000008L; public static final long LOGICAL_TAB = 0x00100000009L; public static final long LOGICAL_ENTER = 0x0010000000dL; public static final long LOGICAL_ESCAPE = 0x0010000001bL; public static final long LOGICAL_DELETE = 0x0010000007fL; public static final long LOGICAL_ACCEL = 0x00100000101L; public static final long LOGICAL_ALT_GRAPH = 0x00100000103L; public static final long LOGICAL_CAPS_LOCK = 0x00100000104L; public static final long LOGICAL_FN = 0x00100000106L; public static final long LOGICAL_FN_LOCK = 0x00100000107L; public static final long LOGICAL_HYPER = 0x00100000108L; public static final long LOGICAL_NUM_LOCK = 0x0010000010aL; public static final long LOGICAL_SCROLL_LOCK = 0x0010000010cL; public static final long LOGICAL_SUPER_KEY = 0x0010000010eL; public static final long LOGICAL_SYMBOL = 0x0010000010fL; public static final long LOGICAL_SYMBOL_LOCK = 0x00100000110L; public static final long LOGICAL_SHIFT_LEVEL5 = 0x00100000111L; public static final long LOGICAL_ARROW_DOWN = 0x00100000301L; public static final long LOGICAL_ARROW_LEFT = 0x00100000302L; public static final long LOGICAL_ARROW_RIGHT = 0x00100000303L; public static final long LOGICAL_ARROW_UP = 0x00100000304L; public static final long LOGICAL_END = 0x00100000305L; public static final long LOGICAL_HOME = 0x00100000306L; public static final long LOGICAL_PAGE_DOWN = 0x00100000307L; public static final long LOGICAL_PAGE_UP = 0x00100000308L; public static final long LOGICAL_CLEAR = 0x00100000401L; public static final long LOGICAL_COPY = 0x00100000402L; public static final long LOGICAL_CR_SEL = 0x00100000403L; public static final long LOGICAL_CUT = 0x00100000404L; public static final long LOGICAL_ERASE_EOF = 0x00100000405L; public static final long LOGICAL_EX_SEL = 0x00100000406L; public static final long LOGICAL_INSERT = 0x00100000407L; public static final long LOGICAL_PASTE = 0x00100000408L; public static final long LOGICAL_REDO = 0x00100000409L; public static final long LOGICAL_UNDO = 0x0010000040aL; public static final long LOGICAL_ACCEPT = 0x00100000501L; public static final long LOGICAL_AGAIN = 0x00100000502L; public static final long LOGICAL_ATTN = 0x00100000503L; public static final long LOGICAL_CANCEL = 0x00100000504L; public static final long LOGICAL_CONTEXT_MENU = 0x00100000505L; public static final long LOGICAL_EXECUTE = 0x00100000506L; public static final long LOGICAL_FIND = 0x00100000507L; public static final long LOGICAL_HELP = 0x00100000508L; public static final long LOGICAL_PAUSE = 0x00100000509L; public static final long LOGICAL_PLAY = 0x0010000050aL; public static final long LOGICAL_PROPS = 0x0010000050bL; public static final long LOGICAL_SELECT = 0x0010000050cL; public static final long LOGICAL_ZOOM_IN = 0x0010000050dL; public static final long LOGICAL_ZOOM_OUT = 0x0010000050eL; public static final long LOGICAL_BRIGHTNESS_DOWN = 0x00100000601L; public static final long LOGICAL_BRIGHTNESS_UP = 0x00100000602L; public static final long LOGICAL_CAMERA = 0x00100000603L; public static final long LOGICAL_EJECT = 0x00100000604L; public static final long LOGICAL_LOG_OFF = 0x00100000605L; public static final long LOGICAL_POWER = 0x00100000606L; public static final long LOGICAL_POWER_OFF = 0x00100000607L; public static final long LOGICAL_PRINT_SCREEN = 0x00100000608L; public static final long LOGICAL_HIBERNATE = 0x00100000609L; public static final long LOGICAL_STANDBY = 0x0010000060aL; public static final long LOGICAL_WAKE_UP = 0x0010000060bL; public static final long LOGICAL_ALL_CANDIDATES = 0x00100000701L; public static final long LOGICAL_ALPHANUMERIC = 0x00100000702L; public static final long LOGICAL_CODE_INPUT = 0x00100000703L; public static final long LOGICAL_COMPOSE = 0x00100000704L; public static final long LOGICAL_CONVERT = 0x00100000705L; public static final long LOGICAL_FINAL_MODE = 0x00100000706L; public static final long LOGICAL_GROUP_FIRST = 0x00100000707L; public static final long LOGICAL_GROUP_LAST = 0x00100000708L; public static final long LOGICAL_GROUP_NEXT = 0x00100000709L; public static final long LOGICAL_GROUP_PREVIOUS = 0x0010000070aL; public static final long LOGICAL_MODE_CHANGE = 0x0010000070bL; public static final long LOGICAL_NEXT_CANDIDATE = 0x0010000070cL; public static final long LOGICAL_NON_CONVERT = 0x0010000070dL; public static final long LOGICAL_PREVIOUS_CANDIDATE = 0x0010000070eL; public static final long LOGICAL_PROCESS = 0x0010000070fL; public static final long LOGICAL_SINGLE_CANDIDATE = 0x00100000710L; public static final long LOGICAL_HANGUL_MODE = 0x00100000711L; public static final long LOGICAL_HANJA_MODE = 0x00100000712L; public static final long LOGICAL_JUNJA_MODE = 0x00100000713L; public static final long LOGICAL_EISU = 0x00100000714L; public static final long LOGICAL_HANKAKU = 0x00100000715L; public static final long LOGICAL_HIRAGANA = 0x00100000716L; public static final long LOGICAL_HIRAGANA_KATAKANA = 0x00100000717L; public static final long LOGICAL_KANA_MODE = 0x00100000718L; public static final long LOGICAL_KANJI_MODE = 0x00100000719L; public static final long LOGICAL_KATAKANA = 0x0010000071aL; public static final long LOGICAL_ROMAJI = 0x0010000071bL; public static final long LOGICAL_ZENKAKU = 0x0010000071cL; public static final long LOGICAL_ZENKAKU_HANKAKU = 0x0010000071dL; public static final long LOGICAL_F1 = 0x00100000801L; public static final long LOGICAL_F2 = 0x00100000802L; public static final long LOGICAL_F3 = 0x00100000803L; public static final long LOGICAL_F4 = 0x00100000804L; public static final long LOGICAL_F5 = 0x00100000805L; public static final long LOGICAL_F6 = 0x00100000806L; public static final long LOGICAL_F7 = 0x00100000807L; public static final long LOGICAL_F8 = 0x00100000808L; public static final long LOGICAL_F9 = 0x00100000809L; public static final long LOGICAL_F10 = 0x0010000080aL; public static final long LOGICAL_F11 = 0x0010000080bL; public static final long LOGICAL_F12 = 0x0010000080cL; public static final long LOGICAL_F13 = 0x0010000080dL; public static final long LOGICAL_F14 = 0x0010000080eL; public static final long LOGICAL_F15 = 0x0010000080fL; public static final long LOGICAL_F16 = 0x00100000810L; public static final long LOGICAL_F17 = 0x00100000811L; public static final long LOGICAL_F18 = 0x00100000812L; public static final long LOGICAL_F19 = 0x00100000813L; public static final long LOGICAL_F20 = 0x00100000814L; public static final long LOGICAL_F21 = 0x00100000815L; public static final long LOGICAL_F22 = 0x00100000816L; public static final long LOGICAL_F23 = 0x00100000817L; public static final long LOGICAL_F24 = 0x00100000818L; public static final long LOGICAL_SOFT1 = 0x00100000901L; public static final long LOGICAL_SOFT2 = 0x00100000902L; public static final long LOGICAL_SOFT3 = 0x00100000903L; public static final long LOGICAL_SOFT4 = 0x00100000904L; public static final long LOGICAL_SOFT5 = 0x00100000905L; public static final long LOGICAL_SOFT6 = 0x00100000906L; public static final long LOGICAL_SOFT7 = 0x00100000907L; public static final long LOGICAL_SOFT8 = 0x00100000908L; public static final long LOGICAL_CLOSE = 0x00100000a01L; public static final long LOGICAL_MAIL_FORWARD = 0x00100000a02L; public static final long LOGICAL_MAIL_REPLY = 0x00100000a03L; public static final long LOGICAL_MAIL_SEND = 0x00100000a04L; public static final long LOGICAL_MEDIA_PLAY_PAUSE = 0x00100000a05L; public static final long LOGICAL_MEDIA_STOP = 0x00100000a07L; public static final long LOGICAL_MEDIA_TRACK_NEXT = 0x00100000a08L; public static final long LOGICAL_MEDIA_TRACK_PREVIOUS = 0x00100000a09L; public static final long LOGICAL_NEW_KEY = 0x00100000a0aL; public static final long LOGICAL_OPEN = 0x00100000a0bL; public static final long LOGICAL_PRINT = 0x00100000a0cL; public static final long LOGICAL_SAVE = 0x00100000a0dL; public static final long LOGICAL_SPELL_CHECK = 0x00100000a0eL; public static final long LOGICAL_AUDIO_VOLUME_DOWN = 0x00100000a0fL; public static final long LOGICAL_AUDIO_VOLUME_UP = 0x00100000a10L; public static final long LOGICAL_AUDIO_VOLUME_MUTE = 0x00100000a11L; public static final long LOGICAL_LAUNCH_APPLICATION2 = 0x00100000b01L; public static final long LOGICAL_LAUNCH_CALENDAR = 0x00100000b02L; public static final long LOGICAL_LAUNCH_MAIL = 0x00100000b03L; public static final long LOGICAL_LAUNCH_MEDIA_PLAYER = 0x00100000b04L; public static final long LOGICAL_LAUNCH_MUSIC_PLAYER = 0x00100000b05L; public static final long LOGICAL_LAUNCH_APPLICATION1 = 0x00100000b06L; public static final long LOGICAL_LAUNCH_SCREEN_SAVER = 0x00100000b07L; public static final long LOGICAL_LAUNCH_SPREADSHEET = 0x00100000b08L; public static final long LOGICAL_LAUNCH_WEB_BROWSER = 0x00100000b09L; public static final long LOGICAL_LAUNCH_WEB_CAM = 0x00100000b0aL; public static final long LOGICAL_LAUNCH_WORD_PROCESSOR = 0x00100000b0bL; public static final long LOGICAL_LAUNCH_CONTACTS = 0x00100000b0cL; public static final long LOGICAL_LAUNCH_PHONE = 0x00100000b0dL; public static final long LOGICAL_LAUNCH_ASSISTANT = 0x00100000b0eL; public static final long LOGICAL_LAUNCH_CONTROL_PANEL = 0x00100000b0fL; public static final long LOGICAL_BROWSER_BACK = 0x00100000c01L; public static final long LOGICAL_BROWSER_FAVORITES = 0x00100000c02L; public static final long LOGICAL_BROWSER_FORWARD = 0x00100000c03L; public static final long LOGICAL_BROWSER_HOME = 0x00100000c04L; public static final long LOGICAL_BROWSER_REFRESH = 0x00100000c05L; public static final long LOGICAL_BROWSER_SEARCH = 0x00100000c06L; public static final long LOGICAL_BROWSER_STOP = 0x00100000c07L; public static final long LOGICAL_AUDIO_BALANCE_LEFT = 0x00100000d01L; public static final long LOGICAL_AUDIO_BALANCE_RIGHT = 0x00100000d02L; public static final long LOGICAL_AUDIO_BASS_BOOST_DOWN = 0x00100000d03L; public static final long LOGICAL_AUDIO_BASS_BOOST_UP = 0x00100000d04L; public static final long LOGICAL_AUDIO_FADER_FRONT = 0x00100000d05L; public static final long LOGICAL_AUDIO_FADER_REAR = 0x00100000d06L; public static final long LOGICAL_AUDIO_SURROUND_MODE_NEXT = 0x00100000d07L; public static final long LOGICAL_AVR_INPUT = 0x00100000d08L; public static final long LOGICAL_AVR_POWER = 0x00100000d09L; public static final long LOGICAL_CHANNEL_DOWN = 0x00100000d0aL; public static final long LOGICAL_CHANNEL_UP = 0x00100000d0bL; public static final long LOGICAL_COLOR_F0_RED = 0x00100000d0cL; public static final long LOGICAL_COLOR_F1_GREEN = 0x00100000d0dL; public static final long LOGICAL_COLOR_F2_YELLOW = 0x00100000d0eL; public static final long LOGICAL_COLOR_F3_BLUE = 0x00100000d0fL; public static final long LOGICAL_COLOR_F4_GREY = 0x00100000d10L; public static final long LOGICAL_COLOR_F5_BROWN = 0x00100000d11L; public static final long LOGICAL_CLOSED_CAPTION_TOGGLE = 0x00100000d12L; public static final long LOGICAL_DIMMER = 0x00100000d13L; public static final long LOGICAL_DISPLAY_SWAP = 0x00100000d14L; public static final long LOGICAL_EXIT = 0x00100000d15L; public static final long LOGICAL_FAVORITE_CLEAR0 = 0x00100000d16L; public static final long LOGICAL_FAVORITE_CLEAR1 = 0x00100000d17L; public static final long LOGICAL_FAVORITE_CLEAR2 = 0x00100000d18L; public static final long LOGICAL_FAVORITE_CLEAR3 = 0x00100000d19L; public static final long LOGICAL_FAVORITE_RECALL0 = 0x00100000d1aL; public static final long LOGICAL_FAVORITE_RECALL1 = 0x00100000d1bL; public static final long LOGICAL_FAVORITE_RECALL2 = 0x00100000d1cL; public static final long LOGICAL_FAVORITE_RECALL3 = 0x00100000d1dL; public static final long LOGICAL_FAVORITE_STORE0 = 0x00100000d1eL; public static final long LOGICAL_FAVORITE_STORE1 = 0x00100000d1fL; public static final long LOGICAL_FAVORITE_STORE2 = 0x00100000d20L; public static final long LOGICAL_FAVORITE_STORE3 = 0x00100000d21L; public static final long LOGICAL_GUIDE = 0x00100000d22L; public static final long LOGICAL_GUIDE_NEXT_DAY = 0x00100000d23L; public static final long LOGICAL_GUIDE_PREVIOUS_DAY = 0x00100000d24L; public static final long LOGICAL_INFO = 0x00100000d25L; public static final long LOGICAL_INSTANT_REPLAY = 0x00100000d26L; public static final long LOGICAL_LINK = 0x00100000d27L; public static final long LOGICAL_LIST_PROGRAM = 0x00100000d28L; public static final long LOGICAL_LIVE_CONTENT = 0x00100000d29L; public static final long LOGICAL_LOCK = 0x00100000d2aL; public static final long LOGICAL_MEDIA_APPS = 0x00100000d2bL; public static final long LOGICAL_MEDIA_FAST_FORWARD = 0x00100000d2cL; public static final long LOGICAL_MEDIA_LAST = 0x00100000d2dL; public static final long LOGICAL_MEDIA_PAUSE = 0x00100000d2eL; public static final long LOGICAL_MEDIA_PLAY = 0x00100000d2fL; public static final long LOGICAL_MEDIA_RECORD = 0x00100000d30L; public static final long LOGICAL_MEDIA_REWIND = 0x00100000d31L; public static final long LOGICAL_MEDIA_SKIP = 0x00100000d32L; public static final long LOGICAL_NEXT_FAVORITE_CHANNEL = 0x00100000d33L; public static final long LOGICAL_NEXT_USER_PROFILE = 0x00100000d34L; public static final long LOGICAL_ON_DEMAND = 0x00100000d35L; public static final long LOGICAL_P_IN_P_DOWN = 0x00100000d36L; public static final long LOGICAL_P_IN_P_MOVE = 0x00100000d37L; public static final long LOGICAL_P_IN_P_TOGGLE = 0x00100000d38L; public static final long LOGICAL_P_IN_P_UP = 0x00100000d39L; public static final long LOGICAL_PLAY_SPEED_DOWN = 0x00100000d3aL; public static final long LOGICAL_PLAY_SPEED_RESET = 0x00100000d3bL; public static final long LOGICAL_PLAY_SPEED_UP = 0x00100000d3cL; public static final long LOGICAL_RANDOM_TOGGLE = 0x00100000d3dL; public static final long LOGICAL_RC_LOW_BATTERY = 0x00100000d3eL; public static final long LOGICAL_RECORD_SPEED_NEXT = 0x00100000d3fL; public static final long LOGICAL_RF_BYPASS = 0x00100000d40L; public static final long LOGICAL_SCAN_CHANNELS_TOGGLE = 0x00100000d41L; public static final long LOGICAL_SCREEN_MODE_NEXT = 0x00100000d42L; public static final long LOGICAL_SETTINGS = 0x00100000d43L; public static final long LOGICAL_SPLIT_SCREEN_TOGGLE = 0x00100000d44L; public static final long LOGICAL_STB_INPUT = 0x00100000d45L; public static final long LOGICAL_STB_POWER = 0x00100000d46L; public static final long LOGICAL_SUBTITLE = 0x00100000d47L; public static final long LOGICAL_TELETEXT = 0x00100000d48L; public static final long LOGICAL_TV = 0x00100000d49L; public static final long LOGICAL_TV_INPUT = 0x00100000d4aL; public static final long LOGICAL_TV_POWER = 0x00100000d4bL; public static final long LOGICAL_VIDEO_MODE_NEXT = 0x00100000d4cL; public static final long LOGICAL_WINK = 0x00100000d4dL; public static final long LOGICAL_ZOOM_TOGGLE = 0x00100000d4eL; public static final long LOGICAL_DVR = 0x00100000d4fL; public static final long LOGICAL_MEDIA_AUDIO_TRACK = 0x00100000d50L; public static final long LOGICAL_MEDIA_SKIP_BACKWARD = 0x00100000d51L; public static final long LOGICAL_MEDIA_SKIP_FORWARD = 0x00100000d52L; public static final long LOGICAL_MEDIA_STEP_BACKWARD = 0x00100000d53L; public static final long LOGICAL_MEDIA_STEP_FORWARD = 0x00100000d54L; public static final long LOGICAL_MEDIA_TOP_MENU = 0x00100000d55L; public static final long LOGICAL_NAVIGATE_IN = 0x00100000d56L; public static final long LOGICAL_NAVIGATE_NEXT = 0x00100000d57L; public static final long LOGICAL_NAVIGATE_OUT = 0x00100000d58L; public static final long LOGICAL_NAVIGATE_PREVIOUS = 0x00100000d59L; public static final long LOGICAL_PAIRING = 0x00100000d5aL; public static final long LOGICAL_MEDIA_CLOSE = 0x00100000d5bL; public static final long LOGICAL_AUDIO_BASS_BOOST_TOGGLE = 0x00100000e02L; public static final long LOGICAL_AUDIO_TREBLE_DOWN = 0x00100000e04L; public static final long LOGICAL_AUDIO_TREBLE_UP = 0x00100000e05L; public static final long LOGICAL_MICROPHONE_TOGGLE = 0x00100000e06L; public static final long LOGICAL_MICROPHONE_VOLUME_DOWN = 0x00100000e07L; public static final long LOGICAL_MICROPHONE_VOLUME_UP = 0x00100000e08L; public static final long LOGICAL_MICROPHONE_VOLUME_MUTE = 0x00100000e09L; public static final long LOGICAL_SPEECH_CORRECTION_LIST = 0x00100000f01L; public static final long LOGICAL_SPEECH_INPUT_TOGGLE = 0x00100000f02L; public static final long LOGICAL_APP_SWITCH = 0x00100001001L; public static final long LOGICAL_CALL = 0x00100001002L; public static final long LOGICAL_CAMERA_FOCUS = 0x00100001003L; public static final long LOGICAL_END_CALL = 0x00100001004L; public static final long LOGICAL_GO_BACK = 0x00100001005L; public static final long LOGICAL_GO_HOME = 0x00100001006L; public static final long LOGICAL_HEADSET_HOOK = 0x00100001007L; public static final long LOGICAL_LAST_NUMBER_REDIAL = 0x00100001008L; public static final long LOGICAL_NOTIFICATION = 0x00100001009L; public static final long LOGICAL_MANNER_MODE = 0x0010000100aL; public static final long LOGICAL_VOICE_DIAL = 0x0010000100bL; public static final long LOGICAL_TV3_D_MODE = 0x00100001101L; public static final long LOGICAL_TV_ANTENNA_CABLE = 0x00100001102L; public static final long LOGICAL_TV_AUDIO_DESCRIPTION = 0x00100001103L; public static final long LOGICAL_TV_AUDIO_DESCRIPTION_MIX_DOWN = 0x00100001104L; public static final long LOGICAL_TV_AUDIO_DESCRIPTION_MIX_UP = 0x00100001105L; public static final long LOGICAL_TV_CONTENTS_MENU = 0x00100001106L; public static final long LOGICAL_TV_DATA_SERVICE = 0x00100001107L; public static final long LOGICAL_TV_INPUT_COMPONENT1 = 0x00100001108L; public static final long LOGICAL_TV_INPUT_COMPONENT2 = 0x00100001109L; public static final long LOGICAL_TV_INPUT_COMPOSITE1 = 0x0010000110aL; public static final long LOGICAL_TV_INPUT_COMPOSITE2 = 0x0010000110bL; public static final long LOGICAL_TV_INPUT_HD_M1 = 0x0010000110cL; public static final long LOGICAL_TV_INPUT_HD_M2 = 0x0010000110dL; public static final long LOGICAL_TV_INPUT_HD_M3 = 0x0010000110eL; public static final long LOGICAL_TV_INPUT_HD_M4 = 0x0010000110fL; public static final long LOGICAL_TV_INPUT_V_G1 = 0x00100001110L; public static final long LOGICAL_TV_MEDIA_CONTEXT = 0x00100001111L; public static final long LOGICAL_TV_NETWORK = 0x00100001112L; public static final long LOGICAL_TV_NUMBER_ENTRY = 0x00100001113L; public static final long LOGICAL_TV_RADIO_SERVICE = 0x00100001114L; public static final long LOGICAL_TV_SATELLITE = 0x00100001115L; public static final long LOGICAL_TV_SATELLITE_B_S = 0x00100001116L; public static final long LOGICAL_TV_SATELLITE_C_S = 0x00100001117L; public static final long LOGICAL_TV_SATELLITE_TOGGLE = 0x00100001118L; public static final long LOGICAL_TV_TERRESTRIAL_ANALOG = 0x00100001119L; public static final long LOGICAL_TV_TERRESTRIAL_DIGITAL = 0x0010000111aL; public static final long LOGICAL_TV_TIMER = 0x0010000111bL; public static final long LOGICAL_KEY11 = 0x00100001201L; public static final long LOGICAL_KEY12 = 0x00100001202L; public static final long LOGICAL_SUSPEND = 0x00200000000L; public static final long LOGICAL_RESUME = 0x00200000001L; public static final long LOGICAL_SLEEP = 0x00200000002L; public static final long LOGICAL_ABORT = 0x00200000003L; public static final long LOGICAL_LANG1 = 0x00200000010L; public static final long LOGICAL_LANG2 = 0x00200000011L; public static final long LOGICAL_LANG3 = 0x00200000012L; public static final long LOGICAL_LANG4 = 0x00200000013L; public static final long LOGICAL_LANG5 = 0x00200000014L; public static final long LOGICAL_INTL_BACKSLASH = 0x00200000020L; public static final long LOGICAL_INTL_RO = 0x00200000021L; public static final long LOGICAL_INTL_YEN = 0x00200000022L; public static final long LOGICAL_CONTROL_LEFT = 0x00200000100L; public static final long LOGICAL_CONTROL_RIGHT = 0x00200000101L; public static final long LOGICAL_SHIFT_LEFT = 0x00200000102L; public static final long LOGICAL_SHIFT_RIGHT = 0x00200000103L; public static final long LOGICAL_ALT_LEFT = 0x00200000104L; public static final long LOGICAL_ALT_RIGHT = 0x00200000105L; public static final long LOGICAL_META_LEFT = 0x00200000106L; public static final long LOGICAL_META_RIGHT = 0x00200000107L; public static final long LOGICAL_CONTROL = 0x002000001f0L; public static final long LOGICAL_SHIFT = 0x002000001f2L; public static final long LOGICAL_ALT = 0x002000001f4L; public static final long LOGICAL_META = 0x002000001f6L; public static final long LOGICAL_NUMPAD_ENTER = 0x0020000020dL; public static final long LOGICAL_NUMPAD_PAREN_LEFT = 0x00200000228L; public static final long LOGICAL_NUMPAD_PAREN_RIGHT = 0x00200000229L; public static final long LOGICAL_NUMPAD_MULTIPLY = 0x0020000022aL; public static final long LOGICAL_NUMPAD_ADD = 0x0020000022bL; public static final long LOGICAL_NUMPAD_COMMA = 0x0020000022cL; public static final long LOGICAL_NUMPAD_SUBTRACT = 0x0020000022dL; public static final long LOGICAL_NUMPAD_DECIMAL = 0x0020000022eL; public static final long LOGICAL_NUMPAD_DIVIDE = 0x0020000022fL; public static final long LOGICAL_NUMPAD0 = 0x00200000230L; public static final long LOGICAL_NUMPAD1 = 0x00200000231L; public static final long LOGICAL_NUMPAD2 = 0x00200000232L; public static final long LOGICAL_NUMPAD3 = 0x00200000233L; public static final long LOGICAL_NUMPAD4 = 0x00200000234L; public static final long LOGICAL_NUMPAD5 = 0x00200000235L; public static final long LOGICAL_NUMPAD6 = 0x00200000236L; public static final long LOGICAL_NUMPAD7 = 0x00200000237L; public static final long LOGICAL_NUMPAD8 = 0x00200000238L; public static final long LOGICAL_NUMPAD9 = 0x00200000239L; public static final long LOGICAL_NUMPAD_EQUAL = 0x0020000023dL; public static final long LOGICAL_GAME_BUTTON1 = 0x00200000301L; public static final long LOGICAL_GAME_BUTTON2 = 0x00200000302L; public static final long LOGICAL_GAME_BUTTON3 = 0x00200000303L; public static final long LOGICAL_GAME_BUTTON4 = 0x00200000304L; public static final long LOGICAL_GAME_BUTTON5 = 0x00200000305L; public static final long LOGICAL_GAME_BUTTON6 = 0x00200000306L; public static final long LOGICAL_GAME_BUTTON7 = 0x00200000307L; public static final long LOGICAL_GAME_BUTTON8 = 0x00200000308L; public static final long LOGICAL_GAME_BUTTON9 = 0x00200000309L; public static final long LOGICAL_GAME_BUTTON10 = 0x0020000030aL; public static final long LOGICAL_GAME_BUTTON11 = 0x0020000030bL; public static final long LOGICAL_GAME_BUTTON12 = 0x0020000030cL; public static final long LOGICAL_GAME_BUTTON13 = 0x0020000030dL; public static final long LOGICAL_GAME_BUTTON14 = 0x0020000030eL; public static final long LOGICAL_GAME_BUTTON15 = 0x0020000030fL; public static final long LOGICAL_GAME_BUTTON16 = 0x00200000310L; public static final long LOGICAL_GAME_BUTTON_A = 0x00200000311L; public static final long LOGICAL_GAME_BUTTON_B = 0x00200000312L; public static final long LOGICAL_GAME_BUTTON_C = 0x00200000313L; public static final long LOGICAL_GAME_BUTTON_LEFT1 = 0x00200000314L; public static final long LOGICAL_GAME_BUTTON_LEFT2 = 0x00200000315L; public static final long LOGICAL_GAME_BUTTON_MODE = 0x00200000316L; public static final long LOGICAL_GAME_BUTTON_RIGHT1 = 0x00200000317L; public static final long LOGICAL_GAME_BUTTON_RIGHT2 = 0x00200000318L; public static final long LOGICAL_GAME_BUTTON_SELECT = 0x00200000319L; public static final long LOGICAL_GAME_BUTTON_START = 0x0020000031aL; public static final long LOGICAL_GAME_BUTTON_THUMB_LEFT = 0x0020000031bL; public static final long LOGICAL_GAME_BUTTON_THUMB_RIGHT = 0x0020000031cL; public static final long LOGICAL_GAME_BUTTON_X = 0x0020000031dL; public static final long LOGICAL_GAME_BUTTON_Y = 0x0020000031eL; public static final long LOGICAL_GAME_BUTTON_Z = 0x0020000031fL; }
engine/shell/platform/android/test/io/flutter/util/KeyCodes.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/util/KeyCodes.java", "repo_id": "engine", "token_count": 16739 }
354
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "accessibility_bridge.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "flutter/third_party/accessibility/ax/ax_tree_manager_map.h" #include "test_accessibility_bridge.h" namespace flutter { namespace testing { using ::testing::Contains; FlutterSemanticsNode2 CreateSemanticsNode( int32_t id, const char* label, const std::vector<int32_t>* children = nullptr) { return { .id = id, .flags = static_cast<FlutterSemanticsFlag>(0), .actions = static_cast<FlutterSemanticsAction>(0), .text_selection_base = -1, .text_selection_extent = -1, .label = label, .hint = "", .value = "", .increased_value = "", .decreased_value = "", .child_count = children ? children->size() : 0, .children_in_traversal_order = children ? children->data() : nullptr, .custom_accessibility_actions_count = 0, .tooltip = "", }; } TEST(AccessibilityBridgeTest, BasicTest) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); std::vector<int32_t> children{1, 2}; FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root", &children); FlutterSemanticsNode2 child1 = CreateSemanticsNode(1, "child 1"); FlutterSemanticsNode2 child2 = CreateSemanticsNode(2, "child 2"); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->AddFlutterSemanticsNodeUpdate(child2); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); auto child2_node = bridge->GetFlutterPlatformNodeDelegateFromID(2).lock(); EXPECT_EQ(root_node->GetChildCount(), 2); EXPECT_EQ(root_node->GetData().child_ids[0], 1); EXPECT_EQ(root_node->GetData().child_ids[1], 2); EXPECT_EQ(root_node->GetName(), "root"); EXPECT_EQ(child1_node->GetChildCount(), 0); EXPECT_EQ(child1_node->GetName(), "child 1"); EXPECT_EQ(child2_node->GetChildCount(), 0); EXPECT_EQ(child2_node->GetName(), "child 2"); } // 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. TEST(AccessibilityBridgeTest, AccessibilityRootId) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); std::vector<int32_t> children{456, 789}; FlutterSemanticsNode2 root = CreateSemanticsNode(123, "root", &children); FlutterSemanticsNode2 child1 = CreateSemanticsNode(456, "child 1"); FlutterSemanticsNode2 child2 = CreateSemanticsNode(789, "child 2"); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->AddFlutterSemanticsNodeUpdate(child2); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(123).lock(); auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(456).lock(); auto child2_node = bridge->GetFlutterPlatformNodeDelegateFromID(789).lock(); auto fake_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); EXPECT_EQ(bridge->GetRootAsAXNode()->id(), 123); EXPECT_EQ(bridge->RootDelegate()->GetName(), "root"); EXPECT_EQ(root_node->GetChildCount(), 2); EXPECT_EQ(root_node->GetData().child_ids[0], 456); EXPECT_EQ(root_node->GetData().child_ids[1], 789); EXPECT_EQ(root_node->GetName(), "root"); EXPECT_EQ(child1_node->GetChildCount(), 0); EXPECT_EQ(child1_node->GetName(), "child 1"); EXPECT_EQ(child2_node->GetChildCount(), 0); EXPECT_EQ(child2_node->GetName(), "child 2"); ASSERT_FALSE(fake_delegate); } // Semantic nodes can be added in any order. TEST(AccessibilityBridgeTest, AddOrder) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); std::vector<int32_t> root_children{34, 56}; std::vector<int32_t> child2_children{78}; std::vector<int32_t> child3_children{90}; FlutterSemanticsNode2 root = CreateSemanticsNode(12, "root", &root_children); FlutterSemanticsNode2 child1 = CreateSemanticsNode(34, "child 1"); FlutterSemanticsNode2 child2 = CreateSemanticsNode(56, "child 2", &child2_children); FlutterSemanticsNode2 child3 = CreateSemanticsNode(78, "child 3", &child3_children); FlutterSemanticsNode2 child4 = CreateSemanticsNode(90, "child 4"); bridge->AddFlutterSemanticsNodeUpdate(child3); bridge->AddFlutterSemanticsNodeUpdate(child2); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->AddFlutterSemanticsNodeUpdate(child4); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(12).lock(); auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(34).lock(); auto child2_node = bridge->GetFlutterPlatformNodeDelegateFromID(56).lock(); auto child3_node = bridge->GetFlutterPlatformNodeDelegateFromID(78).lock(); auto child4_node = bridge->GetFlutterPlatformNodeDelegateFromID(90).lock(); EXPECT_EQ(bridge->GetRootAsAXNode()->id(), 12); EXPECT_EQ(bridge->RootDelegate()->GetName(), "root"); EXPECT_EQ(root_node->GetChildCount(), 2); EXPECT_EQ(root_node->GetData().child_ids[0], 34); EXPECT_EQ(root_node->GetData().child_ids[1], 56); EXPECT_EQ(root_node->GetName(), "root"); EXPECT_EQ(child1_node->GetChildCount(), 0); EXPECT_EQ(child1_node->GetName(), "child 1"); EXPECT_EQ(child2_node->GetChildCount(), 1); EXPECT_EQ(child2_node->GetData().child_ids[0], 78); EXPECT_EQ(child2_node->GetName(), "child 2"); EXPECT_EQ(child3_node->GetChildCount(), 1); EXPECT_EQ(child3_node->GetData().child_ids[0], 90); EXPECT_EQ(child3_node->GetName(), "child 3"); EXPECT_EQ(child4_node->GetChildCount(), 0); EXPECT_EQ(child4_node->GetName(), "child 4"); } TEST(AccessibilityBridgeTest, CanFireChildrenChangedCorrectly) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); std::vector<int32_t> children{1}; FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root", &children); FlutterSemanticsNode2 child1 = CreateSemanticsNode(1, "child 1"); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); EXPECT_EQ(root_node->GetChildCount(), 1); EXPECT_EQ(root_node->GetData().child_ids[0], 1); EXPECT_EQ(root_node->GetName(), "root"); EXPECT_EQ(child1_node->GetChildCount(), 0); EXPECT_EQ(child1_node->GetName(), "child 1"); bridge->accessibility_events.clear(); // Add a child to root. root.child_count = 2; int32_t new_children[] = {1, 2}; root.children_in_traversal_order = new_children; FlutterSemanticsNode2 child2 = CreateSemanticsNode(2, "child 2"); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(child2); bridge->CommitUpdates(); root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); EXPECT_EQ(root_node->GetChildCount(), 2); EXPECT_EQ(root_node->GetData().child_ids[0], 1); EXPECT_EQ(root_node->GetData().child_ids[1], 2); EXPECT_EQ(bridge->accessibility_events.size(), size_t{2}); std::set<ui::AXEventGenerator::Event> actual_event{ bridge->accessibility_events.begin(), bridge->accessibility_events.end()}; EXPECT_THAT(actual_event, Contains(ui::AXEventGenerator::Event::CHILDREN_CHANGED)); EXPECT_THAT(actual_event, Contains(ui::AXEventGenerator::Event::SUBTREE_CREATED)); } TEST(AccessibilityBridgeTest, CanHandleSelectionChangeCorrectly) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); root.flags = static_cast<FlutterSemanticsFlag>( FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField | FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocused); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); const ui::AXTreeData& tree = bridge->GetAXTreeData(); EXPECT_EQ(tree.sel_anchor_object_id, ui::AXNode::kInvalidAXID); bridge->accessibility_events.clear(); // Update the selection. root.text_selection_base = 0; root.text_selection_extent = 5; bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); EXPECT_EQ(tree.sel_anchor_object_id, 0); EXPECT_EQ(tree.sel_anchor_offset, 0); EXPECT_EQ(tree.sel_focus_object_id, 0); EXPECT_EQ(tree.sel_focus_offset, 5); ASSERT_EQ(bridge->accessibility_events.size(), size_t{2}); EXPECT_EQ(bridge->accessibility_events[0], ui::AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED); EXPECT_EQ(bridge->accessibility_events[1], ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED); } TEST(AccessibilityBridgeTest, DoesNotAssignEditableRootToSelectableText) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); root.flags = static_cast<FlutterSemanticsFlag>( FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField | FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); EXPECT_FALSE(root_node->GetData().GetBoolAttribute( ax::mojom::BoolAttribute::kEditableRoot)); } TEST(AccessibilityBridgeTest, SwitchHasSwitchRole) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); root.flags = static_cast<FlutterSemanticsFlag>( FlutterSemanticsFlag::kFlutterSemanticsFlagHasToggledState | FlutterSemanticsFlag::kFlutterSemanticsFlagHasEnabledState | FlutterSemanticsFlag::kFlutterSemanticsFlagIsEnabled); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kSwitch); } TEST(AccessibilityBridgeTest, SliderHasSliderRole) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); root.flags = static_cast<FlutterSemanticsFlag>( FlutterSemanticsFlag::kFlutterSemanticsFlagIsSlider | FlutterSemanticsFlag::kFlutterSemanticsFlagHasEnabledState | FlutterSemanticsFlag::kFlutterSemanticsFlagIsEnabled | FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocusable); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kSlider); } // Ensure that checkboxes have their checked status set apropriately // Previously, only Radios could have this flag updated // Resulted in the issue seen at // https://github.com/flutter/flutter/issues/96218 // As this fix involved code run on all platforms, it is included here. TEST(AccessibilityBridgeTest, CanSetCheckboxChecked) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); root.flags = static_cast<FlutterSemanticsFlag>( FlutterSemanticsFlag::kFlutterSemanticsFlagHasCheckedState | FlutterSemanticsFlag::kFlutterSemanticsFlagIsChecked); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kCheckBox); EXPECT_EQ(root_node->GetData().GetCheckedState(), ax::mojom::CheckedState::kTrue); } // Verify that a node can be moved from one parent to another. TEST(AccessibilityBridgeTest, CanReparentNode) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); std::vector<int32_t> root_children{1}; std::vector<int32_t> child1_children{2}; FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root", &root_children); FlutterSemanticsNode2 child1 = CreateSemanticsNode(1, "child 1", &child1_children); FlutterSemanticsNode2 child2 = CreateSemanticsNode(2, "child 2"); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->AddFlutterSemanticsNodeUpdate(child2); bridge->CommitUpdates(); bridge->accessibility_events.clear(); // Reparent child2 from child1 to the root. child1.child_count = 0; child1.children_in_traversal_order = nullptr; int32_t new_root_children[] = {1, 2}; root.child_count = 2; root.children_in_traversal_order = new_root_children; bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(child1); bridge->AddFlutterSemanticsNodeUpdate(child2); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); auto child2_node = bridge->GetFlutterPlatformNodeDelegateFromID(2).lock(); EXPECT_EQ(root_node->GetChildCount(), 2); EXPECT_EQ(root_node->GetData().child_ids[0], 1); EXPECT_EQ(root_node->GetData().child_ids[1], 2); EXPECT_EQ(root_node->GetName(), "root"); EXPECT_EQ(child1_node->GetChildCount(), 0); EXPECT_EQ(child1_node->GetName(), "child 1"); EXPECT_EQ(child2_node->GetChildCount(), 0); EXPECT_EQ(child2_node->GetName(), "child 2"); ASSERT_EQ(bridge->accessibility_events.size(), size_t{5}); // Child2 is moved from child1 to root. EXPECT_THAT(bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::CHILDREN_CHANGED).Times(2)); EXPECT_THAT(bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::SUBTREE_CREATED).Times(1)); // Child1 is no longer a parent. It loses its group role and disables its // 'clip children' attribute. EXPECT_THAT( bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED).Times(1)); EXPECT_THAT(bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::ROLE_CHANGED).Times(1)); } // Verify that multiple nodes can be moved to new parents. TEST(AccessibilityBridgeTest, CanReparentMultipleNodes) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); int32_t root_id = 0; int32_t intermediary1_id = 1; int32_t intermediary2_id = 2; int32_t leaf1_id = 3; int32_t leaf2_id = 4; int32_t leaf3_id = 5; std::vector<int32_t> root_children{intermediary1_id, intermediary2_id}; std::vector<int32_t> intermediary1_children{leaf1_id}; std::vector<int32_t> intermediary2_children{leaf2_id, leaf3_id}; FlutterSemanticsNode2 root = CreateSemanticsNode(root_id, "root", &root_children); FlutterSemanticsNode2 intermediary1 = CreateSemanticsNode( intermediary1_id, "intermediary 1", &intermediary1_children); FlutterSemanticsNode2 intermediary2 = CreateSemanticsNode( intermediary2_id, "intermediary 2", &intermediary2_children); FlutterSemanticsNode2 leaf1 = CreateSemanticsNode(leaf1_id, "leaf 1"); FlutterSemanticsNode2 leaf2 = CreateSemanticsNode(leaf2_id, "leaf 2"); FlutterSemanticsNode2 leaf3 = CreateSemanticsNode(leaf3_id, "leaf 3"); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(intermediary1); bridge->AddFlutterSemanticsNodeUpdate(intermediary2); bridge->AddFlutterSemanticsNodeUpdate(leaf1); bridge->AddFlutterSemanticsNodeUpdate(leaf2); bridge->AddFlutterSemanticsNodeUpdate(leaf3); bridge->CommitUpdates(); bridge->accessibility_events.clear(); // Swap intermediary 1's and intermediary2's children. int32_t new_intermediary1_children[] = {leaf2_id, leaf3_id}; intermediary1.child_count = 2; intermediary1.children_in_traversal_order = new_intermediary1_children; int32_t new_intermediary2_children[] = {leaf1_id}; intermediary2.child_count = 1; intermediary2.children_in_traversal_order = new_intermediary2_children; bridge->AddFlutterSemanticsNodeUpdate(intermediary1); bridge->AddFlutterSemanticsNodeUpdate(intermediary2); bridge->AddFlutterSemanticsNodeUpdate(leaf1); bridge->AddFlutterSemanticsNodeUpdate(leaf2); bridge->AddFlutterSemanticsNodeUpdate(leaf3); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(root_id).lock(); auto intermediary1_node = bridge->GetFlutterPlatformNodeDelegateFromID(intermediary1_id).lock(); auto intermediary2_node = bridge->GetFlutterPlatformNodeDelegateFromID(intermediary2_id).lock(); auto leaf1_node = bridge->GetFlutterPlatformNodeDelegateFromID(leaf1_id).lock(); auto leaf2_node = bridge->GetFlutterPlatformNodeDelegateFromID(leaf2_id).lock(); auto leaf3_node = bridge->GetFlutterPlatformNodeDelegateFromID(leaf3_id).lock(); EXPECT_EQ(root_node->GetChildCount(), 2); EXPECT_EQ(root_node->GetData().child_ids[0], intermediary1_id); EXPECT_EQ(root_node->GetData().child_ids[1], intermediary2_id); EXPECT_EQ(root_node->GetName(), "root"); EXPECT_EQ(intermediary1_node->GetChildCount(), 2); EXPECT_EQ(intermediary1_node->GetData().child_ids[0], leaf2_id); EXPECT_EQ(intermediary1_node->GetData().child_ids[1], leaf3_id); EXPECT_EQ(intermediary1_node->GetName(), "intermediary 1"); EXPECT_EQ(intermediary2_node->GetChildCount(), 1); EXPECT_EQ(intermediary2_node->GetData().child_ids[0], leaf1_id); EXPECT_EQ(intermediary2_node->GetName(), "intermediary 2"); EXPECT_EQ(leaf1_node->GetChildCount(), 0); EXPECT_EQ(leaf1_node->GetName(), "leaf 1"); EXPECT_EQ(leaf2_node->GetChildCount(), 0); EXPECT_EQ(leaf2_node->GetName(), "leaf 2"); EXPECT_EQ(leaf3_node->GetChildCount(), 0); EXPECT_EQ(leaf3_node->GetName(), "leaf 3"); // Intermediary 1 and intermediary 2 have new children. // Leaf 1, 2, and 3 are all moved. ASSERT_EQ(bridge->accessibility_events.size(), size_t{5}); EXPECT_THAT(bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::CHILDREN_CHANGED).Times(2)); EXPECT_THAT(bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::SUBTREE_CREATED).Times(3)); } // Verify that a node with a child can be moved from one parent to another. TEST(AccessibilityBridgeTest, CanReparentNodeWithChild) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); int32_t root_id = 0; int32_t intermediary1_id = 1; int32_t intermediary2_id = 2; int32_t leaf1_id = 3; std::vector<int32_t> root_children{intermediary1_id, intermediary2_id}; std::vector<int32_t> intermediary1_children{leaf1_id}; FlutterSemanticsNode2 root = CreateSemanticsNode(root_id, "root", &root_children); FlutterSemanticsNode2 intermediary1 = CreateSemanticsNode( intermediary1_id, "intermediary 1", &intermediary1_children); FlutterSemanticsNode2 intermediary2 = CreateSemanticsNode(intermediary2_id, "intermediary 2"); FlutterSemanticsNode2 leaf1 = CreateSemanticsNode(leaf1_id, "leaf 1"); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(intermediary1); bridge->AddFlutterSemanticsNodeUpdate(intermediary2); bridge->AddFlutterSemanticsNodeUpdate(leaf1); bridge->CommitUpdates(); bridge->accessibility_events.clear(); // Move intermediary1 from root to intermediary 2. int32_t new_root_children[] = {intermediary2_id}; root.child_count = 1; root.children_in_traversal_order = new_root_children; int32_t new_intermediary2_children[] = {intermediary1_id}; intermediary2.child_count = 1; intermediary2.children_in_traversal_order = new_intermediary2_children; bridge->AddFlutterSemanticsNodeUpdate(root); bridge->AddFlutterSemanticsNodeUpdate(intermediary1); bridge->AddFlutterSemanticsNodeUpdate(intermediary2); bridge->AddFlutterSemanticsNodeUpdate(leaf1); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(root_id).lock(); auto intermediary1_node = bridge->GetFlutterPlatformNodeDelegateFromID(intermediary1_id).lock(); auto intermediary2_node = bridge->GetFlutterPlatformNodeDelegateFromID(intermediary2_id).lock(); auto leaf1_node = bridge->GetFlutterPlatformNodeDelegateFromID(leaf1_id).lock(); EXPECT_EQ(root_node->GetChildCount(), 1); EXPECT_EQ(root_node->GetData().child_ids[0], intermediary2_id); EXPECT_EQ(root_node->GetName(), "root"); EXPECT_EQ(intermediary2_node->GetChildCount(), 1); EXPECT_EQ(intermediary2_node->GetData().child_ids[0], intermediary1_id); EXPECT_EQ(intermediary2_node->GetName(), "intermediary 2"); EXPECT_EQ(intermediary1_node->GetChildCount(), 1); EXPECT_EQ(intermediary1_node->GetData().child_ids[0], leaf1_id); EXPECT_EQ(intermediary1_node->GetName(), "intermediary 1"); EXPECT_EQ(leaf1_node->GetChildCount(), 0); EXPECT_EQ(leaf1_node->GetName(), "leaf 1"); ASSERT_EQ(bridge->accessibility_events.size(), size_t{5}); EXPECT_THAT(bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::CHILDREN_CHANGED).Times(2)); EXPECT_THAT(bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::SUBTREE_CREATED).Times(1)); // Intermediary 2 becomes a parent node. It updates to group role and enables // its 'clip children' attribute. EXPECT_THAT( bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED).Times(1)); EXPECT_THAT(bridge->accessibility_events, Contains(ui::AXEventGenerator::Event::ROLE_CHANGED).Times(1)); } TEST(AccessibilityBridgeTest, AXTreeManagerTest) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); ui::AXTreeID tree_id = bridge->GetTreeID(); ui::AXTreeManager* manager = ui::AXTreeManagerMap::GetInstance().GetManager(tree_id); ASSERT_EQ(manager, static_cast<ui::AXTreeManager*>(bridge.get())); } TEST(AccessibilityBridgeTest, LineBreakingObjectTest) { std::shared_ptr<TestAccessibilityBridge> bridge = std::make_shared<TestAccessibilityBridge>(); const int32_t root_id = 0; FlutterSemanticsNode2 root = CreateSemanticsNode(root_id, "root", {}); bridge->AddFlutterSemanticsNodeUpdate(root); bridge->CommitUpdates(); auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(root_id).lock(); auto root_data = root_node->GetData(); EXPECT_TRUE(root_data.HasBoolAttribute( ax::mojom::BoolAttribute::kIsLineBreakingObject)); EXPECT_TRUE(root_data.GetBoolAttribute( ax::mojom::BoolAttribute::kIsLineBreakingObject)); } } // namespace testing } // namespace flutter
engine/shell/platform/common/accessibility_bridge_unittests.cc/0
{ "file_path": "engine/shell/platform/common/accessibility_bridge_unittests.cc", "repo_id": "engine", "token_count": 8299 }
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. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BYTE_STREAMS_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BYTE_STREAMS_H_ // Interfaces for interacting with a stream of bytes, for use in codecs. namespace flutter { // An interface for a class that reads from a byte stream. class ByteStreamReader { public: explicit ByteStreamReader() = default; virtual ~ByteStreamReader() = default; // Reads and returns the next byte from the stream. virtual uint8_t ReadByte() = 0; // Reads the next |length| bytes from the stream into |buffer|. The caller // is responsible for ensuring that |buffer| is large enough. virtual void ReadBytes(uint8_t* buffer, size_t length) = 0; // Advances the read cursor to the next multiple of |alignment| relative to // the start of the stream, unless it is already aligned. virtual void ReadAlignment(uint8_t alignment) = 0; // Reads and returns the next 32-bit integer from the stream. int32_t ReadInt32() { int32_t value = 0; ReadBytes(reinterpret_cast<uint8_t*>(&value), 4); return value; } // Reads and returns the next 64-bit integer from the stream. int64_t ReadInt64() { int64_t value = 0; ReadBytes(reinterpret_cast<uint8_t*>(&value), 8); return value; } // Reads and returns the next 64-bit floating point number from the stream. double ReadDouble() { double value = 0; ReadBytes(reinterpret_cast<uint8_t*>(&value), 8); return value; } }; // An interface for a class that writes to a byte stream. class ByteStreamWriter { public: explicit ByteStreamWriter() = default; virtual ~ByteStreamWriter() = default; // Writes |byte| to the stream. virtual void WriteByte(uint8_t byte) = 0; // Writes the next |length| bytes from |bytes| to the stream virtual void WriteBytes(const uint8_t* bytes, size_t length) = 0; // Writes 0s until the next multiple of |alignment| relative to the start // of the stream, unless the write positition is already aligned. virtual void WriteAlignment(uint8_t alignment) = 0; // Writes the given 32-bit int to the stream. void WriteInt32(int32_t value) { WriteBytes(reinterpret_cast<const uint8_t*>(&value), 4); } // Writes the given 64-bit int to the stream. void WriteInt64(int64_t value) { WriteBytes(reinterpret_cast<const uint8_t*>(&value), 8); } // Writes the given 36-bit double to the stream. void WriteDouble(double value) { WriteBytes(reinterpret_cast<const uint8_t*>(&value), 8); } }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BYTE_STREAMS_H_
engine/shell/platform/common/client_wrapper/include/flutter/byte_streams.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/byte_streams.h", "repo_id": "engine", "token_count": 937 }
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_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_MESSAGE_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_MESSAGE_CODEC_H_ #include <memory> #include "encodable_value.h" #include "message_codec.h" #include "standard_codec_serializer.h" namespace flutter { // A binary message encoding/decoding mechanism for communications to/from the // Flutter engine via message channels. class StandardMessageCodec : public MessageCodec<EncodableValue> { public: // Returns an instance of the codec, optionally using a custom serializer to // add support for more types. // // If provided, |serializer| must be long-lived. If no serializer is provided, // the default will be used. // // The instance returned for a given |serializer| will be shared, and // any instance returned from this will be long-lived, and can be safely // passed to, e.g., channel constructors. static const StandardMessageCodec& GetInstance( const StandardCodecSerializer* serializer = nullptr); ~StandardMessageCodec(); // Prevent copying. StandardMessageCodec(StandardMessageCodec const&) = delete; StandardMessageCodec& operator=(StandardMessageCodec const&) = delete; protected: // |flutter::MessageCodec| std::unique_ptr<EncodableValue> DecodeMessageInternal( const uint8_t* binary_message, const size_t message_size) const override; // |flutter::MessageCodec| std::unique_ptr<std::vector<uint8_t>> EncodeMessageInternal( const EncodableValue& message) const override; private: // Instances should be obtained via GetInstance. explicit StandardMessageCodec(const StandardCodecSerializer* serializer); const StandardCodecSerializer* serializer_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_MESSAGE_CODEC_H_
engine/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h", "repo_id": "engine", "token_count": 656 }
357
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TEXTURE_REGISTRAR_IMPL_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TEXTURE_REGISTRAR_IMPL_H_ #include "include/flutter/texture_registrar.h" namespace flutter { // Wrapper around a FlutterDesktopTextureRegistrarRef that implements the // TextureRegistrar API. class TextureRegistrarImpl : public TextureRegistrar { public: explicit TextureRegistrarImpl( FlutterDesktopTextureRegistrarRef texture_registrar_ref); virtual ~TextureRegistrarImpl(); // Prevent copying. TextureRegistrarImpl(TextureRegistrarImpl const&) = delete; TextureRegistrarImpl& operator=(TextureRegistrarImpl const&) = delete; // |flutter::TextureRegistrar| int64_t RegisterTexture(TextureVariant* texture) override; // |flutter::TextureRegistrar| bool MarkTextureFrameAvailable(int64_t texture_id) override; // |flutter::TextureRegistrar| void UnregisterTexture(int64_t texture_id, std::function<void()> callback) override; // |flutter::TextureRegistrar| bool UnregisterTexture(int64_t texture_id) override; private: // Handle for interacting with the C API. FlutterDesktopTextureRegistrarRef texture_registrar_ref_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TEXTURE_REGISTRAR_IMPL_H_
engine/shell/platform/common/client_wrapper/texture_registrar_impl.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/texture_registrar_impl.h", "repo_id": "engine", "token_count": 504 }
358
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/common/json_method_codec.h" #include "flutter/shell/platform/common/json_message_codec.h" namespace flutter { namespace { // Keys used in MethodCall encoding. constexpr char kMessageMethodKey[] = "method"; constexpr char kMessageArgumentsKey[] = "args"; // Returns a new document containing only |element|, which must be an element // in |document|. This is a move rather than a copy, so it is efficient but // destructive to the data in |document|. std::unique_ptr<rapidjson::Document> ExtractElement( rapidjson::Document* document, rapidjson::Value* subtree) { auto extracted = std::make_unique<rapidjson::Document>(); // Pull the subtree up to the root of the document. document->Swap(*subtree); // Swap the entire document into |extracted|. Unlike the swap above this moves // the allocator ownership, so the data won't be deleted when |document| is // destroyed. extracted->Swap(*document); return extracted; } } // namespace // static const JsonMethodCodec& JsonMethodCodec::GetInstance() { static JsonMethodCodec sInstance; return sInstance; } std::unique_ptr<MethodCall<rapidjson::Document>> JsonMethodCodec::DecodeMethodCallInternal(const uint8_t* message, size_t message_size) const { std::unique_ptr<rapidjson::Document> json_message = JsonMessageCodec::GetInstance().DecodeMessage(message, message_size); if (!json_message) { return nullptr; } auto method_name_iter = json_message->FindMember(kMessageMethodKey); if (method_name_iter == json_message->MemberEnd()) { return nullptr; } if (!method_name_iter->value.IsString()) { return nullptr; } std::string method_name(method_name_iter->value.GetString()); auto arguments_iter = json_message->FindMember(kMessageArgumentsKey); std::unique_ptr<rapidjson::Document> arguments; if (arguments_iter != json_message->MemberEnd()) { arguments = ExtractElement(json_message.get(), &(arguments_iter->value)); } return std::make_unique<MethodCall<rapidjson::Document>>( method_name, std::move(arguments)); } std::unique_ptr<std::vector<uint8_t>> JsonMethodCodec::EncodeMethodCallInternal( const MethodCall<rapidjson::Document>& method_call) const { // TODO(stuartmorgan): Consider revisiting the codec APIs to avoid the need // to copy everything when doing encoding (e.g., by having a version that // takes owership of the object to encode, so that it can be moved instead). rapidjson::Document message(rapidjson::kObjectType); auto& allocator = message.GetAllocator(); rapidjson::Value name(method_call.method_name(), allocator); rapidjson::Value arguments; if (method_call.arguments()) { arguments.CopyFrom(*method_call.arguments(), allocator); } message.AddMember(kMessageMethodKey, name, allocator); message.AddMember(kMessageArgumentsKey, arguments, allocator); return JsonMessageCodec::GetInstance().EncodeMessage(message); } std::unique_ptr<std::vector<uint8_t>> JsonMethodCodec::EncodeSuccessEnvelopeInternal( const rapidjson::Document* result) const { rapidjson::Document envelope; envelope.SetArray(); rapidjson::Value result_value; if (result) { result_value.CopyFrom(*result, envelope.GetAllocator()); } envelope.PushBack(result_value, envelope.GetAllocator()); return JsonMessageCodec::GetInstance().EncodeMessage(envelope); } std::unique_ptr<std::vector<uint8_t>> JsonMethodCodec::EncodeErrorEnvelopeInternal( const std::string& error_code, const std::string& error_message, const rapidjson::Document* error_details) const { // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) rapidjson::Document envelope(rapidjson::kArrayType); auto& allocator = envelope.GetAllocator(); envelope.PushBack(rapidjson::Value(error_code, allocator), allocator); envelope.PushBack(rapidjson::Value(error_message, allocator), allocator); rapidjson::Value details_value; if (error_details) { details_value.CopyFrom(*error_details, allocator); } envelope.PushBack(details_value, allocator); return JsonMessageCodec::GetInstance().EncodeMessage(envelope); } bool JsonMethodCodec::DecodeAndProcessResponseEnvelopeInternal( const uint8_t* response, size_t response_size, MethodResult<rapidjson::Document>* result) const { std::unique_ptr<rapidjson::Document> json_response = JsonMessageCodec::GetInstance().DecodeMessage(response, response_size); if (!json_response) { return false; } if (!json_response->IsArray()) { return false; } switch (json_response->Size()) { case 1: { std::unique_ptr<rapidjson::Document> value = ExtractElement(json_response.get(), &((*json_response)[0])); if (value->IsNull()) { result->Success(); } else { result->Success(*value); } return true; } case 3: { std::string code = (*json_response)[0].GetString(); std::string message = (*json_response)[1].GetString(); std::unique_ptr<rapidjson::Document> details = ExtractElement(json_response.get(), &((*json_response)[2])); if (details->IsNull()) { result->Error(code, message); } else { result->Error(code, message, *details); } return true; } default: return false; } } } // namespace flutter
engine/shell/platform/common/json_method_codec.cc/0
{ "file_path": "engine/shell/platform/common/json_method_codec.cc", "repo_id": "engine", "token_count": 1877 }
359
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/common/text_editing_delta.h" #include "gtest/gtest.h" namespace flutter { TEST(TextEditingDeltaTest, TestTextEditingDeltaConstructor) { // Here we are simulating inserting an "o" at the end of "hell". std::string old_text = "hell"; std::string replacement_text = "hello"; TextRange range(0, 4); TextEditingDelta delta = TextEditingDelta(old_text, range, replacement_text); EXPECT_EQ(delta.old_text(), old_text); EXPECT_EQ(delta.delta_text(), "hello"); EXPECT_EQ(delta.delta_start(), 0); EXPECT_EQ(delta.delta_end(), 4); } TEST(TextEditingDeltaTest, TestTextEditingDeltaNonTextConstructor) { // Here we are simulating inserting an "o" at the end of "hell". std::string old_text = "hello"; TextEditingDelta delta = TextEditingDelta(old_text); EXPECT_EQ(delta.old_text(), old_text); EXPECT_EQ(delta.delta_text(), ""); EXPECT_EQ(delta.delta_start(), -1); EXPECT_EQ(delta.delta_end(), -1); } } // namespace flutter
engine/shell/platform/common/text_editing_delta_unittests.cc/0
{ "file_path": "engine/shell/platform/common/text_editing_delta_unittests.cc", "repo_id": "engine", "token_count": 414 }
360
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/common/command_line.h" #import <Foundation/Foundation.h> namespace flutter { fml::CommandLine CommandLineFromNSProcessInfo(NSProcessInfo* processInfoOrNil) { std::vector<std::string> args_vector; auto processInfo = processInfoOrNil ? processInfoOrNil : [NSProcessInfo processInfo]; for (NSString* arg in processInfo.arguments) { args_vector.emplace_back(arg.UTF8String); } return fml::CommandLineFromIterators(args_vector.begin(), args_vector.end()); } } // namespace flutter
engine/shell/platform/darwin/common/command_line.mm/0
{ "file_path": "engine/shell/platform/darwin/common/command_line.mm", "repo_id": "engine", "token_count": 219 }
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. #include "flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.h" #include <stdint.h> #include <vector> #include "flutter/fml/logging.h" // The google-runtime-int lint suggests uint64_t in place of unsigned long, // however these functions are frequently used with NSUInteger, which is // defined as an unsigned long. // // NOLINTBEGIN(google-runtime-int) void FlutterStandardCodecHelperReadAlignment(unsigned long* location, uint8_t alignment) { uint8_t mod = *location % alignment; if (mod) { *location += (alignment - mod); } } static uint8_t PeekByte(unsigned long location, CFDataRef data) { uint8_t result; CFRange range = CFRangeMake(location, 1); CFDataGetBytes(data, range, &result); return result; } void FlutterStandardCodecHelperReadBytes(unsigned long* location, unsigned long length, void* destination, CFDataRef data) { CFRange range = CFRangeMake(*location, length); CFDataGetBytes(data, range, static_cast<UInt8*>(destination)); *location += length; } uint8_t FlutterStandardCodecHelperReadByte(unsigned long* location, CFDataRef data) { uint8_t value; FlutterStandardCodecHelperReadBytes(location, 1, &value, data); return value; } uint32_t FlutterStandardCodecHelperReadSize(unsigned long* location, CFDataRef data) { uint8_t byte = FlutterStandardCodecHelperReadByte(location, data); if (byte < 254) { return (uint32_t)byte; } else if (byte == 254) { UInt16 value; FlutterStandardCodecHelperReadBytes(location, 2, &value, data); return value; } else { UInt32 value; FlutterStandardCodecHelperReadBytes(location, 4, &value, data); return value; } } static CFDataRef ReadDataNoCopy(unsigned long* location, unsigned long length, CFDataRef data) { CFDataRef result = CFDataCreateWithBytesNoCopy( kCFAllocatorDefault, CFDataGetBytePtr(data) + *location, length, kCFAllocatorNull); *location += length; return static_cast<CFDataRef>(CFAutorelease(result)); } CFStringRef FlutterStandardCodecHelperReadUTF8(unsigned long* location, CFDataRef data) { uint32_t size = FlutterStandardCodecHelperReadSize(location, data); CFDataRef bytes = ReadDataNoCopy(location, size, data); CFStringRef result = CFStringCreateFromExternalRepresentation( kCFAllocatorDefault, bytes, kCFStringEncodingUTF8); return static_cast<CFStringRef>(CFAutorelease(result)); } // Peeks ahead to see if we are reading a standard type. If so, recurse // directly to FlutterStandardCodecHelperReadValueOfType, otherwise recurse to // objc. static inline CFTypeRef FastReadValue( unsigned long* location, CFDataRef data, CFTypeRef (*ReadValue)(CFTypeRef), CFTypeRef (*ReadTypedDataOfType)(FlutterStandardField, CFTypeRef), CFTypeRef user_data) { uint8_t type = PeekByte(*location, data); if (FlutterStandardFieldIsStandardType(type)) { *location += 1; return FlutterStandardCodecHelperReadValueOfType( location, data, type, ReadValue, ReadTypedDataOfType, user_data); } else { return ReadValue(user_data); } } CFTypeRef FlutterStandardCodecHelperReadValueOfType( unsigned long* location, CFDataRef data, uint8_t type, CFTypeRef (*ReadValue)(CFTypeRef), CFTypeRef (*ReadTypedDataOfType)(FlutterStandardField, CFTypeRef), CFTypeRef user_data) { FlutterStandardField field = (FlutterStandardField)type; switch (field) { case FlutterStandardFieldNil: return nil; case FlutterStandardFieldTrue: return kCFBooleanTrue; case FlutterStandardFieldFalse: return kCFBooleanFalse; case FlutterStandardFieldInt32: { int32_t value; FlutterStandardCodecHelperReadBytes(location, 4, &value, data); return CFAutorelease( CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value)); } case FlutterStandardFieldInt64: { int64_t value; FlutterStandardCodecHelperReadBytes(location, 8, &value, data); return CFAutorelease( CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &value)); } case FlutterStandardFieldFloat64: { Float64 value; FlutterStandardCodecHelperReadAlignment(location, 8); FlutterStandardCodecHelperReadBytes(location, 8, &value, data); return CFAutorelease( CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &value)); } case FlutterStandardFieldIntHex: case FlutterStandardFieldString: return FlutterStandardCodecHelperReadUTF8(location, data); case FlutterStandardFieldUInt8Data: case FlutterStandardFieldInt32Data: case FlutterStandardFieldInt64Data: case FlutterStandardFieldFloat32Data: case FlutterStandardFieldFloat64Data: return ReadTypedDataOfType(field, user_data); case FlutterStandardFieldList: { UInt32 length = FlutterStandardCodecHelperReadSize(location, data); CFMutableArrayRef array = CFArrayCreateMutable( kCFAllocatorDefault, length, &kCFTypeArrayCallBacks); for (UInt32 i = 0; i < length; i++) { CFTypeRef value = FastReadValue(location, data, ReadValue, ReadTypedDataOfType, user_data); CFArrayAppendValue(array, (value == nil ? kCFNull : value)); } return CFAutorelease(array); } case FlutterStandardFieldMap: { UInt32 size = FlutterStandardCodecHelperReadSize(location, data); CFMutableDictionaryRef dict = CFDictionaryCreateMutable( kCFAllocatorDefault, size, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); for (UInt32 i = 0; i < size; i++) { CFTypeRef key = FastReadValue(location, data, ReadValue, ReadTypedDataOfType, user_data); CFTypeRef val = FastReadValue(location, data, ReadValue, ReadTypedDataOfType, user_data); CFDictionaryAddValue(dict, (key == nil ? kCFNull : key), (val == nil ? kCFNull : val)); } return CFAutorelease(dict); } default: // Malformed message. FML_DCHECK(false); } } void FlutterStandardCodecHelperWriteByte(CFMutableDataRef data, uint8_t value) { CFDataAppendBytes(data, &value, 1); } void FlutterStandardCodecHelperWriteBytes(CFMutableDataRef data, const void* bytes, unsigned long length) { CFDataAppendBytes(data, static_cast<const UInt8*>(bytes), length); } void FlutterStandardCodecHelperWriteSize(CFMutableDataRef data, uint32_t size) { if (size < 254) { FlutterStandardCodecHelperWriteByte(data, size); } else if (size <= 0xffff) { FlutterStandardCodecHelperWriteByte(data, 254); UInt16 value = (UInt16)size; FlutterStandardCodecHelperWriteBytes(data, &value, 2); } else { FlutterStandardCodecHelperWriteByte(data, 255); FlutterStandardCodecHelperWriteBytes(data, &size, 4); } } void FlutterStandardCodecHelperWriteAlignment(CFMutableDataRef data, uint8_t alignment) { uint8_t mod = CFDataGetLength(data) % alignment; if (mod) { for (int i = 0; i < (alignment - mod); i++) { FlutterStandardCodecHelperWriteByte(data, 0); } } } void FlutterStandardCodecHelperWriteUTF8(CFMutableDataRef data, CFStringRef value) { const char* utf8 = CFStringGetCStringPtr(value, kCFStringEncodingUTF8); if (utf8) { size_t length = strlen(utf8); FlutterStandardCodecHelperWriteSize(data, length); FlutterStandardCodecHelperWriteBytes(data, utf8, length); } else { CFIndex length = CFStringGetLength(value); CFIndex used_length = 0; // UTF16 length times 3 will fit all UTF8. CFIndex buffer_length = length * 3; std::vector<UInt8> buffer; buffer.resize(buffer_length); CFStringGetBytes(value, CFRangeMake(0, length), kCFStringEncodingUTF8, 0, false, buffer.data(), buffer_length, &used_length); FlutterStandardCodecHelperWriteSize(data, used_length); FlutterStandardCodecHelperWriteBytes(data, buffer.data(), used_length); } } void FlutterStandardCodecHelperWriteData(CFMutableDataRef data, CFDataRef value) { const UInt8* bytes = CFDataGetBytePtr(value); CFIndex length = CFDataGetLength(value); FlutterStandardCodecHelperWriteBytes(data, bytes, length); } bool FlutterStandardCodecHelperWriteNumber(CFMutableDataRef data, CFNumberRef number) { bool success = false; if (CFGetTypeID(number) == CFBooleanGetTypeID()) { bool b = CFBooleanGetValue((CFBooleanRef)number); FlutterStandardCodecHelperWriteByte( data, (b ? FlutterStandardFieldTrue : FlutterStandardFieldFalse)); success = true; } else if (CFNumberIsFloatType(number)) { Float64 f; success = CFNumberGetValue(number, kCFNumberFloat64Type, &f); if (success) { FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldFloat64); FlutterStandardCodecHelperWriteAlignment(data, 8); FlutterStandardCodecHelperWriteBytes(data, &f, 8); } } else if (CFNumberGetByteSize(number) <= 4) { SInt32 n; success = CFNumberGetValue(number, kCFNumberSInt32Type, &n); if (success) { FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldInt32); FlutterStandardCodecHelperWriteBytes(data, &n, 4); } } else if (CFNumberGetByteSize(number) <= 8) { SInt64 n; success = CFNumberGetValue(number, kCFNumberSInt64Type, &n); if (success) { FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldInt64); FlutterStandardCodecHelperWriteBytes(data, &n, 8); } } return success; } // NOLINTEND(google-runtime-int)
engine/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.cc/0
{ "file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.cc", "repo_id": "engine", "token_count": 4193 }
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. assert(is_ios) import("//build/config/ios/ios_sdk.gni") import("//build/toolchain/clang.gni") import("//flutter/common/config.gni") import("//flutter/shell/config.gni") import("//flutter/shell/gpu/gpu.gni") import("//flutter/shell/platform/darwin/common/framework_common.gni") import("//flutter/testing/testing.gni") _flutter_framework_dir = "$root_out_dir/Flutter.framework" shell_gpu_configuration("ios_gpu_configuration") { enable_software = true enable_gl = false enable_vulkan = false enable_metal = shell_enable_metal } # The headers that will be copied to the Flutter.framework and be accessed # from outside the Flutter engine source root. _flutter_framework_headers = [ "framework/Headers/Flutter.h", "framework/Headers/FlutterAppDelegate.h", "framework/Headers/FlutterCallbackCache.h", "framework/Headers/FlutterEngine.h", "framework/Headers/FlutterEngineGroup.h", "framework/Headers/FlutterHeadlessDartRunner.h", "framework/Headers/FlutterPlatformViews.h", "framework/Headers/FlutterPlugin.h", "framework/Headers/FlutterPluginAppLifeCycleDelegate.h", "framework/Headers/FlutterViewController.h", ] _flutter_framework_headers_copy_dir = "$_flutter_framework_dir/Headers" source_set("flutter_framework_source_arc") { visibility = [ ":*" ] cflags_objc = flutter_cflags_objc_arc cflags_objcc = flutter_cflags_objcc_arc defines = [ "FLUTTER_FRAMEWORK=1" ] if (darwin_extension_safe) { defines += [ "APPLICATION_EXTENSION_API_ONLY=1" ] } allow_circular_includes_from = [ ":flutter_framework_source" ] deps = [ ":flutter_framework_source", "//flutter/fml", "//flutter/shell/platform/common:common_cpp_input", "//flutter/shell/platform/darwin/common:framework_common", "//flutter/third_party/icu", ] public_configs = [ "//flutter:config" ] sources = [ "framework/Source/FlutterMetalLayer.h", "framework/Source/FlutterMetalLayer.mm", "framework/Source/FlutterTextInputDelegate.h", "framework/Source/FlutterTextInputPlugin.h", "framework/Source/FlutterTextInputPlugin.mm", ] frameworks = [ "UIKit.framework", "IOSurface.framework", ] } source_set("flutter_framework_source") { visibility = [ ":*" ] cflags_objc = flutter_cflags_objc cflags_objcc = flutter_cflags_objcc deps = [] sources = [ # iOS embedder is migrating to ARC. # New files are highly encouraged to be in ARC. # To add new files in ARC, add them to the `flutter_framework_source_arc` target. "framework/Source/FlutterAppDelegate.mm", "framework/Source/FlutterCallbackCache.mm", "framework/Source/FlutterCallbackCache_Internal.h", "framework/Source/FlutterChannelKeyResponder.h", "framework/Source/FlutterChannelKeyResponder.mm", "framework/Source/FlutterDartProject.mm", "framework/Source/FlutterDartProject_Internal.h", "framework/Source/FlutterDartVMServicePublisher.h", "framework/Source/FlutterDartVMServicePublisher.mm", "framework/Source/FlutterEmbedderKeyResponder.h", "framework/Source/FlutterEmbedderKeyResponder.mm", "framework/Source/FlutterEngine.mm", "framework/Source/FlutterEngineGroup.mm", "framework/Source/FlutterEngine_Internal.h", "framework/Source/FlutterHeadlessDartRunner.mm", "framework/Source/FlutterKeyPrimaryResponder.h", "framework/Source/FlutterKeySecondaryResponder.h", "framework/Source/FlutterKeyboardManager.h", "framework/Source/FlutterKeyboardManager.mm", "framework/Source/FlutterOverlayView.h", "framework/Source/FlutterOverlayView.mm", "framework/Source/FlutterPlatformPlugin.h", "framework/Source/FlutterPlatformPlugin.mm", "framework/Source/FlutterPlatformViews.mm", "framework/Source/FlutterPlatformViews_Internal.h", "framework/Source/FlutterPlatformViews_Internal.mm", "framework/Source/FlutterPluginAppLifeCycleDelegate.mm", "framework/Source/FlutterRestorationPlugin.h", "framework/Source/FlutterRestorationPlugin.mm", "framework/Source/FlutterSemanticsScrollView.h", "framework/Source/FlutterSemanticsScrollView.mm", "framework/Source/FlutterSpellCheckPlugin.h", "framework/Source/FlutterSpellCheckPlugin.mm", "framework/Source/FlutterTextureRegistryRelay.h", "framework/Source/FlutterTextureRegistryRelay.mm", "framework/Source/FlutterUIPressProxy.h", "framework/Source/FlutterUIPressProxy.mm", "framework/Source/FlutterUndoManagerDelegate.h", "framework/Source/FlutterUndoManagerPlugin.h", "framework/Source/FlutterUndoManagerPlugin.mm", "framework/Source/FlutterView.h", "framework/Source/FlutterView.mm", "framework/Source/FlutterViewController.mm", "framework/Source/FlutterViewController_Internal.h", "framework/Source/KeyCodeMap.g.mm", "framework/Source/KeyCodeMap_Internal.h", "framework/Source/SemanticsObject.h", "framework/Source/SemanticsObject.mm", "framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h", "framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.mm", "framework/Source/accessibility_bridge.h", "framework/Source/accessibility_bridge.mm", "framework/Source/accessibility_text_entry.h", "framework/Source/accessibility_text_entry.mm", "framework/Source/connection_collection.h", "framework/Source/connection_collection.mm", "framework/Source/platform_message_response_darwin.h", "framework/Source/platform_message_response_darwin.mm", "framework/Source/profiler_metrics_ios.h", "framework/Source/profiler_metrics_ios.mm", "framework/Source/vsync_waiter_ios.h", "framework/Source/vsync_waiter_ios.mm", "ios_context.h", "ios_context.mm", "ios_context_software.h", "ios_context_software.mm", "ios_external_view_embedder.h", "ios_external_view_embedder.mm", "ios_surface.h", "ios_surface.mm", "ios_surface_software.h", "ios_surface_software.mm", "platform_message_handler_ios.h", "platform_message_handler_ios.mm", "platform_view_ios.h", "platform_view_ios.mm", "rendering_api_selection.h", "rendering_api_selection.mm", ] sources += _flutter_framework_headers defines = [ "FLUTTER_FRAMEWORK=1" ] if (darwin_extension_safe) { defines += [ "APPLICATION_EXTENSION_API_ONLY=1" ] } if (shell_enable_metal) { sources += [ "ios_context_metal_impeller.h", "ios_context_metal_impeller.mm", "ios_context_metal_skia.h", "ios_context_metal_skia.mm", "ios_external_texture_metal.h", "ios_external_texture_metal.mm", "ios_surface_metal_impeller.h", "ios_surface_metal_impeller.mm", "ios_surface_metal_skia.h", "ios_surface_metal_skia.mm", ] deps += [ "//flutter/shell/platform/darwin/graphics" ] } deps += [ ":ios_gpu_configuration", "//flutter/common", "//flutter/common/graphics", "//flutter/flow", "//flutter/fml", "//flutter/lib/ui", "//flutter/runtime", "//flutter/runtime:libdart", "//flutter/shell/common", "//flutter/shell/platform/common:common_cpp_input", "//flutter/shell/platform/darwin/common", "//flutter/shell/platform/darwin/common:framework_common", "//flutter/shell/platform/embedder:embedder_as_internal_library", "//flutter/shell/profiling:profiling", "//flutter/skia", "//flutter/third_party/spring_animation", ] public_configs = [ ":ios_gpu_configuration_config", "//flutter:config", ] frameworks = [ "AudioToolbox.framework", "CoreMedia.framework", "CoreVideo.framework", "QuartzCore.framework", "UIKit.framework", ] if (flutter_runtime_mode == "profile" || flutter_runtime_mode == "debug") { # This is required by the profiler_metrics_ios.mm to get GPU statistics. # Usage in release builds will cause rejection from the App Store. frameworks += [ "IOKit.framework" ] } } platform_frameworks_path = rebase_path("$ios_sdk_path/../../Library/Frameworks/") shared_library("ios_test_flutter") { testonly = true visibility = [ "*" ] cflags = [ "-fvisibility=default", "-F$platform_frameworks_path", "-fobjc-arc", "-mios-simulator-version-min=$ios_testing_deployment_target", ] # XCode 15 beta has a bug where iOS 17 API usage is not guarded. # This bug results engine build failure since the engine treats warnings as errors. # The `-Wno-unguarded-availability-new` can be removed when the XCode bug is fixed. # See details in https://github.com/flutter/flutter/issues/128958. cflags_objcc = [ "-Wno-unguarded-availability-new" ] ldflags = [ "-F$platform_frameworks_path", "-Wl,-install_name,@rpath/Frameworks/libios_test_flutter.dylib", ] frameworks = [ "XCTest.framework" ] configs -= [ "//build/config/gcc:symbol_visibility_hidden", "//build/config:symbol_visibility_hidden", ] sources = [ "framework/Source/FlutterAppDelegateTest.mm", "framework/Source/FlutterChannelKeyResponderTest.mm", "framework/Source/FlutterDartProjectTest.mm", "framework/Source/FlutterEmbedderKeyResponderTest.mm", "framework/Source/FlutterEngineGroupTest.mm", "framework/Source/FlutterEnginePlatformViewTest.mm", "framework/Source/FlutterEngineTest.mm", "framework/Source/FlutterFakeKeyEvents.h", "framework/Source/FlutterFakeKeyEvents.mm", "framework/Source/FlutterKeyboardManagerTest.mm", "framework/Source/FlutterMetalLayerTest.mm", "framework/Source/FlutterPlatformPluginTest.mm", "framework/Source/FlutterPlatformViewsTest.mm", "framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm", "framework/Source/FlutterRestorationPluginTest.mm", "framework/Source/FlutterSpellCheckPluginTest.mm", "framework/Source/FlutterTextInputPluginTest.mm", "framework/Source/FlutterTextureRegistryRelayTest.mm", "framework/Source/FlutterTouchInterceptingView_Test.h", "framework/Source/FlutterUndoManagerPluginTest.mm", "framework/Source/FlutterViewControllerTest.mm", "framework/Source/FlutterViewTest.mm", "framework/Source/SemanticsObjectTest.mm", "framework/Source/SemanticsObjectTestMocks.h", "framework/Source/UIViewController_FlutterScreenAndSceneIfLoadedTest.mm", "framework/Source/VsyncWaiterIosTest.mm", "framework/Source/accessibility_bridge_test.mm", "framework/Source/availability_version_check_test.mm", "framework/Source/connection_collection_test.mm", "platform_message_handler_ios_test.mm", ] deps = [ ":flutter_framework", ":flutter_framework_source", ":flutter_framework_source_arc", ":ios_gpu_configuration", "//flutter/common:common", "//flutter/lib/ui:ui", "//flutter/shell/platform/darwin/common:framework_common", "//flutter/shell/platform/embedder:embedder_as_internal_library", "//flutter/shell/platform/embedder:embedder_test_utils", "//flutter/skia", "//flutter/third_party/ocmock:ocmock_shared", "//flutter/third_party/rapidjson", "//flutter/third_party/spring_animation", "//flutter/third_party/tonic", "//flutter/third_party/txt", ] public_configs = [ ":ios_gpu_configuration_config", "//flutter:config", ] if (darwin_extension_safe) { defines = [ "APPLICATION_EXTENSION_API_ONLY=1" ] } } shared_library("create_flutter_framework_dylib") { visibility = [ ":*" ] output_name = "Flutter" ldflags = [ "-Wl,-install_name,@rpath/Flutter.framework/Flutter" ] if (darwin_extension_safe) { ldflags += [ "-fapplication-extension" ] } public = _flutter_framework_headers deps = [ ":flutter_framework_source", ":flutter_framework_source_arc", ] public_configs = [ "//flutter:config" ] } copy("copy_dylib") { visibility = [ ":*" ] sources = [ "$root_out_dir/libFlutter.dylib" ] outputs = [ "$_flutter_framework_dir/Flutter" ] deps = [ ":create_flutter_framework_dylib" ] } copy("copy_asan_runtime_dylib") { visibility = [ ":*" ] _libclang_base_path = "//buildtools/mac-x64/clang/lib/clang/13.0.0/lib/darwin/" if (defined(use_ios_simulator) && use_ios_simulator) { _dylib_name = "libclang_rt.asan_iossim_dynamic.dylib" } else { _dylib_name = "libclang_rt.asan_ios_dynamic.dylib" } sources = [ "$_libclang_base_path/$_dylib_name" ] outputs = [ "$root_out_dir/$_dylib_name" ] deps = [ ":create_flutter_framework_dylib" ] } action("copy_framework_info_plist") { script = "//flutter/build/copy_info_plist.py" visibility = [ ":*" ] sources = [ "framework/Info.plist" ] outputs = [ "$_flutter_framework_dir/Info.plist" ] args = [ "--source", rebase_path(sources[0]), "--destination", rebase_path(outputs[0]), "--minversion", ios_deployment_target, ] } copy("copy_framework_module_map") { visibility = [ ":*" ] sources = [ "framework/module.modulemap" ] outputs = [ "$_flutter_framework_dir/Modules/module.modulemap" ] } # Copy privacy manifest. This file is required by Apple for third-party SDKs, # and documents engine and third_party usage of timestamps and boot time APIs. # See https://developer.apple.com/documentation/bundleresources/privacy_manifest_files copy("copy_framework_privacy_manifest") { visibility = [ ":*" ] sources = [ "framework/PrivacyInfo.xcprivacy" ] outputs = [ "$_flutter_framework_dir/PrivacyInfo.xcprivacy" ] } action("copy_framework_headers") { script = "//flutter/sky/tools/install_framework_headers.py" visibility = [ ":*" ] sources = get_path_info(_flutter_framework_headers, "abspath") + framework_common_headers outputs = [] foreach(header, sources) { header_basename = get_path_info(header, "file") outputs += [ "$_flutter_framework_headers_copy_dir/$header_basename" ] } args = [ "--location", rebase_path("$_flutter_framework_headers_copy_dir"), "--headers", ] + rebase_path(sources, "", "//") } copy("copy_framework_icu") { visibility = [ ":*" ] sources = [ "//flutter/third_party/icu/flutter/icudtl.dat" ] outputs = [ "$_flutter_framework_dir/{{source_file_part}}" ] } copy("copy_license") { visibility = [ ":*" ] sources = [ "//LICENSE" ] outputs = [ "$root_out_dir/LICENSE" ] } shared_library("copy_and_verify_framework_module") { framework_search_path = rebase_path("$root_out_dir") visibility = [ ":*" ] cflags_objc = [ "-F$framework_search_path", "-fapplication-extension", ] sources = [ "framework/Source/FlutterUmbrellaImport.m" ] deps = [ ":copy_framework_headers", ":copy_framework_info_plist", ":copy_framework_module_map", ":copy_framework_privacy_manifest", ] if (darwin_extension_safe) { ldflags = [ "-F$framework_search_path", "-fapplication-extension", "-Xlinker", "-fatal_warnings", ] deps += [ ":copy_dylib" ] frameworks = [ "Flutter.framework" ] } } group("universal_flutter_framework") { visibility = [ ":*" ] deps = [ ":copy_and_verify_framework_module", ":copy_dylib", ":copy_framework_icu", ":copy_framework_info_plist", ":copy_framework_module_map", ":copy_framework_privacy_manifest", ":copy_license", ] if (is_asan) { deps += [ ":copy_asan_runtime_dylib" ] } } action("flutter_framework") { script = "//flutter/sky/tools/create_xcframework.py" outputs = [ "$root_out_dir/Flutter.xcframework" ] args = [ "--frameworks", rebase_path("$_flutter_framework_dir"), "--name", "Flutter", "--location", rebase_path("$root_out_dir"), ] deps = [ ":universal_flutter_framework" ] }
engine/shell/platform/darwin/ios/BUILD.gn/0
{ "file_path": "engine/shell/platform/darwin/ios/BUILD.gn", "repo_id": "engine", "token_count": 6021 }
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_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERAPPDELEGATE_TEST_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERAPPDELEGATE_TEST_H_ @class FlutterViewController; @interface FlutterAppDelegate (Test) @property(nonatomic, copy) FlutterViewController* (^rootFlutterViewControllerGetter)(void); @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERAPPDELEGATE_TEST_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate_Test.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate_Test.h", "repo_id": "engine", "token_count": 227 }
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. #import <OCMock/OCMock.h> #import <XCTest/XCTest.h> #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngineGroup.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h" FLUTTER_ASSERT_ARC @interface FlutterEngineGroup () - (FlutterEngine*)makeEngine; @end @interface FlutterEngineGroupTest : XCTestCase @end @implementation FlutterEngineGroupTest - (void)testMake { FlutterEngineGroup* group = [[FlutterEngineGroup alloc] initWithName:@"foo" project:nil]; FlutterEngine* engine = [group makeEngineWithEntrypoint:nil libraryURI:nil]; XCTAssertNotNil(engine); } - (void)testSpawn { FlutterEngineGroup* group = [[FlutterEngineGroup alloc] initWithName:@"foo" project:nil]; FlutterEngine* spawner = [group makeEngineWithEntrypoint:nil libraryURI:nil]; spawner.isGpuDisabled = YES; FlutterEngine* spawnee = [group makeEngineWithEntrypoint:nil libraryURI:nil]; XCTAssertNotNil(spawner); XCTAssertNotNil(spawnee); XCTAssertEqual(&spawner.threadHost, &spawnee.threadHost); XCTAssertEqual(spawner.isGpuDisabled, spawnee.isGpuDisabled); } - (void)testDeleteLastEngine { FlutterEngineGroup* group = [[FlutterEngineGroup alloc] initWithName:@"foo" project:nil]; @autoreleasepool { FlutterEngine* spawner = [group makeEngineWithEntrypoint:nil libraryURI:nil]; XCTAssertNotNil(spawner); } FlutterEngine* spawnee = [group makeEngineWithEntrypoint:nil libraryURI:nil]; XCTAssertNotNil(spawnee); } - (void)testCustomEntrypoint { FlutterEngineGroup* group = OCMPartialMock([[FlutterEngineGroup alloc] initWithName:@"foo" project:nil]); FlutterEngine* mockEngine = OCMClassMock([FlutterEngine class]); OCMStub([group makeEngine]).andReturn(mockEngine); OCMStub([mockEngine spawnWithEntrypoint:[OCMArg any] libraryURI:[OCMArg any] initialRoute:[OCMArg any] entrypointArgs:[OCMArg any]]) .andReturn(OCMClassMock([FlutterEngine class])); FlutterEngine* spawner = [group makeEngineWithEntrypoint:@"firstEntrypoint" libraryURI:@"firstLibraryURI"]; XCTAssertNotNil(spawner); OCMVerify([spawner runWithEntrypoint:@"firstEntrypoint" libraryURI:@"firstLibraryURI" initialRoute:nil entrypointArgs:nil]); FlutterEngine* spawnee = [group makeEngineWithEntrypoint:@"secondEntrypoint" libraryURI:@"secondLibraryURI"]; XCTAssertNotNil(spawnee); OCMVerify([spawner spawnWithEntrypoint:@"secondEntrypoint" libraryURI:@"secondLibraryURI" initialRoute:nil entrypointArgs:nil]); } - (void)testCustomInitialRoute { FlutterEngineGroup* group = OCMPartialMock([[FlutterEngineGroup alloc] initWithName:@"foo" project:nil]); FlutterEngine* mockEngine = OCMClassMock([FlutterEngine class]); OCMStub([group makeEngine]).andReturn(mockEngine); OCMStub([mockEngine spawnWithEntrypoint:[OCMArg any] libraryURI:[OCMArg any] initialRoute:[OCMArg any] entrypointArgs:[OCMArg any]]) .andReturn(OCMClassMock([FlutterEngine class])); FlutterEngine* spawner = [group makeEngineWithEntrypoint:nil libraryURI:nil initialRoute:@"foo"]; XCTAssertNotNil(spawner); OCMVerify([spawner runWithEntrypoint:nil libraryURI:nil initialRoute:@"foo" entrypointArgs:nil]); FlutterEngine* spawnee = [group makeEngineWithEntrypoint:nil libraryURI:nil initialRoute:@"bar"]; XCTAssertNotNil(spawnee); OCMVerify([spawner spawnWithEntrypoint:nil libraryURI:nil initialRoute:@"bar" entrypointArgs:nil]); } - (void)testCustomEntrypointArgs { FlutterEngineGroup* group = OCMPartialMock([[FlutterEngineGroup alloc] initWithName:@"foo" project:nil]); FlutterEngine* mockEngine = OCMClassMock([FlutterEngine class]); OCMStub([group makeEngine]).andReturn(mockEngine); OCMStub([mockEngine spawnWithEntrypoint:[OCMArg any] libraryURI:[OCMArg any] initialRoute:[OCMArg any] entrypointArgs:[OCMArg any]]) .andReturn(OCMClassMock([FlutterEngine class])); FlutterEngineGroupOptions* firstOptions = [[FlutterEngineGroupOptions alloc] init]; NSArray* firstEntrypointArgs = @[ @"foo", @"first" ]; firstOptions.entrypointArgs = firstEntrypointArgs; FlutterEngine* spawner = [group makeEngineWithOptions:firstOptions]; XCTAssertNotNil(spawner); OCMVerify([spawner runWithEntrypoint:nil libraryURI:nil initialRoute:nil entrypointArgs:firstEntrypointArgs]); NSArray* secondEntrypointArgs = @[ @"bar", @"second" ]; FlutterEngineGroupOptions* secondOptions = [[FlutterEngineGroupOptions alloc] init]; secondOptions.entrypointArgs = secondEntrypointArgs; FlutterEngine* spawnee = [group makeEngineWithOptions:secondOptions]; XCTAssertNotNil(spawnee); OCMVerify([spawner spawnWithEntrypoint:nil libraryURI:nil initialRoute:nil entrypointArgs:secondEntrypointArgs]); } - (void)testReleasesProjectOnDealloc { __weak FlutterDartProject* weakProject; @autoreleasepool { FlutterDartProject* mockProject = OCMClassMock([FlutterDartProject class]); FlutterEngineGroup* group = [[FlutterEngineGroup alloc] initWithName:@"foo" project:mockProject]; XCTAssertNotNil(group); weakProject = mockProject; XCTAssertNotNil(weakProject); group = nil; mockProject = nil; } XCTAssertNil(weakProject); } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterEngineGroupTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterEngineGroupTest.mm", "repo_id": "engine", "token_count": 2821 }
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. #import <Metal/Metal.h> #import <OCMock/OCMock.h> #import <QuartzCore/QuartzCore.h> #import <XCTest/XCTest.h> #include "flutter/fml/logging.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h" @interface FlutterMetalLayerTest : XCTestCase @end @interface TestFlutterMetalLayerView : UIView @end @implementation TestFlutterMetalLayerView + (Class)layerClass { return [FlutterMetalLayer class]; } @end /// A fake compositor that simulates presenting layer surface by increasing /// and decreasing IOSurface use count. @interface TestCompositor : NSObject { FlutterMetalLayer* _layer; IOSurfaceRef _presentedSurface; } @end @implementation TestCompositor - (instancetype)initWithLayer:(FlutterMetalLayer*)layer { self = [super init]; if (self) { self->_layer = layer; } return self; } /// Increment use count of currently presented surface and decrement use count /// of previously presented surface. - (void)commitTransaction { IOSurfaceRef surface = (__bridge IOSurfaceRef)self->_layer.contents; if (self->_presentedSurface) { IOSurfaceDecrementUseCount(self->_presentedSurface); } IOSurfaceIncrementUseCount(surface); self->_presentedSurface = surface; } - (void)dealloc { if (self->_presentedSurface) { IOSurfaceDecrementUseCount(self->_presentedSurface); } } @end @implementation FlutterMetalLayerTest - (FlutterMetalLayer*)addMetalLayer { TestFlutterMetalLayerView* view = [[TestFlutterMetalLayerView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; FlutterMetalLayer* layer = (FlutterMetalLayer*)view.layer; layer.drawableSize = CGSizeMake(100, 100); return layer; } - (void)removeMetalLayer:(FlutterMetalLayer*)layer { } // For unknown reason sometimes CI fails to create IOSurface. Bail out // to prevent flakiness. #define BAIL_IF_NO_DRAWABLE(drawable) \ if (drawable == nil) { \ FML_LOG(ERROR) << "Could not allocate drawable"; \ return; \ } - (void)testFlip { FlutterMetalLayer* layer = [self addMetalLayer]; TestCompositor* compositor = [[TestCompositor alloc] initWithLayer:layer]; id<MTLTexture> t1, t2, t3; id<CAMetalDrawable> drawable = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(drawable); t1 = drawable.texture; [drawable present]; [compositor commitTransaction]; drawable = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(drawable); t2 = drawable.texture; [drawable present]; [compositor commitTransaction]; drawable = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(drawable); t3 = drawable.texture; [drawable present]; [compositor commitTransaction]; // If there was no frame drop, layer should return oldest presented // texture. drawable = [layer nextDrawable]; XCTAssertEqual(drawable.texture, t1); [drawable present]; [compositor commitTransaction]; drawable = [layer nextDrawable]; XCTAssertEqual(drawable.texture, t2); [drawable present]; [compositor commitTransaction]; drawable = [layer nextDrawable]; XCTAssertEqual(drawable.texture, t3); [drawable present]; [compositor commitTransaction]; drawable = [layer nextDrawable]; XCTAssertEqual(drawable.texture, t1); [drawable present]; [self removeMetalLayer:layer]; } - (void)testFlipWithDroppedFrame { FlutterMetalLayer* layer = [self addMetalLayer]; TestCompositor* compositor = [[TestCompositor alloc] initWithLayer:layer]; id<MTLTexture> t1, t2, t3; id<CAMetalDrawable> drawable = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(drawable); t1 = drawable.texture; [drawable present]; [compositor commitTransaction]; XCTAssertTrue(IOSurfaceIsInUse(t1.iosurface)); drawable = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(drawable); t2 = drawable.texture; [drawable present]; [compositor commitTransaction]; drawable = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(drawable); t3 = drawable.texture; [drawable present]; [compositor commitTransaction]; // Simulate compositor holding on to t3 for a while. IOSurfaceIncrementUseCount(t3.iosurface); // Here the drawable is presented, but immediately replaced by another drawable // (before the compositor has a chance to pick it up). This should result // in same drawable returned in next call to nextDrawable. drawable = [layer nextDrawable]; XCTAssertEqual(drawable.texture, t1); XCTAssertFalse(IOSurfaceIsInUse(drawable.texture.iosurface)); [drawable present]; drawable = [layer nextDrawable]; XCTAssertEqual(drawable.texture, t2); [drawable present]; [compositor commitTransaction]; // Next drawable should be t1, since it was never picked up by compositor. drawable = [layer nextDrawable]; XCTAssertEqual(drawable.texture, t1); IOSurfaceDecrementUseCount(t3.iosurface); [self removeMetalLayer:layer]; } - (void)testDroppedDrawableReturnsTextureToPool { FlutterMetalLayer* layer = [self addMetalLayer]; // FlutterMetalLayer will keep creating new textures until it has 3. @autoreleasepool { for (int i = 0; i < 3; ++i) { id<CAMetalDrawable> drawable = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(drawable); } } id<MTLTexture> texture; { @autoreleasepool { id<CAMetalDrawable> drawable = [layer nextDrawable]; XCTAssertNotNil(drawable); texture = (id<MTLTexture>)drawable.texture; // Dropping the drawable must return texture to pool, so // next drawable should return the same texture. } } { id<CAMetalDrawable> drawable = [layer nextDrawable]; XCTAssertEqual(texture, drawable.texture); } [self removeMetalLayer:layer]; } - (void)testLayerLimitsDrawableCount { FlutterMetalLayer* layer = [self addMetalLayer]; id<CAMetalDrawable> d1 = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(d1); id<CAMetalDrawable> d2 = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(d2); id<CAMetalDrawable> d3 = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(d3); XCTAssertNotNil(d3); // Layer should not return more than 3 drawables. id<CAMetalDrawable> d4 = [layer nextDrawable]; XCTAssertNil(d4); [d1 present]; // Still no drawable, until the front buffer returns to pool id<CAMetalDrawable> d5 = [layer nextDrawable]; XCTAssertNil(d5); [d2 present]; id<CAMetalDrawable> d6 = [layer nextDrawable]; XCTAssertNotNil(d6); [self removeMetalLayer:layer]; } - (void)testTimeout { FlutterMetalLayer* layer = [self addMetalLayer]; TestCompositor* compositor = [[TestCompositor alloc] initWithLayer:layer]; id<CAMetalDrawable> drawable = [layer nextDrawable]; BAIL_IF_NO_DRAWABLE(drawable); __block MTLCommandBufferHandler handler; id<MTLCommandBuffer> mockCommandBuffer = OCMProtocolMock(@protocol(MTLCommandBuffer)); OCMStub([mockCommandBuffer addCompletedHandler:OCMOCK_ANY]).andDo(^(NSInvocation* invocation) { MTLCommandBufferHandler handlerOnStack; [invocation getArgument:&handlerOnStack atIndex:2]; // Required to copy stack block to heap. handler = handlerOnStack; }); [(id<FlutterMetalDrawable>)drawable flutterPrepareForPresent:mockCommandBuffer]; [drawable present]; [compositor commitTransaction]; // Drawable will not be available until the command buffer completes. drawable = [layer nextDrawable]; XCTAssertNil(drawable); handler(mockCommandBuffer); drawable = [layer nextDrawable]; XCTAssertNotNil(drawable); [self removeMetalLayer:layer]; } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm", "repo_id": "engine", "token_count": 2731 }
366
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSEMANTICSSCROLLVIEW_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSEMANTICSSCROLLVIEW_H_ #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class SemanticsObject; /** * A UIScrollView to represent Flutter scrollable in iOS accessibility * services. * * This class is hidden from the user and can't be interacted with. It * sends all of selector calls from accessibility services to the * owner SemanticsObject. */ @interface FlutterSemanticsScrollView : UIScrollView @property(nonatomic, assign, nullable) SemanticsObject* semanticsObject; - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; - (instancetype)initWithCoder:(NSCoder*)coder NS_UNAVAILABLE; - (instancetype)initWithSemanticsObject:(SemanticsObject*)semanticsObject; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSEMANTICSSCROLLVIEW_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h", "repo_id": "engine", "token_count": 414 }
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_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERDELEGATE_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERDELEGATE_H_ #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSInteger, FlutterUndoRedoDirection) { // NOLINTBEGIN(readability-identifier-naming) FlutterUndoRedoDirectionUndo, FlutterUndoRedoDirectionRedo, // NOLINTEND(readability-identifier-naming) }; @class FlutterUndoManagerPlugin; @protocol FlutterUndoManagerDelegate <NSObject> - (void)flutterUndoManagerPlugin:(FlutterUndoManagerPlugin*)undoManagerPlugin handleUndoWithDirection:(FlutterUndoRedoDirection)direction; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERDELEGATE_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h", "repo_id": "engine", "token_count": 378 }
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. #import <OCMock/OCMock.h> #import <XCTest/XCTest.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTouchInterceptingView_Test.h" #import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" #import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h" FLUTTER_ASSERT_ARC @interface SemanticsObjectTest : XCTestCase @end @implementation SemanticsObjectTest - (void)testCreate { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); SemanticsObject* object = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; XCTAssertNotNil(object); } - (void)testSetChildren { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); SemanticsObject* parent = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; SemanticsObject* child = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; parent.children = @[ child ]; XCTAssertEqual(parent, child.parent); parent.children = @[]; XCTAssertNil(child.parent); } - (void)testAccessibilityHitTestFocusAtLeaf { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); SemanticsObject* object0 = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; SemanticsObject* object1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; SemanticsObject* object2 = [[SemanticsObject alloc] initWithBridge:bridge uid:2]; SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; object0.children = @[ object1 ]; object0.childrenInHitTestOrder = @[ object1 ]; object1.children = @[ object2, object3 ]; object1.childrenInHitTestOrder = @[ object2, object3 ]; flutter::SemanticsNode node0; node0.id = 0; node0.rect = SkRect::MakeXYWH(0, 0, 200, 200); node0.label = "0"; [object0 setSemanticsNode:&node0]; flutter::SemanticsNode node1; node1.id = 1; node1.rect = SkRect::MakeXYWH(0, 0, 200, 200); node1.label = "1"; [object1 setSemanticsNode:&node1]; flutter::SemanticsNode node2; node2.id = 2; node2.rect = SkRect::MakeXYWH(0, 0, 100, 100); node2.label = "2"; [object2 setSemanticsNode:&node2]; flutter::SemanticsNode node3; node3.id = 3; node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); node3.label = "3"; [object3 setSemanticsNode:&node3]; CGPoint point = CGPointMake(10, 10); id hitTestResult = [object0 _accessibilityHitTest:point withEvent:nil]; // Focus to object2 because it's the first object in hit test order XCTAssertEqual(hitTestResult, object2); } - (void)testAccessibilityHitTestNoFocusableItem { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); SemanticsObject* object0 = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; SemanticsObject* object1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; SemanticsObject* object2 = [[SemanticsObject alloc] initWithBridge:bridge uid:2]; SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; object0.children = @[ object1 ]; object0.childrenInHitTestOrder = @[ object1 ]; object1.children = @[ object2, object3 ]; object1.childrenInHitTestOrder = @[ object2, object3 ]; flutter::SemanticsNode node0; node0.id = 0; node0.rect = SkRect::MakeXYWH(0, 0, 200, 200); [object0 setSemanticsNode:&node0]; flutter::SemanticsNode node1; node1.id = 1; node1.rect = SkRect::MakeXYWH(0, 0, 200, 200); [object1 setSemanticsNode:&node1]; flutter::SemanticsNode node2; node2.id = 2; node2.rect = SkRect::MakeXYWH(0, 0, 100, 100); [object2 setSemanticsNode:&node2]; flutter::SemanticsNode node3; node3.id = 3; node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); [object3 setSemanticsNode:&node3]; CGPoint point = CGPointMake(10, 10); id hitTestResult = [object0 _accessibilityHitTest:point withEvent:nil]; XCTAssertNil(hitTestResult); } - (void)testAccessibilityScrollToVisible { fml::WeakPtrFactory<flutter::testing::MockAccessibilityBridge> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::testing::MockAccessibilityBridge> bridge = factory.GetWeakPtr(); SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; flutter::SemanticsNode node3; node3.id = 3; node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); [object3 setSemanticsNode:&node3]; [object3 accessibilityScrollToVisible]; XCTAssertTrue(bridge->observations.size() == 1); XCTAssertTrue(bridge->observations[0].id == 3); XCTAssertTrue(bridge->observations[0].action == flutter::SemanticsAction::kShowOnScreen); } - (void)testAccessibilityScrollToVisibleWithChild { fml::WeakPtrFactory<flutter::testing::MockAccessibilityBridge> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::testing::MockAccessibilityBridge> bridge = factory.GetWeakPtr(); SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; flutter::SemanticsNode node3; node3.id = 3; node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); [object3 setSemanticsNode:&node3]; [object3 accessibilityScrollToVisibleWithChild:object3]; XCTAssertTrue(bridge->observations.size() == 1); XCTAssertTrue(bridge->observations[0].id == 3); XCTAssertTrue(bridge->observations[0].action == flutter::SemanticsAction::kShowOnScreen); } - (void)testAccessibilityHitTestOutOfRect { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); SemanticsObject* object0 = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; SemanticsObject* object1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; SemanticsObject* object2 = [[SemanticsObject alloc] initWithBridge:bridge uid:2]; SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; object0.children = @[ object1 ]; object0.childrenInHitTestOrder = @[ object1 ]; object1.children = @[ object2, object3 ]; object1.childrenInHitTestOrder = @[ object2, object3 ]; flutter::SemanticsNode node0; node0.id = 0; node0.rect = SkRect::MakeXYWH(0, 0, 200, 200); node0.label = "0"; [object0 setSemanticsNode:&node0]; flutter::SemanticsNode node1; node1.id = 1; node1.rect = SkRect::MakeXYWH(0, 0, 200, 200); node1.label = "1"; [object1 setSemanticsNode:&node1]; flutter::SemanticsNode node2; node2.id = 2; node2.rect = SkRect::MakeXYWH(0, 0, 100, 100); node2.label = "2"; [object2 setSemanticsNode:&node2]; flutter::SemanticsNode node3; node3.id = 3; node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); node3.label = "3"; [object3 setSemanticsNode:&node3]; CGPoint point = CGPointMake(300, 300); id hitTestResult = [object0 _accessibilityHitTest:point withEvent:nil]; XCTAssertNil(hitTestResult); } - (void)testReplaceChildAtIndex { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); SemanticsObject* parent = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; SemanticsObject* child1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; SemanticsObject* child2 = [[SemanticsObject alloc] initWithBridge:bridge uid:2]; parent.children = @[ child1 ]; [parent replaceChildAtIndex:0 withChild:child2]; XCTAssertNil(child1.parent); XCTAssertEqual(parent, child2.parent); XCTAssertEqualObjects(parent.children, @[ child2 ]); } - (void)testPlainSemanticsObjectWithLabelHasStaticTextTrait { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.label = "foo"; FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [object setSemanticsNode:&node]; XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitStaticText); } - (void)testNodeWithImplicitScrollIsAnAccessibilityElementWhenItisHidden { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling) | static_cast<int32_t>(flutter::SemanticsFlags::kIsHidden); FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [object setSemanticsNode:&node]; XCTAssertEqual(object.isAccessibilityElement, YES); } - (void)testNodeWithImplicitScrollIsNotAnAccessibilityElementWhenItisNotHidden { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [object setSemanticsNode:&node]; XCTAssertEqual(object.isAccessibilityElement, NO); } - (void)testIntresetingSemanticsObjectWithLabelHasStaticTextTrait { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.label = "foo"; FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; SemanticsObject* child1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; object.children = @[ child1 ]; [object setSemanticsNode:&node]; XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitNone); } - (void)testIntresetingSemanticsObjectWithLabelHasStaticTextTrait1 { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.label = "foo"; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kIsTextField); FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [object setSemanticsNode:&node]; XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitNone); } - (void)testIntresetingSemanticsObjectWithLabelHasStaticTextTrait2 { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.label = "foo"; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kIsButton); FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [object setSemanticsNode:&node]; XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitButton); } - (void)testVerticalFlutterScrollableSemanticsObject { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); float transformScale = 0.5f; float screenScale = [[bridge->view() window] screen].scale; float effectivelyScale = transformScale / screenScale; float x = 10; float y = 10; float w = 100; float h = 200; float scrollExtentMax = 500.0; float scrollPosition = 150.0; flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kVerticalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(x, y, w, h); node.scrollExtentMax = scrollExtentMax; node.scrollPosition = scrollPosition; node.transform = { transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; UIScrollView* scrollView = [scrollable nativeAccessibility]; XCTAssertTrue( CGRectEqualToRect(scrollView.frame, CGRectMake(x * effectivelyScale, y * effectivelyScale, w * effectivelyScale, h * effectivelyScale))); XCTAssertTrue(CGSizeEqualToSize( scrollView.contentSize, CGSizeMake(w * effectivelyScale, (h + scrollExtentMax) * effectivelyScale))); XCTAssertTrue(CGPointEqualToPoint(scrollView.contentOffset, CGPointMake(0, scrollPosition * effectivelyScale))); } - (void)testVerticalFlutterScrollableSemanticsObjectNoWindowDoesNotCrash { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridgeNoWindow()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); float transformScale = 0.5f; float x = 10; float y = 10; float w = 100; float h = 200; float scrollExtentMax = 500.0; float scrollPosition = 150.0; flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kVerticalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(x, y, w, h); node.scrollExtentMax = scrollExtentMax; node.scrollPosition = scrollPosition; node.transform = { transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; XCTAssertNoThrow([scrollable accessibilityBridgeDidFinishUpdate]); } - (void)testHorizontalFlutterScrollableSemanticsObject { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); float transformScale = 0.5f; float screenScale = [[bridge->view() window] screen].scale; float effectivelyScale = transformScale / screenScale; float x = 10; float y = 10; float w = 100; float h = 200; float scrollExtentMax = 500.0; float scrollPosition = 150.0; flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kHorizontalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(x, y, w, h); node.scrollExtentMax = scrollExtentMax; node.scrollPosition = scrollPosition; node.transform = { transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; UIScrollView* scrollView = [scrollable nativeAccessibility]; XCTAssertTrue( CGRectEqualToRect(scrollView.frame, CGRectMake(x * effectivelyScale, y * effectivelyScale, w * effectivelyScale, h * effectivelyScale))); XCTAssertTrue(CGSizeEqualToSize( scrollView.contentSize, CGSizeMake((w + scrollExtentMax) * effectivelyScale, h * effectivelyScale))); XCTAssertTrue(CGPointEqualToPoint(scrollView.contentOffset, CGPointMake(scrollPosition * effectivelyScale, 0))); } - (void)testCanHandleInfiniteScrollExtent { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); float transformScale = 0.5f; float screenScale = [[bridge->view() window] screen].scale; float effectivelyScale = transformScale / screenScale; float x = 10; float y = 10; float w = 100; float h = 200; float scrollExtentMax = INFINITY; float scrollPosition = 150.0; flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kVerticalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(x, y, w, h); node.scrollExtentMax = scrollExtentMax; node.scrollPosition = scrollPosition; node.transform = { transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; UIScrollView* scrollView = [scrollable nativeAccessibility]; XCTAssertTrue( CGRectEqualToRect(scrollView.frame, CGRectMake(x * effectivelyScale, y * effectivelyScale, w * effectivelyScale, h * effectivelyScale))); XCTAssertTrue(CGSizeEqualToSize( scrollView.contentSize, CGSizeMake(w * effectivelyScale, (h + kScrollExtentMaxForInf + scrollPosition) * effectivelyScale))); XCTAssertTrue(CGPointEqualToPoint(scrollView.contentOffset, CGPointMake(0, scrollPosition * effectivelyScale))); } - (void)testCanHandleNaNScrollExtentAndScrollPoisition { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); float transformScale = 0.5f; float screenScale = [[bridge->view() window] screen].scale; float effectivelyScale = transformScale / screenScale; float x = 10; float y = 10; float w = 100; float h = 200; float scrollExtentMax = std::nan(""); float scrollPosition = std::nan(""); flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kVerticalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(x, y, w, h); node.scrollExtentMax = scrollExtentMax; node.scrollPosition = scrollPosition; node.transform = { transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; UIScrollView* scrollView = [scrollable nativeAccessibility]; XCTAssertTrue( CGRectEqualToRect(scrollView.frame, CGRectMake(x * effectivelyScale, y * effectivelyScale, w * effectivelyScale, h * effectivelyScale))); // Content size equal to the scrollable size. XCTAssertTrue(CGSizeEqualToSize(scrollView.contentSize, CGSizeMake(w * effectivelyScale, h * effectivelyScale))); XCTAssertTrue(CGPointEqualToPoint(scrollView.contentOffset, CGPointMake(0, 0))); } - (void)testFlutterScrollableSemanticsObjectIsNotHittestable { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kHorizontalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.scrollExtentMax = 100.0; node.scrollPosition = 0.0; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; UIScrollView* scrollView = [scrollable nativeAccessibility]; XCTAssertEqual([scrollView hitTest:CGPointMake(10, 10) withEvent:nil], nil); } - (void)testFlutterScrollableSemanticsObjectIsHiddenWhenVoiceOverIsRunning { flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); mock->isVoiceOverRunningValue = false; fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory(mock); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kHorizontalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.scrollExtentMax = 100.0; node.scrollPosition = 0.0; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; UIScrollView* scrollView = [scrollable nativeAccessibility]; XCTAssertTrue(scrollView.isAccessibilityElement); mock->isVoiceOverRunningValue = true; XCTAssertFalse(scrollView.isAccessibilityElement); } - (void)testFlutterSemanticsObjectHasIdentifier { flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); mock->isVoiceOverRunningValue = true; fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory(mock); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.identifier = "identifier"; FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [object setSemanticsNode:&node]; XCTAssertTrue([object.accessibilityIdentifier isEqualToString:@"identifier"]); } - (void)testFlutterScrollableSemanticsObjectWithLabelValueHintIsNotHiddenWhenVoiceOverIsRunning { flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); mock->isVoiceOverRunningValue = true; fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory(mock); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kHorizontalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.label = "label"; node.value = "value"; node.hint = "hint"; node.scrollExtentMax = 100.0; node.scrollPosition = 0.0; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; UIScrollView* scrollView = [scrollable nativeAccessibility]; XCTAssertTrue(scrollView.isAccessibilityElement); XCTAssertTrue( [scrollView.accessibilityLabel isEqualToString:NSLocalizedString(@"label", @"test")]); XCTAssertTrue( [scrollView.accessibilityValue isEqualToString:NSLocalizedString(@"value", @"test")]); XCTAssertTrue([scrollView.accessibilityHint isEqualToString:NSLocalizedString(@"hint", @"test")]); } - (void)testFlutterSemanticsObjectMergeTooltipToLabel { flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); mock->isVoiceOverRunningValue = true; fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory(mock); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.label = "label"; node.tooltip = "tooltip"; FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [object setSemanticsNode:&node]; XCTAssertTrue(object.isAccessibilityElement); XCTAssertTrue([object.accessibilityLabel isEqualToString:@"label\ntooltip"]); } - (void)testFlutterSemanticsObjectAttributedStringsDoNotCrashWhenEmpty { flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); mock->isVoiceOverRunningValue = true; fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory(mock); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [object setSemanticsNode:&node]; XCTAssertTrue(object.accessibilityAttributedLabel == nil); } - (void)testFlutterScrollableSemanticsObjectReturnsParentContainerIfNoChildren { flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); mock->isVoiceOverRunningValue = true; fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory(mock); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode parent; parent.id = 0; parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); parent.label = "label"; parent.value = "value"; parent.hint = "hint"; flutter::SemanticsNode node; node.id = 1; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kHorizontalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.label = "label"; node.value = "value"; node.hint = "hint"; node.scrollExtentMax = 100.0; node.scrollPosition = 0.0; parent.childrenInTraversalOrder.push_back(1); FlutterSemanticsObject* parentObject = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [parentObject setSemanticsNode:&parent]; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:1]; [scrollable setSemanticsNode:&node]; UIScrollView* scrollView = [scrollable nativeAccessibility]; parentObject.children = @[ scrollable ]; [parentObject accessibilityBridgeDidFinishUpdate]; [scrollable accessibilityBridgeDidFinishUpdate]; XCTAssertTrue(scrollView.isAccessibilityElement); SemanticsObjectContainer* container = static_cast<SemanticsObjectContainer*>(scrollable.accessibilityContainer); XCTAssertEqual(container.semanticsObject, parentObject); } - (void)testFlutterScrollableSemanticsObjectHidesScrollBar { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kHorizontalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.scrollExtentMax = 100.0; node.scrollPosition = 0.0; FlutterScrollableSemanticsObject* scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; UIScrollView* scrollView = [scrollable nativeAccessibility]; XCTAssertFalse(scrollView.showsHorizontalScrollIndicator); XCTAssertFalse(scrollView.showsVerticalScrollIndicator); } - (void)testSemanticsObjectBuildsAttributedString { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); flutter::SemanticsNode node; node.label = "label"; std::shared_ptr<flutter::SpellOutStringAttribute> attribute = std::make_shared<flutter::SpellOutStringAttribute>(); attribute->start = 1; attribute->end = 2; attribute->type = flutter::StringAttributeType::kSpellOut; node.labelAttributes.push_back(attribute); node.value = "value"; attribute = std::make_shared<flutter::SpellOutStringAttribute>(); attribute->start = 2; attribute->end = 3; attribute->type = flutter::StringAttributeType::kSpellOut; node.valueAttributes.push_back(attribute); node.hint = "hint"; std::shared_ptr<flutter::LocaleStringAttribute> local_attribute = std::make_shared<flutter::LocaleStringAttribute>(); local_attribute->start = 3; local_attribute->end = 4; local_attribute->type = flutter::StringAttributeType::kLocale; local_attribute->locale = "en-MX"; node.hintAttributes.push_back(local_attribute); FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [object setSemanticsNode:&node]; NSMutableAttributedString* expectedAttributedLabel = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"label", @"test")]; NSDictionary* attributeDict = @{ UIAccessibilitySpeechAttributeSpellOut : @YES, }; [expectedAttributedLabel setAttributes:attributeDict range:NSMakeRange(1, 1)]; XCTAssertTrue( [object.accessibilityAttributedLabel isEqualToAttributedString:expectedAttributedLabel]); NSMutableAttributedString* expectedAttributedValue = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"value", @"test")]; attributeDict = @{ UIAccessibilitySpeechAttributeSpellOut : @YES, }; [expectedAttributedValue setAttributes:attributeDict range:NSMakeRange(2, 1)]; XCTAssertTrue( [object.accessibilityAttributedValue isEqualToAttributedString:expectedAttributedValue]); NSMutableAttributedString* expectedAttributedHint = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"hint", @"test")]; attributeDict = @{ UIAccessibilitySpeechAttributeLanguage : @"en-MX", }; [expectedAttributedHint setAttributes:attributeDict range:NSMakeRange(3, 1)]; XCTAssertTrue( [object.accessibilityAttributedHint isEqualToAttributedString:expectedAttributedHint]); } - (void)testShouldTriggerAnnouncement { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); SemanticsObject* object = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; // Handle nil with no node set. XCTAssertFalse([object nodeShouldTriggerAnnouncement:nil]); // Handle initial setting of node with liveRegion flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kIsLiveRegion); node.label = "foo"; XCTAssertTrue([object nodeShouldTriggerAnnouncement:&node]); // Handle nil with node set. [object setSemanticsNode:&node]; XCTAssertFalse([object nodeShouldTriggerAnnouncement:nil]); // Handle new node, still has live region, same label. XCTAssertFalse([object nodeShouldTriggerAnnouncement:&node]); // Handle update node with new label, still has live region. flutter::SemanticsNode updatedNode; updatedNode.flags = static_cast<int32_t>(flutter::SemanticsFlags::kIsLiveRegion); updatedNode.label = "bar"; XCTAssertTrue([object nodeShouldTriggerAnnouncement:&updatedNode]); // Handle dropping the live region flag. updatedNode.flags = 0; XCTAssertFalse([object nodeShouldTriggerAnnouncement:&updatedNode]); // Handle adding the flag when the label has not changed. updatedNode.label = "foo"; [object setSemanticsNode:&updatedNode]; XCTAssertTrue([object nodeShouldTriggerAnnouncement:&node]); } - (void)testShouldDispatchShowOnScreenActionForHeader { fml::WeakPtrFactory<flutter::testing::MockAccessibilityBridge> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::testing::MockAccessibilityBridge> bridge = factory.GetWeakPtr(); SemanticsObject* object = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; // Handle initial setting of node with header. flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kIsHeader); node.label = "foo"; [object setSemanticsNode:&node]; // Simulate accessibility focus. [object accessibilityElementDidBecomeFocused]; XCTAssertTrue(bridge->observations.size() == 1); XCTAssertTrue(bridge->observations[0].id == 1); XCTAssertTrue(bridge->observations[0].action == flutter::SemanticsAction::kShowOnScreen); } - (void)testShouldDispatchShowOnScreenActionForHidden { fml::WeakPtrFactory<flutter::testing::MockAccessibilityBridge> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::testing::MockAccessibilityBridge> bridge = factory.GetWeakPtr(); SemanticsObject* object = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; // Handle initial setting of node with hidden. flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kIsHidden); node.label = "foo"; [object setSemanticsNode:&node]; // Simulate accessibility focus. [object accessibilityElementDidBecomeFocused]; XCTAssertTrue(bridge->observations.size() == 1); XCTAssertTrue(bridge->observations[0].id == 1); XCTAssertTrue(bridge->observations[0].action == flutter::SemanticsAction::kShowOnScreen); } - (void)testFlutterSwitchSemanticsObjectMatchesUISwitch { fml::WeakPtrFactory<flutter::testing::MockAccessibilityBridge> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::testing::MockAccessibilityBridge> bridge = factory.GetWeakPtr(); FlutterSwitchSemanticsObject* object = [[FlutterSwitchSemanticsObject alloc] initWithBridge:bridge uid:1]; // Handle initial setting of node with header. flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasToggledState) | static_cast<int32_t>(flutter::SemanticsFlags::kIsToggled) | static_cast<int32_t>(flutter::SemanticsFlags::kIsEnabled); node.label = "foo"; [object setSemanticsNode:&node]; // Create ab real UISwitch to compare the FlutterSwitchSemanticsObject with. UISwitch* nativeSwitch = [[UISwitch alloc] init]; nativeSwitch.on = YES; XCTAssertEqual(object.accessibilityTraits, nativeSwitch.accessibilityTraits); XCTAssertEqualObjects(object.accessibilityValue, nativeSwitch.accessibilityValue); // Set the toggled to false; flutter::SemanticsNode update; update.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasToggledState) | static_cast<int32_t>(flutter::SemanticsFlags::kIsEnabled); update.label = "foo"; [object setSemanticsNode:&update]; nativeSwitch.on = NO; XCTAssertEqual(object.accessibilityTraits, nativeSwitch.accessibilityTraits); XCTAssertEqualObjects(object.accessibilityValue, nativeSwitch.accessibilityValue); } - (void)testFlutterSemanticsObjectOfRadioButton { fml::WeakPtrFactory<flutter::testing::MockAccessibilityBridge> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::testing::MockAccessibilityBridge> bridge = factory.GetWeakPtr(); FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; // Handle initial setting of node with header. flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup) | static_cast<int32_t>(flutter::SemanticsFlags::kHasCheckedState) | static_cast<int32_t>(flutter::SemanticsFlags::kHasEnabledState) | static_cast<int32_t>(flutter::SemanticsFlags::kIsEnabled); node.label = "foo"; [object setSemanticsNode:&node]; XCTAssertTrue((object.accessibilityTraits & UIAccessibilityTraitButton) > 0); XCTAssertNil(object.accessibilityValue); } - (void)testFlutterSwitchSemanticsObjectMatchesUISwitchDisabled { fml::WeakPtrFactory<flutter::testing::MockAccessibilityBridge> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::testing::MockAccessibilityBridge> bridge = factory.GetWeakPtr(); FlutterSwitchSemanticsObject* object = [[FlutterSwitchSemanticsObject alloc] initWithBridge:bridge uid:1]; // Handle initial setting of node with header. flutter::SemanticsNode node; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasToggledState) | static_cast<int32_t>(flutter::SemanticsFlags::kIsToggled); node.label = "foo"; [object setSemanticsNode:&node]; // Create ab real UISwitch to compare the FlutterSwitchSemanticsObject with. UISwitch* nativeSwitch = [[UISwitch alloc] init]; nativeSwitch.on = YES; nativeSwitch.enabled = NO; XCTAssertEqual(object.accessibilityTraits, nativeSwitch.accessibilityTraits); XCTAssertEqualObjects(object.accessibilityValue, nativeSwitch.accessibilityValue); } - (void)testSemanticsObjectDeallocated { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); SemanticsObject* parent = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; SemanticsObject* child = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; parent.children = @[ child ]; // Validate SemanticsObject deallocation does not crash. // https://github.com/flutter/flutter/issues/66032 __weak SemanticsObject* weakObject = parent; parent = nil; XCTAssertNil(weakObject); } - (void)testFlutterSemanticsObjectReturnsNilContainerWhenBridgeIsNotAlive { FlutterSemanticsObject* parentObject; FlutterScrollableSemanticsObject* scrollable; FlutterSemanticsObject* object2; flutter::SemanticsNode parent; parent.id = 0; parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); parent.label = "label"; parent.value = "value"; parent.hint = "hint"; flutter::SemanticsNode node; node.id = 1; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kHorizontalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.label = "label"; node.value = "value"; node.hint = "hint"; node.scrollExtentMax = 100.0; node.scrollPosition = 0.0; parent.childrenInTraversalOrder.push_back(1); flutter::SemanticsNode node2; node2.id = 2; node2.rect = SkRect::MakeXYWH(0, 0, 100, 200); node2.label = "label"; node2.value = "value"; node2.hint = "hint"; node2.scrollExtentMax = 100.0; node2.scrollPosition = 0.0; parent.childrenInTraversalOrder.push_back(2); { flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); mock->isVoiceOverRunningValue = true; fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory(mock); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); parentObject = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; [parentObject setSemanticsNode:&parent]; scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:1]; [scrollable setSemanticsNode:&node]; [scrollable accessibilityBridgeDidFinishUpdate]; object2 = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:2]; [object2 setSemanticsNode:&node2]; parentObject.children = @[ scrollable, object2 ]; [parentObject accessibilityBridgeDidFinishUpdate]; [scrollable accessibilityBridgeDidFinishUpdate]; [object2 accessibilityBridgeDidFinishUpdate]; // Returns the correct container if the bridge is alive. SemanticsObjectContainer* container = static_cast<SemanticsObjectContainer*>(scrollable.accessibilityContainer); XCTAssertEqual(container.semanticsObject, parentObject); SemanticsObjectContainer* container2 = static_cast<SemanticsObjectContainer*>(object2.accessibilityContainer); XCTAssertEqual(container2.semanticsObject, parentObject); } // The bridge pointer went out of scope and was deallocated. XCTAssertNil(scrollable.accessibilityContainer); XCTAssertNil(object2.accessibilityContainer); } - (void)testAccessibilityHitTestSearchCanReturnPlatformView { fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr(); SemanticsObject* object0 = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; SemanticsObject* object1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; FlutterTouchInterceptingView* platformView = [[FlutterTouchInterceptingView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; FlutterPlatformViewSemanticsContainer* platformViewSemanticsContainer = [[FlutterPlatformViewSemanticsContainer alloc] initWithBridge:bridge uid:1 platformView:platformView]; object0.children = @[ object1 ]; object0.childrenInHitTestOrder = @[ object1 ]; object1.children = @[ platformViewSemanticsContainer, object3 ]; object1.childrenInHitTestOrder = @[ platformViewSemanticsContainer, object3 ]; flutter::SemanticsNode node0; node0.id = 0; node0.rect = SkRect::MakeXYWH(0, 0, 200, 200); node0.label = "0"; [object0 setSemanticsNode:&node0]; flutter::SemanticsNode node1; node1.id = 1; node1.rect = SkRect::MakeXYWH(0, 0, 200, 200); node1.label = "1"; [object1 setSemanticsNode:&node1]; flutter::SemanticsNode node2; node2.id = 2; node2.rect = SkRect::MakeXYWH(0, 0, 100, 100); node2.label = "2"; [platformViewSemanticsContainer setSemanticsNode:&node2]; flutter::SemanticsNode node3; node3.id = 3; node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); node3.label = "3"; [object3 setSemanticsNode:&node3]; CGPoint point = CGPointMake(10, 10); id hitTestResult = [object0 _accessibilityHitTest:point withEvent:nil]; XCTAssertEqual(hitTestResult, platformView); } - (void)testFlutterPlatformViewSemanticsContainer { fml::WeakPtrFactory<flutter::testing::MockAccessibilityBridge> factory( new flutter::testing::MockAccessibilityBridge()); fml::WeakPtr<flutter::testing::MockAccessibilityBridge> bridge = factory.GetWeakPtr(); __weak FlutterTouchInterceptingView* weakPlatformView; @autoreleasepool { FlutterTouchInterceptingView* platformView = [[FlutterTouchInterceptingView alloc] init]; weakPlatformView = platformView; FlutterPlatformViewSemanticsContainer* container = [[FlutterPlatformViewSemanticsContainer alloc] initWithBridge:bridge uid:1 platformView:platformView]; XCTAssertEqualObjects(platformView.accessibilityContainer, container); XCTAssertNotNil(weakPlatformView); } // Check if there's no more strong references to `platformView` after container and platformView // are released. XCTAssertNil(weakPlatformView); } @end
engine/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm", "repo_id": "engine", "token_count": 15108 }
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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_PLATFORM_MESSAGE_RESPONSE_DARWIN_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_PLATFORM_MESSAGE_RESPONSE_DARWIN_H_ #include <Foundation/Foundation.h> #include "flutter/fml/macros.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/platform/darwin/scoped_block.h" #include "flutter/fml/task_runner.h" #include "flutter/lib/ui/window/platform_message_response.h" #import "flutter/shell/platform/darwin/common/buffer_conversions.h" typedef void (^PlatformMessageResponseCallback)(NSData*); namespace flutter { class PlatformMessageResponseDarwin : public flutter::PlatformMessageResponse { public: void Complete(std::unique_ptr<fml::Mapping> data) override; void CompleteEmpty() override; private: explicit PlatformMessageResponseDarwin(PlatformMessageResponseCallback callback, fml::RefPtr<fml::TaskRunner> platform_task_runner); ~PlatformMessageResponseDarwin() override; fml::ScopedBlock<PlatformMessageResponseCallback> callback_; fml::RefPtr<fml::TaskRunner> platform_task_runner_; FML_FRIEND_MAKE_REF_COUNTED(PlatformMessageResponseDarwin); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_PLATFORM_MESSAGE_RESPONSE_DARWIN_H_
engine/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h", "repo_id": "engine", "token_count": 544 }
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/ios/ios_external_texture_metal.h" #include "flow/layers/layer.h" namespace flutter { IOSExternalTextureMetal::IOSExternalTextureMetal( const fml::scoped_nsobject<FlutterDarwinExternalTextureMetal>& darwin_external_texture_metal) : Texture([darwin_external_texture_metal textureID]), darwin_external_texture_metal_(darwin_external_texture_metal) {} IOSExternalTextureMetal::~IOSExternalTextureMetal() = default; void IOSExternalTextureMetal::Paint(PaintContext& context, const SkRect& bounds, bool freeze, const DlImageSampling sampling) { [darwin_external_texture_metal_ paintContext:context bounds:bounds freeze:freeze sampling:sampling]; } void IOSExternalTextureMetal::OnGrContextCreated() { [darwin_external_texture_metal_ onGrContextCreated]; } void IOSExternalTextureMetal::OnGrContextDestroyed() { [darwin_external_texture_metal_ onGrContextDestroyed]; } void IOSExternalTextureMetal::MarkNewFrameAvailable() { [darwin_external_texture_metal_ markNewFrameAvailable]; } void IOSExternalTextureMetal::OnTextureUnregistered() { [darwin_external_texture_metal_ onTextureUnregistered]; } } // namespace flutter
engine/shell/platform/darwin/ios/ios_external_texture_metal.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_external_texture_metal.mm", "repo_id": "engine", "token_count": 638 }
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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_RENDERING_API_SELECTION_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_RENDERING_API_SELECTION_H_ #include <objc/runtime.h> #include "flutter/fml/macros.h" namespace flutter { enum class IOSRenderingAPI { kSoftware, kMetal, }; enum class IOSRenderingBackend { kSkia, kImpeller, }; // Pass force_software to force software rendering. This is only respected on // simulators. IOSRenderingAPI GetRenderingAPIForProcess(bool force_software); Class GetCoreAnimationLayerClassForRenderingAPI(IOSRenderingAPI rendering_api); } // namespace flutter // Flutter supports Metal on all devices with Apple A7 SoC or above that have // been updated to or past iOS 10.0. The processor was selected as it is the // first version at which Metal was supported. The iOS version floor was // selected due to the availability of features used by Skia. // Support for Metal on simulators was added by Apple in the SDK for iOS 13. #if TARGET_OS_SIMULATOR #define METAL_IOS_VERSION_BASELINE 13.0 #else #define METAL_IOS_VERSION_BASELINE 10.0 #endif // TARGET_OS_SIMULATOR #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_RENDERING_API_SELECTION_H_
engine/shell/platform/darwin/ios/rendering_api_selection.h/0
{ "file_path": "engine/shell/platform/darwin/ios/rendering_api_selection.h", "repo_id": "engine", "token_count": 455 }
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/macos/framework/Headers/FlutterAppDelegate.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate_Internal.h" #import <AppKit/AppKit.h> #include "flutter/fml/logging.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate_Internal.h" #include "flutter/shell/platform/embedder/embedder.h" @interface FlutterAppDelegate () /** * Returns the display name of the application as set in the Info.plist. */ - (NSString*)applicationName; @property(nonatomic) FlutterAppLifecycleRegistrar* lifecycleRegistrar; @end @implementation FlutterAppDelegate - (instancetype)init { if (self = [super init]) { _terminationHandler = nil; _lifecycleRegistrar = [[FlutterAppLifecycleRegistrar alloc] init]; } return self; } - (void)applicationWillFinishLaunching:(NSNotification*)notification { // Update UI elements to match the application name. NSString* applicationName = [self applicationName]; _mainFlutterWindow.title = applicationName; for (NSMenuItem* menuItem in _applicationMenu.itemArray) { menuItem.title = [menuItem.title stringByReplacingOccurrencesOfString:@"APP_NAME" withString:applicationName]; } } #pragma mark - Delegate handling - (void)addApplicationLifecycleDelegate:(NSObject<FlutterAppLifecycleDelegate>*)delegate { [self.lifecycleRegistrar addDelegate:delegate]; } - (void)removeApplicationLifecycleDelegate:(NSObject<FlutterAppLifecycleDelegate>*)delegate { [self.lifecycleRegistrar removeDelegate:delegate]; } #pragma mark Private Methods - (NSString*)applicationName { NSString* applicationName = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; if (!applicationName) { applicationName = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleName"]; } return applicationName; } #pragma mark NSApplicationDelegate - (void)application:(NSApplication*)application openURLs:(NSArray<NSURL*>*)urls { for (NSObject<FlutterAppLifecycleDelegate>* delegate in self.lifecycleRegistrar.delegates) { if ([delegate respondsToSelector:@selector(handleOpenURLs:)] && [delegate handleOpenURLs:urls]) { return; } } } - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication* _Nonnull)sender { // If the framework has already told us to terminate, terminate immediately. if ([self terminationHandler] == nil || [[self terminationHandler] shouldTerminate]) { return NSTerminateNow; } // Send a termination request to the framework. FlutterEngineTerminationHandler* terminationHandler = [self terminationHandler]; [terminationHandler requestApplicationTermination:sender exitType:kFlutterAppExitTypeCancelable result:nil]; // Cancel termination to allow the framework to handle the request asynchronously. When the // termination request returns from the app, if termination is desired, this method will be // reinvoked with self.terminationHandler.shouldTerminate set to YES. return NSTerminateCancel; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate.mm", "repo_id": "engine", "token_count": 1188 }
373
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h" #include "flutter/fml/logging.h" #include <algorithm> #include <optional> #include <thread> #include <vector> // Note on thread safety and locking: // // There are three mutexes used within the scope of this file: // - CVDisplayLink internal mutex. This is locked during every CVDisplayLink method // and is also held while display link calls the output handler. // - DisplayLinkManager mutex. // - _FlutterDisplayLink mutex (through @synchronized blocks). // // Special care must be taken to avoid deadlocks. Because CVDisplayLink holds the // mutex for the entire duration of the output handler, it is necessary for // DisplayLinkManager to not call any CVDisplayLink methods while holding its // mutex. Instead it must retain the display link instance and then call the // appropriate method with the mutex unlocked. // // Similarly _FlutterDisplayLink must not call any DisplayLinkManager methods // within the @synchronized block. @class _FlutterDisplayLinkView; @interface _FlutterDisplayLink : FlutterDisplayLink { _FlutterDisplayLinkView* _view; std::optional<CGDirectDisplayID> _display_id; BOOL _paused; } - (void)didFireWithTimestamp:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp; @end namespace { class DisplayLinkManager { public: static DisplayLinkManager& Instance() { static DisplayLinkManager instance; return instance; } void UnregisterDisplayLink(_FlutterDisplayLink* display_link); void RegisterDisplayLink(_FlutterDisplayLink* display_link, CGDirectDisplayID display_id); void PausedDidChange(_FlutterDisplayLink* display_link); CFTimeInterval GetNominalOutputPeriod(CGDirectDisplayID display_id); private: void OnDisplayLink(CVDisplayLinkRef display_link, const CVTimeStamp* in_now, const CVTimeStamp* in_output_time, CVOptionFlags flags_in, CVOptionFlags* flags_out); struct ScreenEntry { CGDirectDisplayID display_id; std::vector<_FlutterDisplayLink*> clients; /// Display link for this screen. It is not safe to call display link methods /// on this object while holding the mutex. Instead the instance should be /// retained, mutex unlocked and then released. CVDisplayLinkRef display_link_locked; bool ShouldBeRunning() { return std::any_of(clients.begin(), clients.end(), [](FlutterDisplayLink* link) { return !link.paused; }); } }; std::vector<ScreenEntry> entries_; std::mutex mutex_; }; void RunOrStopDisplayLink(CVDisplayLinkRef display_link, bool should_be_running) { bool is_running = CVDisplayLinkIsRunning(display_link); if (should_be_running && !is_running) { if (CVDisplayLinkStart(display_link) == kCVReturnError) { // CVDisplayLinkStart will fail if it was called from the display link thread. // The problem is that it CVDisplayLinkStop doesn't clean the pthread_t value in the display // link itself. If the display link is started and stopped before before the UI thread is // started (*), pthread_self() of the UI thread may have same value as the one stored in // CVDisplayLink. Because this can happen at most once starting the display link from a // temporary thread is a reasonable workaround. // // (*) Display link is started before UI thread because FlutterVSyncWaiter will run display // link for one tick at the beginning to determine vsync phase. // // http://www.openradar.me/radar?id=5520107644125184 CVDisplayLinkRef retained = CVDisplayLinkRetain(display_link); [NSThread detachNewThreadWithBlock:^{ CVDisplayLinkStart(retained); CVDisplayLinkRelease(retained); }]; } } else if (!should_be_running && is_running) { CVDisplayLinkStop(display_link); } } void DisplayLinkManager::UnregisterDisplayLink(_FlutterDisplayLink* display_link) { std::unique_lock<std::mutex> lock(mutex_); for (auto entry = entries_.begin(); entry != entries_.end(); ++entry) { auto it = std::find(entry->clients.begin(), entry->clients.end(), display_link); if (it != entry->clients.end()) { entry->clients.erase(it); if (entry->clients.empty()) { // Erasing the entry - take the display link instance and stop / release it // outside of the mutex. CVDisplayLinkRef display_link = entry->display_link_locked; entries_.erase(entry); lock.unlock(); CVDisplayLinkStop(display_link); CVDisplayLinkRelease(display_link); } else { // Update the display link state outside of the mutex. bool should_be_running = entry->ShouldBeRunning(); CVDisplayLinkRef display_link = CVDisplayLinkRetain(entry->display_link_locked); lock.unlock(); RunOrStopDisplayLink(display_link, should_be_running); CVDisplayLinkRelease(display_link); } return; } } } void DisplayLinkManager::RegisterDisplayLink(_FlutterDisplayLink* display_link, CGDirectDisplayID display_id) { std::unique_lock<std::mutex> lock(mutex_); for (ScreenEntry& entry : entries_) { if (entry.display_id == display_id) { entry.clients.push_back(display_link); bool should_be_running = entry.ShouldBeRunning(); CVDisplayLinkRef display_link = CVDisplayLinkRetain(entry.display_link_locked); lock.unlock(); RunOrStopDisplayLink(display_link, should_be_running); CVDisplayLinkRelease(display_link); return; } } ScreenEntry entry; entry.display_id = display_id; entry.clients.push_back(display_link); CVDisplayLinkCreateWithCGDisplay(display_id, &entry.display_link_locked); CVDisplayLinkSetOutputHandler( entry.display_link_locked, ^(CVDisplayLinkRef display_link, const CVTimeStamp* in_now, const CVTimeStamp* in_output_time, CVOptionFlags flags_in, CVOptionFlags* flags_out) { OnDisplayLink(display_link, in_now, in_output_time, flags_in, flags_out); return 0; }); // This is a new display link so it is safe to start it with mutex held. bool should_be_running = entry.ShouldBeRunning(); RunOrStopDisplayLink(entry.display_link_locked, should_be_running); entries_.push_back(entry); } void DisplayLinkManager::PausedDidChange(_FlutterDisplayLink* display_link) { std::unique_lock<std::mutex> lock(mutex_); for (ScreenEntry& entry : entries_) { auto it = std::find(entry.clients.begin(), entry.clients.end(), display_link); if (it != entry.clients.end()) { bool running = entry.ShouldBeRunning(); CVDisplayLinkRef display_link = CVDisplayLinkRetain(entry.display_link_locked); lock.unlock(); RunOrStopDisplayLink(display_link, running); CVDisplayLinkRelease(display_link); return; } } } CFTimeInterval DisplayLinkManager::GetNominalOutputPeriod(CGDirectDisplayID display_id) { std::unique_lock<std::mutex> lock(mutex_); for (ScreenEntry& entry : entries_) { if (entry.display_id == display_id) { CVDisplayLinkRef display_link = CVDisplayLinkRetain(entry.display_link_locked); lock.unlock(); CVTime latency = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(display_link); CVDisplayLinkRelease(display_link); return (CFTimeInterval)latency.timeValue / (CFTimeInterval)latency.timeScale; } } return 0; } void DisplayLinkManager::OnDisplayLink(CVDisplayLinkRef display_link, const CVTimeStamp* in_now, const CVTimeStamp* in_output_time, CVOptionFlags flags_in, CVOptionFlags* flags_out) { // Hold the mutex only while copying clients. std::vector<_FlutterDisplayLink*> clients; { std::lock_guard<std::mutex> lock(mutex_); for (ScreenEntry& entry : entries_) { if (entry.display_link_locked == display_link) { clients = entry.clients; break; } } } CFTimeInterval timestamp = (CFTimeInterval)in_now->hostTime / CVGetHostClockFrequency(); CFTimeInterval target_timestamp = (CFTimeInterval)in_output_time->hostTime / CVGetHostClockFrequency(); for (_FlutterDisplayLink* client : clients) { [client didFireWithTimestamp:timestamp targetTimestamp:target_timestamp]; } } } // namespace @interface _FlutterDisplayLinkView : NSView { } @end static NSString* const kFlutterDisplayLinkViewDidMoveToWindow = @"FlutterDisplayLinkViewDidMoveToWindow"; @implementation _FlutterDisplayLinkView - (void)viewDidMoveToWindow { [super viewDidMoveToWindow]; [[NSNotificationCenter defaultCenter] postNotificationName:kFlutterDisplayLinkViewDidMoveToWindow object:self]; } @end @implementation _FlutterDisplayLink @synthesize delegate = _delegate; - (instancetype)initWithView:(NSView*)view { FML_DCHECK([NSThread isMainThread]); if (self = [super init]) { self->_view = [[_FlutterDisplayLinkView alloc] initWithFrame:CGRectZero]; [view addSubview:self->_view]; _paused = YES; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidChangeWindow:) name:kFlutterDisplayLinkViewDidMoveToWindow object:self->_view]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidChangeScreen:) name:NSWindowDidChangeScreenNotification object:nil]; [self updateScreen]; } return self; } - (void)invalidate { @synchronized(self) { FML_DCHECK([NSThread isMainThread]); // Unregister observer before removing the view to ensure // that the viewDidChangeWindow notification is not received // while in @synchronized block. [[NSNotificationCenter defaultCenter] removeObserver:self]; [_view removeFromSuperview]; _view = nil; _delegate = nil; } DisplayLinkManager::Instance().UnregisterDisplayLink(self); } - (void)updateScreen { DisplayLinkManager::Instance().UnregisterDisplayLink(self); std::optional<CGDirectDisplayID> displayId; @synchronized(self) { NSScreen* screen = _view.window.screen; if (screen != nil) { // https://developer.apple.com/documentation/appkit/nsscreen/1388360-devicedescription?language=objc _display_id = (CGDirectDisplayID)[ [[screen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; } else { _display_id = std::nullopt; } displayId = _display_id; } if (displayId.has_value()) { DisplayLinkManager::Instance().RegisterDisplayLink(self, *displayId); } } - (void)viewDidChangeWindow:(NSNotification*)notification { NSView* view = notification.object; if (_view == view) { [self updateScreen]; } } - (void)windowDidChangeScreen:(NSNotification*)notification { NSWindow* window = notification.object; if (_view.window == window) { [self updateScreen]; } } - (void)didFireWithTimestamp:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp { @synchronized(self) { if (!_paused) { id<FlutterDisplayLinkDelegate> delegate = _delegate; [delegate onDisplayLink:timestamp targetTimestamp:targetTimestamp]; } } } - (BOOL)paused { @synchronized(self) { return _paused; } } - (void)setPaused:(BOOL)paused { @synchronized(self) { if (_paused == paused) { return; } _paused = paused; } DisplayLinkManager::Instance().PausedDidChange(self); } - (CFTimeInterval)nominalOutputRefreshPeriod { CGDirectDisplayID display_id; @synchronized(self) { if (_display_id.has_value()) { display_id = *_display_id; } else { return 0; } } return DisplayLinkManager::Instance().GetNominalOutputPeriod(display_id); } @end @implementation FlutterDisplayLink + (instancetype)displayLinkWithView:(NSView*)view { return [[_FlutterDisplayLink alloc] initWithView:view]; } - (void)invalidate { [self doesNotRecognizeSelector:_cmd]; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.mm", "repo_id": "engine", "token_count": 4687 }
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. #include <Carbon/Carbon.h> #import <Foundation/Foundation.h> #import <OCMock/OCMock.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/FlutterKeyboardManager.h" #include "flutter/shell/platform/embedder/test_utils/key_codes.g.h" #import "flutter/testing/testing.h" #include "third_party/googletest/googletest/include/gtest/gtest.h" namespace { using flutter::testing::keycodes::kLogicalBracketLeft; using flutter::testing::keycodes::kLogicalDigit1; using flutter::testing::keycodes::kLogicalDigit2; using flutter::testing::keycodes::kLogicalKeyA; using flutter::testing::keycodes::kLogicalKeyM; using flutter::testing::keycodes::kLogicalKeyQ; using flutter::testing::keycodes::kLogicalKeyT; using flutter::testing::keycodes::kPhysicalKeyA; using flutter::LayoutClue; typedef BOOL (^BoolGetter)(); typedef void (^AsyncKeyCallbackHandler)(FlutterAsyncKeyCallback callback); typedef void (^AsyncEmbedderCallbackHandler)(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback); typedef BOOL (^TextInputCallback)(NSEvent*); // When the Vietnamese IME converts messages into "pure text" messages, their // key codes are set to "empty". // // The 0 also happens to be the key code for key A. constexpr uint16_t kKeyCodeEmpty = 0x00; // Constants used for `recordCallTypesTo:forTypes:`. constexpr uint32_t kEmbedderCall = 0x1; constexpr uint32_t kChannelCall = 0x2; constexpr uint32_t kTextCall = 0x4; // All key clues for a keyboard layout. // // The index is (keyCode * 2 + hasShift). The value is 0xMNNNN, where: // // - M is whether the key is a dead key (0x1 for true, 0x0 for false). // - N is the character for this key. (It only supports UTF-16, but we don't // need full UTF-32 support for unit tests. Moreover, Carbon's UCKeyTranslate // only returns UniChar (UInt16) anyway.) typedef const std::array<uint32_t, 256> MockLayoutData; // The following layout data is generated using DEBUG_PRINT_LAYOUT. MockLayoutData kUsLayout = { // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift /* 0x00 */ 0x00061, 0x00041, 0x00073, 0x00053, 0x00064, 0x00044, 0x00066, 0x00046, /* 0x04 */ 0x00068, 0x00048, 0x00067, 0x00047, 0x0007a, 0x0005a, 0x00078, 0x00058, /* 0x08 */ 0x00063, 0x00043, 0x00076, 0x00056, 0x000a7, 0x000b1, 0x00062, 0x00042, /* 0x0c */ 0x00071, 0x00051, 0x00077, 0x00057, 0x00065, 0x00045, 0x00072, 0x00052, /* 0x10 */ 0x00079, 0x00059, 0x00074, 0x00054, 0x00031, 0x00021, 0x00032, 0x00040, /* 0x14 */ 0x00033, 0x00023, 0x00034, 0x00024, 0x00036, 0x0005e, 0x00035, 0x00025, /* 0x18 */ 0x0003d, 0x0002b, 0x00039, 0x00028, 0x00037, 0x00026, 0x0002d, 0x0005f, /* 0x1c */ 0x00038, 0x0002a, 0x00030, 0x00029, 0x0005d, 0x0007d, 0x0006f, 0x0004f, /* 0x20 */ 0x00075, 0x00055, 0x0005b, 0x0007b, 0x00069, 0x00049, 0x00070, 0x00050, /* 0x24 */ 0x00000, 0x00000, 0x0006c, 0x0004c, 0x0006a, 0x0004a, 0x00027, 0x00022, /* 0x28 */ 0x0006b, 0x0004b, 0x0003b, 0x0003a, 0x0005c, 0x0007c, 0x0002c, 0x0003c, /* 0x2c */ 0x0002f, 0x0003f, 0x0006e, 0x0004e, 0x0006d, 0x0004d, 0x0002e, 0x0003e, /* 0x30 */ 0x00000, 0x00000, 0x00020, 0x00020, 0x00060, 0x0007e, }; MockLayoutData kFrenchLayout = { // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift /* 0x00 */ 0x00071, 0x00051, 0x00073, 0x00053, 0x00064, 0x00044, 0x00066, 0x00046, /* 0x04 */ 0x00068, 0x00048, 0x00067, 0x00047, 0x00077, 0x00057, 0x00078, 0x00058, /* 0x08 */ 0x00063, 0x00043, 0x00076, 0x00056, 0x00040, 0x00023, 0x00062, 0x00042, /* 0x0c */ 0x00061, 0x00041, 0x0007a, 0x0005a, 0x00065, 0x00045, 0x00072, 0x00052, /* 0x10 */ 0x00079, 0x00059, 0x00074, 0x00054, 0x00026, 0x00031, 0x000e9, 0x00032, /* 0x14 */ 0x00022, 0x00033, 0x00027, 0x00034, 0x000a7, 0x00036, 0x00028, 0x00035, /* 0x18 */ 0x0002d, 0x0005f, 0x000e7, 0x00039, 0x000e8, 0x00037, 0x00029, 0x000b0, /* 0x1c */ 0x00021, 0x00038, 0x000e0, 0x00030, 0x00024, 0x0002a, 0x0006f, 0x0004f, /* 0x20 */ 0x00075, 0x00055, 0x1005e, 0x100a8, 0x00069, 0x00049, 0x00070, 0x00050, /* 0x24 */ 0x00000, 0x00000, 0x0006c, 0x0004c, 0x0006a, 0x0004a, 0x000f9, 0x00025, /* 0x28 */ 0x0006b, 0x0004b, 0x0006d, 0x0004d, 0x10060, 0x000a3, 0x0003b, 0x0002e, /* 0x2c */ 0x0003d, 0x0002b, 0x0006e, 0x0004e, 0x0002c, 0x0003f, 0x0003a, 0x0002f, /* 0x30 */ 0x00000, 0x00000, 0x00020, 0x00020, 0x0003c, 0x0003e, }; MockLayoutData kRussianLayout = { // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift /* 0x00 */ 0x00444, 0x00424, 0x0044b, 0x0042b, 0x00432, 0x00412, 0x00430, 0x00410, /* 0x04 */ 0x00440, 0x00420, 0x0043f, 0x0041f, 0x0044f, 0x0042f, 0x00447, 0x00427, /* 0x08 */ 0x00441, 0x00421, 0x0043c, 0x0041c, 0x0003e, 0x0003c, 0x00438, 0x00418, /* 0x0c */ 0x00439, 0x00419, 0x00446, 0x00426, 0x00443, 0x00423, 0x0043a, 0x0041a, /* 0x10 */ 0x0043d, 0x0041d, 0x00435, 0x00415, 0x00031, 0x00021, 0x00032, 0x00022, /* 0x14 */ 0x00033, 0x02116, 0x00034, 0x00025, 0x00036, 0x0002c, 0x00035, 0x0003a, /* 0x18 */ 0x0003d, 0x0002b, 0x00039, 0x00028, 0x00037, 0x0002e, 0x0002d, 0x0005f, /* 0x1c */ 0x00038, 0x0003b, 0x00030, 0x00029, 0x0044a, 0x0042a, 0x00449, 0x00429, /* 0x20 */ 0x00433, 0x00413, 0x00445, 0x00425, 0x00448, 0x00428, 0x00437, 0x00417, /* 0x24 */ 0x00000, 0x00000, 0x00434, 0x00414, 0x0043e, 0x0041e, 0x0044d, 0x0042d, /* 0x28 */ 0x0043b, 0x0041b, 0x00436, 0x00416, 0x00451, 0x00401, 0x00431, 0x00411, /* 0x2c */ 0x0002f, 0x0003f, 0x00442, 0x00422, 0x0044c, 0x0042c, 0x0044e, 0x0042e, /* 0x30 */ 0x00000, 0x00000, 0x00020, 0x00020, 0x0005d, 0x0005b, }; MockLayoutData kKhmerLayout = { // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift /* 0x00 */ 0x017b6, 0x017ab, 0x0179f, 0x017c3, 0x0178a, 0x0178c, 0x01790, 0x01792, /* 0x04 */ 0x017a0, 0x017c7, 0x01784, 0x017a2, 0x0178b, 0x0178d, 0x01781, 0x01783, /* 0x08 */ 0x01785, 0x01787, 0x0179c, 0x017c8, 0x00000, 0x00000, 0x01794, 0x01796, /* 0x0c */ 0x01786, 0x01788, 0x017b9, 0x017ba, 0x017c1, 0x017c2, 0x0179a, 0x017ac, /* 0x10 */ 0x01799, 0x017bd, 0x0178f, 0x01791, 0x017e1, 0x00021, 0x017e2, 0x017d7, /* 0x14 */ 0x017e3, 0x00022, 0x017e4, 0x017db, 0x017e6, 0x017cd, 0x017e5, 0x00025, /* 0x18 */ 0x017b2, 0x017ce, 0x017e9, 0x017b0, 0x017e7, 0x017d0, 0x017a5, 0x017cc, /* 0x1c */ 0x017e8, 0x017cf, 0x017e0, 0x017b3, 0x017aa, 0x017a7, 0x017c4, 0x017c5, /* 0x20 */ 0x017bb, 0x017bc, 0x017c0, 0x017bf, 0x017b7, 0x017b8, 0x01795, 0x01797, /* 0x24 */ 0x00000, 0x00000, 0x0179b, 0x017a1, 0x017d2, 0x01789, 0x017cb, 0x017c9, /* 0x28 */ 0x01780, 0x01782, 0x017be, 0x017d6, 0x017ad, 0x017ae, 0x017a6, 0x017b1, /* 0x2c */ 0x017ca, 0x017af, 0x01793, 0x0178e, 0x01798, 0x017c6, 0x017d4, 0x017d5, /* 0x30 */ 0x00000, 0x00000, 0x00020, 0x0200b, 0x000ab, 0x000bb, }; NSEvent* keyDownEvent(unsigned short keyCode, NSString* chars = @"", NSString* charsUnmod = @"") { return [NSEvent keyEventWithType:NSEventTypeKeyDown location:NSZeroPoint modifierFlags:0x100 timestamp:0 windowNumber:0 context:nil characters:chars charactersIgnoringModifiers:charsUnmod isARepeat:NO keyCode:keyCode]; } NSEvent* keyUpEvent(unsigned short keyCode) { return [NSEvent keyEventWithType:NSEventTypeKeyUp location:NSZeroPoint modifierFlags:0x100 timestamp:0 windowNumber:0 context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:keyCode]; } id checkKeyDownEvent(unsigned short keyCode) { return [OCMArg checkWithBlock:^BOOL(id value) { if (![value isKindOfClass:[NSEvent class]]) { return NO; } NSEvent* event = value; return event.keyCode == keyCode; }]; } // Clear a list of `FlutterKeyEvent` whose `character` is dynamically allocated. void clearEvents(std::vector<FlutterKeyEvent>& events) { for (FlutterKeyEvent& event : events) { if (event.character != nullptr) { delete[] event.character; } } events.clear(); } #define VERIFY_DOWN(OUT_LOGICAL, OUT_CHAR) \ EXPECT_EQ(events[0].type, kFlutterKeyEventTypeDown); \ EXPECT_EQ(events[0].logical, static_cast<uint64_t>(OUT_LOGICAL)); \ EXPECT_STREQ(events[0].character, (OUT_CHAR)); \ clearEvents(events); } // namespace @interface KeyboardTester : NSObject - (nonnull instancetype)init; // Set embedder calls to respond immediately with the given response. - (void)respondEmbedderCallsWith:(BOOL)response; // Record embedder calls to the given storage. // // They are not responded to until the stored callbacks are manually called. - (void)recordEmbedderCallsTo:(nonnull NSMutableArray<FlutterAsyncKeyCallback>*)storage; - (void)recordEmbedderEventsTo:(nonnull std::vector<FlutterKeyEvent>*)storage returning:(bool)handled; // Set channel calls to respond immediately with the given response. - (void)respondChannelCallsWith:(BOOL)response; // Record channel calls to the given storage. // // They are not responded to until the stored callbacks are manually called. - (void)recordChannelCallsTo:(nonnull NSMutableArray<FlutterAsyncKeyCallback>*)storage; // Set text calls to respond with the given response. - (void)respondTextInputWith:(BOOL)response; // At the start of any kind of call, record the call type to the given storage. // // Only calls that are included in `typeMask` will be added. Options are // kEmbedderCall, kChannelCall, and kTextCall. // // This method does not conflict with other call settings, and the recording // takes place before the callbacks are (or are not) invoked. - (void)recordCallTypesTo:(nonnull NSMutableArray<NSNumber*>*)typeStorage forTypes:(uint32_t)typeMask; - (id)lastKeyboardChannelResult; - (void)sendKeyboardChannelMessage:(NSData* _Nullable)message; @property(readonly, nonatomic, strong) FlutterKeyboardManager* manager; @property(nonatomic, nullable, strong) NSResponder* nextResponder; #pragma mark - Private - (void)handleEmbedderEvent:(const FlutterKeyEvent&)event callback:(nullable FlutterKeyEventCallback)callback userData:(nullable void*)userData; - (void)handleChannelMessage:(NSString*)channel message:(NSData* _Nullable)message binaryReply:(FlutterBinaryReply _Nullable)callback; - (BOOL)handleTextInputKeyEvent:(NSEvent*)event; @end @implementation KeyboardTester { AsyncEmbedderCallbackHandler _embedderHandler; AsyncKeyCallbackHandler _channelHandler; TextInputCallback _textCallback; NSMutableArray<NSNumber*>* _typeStorage; uint32_t _typeStorageMask; flutter::KeyboardLayoutNotifier _keyboardLayoutNotifier; const MockLayoutData* _currentLayout; id _keyboardChannelResult; NSObject<FlutterBinaryMessenger>* _messengerMock; FlutterBinaryMessageHandler _keyboardHandler; } - (nonnull instancetype)init { self = [super init]; if (self == nil) { return nil; } _nextResponder = OCMClassMock([NSResponder class]); [self respondChannelCallsWith:FALSE]; [self respondEmbedderCallsWith:FALSE]; [self respondTextInputWith:FALSE]; _currentLayout = &kUsLayout; _messengerMock = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub([_messengerMock sendOnChannel:@"flutter/keyevent" message:[OCMArg any] binaryReply:[OCMArg any]]) .andCall(self, @selector(handleChannelMessage:message:binaryReply:)); OCMStub([_messengerMock setMessageHandlerOnChannel:@"flutter/keyboard" binaryMessageHandler:[OCMArg any]]) .andCall(self, @selector(setKeyboardChannelHandler:handler:)); OCMStub([_messengerMock sendOnChannel:@"flutter/keyboard" message:[OCMArg any]]) .andCall(self, @selector(handleKeyboardChannelMessage:message:)); id viewDelegateMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardViewDelegate)); OCMStub([viewDelegateMock nextResponder]).andReturn(_nextResponder); OCMStub([viewDelegateMock onTextInputKeyEvent:[OCMArg any]]) .andCall(self, @selector(handleTextInputKeyEvent:)); OCMStub([viewDelegateMock getBinaryMessenger]).andReturn(_messengerMock); OCMStub([viewDelegateMock sendKeyEvent:*(const FlutterKeyEvent*)[OCMArg anyPointer] callback:nil userData:nil]) .ignoringNonObjectArgs() .andCall(self, @selector(handleEmbedderEvent:callback:userData:)); OCMStub([viewDelegateMock subscribeToKeyboardLayoutChange:[OCMArg any]]) .andCall(self, @selector(onSetKeyboardLayoutNotifier:)); OCMStub([viewDelegateMock lookUpLayoutForKeyCode:0 shift:false]) .ignoringNonObjectArgs() .andCall(self, @selector(lookUpLayoutForKeyCode:shift:)); _manager = [[FlutterKeyboardManager alloc] initWithViewDelegate:viewDelegateMock]; return self; } - (id)lastKeyboardChannelResult { return _keyboardChannelResult; } - (void)respondEmbedderCallsWith:(BOOL)response { _embedderHandler = ^(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback) { callback(response); }; } - (void)recordEmbedderCallsTo:(nonnull NSMutableArray<FlutterAsyncKeyCallback>*)storage { _embedderHandler = ^(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback) { [storage addObject:callback]; }; } - (void)recordEmbedderEventsTo:(nonnull std::vector<FlutterKeyEvent>*)storage returning:(bool)handled { _embedderHandler = ^(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback) { FlutterKeyEvent newEvent = *event; if (event->character != nullptr) { size_t charLen = strlen(event->character); char* newCharacter = new char[charLen + 1]; strlcpy(newCharacter, event->character, charLen + 1); newEvent.character = newCharacter; } storage->push_back(newEvent); callback(handled); }; } - (void)respondChannelCallsWith:(BOOL)response { _channelHandler = ^(FlutterAsyncKeyCallback callback) { callback(response); }; } - (void)recordChannelCallsTo:(nonnull NSMutableArray<FlutterAsyncKeyCallback>*)storage { _channelHandler = ^(FlutterAsyncKeyCallback callback) { [storage addObject:callback]; }; } - (void)respondTextInputWith:(BOOL)response { _textCallback = ^(NSEvent* event) { return response; }; } - (void)recordCallTypesTo:(nonnull NSMutableArray<NSNumber*>*)typeStorage forTypes:(uint32_t)typeMask { _typeStorage = typeStorage; _typeStorageMask = typeMask; } - (void)sendKeyboardChannelMessage:(NSData* _Nullable)message { [_messengerMock sendOnChannel:@"flutter/keyboard" message:message]; } - (void)setLayout:(const MockLayoutData&)layout { _currentLayout = &layout; if (_keyboardLayoutNotifier != nil) { _keyboardLayoutNotifier(); } } #pragma mark - Private - (void)handleEmbedderEvent:(const FlutterKeyEvent&)event callback:(nullable FlutterKeyEventCallback)callback userData:(nullable void*)userData { if (_typeStorage != nil && (_typeStorageMask & kEmbedderCall) != 0) { [_typeStorage addObject:@(kEmbedderCall)]; } if (callback != nullptr) { _embedderHandler(&event, ^(BOOL handled) { callback(handled, userData); }); } } - (void)handleChannelMessage:(NSString*)channel message:(NSData* _Nullable)message binaryReply:(FlutterBinaryReply _Nullable)callback { if (_typeStorage != nil && (_typeStorageMask & kChannelCall) != 0) { [_typeStorage addObject:@(kChannelCall)]; } _channelHandler(^(BOOL handled) { NSDictionary* result = @{ @"handled" : @(handled), }; NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:result]; callback(encodedKeyEvent); }); } - (void)handleKeyboardChannelMessage:(NSString*)channel message:(NSData* _Nullable)message { _keyboardHandler(message, ^(id result) { _keyboardChannelResult = result; }); } - (BOOL)handleTextInputKeyEvent:(NSEvent*)event { if (_typeStorage != nil && (_typeStorageMask & kTextCall) != 0) { [_typeStorage addObject:@(kTextCall)]; } return _textCallback(event); } - (void)onSetKeyboardLayoutNotifier:(nullable flutter::KeyboardLayoutNotifier)callback { _keyboardLayoutNotifier = callback; } - (LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift { uint32_t cluePair = (*_currentLayout)[(keyCode * 2) + (shift ? 1 : 0)]; const uint32_t kCharMask = 0xffff; const uint32_t kDeadKeyMask = 0x10000; return LayoutClue{cluePair & kCharMask, (cluePair & kDeadKeyMask) != 0}; } - (void)setKeyboardChannelHandler:(NSString*)channel handler:(FlutterBinaryMessageHandler)handler { _keyboardHandler = handler; } @end @interface FlutterKeyboardManagerUnittestsObjC : NSObject - (bool)singlePrimaryResponder; - (bool)doublePrimaryResponder; - (bool)textInputPlugin; - (bool)emptyNextResponder; - (bool)getPressedState; - (bool)keyboardChannelGetPressedState; - (bool)racingConditionBetweenKeyAndText; - (bool)correctLogicalKeyForLayouts; - (bool)shouldNotHoldStrongReferenceToViewDelegate; @end namespace flutter::testing { TEST(FlutterKeyboardManagerUnittests, SinglePrimaryResponder) { ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] singlePrimaryResponder]); } TEST(FlutterKeyboardManagerUnittests, DoublePrimaryResponder) { ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] doublePrimaryResponder]); } TEST(FlutterKeyboardManagerUnittests, SingleFinalResponder) { ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] textInputPlugin]); } TEST(FlutterKeyboardManagerUnittests, EmptyNextResponder) { ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] emptyNextResponder]); } TEST(FlutterKeyboardManagerUnittests, GetPressedState) { ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] getPressedState]); } TEST(FlutterKeyboardManagerUnittests, KeyboardChannelGetPressedState) { ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] keyboardChannelGetPressedState]); } TEST(FlutterKeyboardManagerUnittests, RacingConditionBetweenKeyAndText) { ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] racingConditionBetweenKeyAndText]); } TEST(FlutterKeyboardManagerUnittests, CorrectLogicalKeyForLayouts) { ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] correctLogicalKeyForLayouts]); } TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate) { ASSERT_TRUE( [[FlutterKeyboardManagerUnittestsObjC alloc] shouldNotHoldStrongReferenceToViewDelegate]); } } // namespace flutter::testing @implementation FlutterKeyboardManagerUnittestsObjC - (bool)singlePrimaryResponder { KeyboardTester* tester = [[KeyboardTester alloc] init]; NSMutableArray<FlutterAsyncKeyCallback>* embedderCallbacks = [NSMutableArray<FlutterAsyncKeyCallback> array]; [tester recordEmbedderCallsTo:embedderCallbacks]; // Case: The responder reports FALSE [tester.manager handleEvent:keyDownEvent(0x50)]; EXPECT_EQ([embedderCallbacks count], 1u); embedderCallbacks[0](FALSE); OCMVerify([tester.nextResponder keyDown:checkKeyDownEvent(0x50)]); [embedderCallbacks removeAllObjects]; // Case: The responder reports TRUE [tester.manager handleEvent:keyUpEvent(0x50)]; EXPECT_EQ([embedderCallbacks count], 1u); embedderCallbacks[0](TRUE); // [owner.nextResponder keyUp:] should not be called, otherwise an error will be thrown. return true; } - (bool)doublePrimaryResponder { KeyboardTester* tester = [[KeyboardTester alloc] init]; // Send a down event first so we can send an up event later. [tester respondEmbedderCallsWith:false]; [tester respondChannelCallsWith:false]; [tester.manager handleEvent:keyDownEvent(0x50)]; NSMutableArray<FlutterAsyncKeyCallback>* embedderCallbacks = [NSMutableArray<FlutterAsyncKeyCallback> array]; NSMutableArray<FlutterAsyncKeyCallback>* channelCallbacks = [NSMutableArray<FlutterAsyncKeyCallback> array]; [tester recordEmbedderCallsTo:embedderCallbacks]; [tester recordChannelCallsTo:channelCallbacks]; // Case: Both responders report TRUE. [tester.manager handleEvent:keyUpEvent(0x50)]; EXPECT_EQ([embedderCallbacks count], 1u); EXPECT_EQ([channelCallbacks count], 1u); embedderCallbacks[0](TRUE); channelCallbacks[0](TRUE); EXPECT_EQ([embedderCallbacks count], 1u); EXPECT_EQ([channelCallbacks count], 1u); // [tester.nextResponder keyUp:] should not be called, otherwise an error will be thrown. [embedderCallbacks removeAllObjects]; [channelCallbacks removeAllObjects]; // Case: One responder reports TRUE. [tester respondEmbedderCallsWith:false]; [tester respondChannelCallsWith:false]; [tester.manager handleEvent:keyDownEvent(0x50)]; [tester recordEmbedderCallsTo:embedderCallbacks]; [tester recordChannelCallsTo:channelCallbacks]; [tester.manager handleEvent:keyUpEvent(0x50)]; EXPECT_EQ([embedderCallbacks count], 1u); EXPECT_EQ([channelCallbacks count], 1u); embedderCallbacks[0](FALSE); channelCallbacks[0](TRUE); EXPECT_EQ([embedderCallbacks count], 1u); EXPECT_EQ([channelCallbacks count], 1u); // [tester.nextResponder keyUp:] should not be called, otherwise an error will be thrown. [embedderCallbacks removeAllObjects]; [channelCallbacks removeAllObjects]; // Case: Both responders report FALSE. [tester.manager handleEvent:keyDownEvent(0x53)]; EXPECT_EQ([embedderCallbacks count], 1u); EXPECT_EQ([channelCallbacks count], 1u); embedderCallbacks[0](FALSE); channelCallbacks[0](FALSE); EXPECT_EQ([embedderCallbacks count], 1u); EXPECT_EQ([channelCallbacks count], 1u); OCMVerify([tester.nextResponder keyDown:checkKeyDownEvent(0x53)]); [embedderCallbacks removeAllObjects]; [channelCallbacks removeAllObjects]; return true; } - (bool)textInputPlugin { KeyboardTester* tester = [[KeyboardTester alloc] init]; // Send a down event first so we can send an up event later. [tester respondEmbedderCallsWith:false]; [tester respondChannelCallsWith:false]; [tester.manager handleEvent:keyDownEvent(0x50)]; NSMutableArray<FlutterAsyncKeyCallback>* callbacks = [NSMutableArray<FlutterAsyncKeyCallback> array]; [tester recordEmbedderCallsTo:callbacks]; // Case: Primary responder responds TRUE. The event shouldn't be handled by // the secondary responder. [tester respondTextInputWith:FALSE]; [tester.manager handleEvent:keyUpEvent(0x50)]; EXPECT_EQ([callbacks count], 1u); callbacks[0](TRUE); // [owner.nextResponder keyUp:] should not be called, otherwise an error will be thrown. [callbacks removeAllObjects]; // Send a down event first so we can send an up event later. [tester respondEmbedderCallsWith:false]; [tester.manager handleEvent:keyDownEvent(0x50)]; // Case: Primary responder responds FALSE. The secondary responder returns // TRUE. [tester recordEmbedderCallsTo:callbacks]; [tester respondTextInputWith:TRUE]; [tester.manager handleEvent:keyUpEvent(0x50)]; EXPECT_EQ([callbacks count], 1u); callbacks[0](FALSE); // [owner.nextResponder keyUp:] should not be called, otherwise an error will be thrown. [callbacks removeAllObjects]; // Case: Primary responder responds FALSE. The secondary responder returns FALSE. [tester respondTextInputWith:FALSE]; [tester.manager handleEvent:keyDownEvent(0x50)]; EXPECT_EQ([callbacks count], 1u); callbacks[0](FALSE); OCMVerify([tester.nextResponder keyDown:checkKeyDownEvent(0x50)]); [callbacks removeAllObjects]; return true; } - (bool)emptyNextResponder { KeyboardTester* tester = [[KeyboardTester alloc] init]; tester.nextResponder = nil; [tester respondEmbedderCallsWith:false]; [tester respondChannelCallsWith:false]; [tester respondTextInputWith:false]; [tester.manager handleEvent:keyDownEvent(0x50)]; // Passes if no error is thrown. return true; } - (bool)getPressedState { KeyboardTester* tester = [[KeyboardTester alloc] init]; [tester respondEmbedderCallsWith:false]; [tester respondChannelCallsWith:false]; [tester respondTextInputWith:false]; [tester.manager handleEvent:keyDownEvent(kVK_ANSI_A)]; NSDictionary* pressingRecords = [tester.manager getPressedState]; EXPECT_EQ([pressingRecords count], 1u); EXPECT_EQ(pressingRecords[@(kPhysicalKeyA)], @(kLogicalKeyA)); return true; } - (bool)keyboardChannelGetPressedState { KeyboardTester* tester = [[KeyboardTester alloc] init]; [tester respondEmbedderCallsWith:false]; [tester respondChannelCallsWith:false]; [tester respondTextInputWith:false]; [tester.manager handleEvent:keyDownEvent(kVK_ANSI_A)]; FlutterMethodCall* getKeyboardStateMethodCall = [FlutterMethodCall methodCallWithMethodName:@"getKeyboardState" arguments:nil]; NSData* getKeyboardStateMessage = [[FlutterStandardMethodCodec sharedInstance] encodeMethodCall:getKeyboardStateMethodCall]; [tester sendKeyboardChannelMessage:getKeyboardStateMessage]; id encodedResult = [tester lastKeyboardChannelResult]; id decoded = [[FlutterStandardMethodCodec sharedInstance] decodeEnvelope:encodedResult]; EXPECT_EQ([decoded count], 1u); EXPECT_EQ(decoded[@(kPhysicalKeyA)], @(kLogicalKeyA)); return true; } // Regression test for https://github.com/flutter/flutter/issues/82673. - (bool)racingConditionBetweenKeyAndText { KeyboardTester* tester = [[KeyboardTester alloc] init]; // Use Vietnamese IME (GoTiengViet, Telex mode) to type "uco". // The events received by the framework. The engine might receive // a channel message "setEditingState" from the framework. NSMutableArray<FlutterAsyncKeyCallback>* keyCallbacks = [NSMutableArray<FlutterAsyncKeyCallback> array]; [tester recordEmbedderCallsTo:keyCallbacks]; NSMutableArray<NSNumber*>* allCalls = [NSMutableArray<NSNumber*> array]; [tester recordCallTypesTo:allCalls forTypes:(kEmbedderCall | kTextCall)]; // Tap key U, which is converted by IME into a pure text message "ư". [tester.manager handleEvent:keyDownEvent(kKeyCodeEmpty, @"ư", @"ư")]; EXPECT_EQ([keyCallbacks count], 1u); EXPECT_EQ([allCalls count], 1u); EXPECT_EQ(allCalls[0], @(kEmbedderCall)); keyCallbacks[0](false); EXPECT_EQ([keyCallbacks count], 1u); EXPECT_EQ([allCalls count], 2u); EXPECT_EQ(allCalls[1], @(kTextCall)); [keyCallbacks removeAllObjects]; [allCalls removeAllObjects]; [tester.manager handleEvent:keyUpEvent(kKeyCodeEmpty)]; EXPECT_EQ([keyCallbacks count], 1u); keyCallbacks[0](false); EXPECT_EQ([keyCallbacks count], 1u); EXPECT_EQ([allCalls count], 2u); [keyCallbacks removeAllObjects]; [allCalls removeAllObjects]; // Tap key O, which is converted to normal KeyO events, but the responses are // slow. [tester.manager handleEvent:keyDownEvent(kVK_ANSI_O, @"o", @"o")]; [tester.manager handleEvent:keyUpEvent(kVK_ANSI_O)]; EXPECT_EQ([keyCallbacks count], 1u); EXPECT_EQ([allCalls count], 1u); EXPECT_EQ(allCalls[0], @(kEmbedderCall)); // Tap key C, which results in two Backspace messages first - and here they // arrive before the key O messages are responded. [tester.manager handleEvent:keyDownEvent(kVK_Delete)]; [tester.manager handleEvent:keyUpEvent(kVK_Delete)]; EXPECT_EQ([keyCallbacks count], 1u); EXPECT_EQ([allCalls count], 1u); // The key O down is responded, which releases a text call (for KeyO down) and // an embedder call (for KeyO up) immediately. keyCallbacks[0](false); EXPECT_EQ([keyCallbacks count], 2u); EXPECT_EQ([allCalls count], 3u); EXPECT_EQ(allCalls[1], @(kTextCall)); // The order is important! EXPECT_EQ(allCalls[2], @(kEmbedderCall)); // The key O up is responded, which releases a text call (for KeyO up) and // an embedder call (for Backspace down) immediately. keyCallbacks[1](false); EXPECT_EQ([keyCallbacks count], 3u); EXPECT_EQ([allCalls count], 5u); EXPECT_EQ(allCalls[3], @(kTextCall)); // The order is important! EXPECT_EQ(allCalls[4], @(kEmbedderCall)); // Finish up callbacks. keyCallbacks[2](false); keyCallbacks[3](false); return true; } - (bool)correctLogicalKeyForLayouts { KeyboardTester* tester = [[KeyboardTester alloc] init]; tester.nextResponder = nil; std::vector<FlutterKeyEvent> events; [tester recordEmbedderEventsTo:&events returning:true]; [tester respondChannelCallsWith:false]; [tester respondTextInputWith:false]; auto sendTap = [&](uint16_t keyCode, NSString* chars, NSString* charsUnmod) { [tester.manager handleEvent:keyDownEvent(keyCode, chars, charsUnmod)]; [tester.manager handleEvent:keyUpEvent(keyCode)]; }; /* US keyboard layout */ sendTap(kVK_ANSI_A, @"a", @"a"); // KeyA VERIFY_DOWN(kLogicalKeyA, "a"); sendTap(kVK_ANSI_A, @"A", @"A"); // Shift-KeyA VERIFY_DOWN(kLogicalKeyA, "A"); sendTap(kVK_ANSI_A, @"å", @"a"); // Option-KeyA VERIFY_DOWN(kLogicalKeyA, "å"); sendTap(kVK_ANSI_T, @"t", @"t"); // KeyT VERIFY_DOWN(kLogicalKeyT, "t"); sendTap(kVK_ANSI_1, @"1", @"1"); // Digit1 VERIFY_DOWN(kLogicalDigit1, "1"); sendTap(kVK_ANSI_1, @"!", @"!"); // Shift-Digit1 VERIFY_DOWN(kLogicalDigit1, "!"); sendTap(kVK_ANSI_Minus, @"-", @"-"); // Minus VERIFY_DOWN('-', "-"); sendTap(kVK_ANSI_Minus, @"=", @"="); // Shift-Minus VERIFY_DOWN('=', "="); /* French keyboard layout */ [tester setLayout:kFrenchLayout]; sendTap(kVK_ANSI_A, @"q", @"q"); // KeyA VERIFY_DOWN(kLogicalKeyQ, "q"); sendTap(kVK_ANSI_A, @"Q", @"Q"); // Shift-KeyA VERIFY_DOWN(kLogicalKeyQ, "Q"); sendTap(kVK_ANSI_Semicolon, @"m", @"m"); // ; but prints M VERIFY_DOWN(kLogicalKeyM, "m"); sendTap(kVK_ANSI_M, @",", @","); // M but prints , VERIFY_DOWN(',', ","); sendTap(kVK_ANSI_1, @"&", @"&"); // Digit1 VERIFY_DOWN(kLogicalDigit1, "&"); sendTap(kVK_ANSI_1, @"1", @"1"); // Shift-Digit1 VERIFY_DOWN(kLogicalDigit1, "1"); sendTap(kVK_ANSI_Minus, @")", @")"); // Minus VERIFY_DOWN(')', ")"); sendTap(kVK_ANSI_Minus, @"°", @"°"); // Shift-Minus VERIFY_DOWN(L'°', "°"); /* Russian keyboard layout */ [tester setLayout:kRussianLayout]; sendTap(kVK_ANSI_A, @"ф", @"ф"); // KeyA VERIFY_DOWN(kLogicalKeyA, "ф"); sendTap(kVK_ANSI_1, @"1", @"1"); // Digit1 VERIFY_DOWN(kLogicalDigit1, "1"); sendTap(kVK_ANSI_LeftBracket, @"х", @"х"); VERIFY_DOWN(kLogicalBracketLeft, "х"); /* Khmer keyboard layout */ // Regression test for https://github.com/flutter/flutter/issues/108729 [tester setLayout:kKhmerLayout]; sendTap(kVK_ANSI_2, @"២", @"២"); // Digit2 VERIFY_DOWN(kLogicalDigit2, "២"); return TRUE; } - (bool)shouldNotHoldStrongReferenceToViewDelegate { __strong FlutterKeyboardManager* strongKeyboardManager; __weak id weakViewDelegate; @autoreleasepool { id binaryMessengerMock = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub([binaryMessengerMock setMessageHandlerOnChannel:[OCMArg any] binaryMessageHandler:[OCMArg any]]); id viewDelegateMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardViewDelegate)); OCMStub([viewDelegateMock getBinaryMessenger]).andReturn(binaryMessengerMock); OCMStub([viewDelegateMock subscribeToKeyboardLayoutChange:[OCMArg any]]); LayoutClue layoutClue; OCMStub([viewDelegateMock lookUpLayoutForKeyCode:0 shift:NO]) .ignoringNonObjectArgs() .andReturn(layoutClue); FlutterKeyboardManager* keyboardManager = [[FlutterKeyboardManager alloc] initWithViewDelegate:viewDelegateMock]; strongKeyboardManager = keyboardManager; weakViewDelegate = viewDelegateMock; } return weakViewDelegate == nil; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManagerTest.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManagerTest.mm", "repo_id": "engine", "token_count": 13119 }
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. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" #import "flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.h" #include "flutter/testing/testing.h" namespace flutter::testing { TEST(FlutterPlatformViewController, TestCreatePlatformViewNoMatchingViewType) { // Use id so we can access handleMethodCall method. id platformViewController = [[FlutterPlatformViewController alloc] init]; FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{ @"id" : @2, @"viewType" : @"FlutterPlatformViewMock" }]; __block bool errored = false; FlutterResult result = ^(id result) { if ([result isKindOfClass:[FlutterError class]]) { errored = true; } }; [platformViewController handleMethodCall:methodCall result:result]; // We expect the call to error since no factories are registered. EXPECT_TRUE(errored); } TEST(FlutterPlatformViewController, TestRegisterPlatformViewFactoryAndCreate) { // Use id so we can access handleMethodCall method. id platformViewController = [[FlutterPlatformViewController alloc] init]; TestFlutterPlatformViewFactory* factory = [TestFlutterPlatformViewFactory alloc]; [platformViewController registerViewFactory:factory withId:@"MockPlatformView"]; NSDictionary* creationArgs = @{ @"album" : @"スコットとリバース", @"releaseYear" : @2013, @"artists" : @[ @"Scott Murphy", @"Rivers Cuomo" ], @"playlist" : @[ @"おかしいやつ", @"ほどけていたんだ" ], }; NSObject<FlutterMessageCodec>* codec = [factory createArgsCodec]; FlutterStandardTypedData* creationArgsData = [FlutterStandardTypedData typedDataWithBytes:[codec encode:creationArgs]]; FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{ @"id" : @2, @"viewType" : @"MockPlatformView", @"params" : creationArgsData, }]; __block bool success = false; FlutterResult result = ^(id result) { // If a platform view is successfully created, the result is nil. if (result == nil) { success = true; } }; [platformViewController handleMethodCall:methodCall result:result]; EXPECT_TRUE(success); // Verify PlatformView parameters are decoded correctly. TestFlutterPlatformView* view = (TestFlutterPlatformView*)[platformViewController platformViewWithID:2]; ASSERT_TRUE(view != nil); ASSERT_TRUE(view.args != nil); // Verify string type. NSString* album = [view.args objectForKey:@"album"]; EXPECT_TRUE([album isEqualToString:@"スコットとリバース"]); // Verify int type. NSNumber* releaseYear = [view.args objectForKey:@"releaseYear"]; EXPECT_EQ(releaseYear.intValue, 2013); // Verify list/array types. NSArray* artists = [view.args objectForKey:@"artists"]; ASSERT_TRUE(artists != nil); ASSERT_EQ(artists.count, 2ul); EXPECT_TRUE([artists[0] isEqualToString:@"Scott Murphy"]); EXPECT_TRUE([artists[1] isEqualToString:@"Rivers Cuomo"]); NSArray* playlist = [view.args objectForKey:@"playlist"]; ASSERT_EQ(playlist.count, 2ul); EXPECT_TRUE([playlist[0] isEqualToString:@"おかしいやつ"]); EXPECT_TRUE([playlist[1] isEqualToString:@"ほどけていたんだ"]); } TEST(FlutterPlatformViewController, TestCreateAndDispose) { // Use id so we can access handleMethodCall method. id platformViewController = [[FlutterPlatformViewController alloc] init]; TestFlutterPlatformViewFactory* factory = [TestFlutterPlatformViewFactory alloc]; [platformViewController registerViewFactory:factory withId:@"MockPlatformView"]; FlutterMethodCall* methodCallOnCreate = [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{ @"id" : @2, @"viewType" : @"MockPlatformView" }]; __block bool created = false; FlutterResult resultOnCreate = ^(id result) { // If a platform view is successfully created, the result is nil. if (result == nil) { created = true; } }; [platformViewController handleMethodCall:methodCallOnCreate result:resultOnCreate]; FlutterMethodCall* methodCallOnDispose = [FlutterMethodCall methodCallWithMethodName:@"dispose" arguments:[NSNumber numberWithLongLong:2]]; __block bool disposed = false; FlutterResult resultOnDispose = ^(id result) { // If a platform view is successfully created, the result is nil. if (result == nil) { disposed = true; } }; [platformViewController handleMethodCall:methodCallOnDispose result:resultOnDispose]; EXPECT_TRUE(created); EXPECT_TRUE(disposed); } TEST(FlutterPlatformViewController, TestDisposeOnMissingViewId) { // Use id so we can access handleMethodCall method. id platformViewController = [[FlutterPlatformViewController alloc] init]; FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"dispose" arguments:[NSNumber numberWithLongLong:20]]; __block bool errored = false; FlutterResult result = ^(id result) { if ([result isKindOfClass:[FlutterError class]]) { errored = true; } }; [platformViewController handleMethodCall:methodCall result:result]; EXPECT_TRUE(errored); } TEST(FlutterPlatformViewController, TestAcceptGesture) { FlutterPlatformViewController* platformViewController = [[FlutterPlatformViewController alloc] init]; [platformViewController registerViewFactory:[TestFlutterPlatformViewFactory alloc] withId:@"MockPlatformView"]; // Create the PlatformView. const NSNumber* viewId = [NSNumber numberWithLongLong:2]; FlutterMethodCall* methodCallOnCreate = [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : viewId, @"viewType" : @"MockPlatformView"}]; __block bool created = false; FlutterResult resultOnCreate = ^(id result) { // If a platform view is successfully created, the result is nil. if (result == nil) { created = true; } }; [platformViewController handleMethodCall:methodCallOnCreate result:resultOnCreate]; // Call acceptGesture. FlutterMethodCall* methodCallAcceptGesture = [FlutterMethodCall methodCallWithMethodName:@"acceptGesture" arguments:@{@"id" : viewId}]; __block bool acceptGestureCalled = false; FlutterResult resultAcceptGesture = ^(id result) { // If a acceptGesture is successful, the result is nil. if (result == nil) { acceptGestureCalled = true; } }; [platformViewController handleMethodCall:methodCallAcceptGesture result:resultAcceptGesture]; EXPECT_TRUE(created); EXPECT_TRUE(acceptGestureCalled); } TEST(FlutterPlatformViewController, TestAcceptGestureOnMissingViewId) { FlutterPlatformViewController* platformViewController = [[FlutterPlatformViewController alloc] init]; [platformViewController registerViewFactory:[TestFlutterPlatformViewFactory alloc] withId:@"MockPlatformView"]; // Call rejectGesture. FlutterMethodCall* methodCallAcceptGesture = [FlutterMethodCall methodCallWithMethodName:@"acceptGesture" arguments:@{ @"id" : @20 }]; __block bool errored = false; FlutterResult result = ^(id result) { if ([result isKindOfClass:[FlutterError class]]) { errored = true; } }; [platformViewController handleMethodCall:methodCallAcceptGesture result:result]; EXPECT_TRUE(errored); } TEST(FlutterPlatformViewController, TestRejectGesture) { FlutterPlatformViewController* platformViewController = [[FlutterPlatformViewController alloc] init]; [platformViewController registerViewFactory:[TestFlutterPlatformViewFactory alloc] withId:@"MockPlatformView"]; // Create the PlatformView. const NSNumber* viewId = [NSNumber numberWithLongLong:2]; FlutterMethodCall* methodCallOnCreate = [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : viewId, @"viewType" : @"MockPlatformView"}]; __block bool created = false; FlutterResult resultOnCreate = ^(id result) { // If a platform view is successfully created, the result is nil. if (result == nil) { created = true; } }; [platformViewController handleMethodCall:methodCallOnCreate result:resultOnCreate]; // Call rejectGesture. FlutterMethodCall* methodCallRejectGesture = [FlutterMethodCall methodCallWithMethodName:@"rejectGesture" arguments:@{@"id" : viewId}]; __block bool rejectGestureCalled = false; FlutterResult resultRejectGesture = ^(id result) { // If a rejectGesture is successful, the result is nil. if (result == nil) { rejectGestureCalled = true; } }; [platformViewController handleMethodCall:methodCallRejectGesture result:resultRejectGesture]; EXPECT_TRUE(created); EXPECT_TRUE(rejectGestureCalled); } TEST(FlutterPlatformViewController, TestRejectGestureOnMissingViewId) { FlutterPlatformViewController* platformViewController = [[FlutterPlatformViewController alloc] init]; [platformViewController registerViewFactory:[TestFlutterPlatformViewFactory alloc] withId:@"MockPlatformView"]; // Call rejectGesture. FlutterMethodCall* methodCallRejectGesture = [FlutterMethodCall methodCallWithMethodName:@"rejectGesture" arguments:@{ @"id" : @20 }]; __block bool errored = false; FlutterResult result = ^(id result) { if ([result isKindOfClass:[FlutterError class]]) { errored = true; } }; [platformViewController handleMethodCall:methodCallRejectGesture result:result]; EXPECT_TRUE(errored); } } // namespace flutter::testing
engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewControllerTest.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewControllerTest.mm", "repo_id": "engine", "token_count": 3996 }
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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTHREADSYNCHRONIZER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTHREADSYNCHRONIZER_H_ #import <Cocoa/Cocoa.h> /** * Takes care of synchronization between raster and platform thread. * * All methods of this class must be called from the platform thread, * except for performCommitForView:size:notify:. */ @interface FlutterThreadSynchronizer : NSObject /** * Creates a FlutterThreadSynchronizer that uses the OS main thread as the * platform thread. */ - (nullable instancetype)init; /** * Blocks until all views have a commit with their given sizes (or empty) is requested. */ - (void)beginResizeForView:(int64_t)viewId size:(CGSize)size notify:(nonnull dispatch_block_t)notify; /** * Called from raster thread. Schedules the given block on platform thread * and blocks until it is performed. * * If platform thread is blocked in `beginResize:` for given size (or size is empty), * unblocks platform thread. * * The notify block is guaranteed to be called within a core animation transaction. */ - (void)performCommitForView:(int64_t)viewId size:(CGSize)size notify:(nonnull dispatch_block_t)notify; /** * Schedules the given block to be performed on the platform thread. * The block will be performed even if the platform thread is blocked waiting * for a commit. */ - (void)performOnPlatformThread:(nonnull dispatch_block_t)block; /** * Requests the synchronizer to track another view. * * A view must be registered before calling begineResizeForView: or * performCommitForView:. It is typically done when the view controller is * created. */ - (void)registerView:(int64_t)viewId; /** * Requests the synchronizer to no longer track a view. * * It is typically done when the view controller is destroyed. */ - (void)deregisterView:(int64_t)viewId; /** * Called when the engine shuts down. * * Prevents any further synchronization and no longer blocks any threads. */ - (void)shutdown; @end @interface FlutterThreadSynchronizer (TestUtils) /** * Creates a FlutterThreadSynchronizer that uses the specified queue as the * platform thread. */ - (nullable instancetype)initWithMainQueue:(nonnull dispatch_queue_t)queue; /** * Blocks current thread until the mutex is available, then return whether the * synchronizer is waiting for a correct commit during resizing. * * After calling an operation of the thread synchronizer, call this method, * and when it returns, the thread synchronizer can be at one of the following 3 * states: * * 1. The operation has not started at all (with a return value FALSE.) * 2. The operation has ended (with a return value FALSE.) * 3. beginResizeForView: is in progress, waiting (with a return value TRUE.) * * By eliminating the 1st case (such as using the notify callback), we can use * this return value to decide whether the synchronizer is in case 2 or case 3, * that is whether the resizing is blocked by a mismatching commit. */ - (BOOL)isWaitingWhenMutexIsAvailable; /** * Blocks current thread until there is frame available. * Used in FlutterEngineTest. */ - (void)blockUntilFrameAvailable; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTHREADSYNCHRONIZER_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizer.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizer.h", "repo_id": "engine", "token_count": 1105 }
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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWENGINEPROVIDER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWENGINEPROVIDER_H_ #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewProvider.h" @class FlutterEngine; /** * A facade over FlutterEngine that allows FlutterEngine's children components * to query FlutterView. * * FlutterViewProvider only holds a weak reference to FlutterEngine. */ @interface FlutterViewEngineProvider : NSObject <FlutterViewProvider> /** * Create a FlutterViewProvider with the underlying engine. */ - (nonnull instancetype)initWithEngine:(nonnull __weak FlutterEngine*)engine; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWENGINEPROVIDER_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h", "repo_id": "engine", "token_count": 311 }
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. #define FML_USED_ON_EMBEDDER #define RAPIDJSON_HAS_STDSTRING 1 #include <cstring> #include <iostream> #include <memory> #include <set> #include <string> #include <vector> #include "flutter/fml/build_config.h" #include "flutter/fml/closure.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/native_library.h" #include "flutter/fml/thread.h" #include "third_party/dart/runtime/bin/elf_loader.h" #include "third_party/dart/runtime/include/dart_native_api.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GpuTypes.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" #if !defined(FLUTTER_NO_EXPORT) #if FML_OS_WIN #define FLUTTER_EXPORT __declspec(dllexport) #else // FML_OS_WIN #define FLUTTER_EXPORT __attribute__((visibility("default"))) #endif // FML_OS_WIN #endif // !FLUTTER_NO_EXPORT extern "C" { #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG // Used for debugging dart:* sources. extern const uint8_t kPlatformStrongDill[]; extern const intptr_t kPlatformStrongDillSize; #endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG } #include "flutter/assets/directory_asset_bundle.h" #include "flutter/common/graphics/persistent_cache.h" #include "flutter/common/task_runners.h" #include "flutter/fml/command_line.h" #include "flutter/fml/file.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/paths.h" #include "flutter/fml/trace_event.h" #include "flutter/shell/common/rasterizer.h" #include "flutter/shell/common/switches.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/embedder_engine.h" #include "flutter/shell/platform/embedder/embedder_external_texture_resolver.h" #include "flutter/shell/platform/embedder/embedder_platform_message_response.h" #include "flutter/shell/platform/embedder/embedder_render_target.h" #include "flutter/shell/platform/embedder/embedder_render_target_skia.h" #include "flutter/shell/platform/embedder/embedder_semantics_update.h" #include "flutter/shell/platform/embedder/embedder_struct_macros.h" #include "flutter/shell/platform/embedder/embedder_task_runner.h" #include "flutter/shell/platform/embedder/embedder_thread_host.h" #include "flutter/shell/platform/embedder/pixel_formats.h" #include "flutter/shell/platform/embedder/platform_view_embedder.h" #include "rapidjson/rapidjson.h" #include "rapidjson/writer.h" // Note: the IMPELLER_SUPPORTS_RENDERING may be defined even when the // embedder/BUILD.gn variable impeller_supports_rendering is disabled. #ifdef SHELL_ENABLE_GL #include "flutter/shell/platform/embedder/embedder_external_texture_gl.h" #include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" #ifdef IMPELLER_SUPPORTS_RENDERING #include "flutter/shell/platform/embedder/embedder_render_target_impeller.h" // nogncheck #include "flutter/shell/platform/embedder/embedder_surface_gl_impeller.h" // nogncheck #include "impeller/core/texture.h" // nogncheck #include "impeller/renderer/backend/gles/context_gles.h" // nogncheck #include "impeller/renderer/backend/gles/texture_gles.h" // nogncheck #include "impeller/renderer/context.h" // nogncheck #include "impeller/renderer/render_target.h" // nogncheck #endif // IMPELLER_SUPPORTS_RENDERING #endif // SHELL_ENABLE_GL #ifdef SHELL_ENABLE_METAL #include "flutter/shell/platform/embedder/embedder_surface_metal.h" #include "third_party/skia/include/ports/SkCFObject.h" #ifdef IMPELLER_SUPPORTS_RENDERING #include "flutter/shell/platform/embedder/embedder_render_target_impeller.h" // nogncheck #include "flutter/shell/platform/embedder/embedder_surface_metal_impeller.h" // nogncheck #include "impeller/core/texture.h" // nogncheck #include "impeller/renderer/backend/metal/texture_wrapper_mtl.h" // nogncheck #include "impeller/renderer/render_target.h" // nogncheck #endif // IMPELLER_SUPPORTS_RENDERING #endif // SHELL_ENABLE_METAL #ifdef SHELL_ENABLE_VULKAN #include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h" #endif // SHELL_ENABLE_VULKAN const int32_t kFlutterSemanticsNodeIdBatchEnd = -1; const int32_t kFlutterSemanticsCustomActionIdBatchEnd = -1; static constexpr FlutterViewId kFlutterImplicitViewId = 0; // A message channel to send platform-independent FlutterKeyData to the // framework. // // This should be kept in sync with the following variables: // // - lib/ui/platform_dispatcher.dart, _kFlutterKeyDataChannel // - shell/platform/darwin/ios/framework/Source/FlutterEngine.mm, // FlutterKeyDataChannel // - io/flutter/embedding/android/KeyData.java, // CHANNEL // // Not to be confused with "flutter/keyevent", which is used to send raw // key event data in a platform-dependent format. // // ## Format // // Send: KeyDataPacket.data(). // // Expected reply: Whether the event is handled. Exactly 1 byte long, with value // 1 for handled, and 0 for not. Malformed value is considered false. const char* kFlutterKeyDataChannel = "flutter/keydata"; static FlutterEngineResult LogEmbedderError(FlutterEngineResult code, const char* reason, const char* code_name, const char* function, const char* file, int line) { #if FML_OS_WIN constexpr char kSeparator = '\\'; #else constexpr char kSeparator = '/'; #endif const auto file_base = (::strrchr(file, kSeparator) ? strrchr(file, kSeparator) + 1 : file); char error[256] = {}; snprintf(error, (sizeof(error) / sizeof(char)), "%s (%d): '%s' returned '%s'. %s", file_base, line, function, code_name, reason); std::cerr << error << std::endl; return code; } #define LOG_EMBEDDER_ERROR(code, reason) \ LogEmbedderError(code, reason, #code, __FUNCTION__, __FILE__, __LINE__) static bool IsOpenGLRendererConfigValid(const FlutterRendererConfig* config) { if (config->type != kOpenGL) { return false; } const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl; if (!SAFE_EXISTS(open_gl_config, make_current) || !SAFE_EXISTS(open_gl_config, clear_current) || !SAFE_EXISTS_ONE_OF(open_gl_config, fbo_callback, fbo_with_frame_info_callback) || !SAFE_EXISTS_ONE_OF(open_gl_config, present, present_with_info)) { return false; } return true; } static bool IsSoftwareRendererConfigValid(const FlutterRendererConfig* config) { if (config->type != kSoftware) { return false; } const FlutterSoftwareRendererConfig* software_config = &config->software; if (SAFE_ACCESS(software_config, surface_present_callback, nullptr) == nullptr) { return false; } return true; } static bool IsMetalRendererConfigValid(const FlutterRendererConfig* config) { if (config->type != kMetal) { return false; } const FlutterMetalRendererConfig* metal_config = &config->metal; bool device = SAFE_ACCESS(metal_config, device, nullptr); bool command_queue = SAFE_ACCESS(metal_config, present_command_queue, nullptr); bool present = SAFE_ACCESS(metal_config, present_drawable_callback, nullptr); bool get_texture = SAFE_ACCESS(metal_config, get_next_drawable_callback, nullptr); return device && command_queue && present && get_texture; } static bool IsVulkanRendererConfigValid(const FlutterRendererConfig* config) { if (config->type != kVulkan) { return false; } const FlutterVulkanRendererConfig* vulkan_config = &config->vulkan; if (!SAFE_EXISTS(vulkan_config, instance) || !SAFE_EXISTS(vulkan_config, physical_device) || !SAFE_EXISTS(vulkan_config, device) || !SAFE_EXISTS(vulkan_config, queue) || !SAFE_EXISTS(vulkan_config, get_instance_proc_address_callback) || !SAFE_EXISTS(vulkan_config, get_next_image_callback) || !SAFE_EXISTS(vulkan_config, present_image_callback)) { return false; } return true; } static bool IsRendererValid(const FlutterRendererConfig* config) { if (config == nullptr) { return false; } switch (config->type) { case kOpenGL: return IsOpenGLRendererConfigValid(config); case kSoftware: return IsSoftwareRendererConfigValid(config); case kMetal: return IsMetalRendererConfigValid(config); case kVulkan: return IsVulkanRendererConfigValid(config); default: return false; } return false; } #if FML_OS_LINUX || FML_OS_WIN static void* DefaultGLProcResolver(const char* name) { static fml::RefPtr<fml::NativeLibrary> proc_library = #if FML_OS_LINUX fml::NativeLibrary::CreateForCurrentProcess(); #elif FML_OS_WIN // FML_OS_LINUX fml::NativeLibrary::Create("opengl32.dll"); #endif // FML_OS_WIN return static_cast<void*>( const_cast<uint8_t*>(proc_library->ResolveSymbol(name))); } #endif // FML_OS_LINUX || FML_OS_WIN #ifdef SHELL_ENABLE_GL // Auxiliary function used to translate rectangles of type SkIRect to // FlutterRect. static FlutterRect SkIRectToFlutterRect(const SkIRect sk_rect) { FlutterRect flutter_rect = {static_cast<double>(sk_rect.fLeft), static_cast<double>(sk_rect.fTop), static_cast<double>(sk_rect.fRight), static_cast<double>(sk_rect.fBottom)}; return flutter_rect; } // Auxiliary function used to translate rectangles of type FlutterRect to // SkIRect. static const SkIRect FlutterRectToSkIRect(FlutterRect flutter_rect) { SkIRect rect = {static_cast<int32_t>(flutter_rect.left), static_cast<int32_t>(flutter_rect.top), static_cast<int32_t>(flutter_rect.right), static_cast<int32_t>(flutter_rect.bottom)}; return rect; } #endif static inline flutter::Shell::CreateCallback<flutter::PlatformView> InferOpenGLPlatformViewCreationCallback( const FlutterRendererConfig* config, void* user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable& platform_dispatch_table, std::unique_ptr<flutter::EmbedderExternalViewEmbedder> external_view_embedder, bool enable_impeller) { #ifdef SHELL_ENABLE_GL if (config->type != kOpenGL) { return nullptr; } auto gl_make_current = [ptr = config->open_gl.make_current, user_data]() -> bool { return ptr(user_data); }; auto gl_clear_current = [ptr = config->open_gl.clear_current, user_data]() -> bool { return ptr(user_data); }; auto gl_present = [present = config->open_gl.present, present_with_info = config->open_gl.present_with_info, user_data](flutter::GLPresentInfo gl_present_info) -> bool { if (present) { return present(user_data); } else { // Format the frame and buffer damages accordingly. Note that, since the // current compute damage algorithm only returns one rectangle for damage // we are assuming the number of rectangles provided in frame and buffer // damage are always 1. Once the function that computes damage implements // support for multiple damage rectangles, GLPresentInfo should also // contain the number of damage rectangles. std::optional<FlutterRect> frame_damage_rect; if (gl_present_info.frame_damage) { frame_damage_rect = SkIRectToFlutterRect(*(gl_present_info.frame_damage)); } std::optional<FlutterRect> buffer_damage_rect; if (gl_present_info.buffer_damage) { buffer_damage_rect = SkIRectToFlutterRect(*(gl_present_info.buffer_damage)); } FlutterDamage frame_damage{ .struct_size = sizeof(FlutterDamage), .num_rects = frame_damage_rect ? size_t{1} : size_t{0}, .damage = frame_damage_rect ? &frame_damage_rect.value() : nullptr, }; FlutterDamage buffer_damage{ .struct_size = sizeof(FlutterDamage), .num_rects = buffer_damage_rect ? size_t{1} : size_t{0}, .damage = buffer_damage_rect ? &buffer_damage_rect.value() : nullptr, }; // Construct the present information concerning the frame being rendered. FlutterPresentInfo present_info = { .struct_size = sizeof(FlutterPresentInfo), .fbo_id = gl_present_info.fbo_id, .frame_damage = frame_damage, .buffer_damage = buffer_damage, }; return present_with_info(user_data, &present_info); } }; auto gl_fbo_callback = [fbo_callback = config->open_gl.fbo_callback, fbo_with_frame_info_callback = config->open_gl.fbo_with_frame_info_callback, user_data](flutter::GLFrameInfo gl_frame_info) -> intptr_t { if (fbo_callback) { return fbo_callback(user_data); } else { FlutterFrameInfo frame_info = {}; frame_info.struct_size = sizeof(FlutterFrameInfo); frame_info.size = {gl_frame_info.width, gl_frame_info.height}; return fbo_with_frame_info_callback(user_data, &frame_info); } }; auto gl_populate_existing_damage = [populate_existing_damage = config->open_gl.populate_existing_damage, user_data](intptr_t id) -> flutter::GLFBOInfo { // If no populate_existing_damage was provided, disable partial // repaint. if (!populate_existing_damage) { return flutter::GLFBOInfo{ .fbo_id = static_cast<uint32_t>(id), .existing_damage = std::nullopt, }; } // Given the FBO's ID, get its existing damage. FlutterDamage existing_damage; populate_existing_damage(user_data, id, &existing_damage); std::optional<SkIRect> existing_damage_rect = std::nullopt; // Verify that at least one damage rectangle was provided. if (existing_damage.num_rects <= 0 || existing_damage.damage == nullptr) { FML_LOG(INFO) << "No damage was provided. Forcing full repaint."; } else { existing_damage_rect = SkIRect::MakeEmpty(); for (size_t i = 0; i < existing_damage.num_rects; i++) { existing_damage_rect->join( FlutterRectToSkIRect(existing_damage.damage[i])); } } // Pass the information about this FBO to the rendering backend. return flutter::GLFBOInfo{ .fbo_id = static_cast<uint32_t>(id), .existing_damage = existing_damage_rect, }; }; const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl; std::function<bool()> gl_make_resource_current_callback = nullptr; if (SAFE_ACCESS(open_gl_config, make_resource_current, nullptr) != nullptr) { gl_make_resource_current_callback = [ptr = config->open_gl.make_resource_current, user_data]() { return ptr(user_data); }; } std::function<SkMatrix(void)> gl_surface_transformation_callback = nullptr; if (SAFE_ACCESS(open_gl_config, surface_transformation, nullptr) != nullptr) { gl_surface_transformation_callback = [ptr = config->open_gl.surface_transformation, user_data]() { FlutterTransformation transformation = ptr(user_data); return SkMatrix::MakeAll(transformation.scaleX, // transformation.skewX, // transformation.transX, // transformation.skewY, // transformation.scaleY, // transformation.transY, // transformation.pers0, // transformation.pers1, // transformation.pers2 // ); }; // If there is an external view embedder, ask it to apply the surface // transformation to its surfaces as well. if (external_view_embedder) { external_view_embedder->SetSurfaceTransformationCallback( gl_surface_transformation_callback); } } flutter::GPUSurfaceGLDelegate::GLProcResolver gl_proc_resolver = nullptr; if (SAFE_ACCESS(open_gl_config, gl_proc_resolver, nullptr) != nullptr) { gl_proc_resolver = [ptr = config->open_gl.gl_proc_resolver, user_data](const char* gl_proc_name) { return ptr(user_data, gl_proc_name); }; } else { #if FML_OS_LINUX || FML_OS_WIN gl_proc_resolver = DefaultGLProcResolver; #endif } bool fbo_reset_after_present = SAFE_ACCESS(open_gl_config, fbo_reset_after_present, false); flutter::EmbedderSurfaceGL::GLDispatchTable gl_dispatch_table = { gl_make_current, // gl_make_current_callback gl_clear_current, // gl_clear_current_callback gl_present, // gl_present_callback gl_fbo_callback, // gl_fbo_callback gl_make_resource_current_callback, // gl_make_resource_current_callback gl_surface_transformation_callback, // gl_surface_transformation_callback gl_proc_resolver, // gl_proc_resolver gl_populate_existing_damage, // gl_populate_existing_damage }; return fml::MakeCopyable( [gl_dispatch_table, fbo_reset_after_present, platform_dispatch_table, enable_impeller, external_view_embedder = std::move(external_view_embedder)](flutter::Shell& shell) mutable { std::shared_ptr<flutter::EmbedderExternalViewEmbedder> view_embedder = std::move(external_view_embedder); if (enable_impeller) { return std::make_unique<flutter::PlatformViewEmbedder>( shell, // delegate shell.GetTaskRunners(), // task runners std::make_unique<flutter::EmbedderSurfaceGLImpeller>( gl_dispatch_table, fbo_reset_after_present, view_embedder), // embedder_surface platform_dispatch_table, // embedder platform dispatch table view_embedder // external view embedder ); } return std::make_unique<flutter::PlatformViewEmbedder>( shell, // delegate shell.GetTaskRunners(), // task runners std::make_unique<flutter::EmbedderSurfaceGL>( gl_dispatch_table, fbo_reset_after_present, view_embedder), // embedder_surface platform_dispatch_table, // embedder platform dispatch table view_embedder // external view embedder ); }); #else return nullptr; #endif } static flutter::Shell::CreateCallback<flutter::PlatformView> InferMetalPlatformViewCreationCallback( const FlutterRendererConfig* config, void* user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable& platform_dispatch_table, std::unique_ptr<flutter::EmbedderExternalViewEmbedder> external_view_embedder, bool enable_impeller) { if (config->type != kMetal) { return nullptr; } #ifdef SHELL_ENABLE_METAL std::function<bool(flutter::GPUMTLTextureInfo texture)> metal_present = [ptr = config->metal.present_drawable_callback, user_data](flutter::GPUMTLTextureInfo texture) { FlutterMetalTexture embedder_texture; embedder_texture.struct_size = sizeof(FlutterMetalTexture); embedder_texture.texture = texture.texture; embedder_texture.texture_id = texture.texture_id; embedder_texture.user_data = texture.destruction_context; embedder_texture.destruction_callback = texture.destruction_callback; return ptr(user_data, &embedder_texture); }; auto metal_get_texture = [ptr = config->metal.get_next_drawable_callback, user_data](const SkISize& frame_size) -> flutter::GPUMTLTextureInfo { FlutterFrameInfo frame_info = {}; frame_info.struct_size = sizeof(FlutterFrameInfo); frame_info.size = {static_cast<uint32_t>(frame_size.width()), static_cast<uint32_t>(frame_size.height())}; flutter::GPUMTLTextureInfo texture_info; FlutterMetalTexture metal_texture = ptr(user_data, &frame_info); texture_info.texture_id = metal_texture.texture_id; texture_info.texture = metal_texture.texture; texture_info.destruction_callback = metal_texture.destruction_callback; texture_info.destruction_context = metal_texture.user_data; return texture_info; }; std::shared_ptr<flutter::EmbedderExternalViewEmbedder> view_embedder = std::move(external_view_embedder); std::unique_ptr<flutter::EmbedderSurface> embedder_surface; if (enable_impeller) { flutter::EmbedderSurfaceMetalImpeller::MetalDispatchTable metal_dispatch_table = { .present = metal_present, .get_texture = metal_get_texture, }; embedder_surface = std::make_unique<flutter::EmbedderSurfaceMetalImpeller>( const_cast<flutter::GPUMTLDeviceHandle>(config->metal.device), const_cast<flutter::GPUMTLCommandQueueHandle>( config->metal.present_command_queue), metal_dispatch_table, view_embedder); } else { flutter::EmbedderSurfaceMetal::MetalDispatchTable metal_dispatch_table = { .present = metal_present, .get_texture = metal_get_texture, }; embedder_surface = std::make_unique<flutter::EmbedderSurfaceMetal>( const_cast<flutter::GPUMTLDeviceHandle>(config->metal.device), const_cast<flutter::GPUMTLCommandQueueHandle>( config->metal.present_command_queue), metal_dispatch_table, view_embedder); } // The static leak checker gets confused by the use of fml::MakeCopyable. // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) return fml::MakeCopyable( [embedder_surface = std::move(embedder_surface), platform_dispatch_table, external_view_embedder = view_embedder](flutter::Shell& shell) mutable { return std::make_unique<flutter::PlatformViewEmbedder>( shell, // delegate shell.GetTaskRunners(), // task runners std::move(embedder_surface), // embedder surface platform_dispatch_table, // platform dispatch table std::move(external_view_embedder) // external view embedder ); }); #else return nullptr; #endif } static flutter::Shell::CreateCallback<flutter::PlatformView> InferVulkanPlatformViewCreationCallback( const FlutterRendererConfig* config, void* user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable& platform_dispatch_table, std::unique_ptr<flutter::EmbedderExternalViewEmbedder> external_view_embedder) { if (config->type != kVulkan) { return nullptr; } #ifdef SHELL_ENABLE_VULKAN std::function<void*(VkInstance, const char*)> vulkan_get_instance_proc_address = [ptr = config->vulkan.get_instance_proc_address_callback, user_data]( VkInstance instance, const char* proc_name) -> void* { return ptr(user_data, instance, proc_name); }; auto vulkan_get_next_image = [ptr = config->vulkan.get_next_image_callback, user_data](const SkISize& frame_size) -> FlutterVulkanImage { FlutterFrameInfo frame_info = { .struct_size = sizeof(FlutterFrameInfo), .size = {static_cast<uint32_t>(frame_size.width()), static_cast<uint32_t>(frame_size.height())}, }; return ptr(user_data, &frame_info); }; auto vulkan_present_image_callback = [ptr = config->vulkan.present_image_callback, user_data]( VkImage image, VkFormat format) -> bool { FlutterVulkanImage image_desc = { .struct_size = sizeof(FlutterVulkanImage), .image = reinterpret_cast<uint64_t>(image), .format = static_cast<uint32_t>(format), }; return ptr(user_data, &image_desc); }; auto vk_instance = static_cast<VkInstance>(config->vulkan.instance); auto proc_addr = vulkan_get_instance_proc_address(vk_instance, "vkGetInstanceProcAddr"); flutter::EmbedderSurfaceVulkan::VulkanDispatchTable vulkan_dispatch_table = { .get_instance_proc_address = reinterpret_cast<PFN_vkGetInstanceProcAddr>(proc_addr), .get_next_image = vulkan_get_next_image, .present_image = vulkan_present_image_callback, }; std::shared_ptr<flutter::EmbedderExternalViewEmbedder> view_embedder = std::move(external_view_embedder); std::unique_ptr<flutter::EmbedderSurfaceVulkan> embedder_surface = std::make_unique<flutter::EmbedderSurfaceVulkan>( config->vulkan.version, vk_instance, config->vulkan.enabled_instance_extension_count, config->vulkan.enabled_instance_extensions, config->vulkan.enabled_device_extension_count, config->vulkan.enabled_device_extensions, static_cast<VkPhysicalDevice>(config->vulkan.physical_device), static_cast<VkDevice>(config->vulkan.device), config->vulkan.queue_family_index, static_cast<VkQueue>(config->vulkan.queue), vulkan_dispatch_table, view_embedder); return fml::MakeCopyable( [embedder_surface = std::move(embedder_surface), platform_dispatch_table, external_view_embedder = std::move(view_embedder)](flutter::Shell& shell) mutable { return std::make_unique<flutter::PlatformViewEmbedder>( shell, // delegate shell.GetTaskRunners(), // task runners std::move(embedder_surface), // embedder surface platform_dispatch_table, // platform dispatch table std::move(external_view_embedder) // external view embedder ); }); #else return nullptr; #endif } static flutter::Shell::CreateCallback<flutter::PlatformView> InferSoftwarePlatformViewCreationCallback( const FlutterRendererConfig* config, void* user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable& platform_dispatch_table, std::unique_ptr<flutter::EmbedderExternalViewEmbedder> external_view_embedder) { if (config->type != kSoftware) { return nullptr; } auto software_present_backing_store = [ptr = config->software.surface_present_callback, user_data]( const void* allocation, size_t row_bytes, size_t height) -> bool { return ptr(user_data, allocation, row_bytes, height); }; flutter::EmbedderSurfaceSoftware::SoftwareDispatchTable software_dispatch_table = { software_present_backing_store, // required }; return fml::MakeCopyable( [software_dispatch_table, platform_dispatch_table, external_view_embedder = std::move(external_view_embedder)](flutter::Shell& shell) mutable { return std::make_unique<flutter::PlatformViewEmbedder>( shell, // delegate shell.GetTaskRunners(), // task runners software_dispatch_table, // software dispatch table platform_dispatch_table, // platform dispatch table std::move(external_view_embedder) // external view embedder ); }); } static flutter::Shell::CreateCallback<flutter::PlatformView> InferPlatformViewCreationCallback( const FlutterRendererConfig* config, void* user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable& platform_dispatch_table, std::unique_ptr<flutter::EmbedderExternalViewEmbedder> external_view_embedder, bool enable_impeller) { if (config == nullptr) { return nullptr; } switch (config->type) { case kOpenGL: return InferOpenGLPlatformViewCreationCallback( config, user_data, platform_dispatch_table, std::move(external_view_embedder), enable_impeller); case kSoftware: return InferSoftwarePlatformViewCreationCallback( config, user_data, platform_dispatch_table, std::move(external_view_embedder)); case kMetal: return InferMetalPlatformViewCreationCallback( config, user_data, platform_dispatch_table, std::move(external_view_embedder), enable_impeller); case kVulkan: return InferVulkanPlatformViewCreationCallback( config, user_data, platform_dispatch_table, std::move(external_view_embedder)); default: return nullptr; } return nullptr; } static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore( GrDirectContext* context, const FlutterBackingStoreConfig& config, const FlutterOpenGLTexture* texture) { #ifdef SHELL_ENABLE_GL GrGLTextureInfo texture_info; texture_info.fTarget = texture->target; texture_info.fID = texture->name; texture_info.fFormat = texture->format; auto backend_texture = GrBackendTextures::MakeGL(config.size.width, // config.size.height, // skgpu::Mipmapped::kNo, // texture_info // ); SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry); auto surface = SkSurfaces::WrapBackendTexture( context, // context backend_texture, // back-end texture kBottomLeft_GrSurfaceOrigin, // surface origin 1, // sample count kN32_SkColorType, // color type SkColorSpace::MakeSRGB(), // color space &surface_properties, // surface properties static_cast<SkSurfaces::TextureReleaseProc>( texture->destruction_callback), // release proc texture->user_data // release context ); if (!surface) { FML_LOG(ERROR) << "Could not wrap embedder supplied render texture."; return nullptr; } return surface; #else return nullptr; #endif } static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore( GrDirectContext* context, const FlutterBackingStoreConfig& config, const FlutterOpenGLFramebuffer* framebuffer) { #ifdef SHELL_ENABLE_GL GrGLFramebufferInfo framebuffer_info = {}; framebuffer_info.fFormat = framebuffer->target; framebuffer_info.fFBOID = framebuffer->name; auto backend_render_target = GrBackendRenderTargets::MakeGL(config.size.width, // width config.size.height, // height 1, // sample count 0, // stencil bits framebuffer_info // framebuffer info ); SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry); auto surface = SkSurfaces::WrapBackendRenderTarget( context, // context backend_render_target, // backend render target kBottomLeft_GrSurfaceOrigin, // surface origin kN32_SkColorType, // color type SkColorSpace::MakeSRGB(), // color space &surface_properties, // surface properties static_cast<SkSurfaces::RenderTargetReleaseProc>( framebuffer->destruction_callback), // release proc framebuffer->user_data // release context ); if (!surface) { FML_LOG(ERROR) << "Could not wrap embedder supplied frame-buffer."; return nullptr; } return surface; #else return nullptr; #endif } static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore( GrDirectContext* context, const FlutterBackingStoreConfig& config, const FlutterSoftwareBackingStore* software) { const auto image_info = SkImageInfo::MakeN32Premul(config.size.width, config.size.height); struct Captures { VoidCallback destruction_callback; void* user_data; }; auto captures = std::make_unique<Captures>(); captures->destruction_callback = software->destruction_callback; captures->user_data = software->user_data; auto release_proc = [](void* pixels, void* context) { auto captures = reinterpret_cast<Captures*>(context); if (captures->destruction_callback) { captures->destruction_callback(captures->user_data); } delete captures; }; auto surface = SkSurfaces::WrapPixels(image_info, // image info const_cast<void*>(software->allocation), // pixels software->row_bytes, // row bytes release_proc, // release proc captures.get() // get context ); if (!surface) { FML_LOG(ERROR) << "Could not wrap embedder supplied software render buffer."; if (software->destruction_callback) { software->destruction_callback(software->user_data); } return nullptr; } if (surface) { captures.release(); // Skia has assumed ownership of the struct. } return surface; } static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore( GrDirectContext* context, const FlutterBackingStoreConfig& config, const FlutterSoftwareBackingStore2* software) { const auto color_info = getSkColorInfo(software->pixel_format); if (!color_info) { return nullptr; } const auto image_info = SkImageInfo::Make( SkISize::Make(config.size.width, config.size.height), *color_info); struct Captures { VoidCallback destruction_callback; void* user_data; }; auto captures = std::make_unique<Captures>(); captures->destruction_callback = software->destruction_callback; captures->user_data = software->user_data; auto release_proc = [](void* pixels, void* context) { auto captures = reinterpret_cast<Captures*>(context); if (captures->destruction_callback) { captures->destruction_callback(captures->user_data); } }; auto surface = SkSurfaces::WrapPixels(image_info, // image info const_cast<void*>(software->allocation), // pixels software->row_bytes, // row bytes release_proc, // release proc captures.release() // release context ); if (!surface) { FML_LOG(ERROR) << "Could not wrap embedder supplied software render buffer."; if (software->destruction_callback) { software->destruction_callback(software->user_data); } return nullptr; } return surface; } static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore( GrDirectContext* context, const FlutterBackingStoreConfig& config, const FlutterMetalBackingStore* metal) { #ifdef SHELL_ENABLE_METAL GrMtlTextureInfo texture_info; if (!metal->texture.texture) { FML_LOG(ERROR) << "Embedder supplied null Metal texture."; return nullptr; } sk_cfp<FlutterMetalTextureHandle> mtl_texture; mtl_texture.retain(metal->texture.texture); texture_info.fTexture = mtl_texture; GrBackendTexture backend_texture(config.size.width, // config.size.height, // skgpu::Mipmapped::kNo, // texture_info // ); SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry); auto surface = SkSurfaces::WrapBackendTexture( context, // context backend_texture, // back-end texture kTopLeft_GrSurfaceOrigin, // surface origin // TODO(dnfield): Update this when embedders support MSAA, see // https://github.com/flutter/flutter/issues/100392 1, // sample count kBGRA_8888_SkColorType, // color type nullptr, // color space &surface_properties, // surface properties static_cast<SkSurfaces::TextureReleaseProc>( metal->texture.destruction_callback), // release proc metal->texture.user_data // release context ); if (!surface) { FML_LOG(ERROR) << "Could not wrap embedder supplied Metal render texture."; return nullptr; } return surface; #else return nullptr; #endif } static std::unique_ptr<flutter::EmbedderRenderTarget> MakeRenderTargetFromBackingStoreImpeller( FlutterBackingStore backing_store, const fml::closure& on_release, const std::shared_ptr<impeller::AiksContext>& aiks_context, const FlutterBackingStoreConfig& config, const FlutterOpenGLFramebuffer* framebuffer) { #if defined(SHELL_ENABLE_GL) && defined(IMPELLER_SUPPORTS_RENDERING) const auto& gl_context = impeller::ContextGLES::Cast(*aiks_context->GetContext()); const auto size = impeller::ISize(config.size.width, config.size.height); impeller::TextureDescriptor color0_tex; color0_tex.type = impeller::TextureType::kTexture2D; color0_tex.format = impeller::PixelFormat::kR8G8B8A8UNormInt; color0_tex.size = size; color0_tex.usage = static_cast<impeller::TextureUsageMask>( impeller::TextureUsage::kRenderTarget); color0_tex.sample_count = impeller::SampleCount::kCount1; color0_tex.storage_mode = impeller::StorageMode::kDevicePrivate; impeller::ColorAttachment color0; color0.texture = std::make_shared<impeller::TextureGLES>( gl_context.GetReactor(), color0_tex, impeller::TextureGLES::IsWrapped::kWrapped); color0.clear_color = impeller::Color::DarkSlateGray(); color0.load_action = impeller::LoadAction::kClear; color0.store_action = impeller::StoreAction::kStore; impeller::TextureDescriptor depth_stencil_texture_desc; depth_stencil_texture_desc.type = impeller::TextureType::kTexture2D; depth_stencil_texture_desc.format = impeller::PixelFormat::kR8G8B8A8UNormInt; depth_stencil_texture_desc.size = size; depth_stencil_texture_desc.usage = static_cast<impeller::TextureUsageMask>( impeller::TextureUsage::kRenderTarget); depth_stencil_texture_desc.sample_count = impeller::SampleCount::kCount1; auto depth_stencil_tex = std::make_shared<impeller::TextureGLES>( gl_context.GetReactor(), depth_stencil_texture_desc, impeller::TextureGLES::IsWrapped::kWrapped); impeller::DepthAttachment depth0; depth0.clear_depth = 0; depth0.texture = depth_stencil_tex; depth0.load_action = impeller::LoadAction::kClear; depth0.store_action = impeller::StoreAction::kDontCare; impeller::StencilAttachment stencil0; stencil0.clear_stencil = 0; stencil0.texture = depth_stencil_tex; stencil0.load_action = impeller::LoadAction::kClear; stencil0.store_action = impeller::StoreAction::kDontCare; impeller::RenderTarget render_target_desc; render_target_desc.SetColorAttachment(color0, 0u); render_target_desc.SetDepthAttachment(depth0); render_target_desc.SetStencilAttachment(stencil0); fml::closure framebuffer_destruct = [callback = framebuffer->destruction_callback, user_data = framebuffer->user_data]() { callback(user_data); }; return std::make_unique<flutter::EmbedderRenderTargetImpeller>( backing_store, aiks_context, std::make_unique<impeller::RenderTarget>(std::move(render_target_desc)), on_release, framebuffer_destruct); #else return nullptr; #endif } static std::unique_ptr<flutter::EmbedderRenderTarget> MakeRenderTargetFromBackingStoreImpeller( FlutterBackingStore backing_store, const fml::closure& on_release, const std::shared_ptr<impeller::AiksContext>& aiks_context, const FlutterBackingStoreConfig& config, const FlutterMetalBackingStore* metal) { #if defined(SHELL_ENABLE_METAL) && defined(IMPELLER_SUPPORTS_RENDERING) if (!metal->texture.texture) { FML_LOG(ERROR) << "Embedder supplied null Metal texture."; return nullptr; } const auto size = impeller::ISize(config.size.width, config.size.height); impeller::TextureDescriptor resolve_tex_desc; resolve_tex_desc.size = size; resolve_tex_desc.sample_count = impeller::SampleCount::kCount1; resolve_tex_desc.storage_mode = impeller::StorageMode::kDevicePrivate; resolve_tex_desc.usage = impeller::TextureUsage::kRenderTarget | impeller::TextureUsage::kShaderRead; auto resolve_tex = impeller::WrapTextureMTL( resolve_tex_desc, metal->texture.texture, [callback = metal->texture.destruction_callback, user_data = metal->texture.user_data]() { callback(user_data); }); if (!resolve_tex) { FML_LOG(ERROR) << "Could not wrap embedder supplied Metal render texture."; return nullptr; } resolve_tex->SetLabel("ImpellerBackingStoreResolve"); impeller::TextureDescriptor msaa_tex_desc; msaa_tex_desc.storage_mode = impeller::StorageMode::kDeviceTransient; msaa_tex_desc.type = impeller::TextureType::kTexture2DMultisample; msaa_tex_desc.sample_count = impeller::SampleCount::kCount4; msaa_tex_desc.format = resolve_tex->GetTextureDescriptor().format; msaa_tex_desc.size = size; msaa_tex_desc.usage = impeller::TextureUsage::kRenderTarget; auto msaa_tex = aiks_context->GetContext()->GetResourceAllocator()->CreateTexture( msaa_tex_desc); if (!msaa_tex) { FML_LOG(ERROR) << "Could not allocate MSAA color texture."; return nullptr; } msaa_tex->SetLabel("ImpellerBackingStoreColorMSAA"); impeller::ColorAttachment color0; color0.texture = msaa_tex; color0.clear_color = impeller::Color::DarkSlateGray(); color0.load_action = impeller::LoadAction::kClear; color0.store_action = impeller::StoreAction::kMultisampleResolve; color0.resolve_texture = resolve_tex; impeller::RenderTarget render_target_desc; render_target_desc.SetColorAttachment(color0, 0u); return std::make_unique<flutter::EmbedderRenderTargetImpeller>( backing_store, aiks_context, std::make_unique<impeller::RenderTarget>(std::move(render_target_desc)), on_release, fml::closure()); #else return nullptr; #endif } static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore( GrDirectContext* context, const FlutterBackingStoreConfig& config, const FlutterVulkanBackingStore* vulkan) { #ifdef SHELL_ENABLE_VULKAN if (!vulkan->image) { FML_LOG(ERROR) << "Embedder supplied null Vulkan image."; return nullptr; } GrVkImageInfo image_info = { .fImage = reinterpret_cast<VkImage>(vulkan->image->image), .fImageTiling = VK_IMAGE_TILING_OPTIMAL, .fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED, .fFormat = static_cast<VkFormat>(vulkan->image->format), .fImageUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, .fSampleCount = 1, .fLevelCount = 1, }; auto backend_texture = GrBackendTextures::MakeVk( config.size.width, config.size.height, image_info); SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry); auto surface = SkSurfaces::WrapBackendTexture( context, // context backend_texture, // back-end texture kTopLeft_GrSurfaceOrigin, // surface origin 1, // sample count flutter::GPUSurfaceVulkan::ColorTypeFromFormat( static_cast<VkFormat>(vulkan->image->format)), // color type SkColorSpace::MakeSRGB(), // color space &surface_properties, // surface properties static_cast<SkSurfaces::TextureReleaseProc>( vulkan->destruction_callback), // release proc vulkan->user_data // release context ); if (!surface) { FML_LOG(ERROR) << "Could not wrap embedder supplied Vulkan render texture."; return nullptr; } return surface; #else return nullptr; #endif } static std::unique_ptr<flutter::EmbedderRenderTarget> MakeRenderTargetFromSkSurface(FlutterBackingStore backing_store, sk_sp<SkSurface> skia_surface, fml::closure on_release) { if (!skia_surface) { return nullptr; } return std::make_unique<flutter::EmbedderRenderTargetSkia>( backing_store, std::move(skia_surface), std::move(on_release)); } static std::unique_ptr<flutter::EmbedderRenderTarget> CreateEmbedderRenderTarget( const FlutterCompositor* compositor, const FlutterBackingStoreConfig& config, GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, bool enable_impeller) { FlutterBackingStore backing_store = {}; backing_store.struct_size = sizeof(backing_store); // Safe access checks on the compositor struct have been performed in // InferExternalViewEmbedderFromArgs and are not necessary here. auto c_create_callback = compositor->create_backing_store_callback; auto c_collect_callback = compositor->collect_backing_store_callback; { TRACE_EVENT0("flutter", "FlutterCompositorCreateBackingStore"); if (!c_create_callback(&config, &backing_store, compositor->user_data)) { FML_LOG(ERROR) << "Could not create the embedder backing store."; return nullptr; } } if (backing_store.struct_size != sizeof(backing_store)) { FML_LOG(ERROR) << "Embedder modified the backing store struct size."; return nullptr; } // In case we return early without creating an embedder render target, the // embedder has still given us ownership of its baton which we must return // back to it. If this method is successful, the closure is released when the // render target is eventually released. fml::ScopedCleanupClosure collect_callback( [c_collect_callback, backing_store, user_data = compositor->user_data]() { TRACE_EVENT0("flutter", "FlutterCompositorCollectBackingStore"); c_collect_callback(&backing_store, user_data); }); // No safe access checks on the renderer are necessary since we allocated // the struct. std::unique_ptr<flutter::EmbedderRenderTarget> render_target; switch (backing_store.type) { case kFlutterBackingStoreTypeOpenGL: { switch (backing_store.open_gl.type) { case kFlutterOpenGLTargetTypeTexture: { auto skia_surface = MakeSkSurfaceFromBackingStore( context, config, &backing_store.open_gl.texture); render_target = MakeRenderTargetFromSkSurface( backing_store, std::move(skia_surface), collect_callback.Release()); break; } case kFlutterOpenGLTargetTypeFramebuffer: { if (enable_impeller) { render_target = MakeRenderTargetFromBackingStoreImpeller( backing_store, collect_callback.Release(), aiks_context, config, &backing_store.open_gl.framebuffer); break; } else { auto skia_surface = MakeSkSurfaceFromBackingStore( context, config, &backing_store.open_gl.framebuffer); render_target = MakeRenderTargetFromSkSurface( backing_store, std::move(skia_surface), collect_callback.Release()); break; } } } break; } case kFlutterBackingStoreTypeSoftware: { auto skia_surface = MakeSkSurfaceFromBackingStore( context, config, &backing_store.software); render_target = MakeRenderTargetFromSkSurface( backing_store, std::move(skia_surface), collect_callback.Release()); break; } case kFlutterBackingStoreTypeSoftware2: { auto skia_surface = MakeSkSurfaceFromBackingStore( context, config, &backing_store.software2); render_target = MakeRenderTargetFromSkSurface( backing_store, std::move(skia_surface), collect_callback.Release()); break; } case kFlutterBackingStoreTypeMetal: { if (enable_impeller) { render_target = MakeRenderTargetFromBackingStoreImpeller( backing_store, collect_callback.Release(), aiks_context, config, &backing_store.metal); } else { auto skia_surface = MakeSkSurfaceFromBackingStore(context, config, &backing_store.metal); render_target = MakeRenderTargetFromSkSurface( backing_store, std::move(skia_surface), collect_callback.Release()); } break; } case kFlutterBackingStoreTypeVulkan: { auto skia_surface = MakeSkSurfaceFromBackingStore(context, config, &backing_store.vulkan); render_target = MakeRenderTargetFromSkSurface( backing_store, std::move(skia_surface), collect_callback.Release()); break; } }; if (!render_target) { FML_LOG(ERROR) << "Could not create a surface from an embedder provided " "render target."; } return render_target; } static std::pair<std::unique_ptr<flutter::EmbedderExternalViewEmbedder>, bool /* halt engine launch if true */> InferExternalViewEmbedderFromArgs(const FlutterCompositor* compositor, bool enable_impeller) { if (compositor == nullptr) { return {nullptr, false}; } auto c_create_callback = SAFE_ACCESS(compositor, create_backing_store_callback, nullptr); auto c_collect_callback = SAFE_ACCESS(compositor, collect_backing_store_callback, nullptr); auto c_present_callback = SAFE_ACCESS(compositor, present_layers_callback, nullptr); auto c_present_view_callback = SAFE_ACCESS(compositor, present_view_callback, nullptr); bool avoid_backing_store_cache = SAFE_ACCESS(compositor, avoid_backing_store_cache, false); // Make sure the required callbacks are present if (!c_create_callback || !c_collect_callback) { FML_LOG(ERROR) << "Required compositor callbacks absent."; return {nullptr, true}; } // Either the present view or the present layers callback must be provided. if ((!c_present_view_callback && !c_present_callback) || (c_present_view_callback && c_present_callback)) { FML_LOG(ERROR) << "Either present_layers_callback or present_view_callback " "must be provided but not both."; return {nullptr, true}; } FlutterCompositor captured_compositor = *compositor; flutter::EmbedderExternalViewEmbedder::CreateRenderTargetCallback create_render_target_callback = [captured_compositor, enable_impeller]( GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, const auto& config) { return CreateEmbedderRenderTarget(&captured_compositor, config, context, aiks_context, enable_impeller); }; flutter::EmbedderExternalViewEmbedder::PresentCallback present_callback; if (c_present_callback) { present_callback = [c_present_callback, user_data = compositor->user_data]( FlutterViewId view_id, const auto& layers) { TRACE_EVENT0("flutter", "FlutterCompositorPresentLayers"); return c_present_callback(const_cast<const FlutterLayer**>(layers.data()), layers.size(), user_data); }; } else { FML_DCHECK(c_present_view_callback != nullptr); present_callback = [c_present_view_callback, user_data = compositor->user_data]( FlutterViewId view_id, const auto& layers) { TRACE_EVENT0("flutter", "FlutterCompositorPresentLayers"); FlutterPresentViewInfo info = { .struct_size = sizeof(FlutterPresentViewInfo), .view_id = view_id, .layers = const_cast<const FlutterLayer**>(layers.data()), .layers_count = layers.size(), .user_data = user_data, }; return c_present_view_callback(&info); }; } return {std::make_unique<flutter::EmbedderExternalViewEmbedder>( avoid_backing_store_cache, create_render_target_callback, present_callback), false}; } struct _FlutterPlatformMessageResponseHandle { std::unique_ptr<flutter::PlatformMessage> message; }; struct LoadedElfDeleter { void operator()(Dart_LoadedElf* elf) { if (elf) { ::Dart_UnloadELF(elf); } } }; using UniqueLoadedElf = std::unique_ptr<Dart_LoadedElf, LoadedElfDeleter>; struct _FlutterEngineAOTData { UniqueLoadedElf loaded_elf = nullptr; const uint8_t* vm_snapshot_data = nullptr; const uint8_t* vm_snapshot_instrs = nullptr; const uint8_t* vm_isolate_data = nullptr; const uint8_t* vm_isolate_instrs = nullptr; }; FlutterEngineResult FlutterEngineCreateAOTData( const FlutterEngineAOTDataSource* source, FlutterEngineAOTData* data_out) { if (!flutter::DartVM::IsRunningPrecompiledCode()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "AOT data can only be created in AOT mode."); } else if (!source) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null source specified."); } else if (!data_out) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null data_out specified."); } switch (source->type) { case kFlutterEngineAOTDataSourceTypeElfPath: { if (!source->elf_path || !fml::IsFile(source->elf_path)) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid ELF path specified."); } auto aot_data = std::make_unique<_FlutterEngineAOTData>(); const char* error = nullptr; #if OS_FUCHSIA // TODO(gw280): https://github.com/flutter/flutter/issues/50285 // Dart doesn't implement Dart_LoadELF on Fuchsia Dart_LoadedElf* loaded_elf = nullptr; #else Dart_LoadedElf* loaded_elf = Dart_LoadELF( source->elf_path, // file path 0, // file offset &error, // error (out) &aot_data->vm_snapshot_data, // vm snapshot data (out) &aot_data->vm_snapshot_instrs, // vm snapshot instr (out) &aot_data->vm_isolate_data, // vm isolate data (out) &aot_data->vm_isolate_instrs // vm isolate instr (out) ); #endif if (loaded_elf == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, error); } aot_data->loaded_elf.reset(loaded_elf); *data_out = aot_data.release(); return kSuccess; } } return LOG_EMBEDDER_ERROR( kInvalidArguments, "Invalid FlutterEngineAOTDataSourceType type specified."); } FlutterEngineResult FlutterEngineCollectAOTData(FlutterEngineAOTData data) { if (!data) { // Deleting a null object should be a no-op. return kSuccess; } // Created in a unique pointer in `FlutterEngineCreateAOTData`. delete data; return kSuccess; } // Constructs appropriate mapping callbacks if JIT snapshot locations have been // explictly specified. void PopulateJITSnapshotMappingCallbacks(const FlutterProjectArgs* args, flutter::Settings& settings) { auto make_mapping_callback = [](const char* path, bool executable) { return [path, executable]() { if (executable) { return fml::FileMapping::CreateReadExecute(path); } else { return fml::FileMapping::CreateReadOnly(path); } }; }; // Users are allowed to specify only certain snapshots if they so desire. if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) != nullptr) { settings.vm_snapshot_data = make_mapping_callback( reinterpret_cast<const char*>(args->vm_snapshot_data), false); } if (SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) != nullptr) { settings.vm_snapshot_instr = make_mapping_callback( reinterpret_cast<const char*>(args->vm_snapshot_instructions), true); } if (SAFE_ACCESS(args, isolate_snapshot_data, nullptr) != nullptr) { settings.isolate_snapshot_data = make_mapping_callback( reinterpret_cast<const char*>(args->isolate_snapshot_data), false); } if (SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr) != nullptr) { settings.isolate_snapshot_instr = make_mapping_callback( reinterpret_cast<const char*>(args->isolate_snapshot_instructions), true); } #if !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) settings.dart_library_sources_kernel = []() { return std::make_unique<fml::NonOwnedMapping>(kPlatformStrongDill, kPlatformStrongDillSize); }; #endif // !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE == // FLUTTER_RUNTIME_MODE_DEBUG) } void PopulateAOTSnapshotMappingCallbacks( const FlutterProjectArgs* args, flutter::Settings& settings) { // NOLINT(google-runtime-references) // There are no ownership concerns here as all mappings are owned by the // embedder and not the engine. auto make_mapping_callback = [](const uint8_t* mapping, size_t size) { return [mapping, size]() { return std::make_unique<fml::NonOwnedMapping>(mapping, size); }; }; if (SAFE_ACCESS(args, aot_data, nullptr) != nullptr) { settings.vm_snapshot_data = make_mapping_callback(args->aot_data->vm_snapshot_data, 0); settings.vm_snapshot_instr = make_mapping_callback(args->aot_data->vm_snapshot_instrs, 0); settings.isolate_snapshot_data = make_mapping_callback(args->aot_data->vm_isolate_data, 0); settings.isolate_snapshot_instr = make_mapping_callback(args->aot_data->vm_isolate_instrs, 0); } if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) != nullptr) { settings.vm_snapshot_data = make_mapping_callback( args->vm_snapshot_data, SAFE_ACCESS(args, vm_snapshot_data_size, 0)); } if (SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) != nullptr) { settings.vm_snapshot_instr = make_mapping_callback( args->vm_snapshot_instructions, SAFE_ACCESS(args, vm_snapshot_instructions_size, 0)); } if (SAFE_ACCESS(args, isolate_snapshot_data, nullptr) != nullptr) { settings.isolate_snapshot_data = make_mapping_callback(args->isolate_snapshot_data, SAFE_ACCESS(args, isolate_snapshot_data_size, 0)); } if (SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr) != nullptr) { settings.isolate_snapshot_instr = make_mapping_callback( args->isolate_snapshot_instructions, SAFE_ACCESS(args, isolate_snapshot_instructions_size, 0)); } } // Create a callback to notify the embedder of semantic updates // using the legacy embedder callbacks 'update_semantics_node_callback' and // 'update_semantics_custom_action_callback'. flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV1( FlutterUpdateSemanticsNodeCallback update_semantics_node_callback, FlutterUpdateSemanticsCustomActionCallback update_semantics_custom_action_callback, void* user_data) { return [update_semantics_node_callback, update_semantics_custom_action_callback, user_data](const flutter::SemanticsNodeUpdates& nodes, const flutter::CustomAccessibilityActionUpdates& actions) { flutter::EmbedderSemanticsUpdate update{nodes, actions}; FlutterSemanticsUpdate* update_ptr = update.get(); // First, queue all node and custom action updates. if (update_semantics_node_callback != nullptr) { for (size_t i = 0; i < update_ptr->nodes_count; i++) { update_semantics_node_callback(&update_ptr->nodes[i], user_data); } } if (update_semantics_custom_action_callback != nullptr) { for (size_t i = 0; i < update_ptr->custom_actions_count; i++) { update_semantics_custom_action_callback(&update_ptr->custom_actions[i], user_data); } } // Second, mark node and action batches completed now that all // updates are queued. if (update_semantics_node_callback != nullptr) { const FlutterSemanticsNode batch_end_sentinel = { sizeof(FlutterSemanticsNode), kFlutterSemanticsNodeIdBatchEnd, }; update_semantics_node_callback(&batch_end_sentinel, user_data); } if (update_semantics_custom_action_callback != nullptr) { const FlutterSemanticsCustomAction batch_end_sentinel = { sizeof(FlutterSemanticsCustomAction), kFlutterSemanticsCustomActionIdBatchEnd, }; update_semantics_custom_action_callback(&batch_end_sentinel, user_data); } }; } // Create a callback to notify the embedder of semantic updates // using the deprecated embedder callback 'update_semantics_callback'. flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV2( FlutterUpdateSemanticsCallback update_semantics_callback, void* user_data) { return [update_semantics_callback, user_data]( const flutter::SemanticsNodeUpdates& nodes, const flutter::CustomAccessibilityActionUpdates& actions) { flutter::EmbedderSemanticsUpdate update{nodes, actions}; update_semantics_callback(update.get(), user_data); }; } // Create a callback to notify the embedder of semantic updates // using the new embedder callback 'update_semantics_callback2'. flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV3( FlutterUpdateSemanticsCallback2 update_semantics_callback, void* user_data) { return [update_semantics_callback, user_data]( const flutter::SemanticsNodeUpdates& nodes, const flutter::CustomAccessibilityActionUpdates& actions) { flutter::EmbedderSemanticsUpdate2 update{nodes, actions}; update_semantics_callback(update.get(), user_data); }; } // Creates a callback that receives semantic updates from the engine // and notifies the embedder's callback(s). Returns null if the embedder // did not register any callbacks. flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallback(const FlutterProjectArgs* args, void* user_data) { // There are three variants for the embedder API's semantic update callbacks. // Create a callback that maps to the embedder's desired semantic update API. // // Handle the case where the embedder registered the callback // 'updated_semantics_callback2' if (SAFE_ACCESS(args, update_semantics_callback2, nullptr) != nullptr) { return CreateEmbedderSemanticsUpdateCallbackV3( args->update_semantics_callback2, user_data); } // Handle the case where the embedder registered the deprecated callback // 'update_semantics_callback'. if (SAFE_ACCESS(args, update_semantics_callback, nullptr) != nullptr) { return CreateEmbedderSemanticsUpdateCallbackV2( args->update_semantics_callback, user_data); } // Handle the case where the embedder registered the deprecated callbacks // 'update_semantics_node_callback' and // 'update_semantics_custom_action_callback'. FlutterUpdateSemanticsNodeCallback update_semantics_node_callback = nullptr; if (SAFE_ACCESS(args, update_semantics_node_callback, nullptr) != nullptr) { update_semantics_node_callback = args->update_semantics_node_callback; } FlutterUpdateSemanticsCustomActionCallback update_semantics_custom_action_callback = nullptr; if (SAFE_ACCESS(args, update_semantics_custom_action_callback, nullptr) != nullptr) { update_semantics_custom_action_callback = args->update_semantics_custom_action_callback; } if (update_semantics_node_callback != nullptr || update_semantics_custom_action_callback != nullptr) { return CreateEmbedderSemanticsUpdateCallbackV1( update_semantics_node_callback, update_semantics_custom_action_callback, user_data); } // Handle the case where the embedder registered no callbacks. return nullptr; } FlutterEngineResult FlutterEngineRun(size_t version, const FlutterRendererConfig* config, const FlutterProjectArgs* args, void* user_data, FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) { auto result = FlutterEngineInitialize(version, config, args, user_data, engine_out); if (result != kSuccess) { return result; } return FlutterEngineRunInitialized(*engine_out); } FlutterEngineResult FlutterEngineInitialize(size_t version, const FlutterRendererConfig* config, const FlutterProjectArgs* args, void* user_data, FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) { // Step 0: Figure out arguments for shell creation. if (version != FLUTTER_ENGINE_VERSION) { return LOG_EMBEDDER_ERROR( kInvalidLibraryVersion, "Flutter embedder version mismatch. There has been a breaking change. " "Please consult the changelog and update the embedder."); } if (engine_out == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "The engine out parameter was missing."); } if (args == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "The Flutter project arguments were missing."); } if (SAFE_ACCESS(args, assets_path, nullptr) == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "The assets path in the Flutter project arguments was missing."); } if (SAFE_ACCESS(args, main_path__unused__, nullptr) != nullptr) { FML_LOG(WARNING) << "FlutterProjectArgs.main_path is deprecated and should be set null."; } if (SAFE_ACCESS(args, packages_path__unused__, nullptr) != nullptr) { FML_LOG(WARNING) << "FlutterProjectArgs.packages_path is deprecated and " "should be set null."; } if (!IsRendererValid(config)) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "The renderer configuration was invalid."); } std::string icu_data_path; if (SAFE_ACCESS(args, icu_data_path, nullptr) != nullptr) { icu_data_path = SAFE_ACCESS(args, icu_data_path, nullptr); } if (SAFE_ACCESS(args, persistent_cache_path, nullptr) != nullptr) { std::string persistent_cache_path = SAFE_ACCESS(args, persistent_cache_path, nullptr); flutter::PersistentCache::SetCacheDirectoryPath(persistent_cache_path); } if (SAFE_ACCESS(args, is_persistent_cache_read_only, false)) { flutter::PersistentCache::gIsReadOnly = true; } fml::CommandLine command_line; if (SAFE_ACCESS(args, command_line_argc, 0) != 0 && SAFE_ACCESS(args, command_line_argv, nullptr) != nullptr) { command_line = fml::CommandLineFromArgcArgv( SAFE_ACCESS(args, command_line_argc, 0), SAFE_ACCESS(args, command_line_argv, nullptr)); } flutter::Settings settings = flutter::SettingsFromCommandLine(command_line); if (SAFE_ACCESS(args, aot_data, nullptr)) { if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) || SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) || SAFE_ACCESS(args, isolate_snapshot_data, nullptr) || SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr)) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Multiple AOT sources specified. Embedders should provide either " "*_snapshot_* buffers or aot_data, not both."); } } if (flutter::DartVM::IsRunningPrecompiledCode()) { PopulateAOTSnapshotMappingCallbacks(args, settings); } else { PopulateJITSnapshotMappingCallbacks(args, settings); } settings.icu_data_path = icu_data_path; settings.assets_path = args->assets_path; settings.leak_vm = !SAFE_ACCESS(args, shutdown_dart_vm_when_done, false); settings.old_gen_heap_size = SAFE_ACCESS(args, dart_old_gen_heap_size, -1); if (!flutter::DartVM::IsRunningPrecompiledCode()) { // Verify the assets path contains Dart 2 kernel assets. const std::string kApplicationKernelSnapshotFileName = "kernel_blob.bin"; std::string application_kernel_path = fml::paths::JoinPaths( {settings.assets_path, kApplicationKernelSnapshotFileName}); if (!fml::IsFile(application_kernel_path)) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Not running in AOT mode but could not resolve the kernel binary."); } settings.application_kernel_asset = kApplicationKernelSnapshotFileName; } settings.task_observer_add = [](intptr_t key, const fml::closure& callback) { fml::MessageLoop::GetCurrent().AddTaskObserver(key, callback); }; settings.task_observer_remove = [](intptr_t key) { fml::MessageLoop::GetCurrent().RemoveTaskObserver(key); }; if (SAFE_ACCESS(args, root_isolate_create_callback, nullptr) != nullptr) { VoidCallback callback = SAFE_ACCESS(args, root_isolate_create_callback, nullptr); settings.root_isolate_create_callback = [callback, user_data](const auto& isolate) { callback(user_data); }; } if (SAFE_ACCESS(args, log_message_callback, nullptr) != nullptr) { FlutterLogMessageCallback callback = SAFE_ACCESS(args, log_message_callback, nullptr); settings.log_message_callback = [callback, user_data]( const std::string& tag, const std::string& message) { callback(tag.c_str(), message.c_str(), user_data); }; } if (SAFE_ACCESS(args, log_tag, nullptr) != nullptr) { settings.log_tag = SAFE_ACCESS(args, log_tag, nullptr); } bool has_update_semantics_2_callback = SAFE_ACCESS(args, update_semantics_callback2, nullptr) != nullptr; bool has_update_semantics_callback = SAFE_ACCESS(args, update_semantics_callback, nullptr) != nullptr; bool has_legacy_update_semantics_callback = SAFE_ACCESS(args, update_semantics_node_callback, nullptr) != nullptr || SAFE_ACCESS(args, update_semantics_custom_action_callback, nullptr) != nullptr; int semantic_callback_count = (has_update_semantics_2_callback ? 1 : 0) + (has_update_semantics_callback ? 1 : 0) + (has_legacy_update_semantics_callback ? 1 : 0); if (semantic_callback_count > 1) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Multiple semantics update callbacks provided. " "Embedders should provide either `update_semantics_callback2`, " "`update_semantics_callback`, or both " "`update_semantics_node_callback` and " "`update_semantics_custom_action_callback`."); } flutter::PlatformViewEmbedder::UpdateSemanticsCallback update_semantics_callback = CreateEmbedderSemanticsUpdateCallback(args, user_data); flutter::PlatformViewEmbedder::PlatformMessageResponseCallback platform_message_response_callback = nullptr; if (SAFE_ACCESS(args, platform_message_callback, nullptr) != nullptr) { platform_message_response_callback = [ptr = args->platform_message_callback, user_data](std::unique_ptr<flutter::PlatformMessage> message) { auto handle = new FlutterPlatformMessageResponseHandle(); const FlutterPlatformMessage incoming_message = { sizeof(FlutterPlatformMessage), // struct_size message->channel().c_str(), // channel message->data().GetMapping(), // message message->data().GetSize(), // message_size handle, // response_handle }; handle->message = std::move(message); return ptr(&incoming_message, user_data); }; } flutter::VsyncWaiterEmbedder::VsyncCallback vsync_callback = nullptr; if (SAFE_ACCESS(args, vsync_callback, nullptr) != nullptr) { vsync_callback = [ptr = args->vsync_callback, user_data](intptr_t baton) { return ptr(user_data, baton); }; } flutter::PlatformViewEmbedder::ComputePlatformResolvedLocaleCallback compute_platform_resolved_locale_callback = nullptr; if (SAFE_ACCESS(args, compute_platform_resolved_locale_callback, nullptr) != nullptr) { compute_platform_resolved_locale_callback = [ptr = args->compute_platform_resolved_locale_callback]( const std::vector<std::string>& supported_locales_data) { const size_t number_of_strings_per_locale = 3; size_t locale_count = supported_locales_data.size() / number_of_strings_per_locale; std::vector<FlutterLocale> supported_locales; std::vector<const FlutterLocale*> supported_locales_ptr; for (size_t i = 0; i < locale_count; ++i) { supported_locales.push_back( {.struct_size = sizeof(FlutterLocale), .language_code = supported_locales_data[i * number_of_strings_per_locale + 0] .c_str(), .country_code = supported_locales_data[i * number_of_strings_per_locale + 1] .c_str(), .script_code = supported_locales_data[i * number_of_strings_per_locale + 2] .c_str(), .variant_code = nullptr}); supported_locales_ptr.push_back(&supported_locales[i]); } const FlutterLocale* result = ptr(supported_locales_ptr.data(), locale_count); std::unique_ptr<std::vector<std::string>> out = std::make_unique<std::vector<std::string>>(); if (result) { std::string language_code(SAFE_ACCESS(result, language_code, "")); if (language_code != "") { out->push_back(language_code); out->emplace_back(SAFE_ACCESS(result, country_code, "")); out->emplace_back(SAFE_ACCESS(result, script_code, "")); } } return out; }; } flutter::PlatformViewEmbedder::OnPreEngineRestartCallback on_pre_engine_restart_callback = nullptr; if (SAFE_ACCESS(args, on_pre_engine_restart_callback, nullptr) != nullptr) { on_pre_engine_restart_callback = [ptr = args->on_pre_engine_restart_callback, user_data]() { return ptr(user_data); }; } flutter::PlatformViewEmbedder::ChanneUpdateCallback channel_update_callback = nullptr; if (SAFE_ACCESS(args, channel_update_callback, nullptr) != nullptr) { channel_update_callback = [ptr = args->channel_update_callback, user_data]( const std::string& name, bool listening) { FlutterChannelUpdate update{sizeof(FlutterChannelUpdate), name.c_str(), listening}; ptr(&update, user_data); }; } auto external_view_embedder_result = InferExternalViewEmbedderFromArgs( SAFE_ACCESS(args, compositor, nullptr), settings.enable_impeller); if (external_view_embedder_result.second) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Compositor arguments were invalid."); } flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table = { update_semantics_callback, // platform_message_response_callback, // vsync_callback, // compute_platform_resolved_locale_callback, // on_pre_engine_restart_callback, // channel_update_callback, // }; auto on_create_platform_view = InferPlatformViewCreationCallback( config, user_data, platform_dispatch_table, std::move(external_view_embedder_result.first), settings.enable_impeller); if (!on_create_platform_view) { return LOG_EMBEDDER_ERROR( kInternalInconsistency, "Could not infer platform view creation callback."); } flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer = [](flutter::Shell& shell) { return std::make_unique<flutter::Rasterizer>(shell); }; using ExternalTextureResolver = flutter::EmbedderExternalTextureResolver; std::unique_ptr<ExternalTextureResolver> external_texture_resolver; external_texture_resolver = std::make_unique<ExternalTextureResolver>(); #ifdef SHELL_ENABLE_GL flutter::EmbedderExternalTextureGL::ExternalTextureCallback external_texture_callback; if (config->type == kOpenGL) { const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl; if (SAFE_ACCESS(open_gl_config, gl_external_texture_frame_callback, nullptr) != nullptr) { external_texture_callback = [ptr = open_gl_config->gl_external_texture_frame_callback, user_data]( int64_t texture_identifier, size_t width, size_t height) -> std::unique_ptr<FlutterOpenGLTexture> { std::unique_ptr<FlutterOpenGLTexture> texture = std::make_unique<FlutterOpenGLTexture>(); if (!ptr(user_data, texture_identifier, width, height, texture.get())) { return nullptr; } return texture; }; external_texture_resolver = std::make_unique<ExternalTextureResolver>(external_texture_callback); } } #endif #ifdef SHELL_ENABLE_METAL flutter::EmbedderExternalTextureMetal::ExternalTextureCallback external_texture_metal_callback; if (config->type == kMetal) { const FlutterMetalRendererConfig* metal_config = &config->metal; if (SAFE_ACCESS(metal_config, external_texture_frame_callback, nullptr)) { external_texture_metal_callback = [ptr = metal_config->external_texture_frame_callback, user_data]( int64_t texture_identifier, size_t width, size_t height) -> std::unique_ptr<FlutterMetalExternalTexture> { std::unique_ptr<FlutterMetalExternalTexture> texture = std::make_unique<FlutterMetalExternalTexture>(); texture->struct_size = sizeof(FlutterMetalExternalTexture); if (!ptr(user_data, texture_identifier, width, height, texture.get())) { return nullptr; } return texture; }; external_texture_resolver = std::make_unique<ExternalTextureResolver>( external_texture_metal_callback); } } #endif auto custom_task_runners = SAFE_ACCESS(args, custom_task_runners, nullptr); auto thread_config_callback = [&custom_task_runners]( const fml::Thread::ThreadConfig& config) { fml::Thread::SetCurrentThreadName(config); if (!custom_task_runners || !custom_task_runners->thread_priority_setter) { return; } FlutterThreadPriority priority = FlutterThreadPriority::kNormal; switch (config.priority) { case fml::Thread::ThreadPriority::kBackground: priority = FlutterThreadPriority::kBackground; break; case fml::Thread::ThreadPriority::kNormal: priority = FlutterThreadPriority::kNormal; break; case fml::Thread::ThreadPriority::kDisplay: priority = FlutterThreadPriority::kDisplay; break; case fml::Thread::ThreadPriority::kRaster: priority = FlutterThreadPriority::kRaster; break; } custom_task_runners->thread_priority_setter(priority); }; auto thread_host = flutter::EmbedderThreadHost::CreateEmbedderOrEngineManagedThreadHost( custom_task_runners, thread_config_callback); if (!thread_host || !thread_host->IsValid()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Could not set up or infer thread configuration " "to run the Flutter engine on."); } auto task_runners = thread_host->GetTaskRunners(); if (!task_runners.IsValid()) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Task runner configuration was invalid."); } auto run_configuration = flutter::RunConfiguration::InferFromSettings(settings); if (SAFE_ACCESS(args, custom_dart_entrypoint, nullptr) != nullptr) { auto dart_entrypoint = std::string{args->custom_dart_entrypoint}; if (!dart_entrypoint.empty()) { run_configuration.SetEntrypoint(std::move(dart_entrypoint)); } } if (SAFE_ACCESS(args, dart_entrypoint_argc, 0) > 0) { if (SAFE_ACCESS(args, dart_entrypoint_argv, nullptr) == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Could not determine Dart entrypoint arguments " "as dart_entrypoint_argc " "was set, but dart_entrypoint_argv was null."); } std::vector<std::string> arguments(args->dart_entrypoint_argc); for (int i = 0; i < args->dart_entrypoint_argc; ++i) { arguments[i] = std::string{args->dart_entrypoint_argv[i]}; } run_configuration.SetEntrypointArgs(std::move(arguments)); } if (!run_configuration.IsValid()) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Could not infer the Flutter project to run from given arguments."); } // Create the engine but don't launch the shell or run the root isolate. auto embedder_engine = std::make_unique<flutter::EmbedderEngine>( std::move(thread_host), // std::move(task_runners), // std::move(settings), // std::move(run_configuration), // on_create_platform_view, // on_create_rasterizer, // std::move(external_texture_resolver) // ); // Release the ownership of the embedder engine to the caller. *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>( embedder_engine.release()); return kSuccess; } FlutterEngineResult FlutterEngineRunInitialized( FLUTTER_API_SYMBOL(FlutterEngine) engine) { if (!engine) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine); // The engine must not already be running. Initialize may only be called // once on an engine instance. if (embedder_engine->IsValid()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } // Step 1: Launch the shell. if (!embedder_engine->LaunchShell()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Could not launch the engine using supplied " "initialization arguments."); } // Step 2: Tell the platform view to initialize itself. if (!embedder_engine->NotifyCreated()) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not create platform view components."); } // Step 3: Launch the root isolate. if (!embedder_engine->RunRootIsolate()) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Could not run the root isolate of the Flutter application using the " "project arguments specified."); } return kSuccess; } FLUTTER_EXPORT FlutterEngineResult FlutterEngineRemoveView(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterRemoveViewInfo* info) { if (!engine) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } if (!info || !info->remove_view_callback) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Remove view info handle was invalid."); } if (info->view_id == kFlutterImplicitViewId) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Remove view info was invalid. The implicit view cannot be removed."); } // The engine must be running to remove a view. auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine); if (!embedder_engine->IsValid()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } flutter::Shell::RemoveViewCallback callback = [c_callback = info->remove_view_callback, user_data = info->user_data](bool removed) { FlutterRemoveViewResult result = {}; result.struct_size = sizeof(FlutterRemoveViewResult); result.removed = removed; result.user_data = user_data; c_callback(&result); }; embedder_engine->GetShell().RemoveView(info->view_id, callback); return kSuccess; } FLUTTER_EXPORT FlutterEngineResult FlutterEngineDeinitialize(FLUTTER_API_SYMBOL(FlutterEngine) engine) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine); embedder_engine->NotifyDestroyed(); embedder_engine->CollectShell(); return kSuccess; } FlutterEngineResult FlutterEngineShutdown(FLUTTER_API_SYMBOL(FlutterEngine) engine) { auto result = FlutterEngineDeinitialize(engine); if (result != kSuccess) { return result; } auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine); delete embedder_engine; return kSuccess; } FlutterEngineResult FlutterEngineSendWindowMetricsEvent( FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterWindowMetricsEvent* flutter_metrics) { if (engine == nullptr || flutter_metrics == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } FlutterViewId view_id = SAFE_ACCESS(flutter_metrics, view_id, kFlutterImplicitViewId); flutter::ViewportMetrics metrics; metrics.physical_width = SAFE_ACCESS(flutter_metrics, width, 0.0); metrics.physical_height = SAFE_ACCESS(flutter_metrics, height, 0.0); metrics.device_pixel_ratio = SAFE_ACCESS(flutter_metrics, pixel_ratio, 1.0); metrics.physical_view_inset_top = SAFE_ACCESS(flutter_metrics, physical_view_inset_top, 0.0); metrics.physical_view_inset_right = SAFE_ACCESS(flutter_metrics, physical_view_inset_right, 0.0); metrics.physical_view_inset_bottom = SAFE_ACCESS(flutter_metrics, physical_view_inset_bottom, 0.0); metrics.physical_view_inset_left = SAFE_ACCESS(flutter_metrics, physical_view_inset_left, 0.0); metrics.display_id = SAFE_ACCESS(flutter_metrics, display_id, 0); if (metrics.device_pixel_ratio <= 0.0) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Device pixel ratio was invalid. It must be greater than zero."); } if (metrics.physical_view_inset_top < 0 || metrics.physical_view_inset_right < 0 || metrics.physical_view_inset_bottom < 0 || metrics.physical_view_inset_left < 0) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Physical view insets are invalid. They must be non-negative."); } if (metrics.physical_view_inset_top > metrics.physical_height || metrics.physical_view_inset_right > metrics.physical_width || metrics.physical_view_inset_bottom > metrics.physical_height || metrics.physical_view_inset_left > metrics.physical_width) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Physical view insets are invalid. They cannot " "be greater than physical height or width."); } return reinterpret_cast<flutter::EmbedderEngine*>(engine)->SetViewportMetrics( view_id, metrics) ? kSuccess : LOG_EMBEDDER_ERROR(kInvalidArguments, "Viewport metrics were invalid."); } // Returns the flutter::PointerData::Change for the given FlutterPointerPhase. inline flutter::PointerData::Change ToPointerDataChange( FlutterPointerPhase phase) { switch (phase) { case kCancel: return flutter::PointerData::Change::kCancel; case kUp: return flutter::PointerData::Change::kUp; case kDown: return flutter::PointerData::Change::kDown; case kMove: return flutter::PointerData::Change::kMove; case kAdd: return flutter::PointerData::Change::kAdd; case kRemove: return flutter::PointerData::Change::kRemove; case kHover: return flutter::PointerData::Change::kHover; case kPanZoomStart: return flutter::PointerData::Change::kPanZoomStart; case kPanZoomUpdate: return flutter::PointerData::Change::kPanZoomUpdate; case kPanZoomEnd: return flutter::PointerData::Change::kPanZoomEnd; } return flutter::PointerData::Change::kCancel; } // Returns the flutter::PointerData::DeviceKind for the given // FlutterPointerDeviceKind. inline flutter::PointerData::DeviceKind ToPointerDataKind( FlutterPointerDeviceKind device_kind) { switch (device_kind) { case kFlutterPointerDeviceKindMouse: return flutter::PointerData::DeviceKind::kMouse; case kFlutterPointerDeviceKindTouch: return flutter::PointerData::DeviceKind::kTouch; case kFlutterPointerDeviceKindStylus: return flutter::PointerData::DeviceKind::kStylus; case kFlutterPointerDeviceKindTrackpad: return flutter::PointerData::DeviceKind::kTrackpad; } return flutter::PointerData::DeviceKind::kMouse; } // Returns the flutter::PointerData::SignalKind for the given // FlutterPointerSignaKind. inline flutter::PointerData::SignalKind ToPointerDataSignalKind( FlutterPointerSignalKind kind) { switch (kind) { case kFlutterPointerSignalKindNone: return flutter::PointerData::SignalKind::kNone; case kFlutterPointerSignalKindScroll: return flutter::PointerData::SignalKind::kScroll; case kFlutterPointerSignalKindScrollInertiaCancel: return flutter::PointerData::SignalKind::kScrollInertiaCancel; case kFlutterPointerSignalKindScale: return flutter::PointerData::SignalKind::kScale; } return flutter::PointerData::SignalKind::kNone; } // Returns the buttons to synthesize for a PointerData from a // FlutterPointerEvent with no type or buttons set. inline int64_t PointerDataButtonsForLegacyEvent( flutter::PointerData::Change change) { switch (change) { case flutter::PointerData::Change::kDown: case flutter::PointerData::Change::kMove: // These kinds of change must have a non-zero `buttons`, otherwise // gesture recognizers will ignore these events. return flutter::kPointerButtonMousePrimary; case flutter::PointerData::Change::kCancel: case flutter::PointerData::Change::kAdd: case flutter::PointerData::Change::kRemove: case flutter::PointerData::Change::kHover: case flutter::PointerData::Change::kUp: case flutter::PointerData::Change::kPanZoomStart: case flutter::PointerData::Change::kPanZoomUpdate: case flutter::PointerData::Change::kPanZoomEnd: return 0; } return 0; } FlutterEngineResult FlutterEngineSendPointerEvent( FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPointerEvent* pointers, size_t events_count) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } if (pointers == nullptr || events_count == 0) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid pointer events."); } auto packet = std::make_unique<flutter::PointerDataPacket>(events_count); const FlutterPointerEvent* current = pointers; for (size_t i = 0; i < events_count; ++i) { flutter::PointerData pointer_data; pointer_data.Clear(); // this is currely in use only on android embedding. pointer_data.embedder_id = 0; pointer_data.time_stamp = SAFE_ACCESS(current, timestamp, 0); pointer_data.change = ToPointerDataChange( SAFE_ACCESS(current, phase, FlutterPointerPhase::kCancel)); pointer_data.physical_x = SAFE_ACCESS(current, x, 0.0); pointer_data.physical_y = SAFE_ACCESS(current, y, 0.0); // Delta will be generated in pointer_data_packet_converter.cc. pointer_data.physical_delta_x = 0.0; pointer_data.physical_delta_y = 0.0; pointer_data.device = SAFE_ACCESS(current, device, 0); // Pointer identifier will be generated in // pointer_data_packet_converter.cc. pointer_data.pointer_identifier = 0; pointer_data.signal_kind = ToPointerDataSignalKind( SAFE_ACCESS(current, signal_kind, kFlutterPointerSignalKindNone)); pointer_data.scroll_delta_x = SAFE_ACCESS(current, scroll_delta_x, 0.0); pointer_data.scroll_delta_y = SAFE_ACCESS(current, scroll_delta_y, 0.0); FlutterPointerDeviceKind device_kind = SAFE_ACCESS(current, device_kind, 0); // For backwards compatibility with embedders written before the device // kind and buttons were exposed, if the device kind is not set treat it // as a mouse, with a synthesized primary button state based on the phase. if (device_kind == 0) { pointer_data.kind = flutter::PointerData::DeviceKind::kMouse; pointer_data.buttons = PointerDataButtonsForLegacyEvent(pointer_data.change); } else { pointer_data.kind = ToPointerDataKind(device_kind); if (pointer_data.kind == flutter::PointerData::DeviceKind::kTouch) { // For touch events, set the button internally rather than requiring // it at the API level, since it's a confusing construction to expose. if (pointer_data.change == flutter::PointerData::Change::kDown || pointer_data.change == flutter::PointerData::Change::kMove) { pointer_data.buttons = flutter::kPointerButtonTouchContact; } } else { // Buttons use the same mask values, so pass them through directly. pointer_data.buttons = SAFE_ACCESS(current, buttons, 0); } } pointer_data.pan_x = SAFE_ACCESS(current, pan_x, 0.0); pointer_data.pan_y = SAFE_ACCESS(current, pan_y, 0.0); // Delta will be generated in pointer_data_packet_converter.cc. pointer_data.pan_delta_x = 0.0; pointer_data.pan_delta_y = 0.0; pointer_data.scale = SAFE_ACCESS(current, scale, 0.0); pointer_data.rotation = SAFE_ACCESS(current, rotation, 0.0); pointer_data.view_id = SAFE_ACCESS(current, view_id, kFlutterImplicitViewId); packet->SetPointerData(i, pointer_data); current = reinterpret_cast<const FlutterPointerEvent*>( reinterpret_cast<const uint8_t*>(current) + current->struct_size); } return reinterpret_cast<flutter::EmbedderEngine*>(engine) ->DispatchPointerDataPacket(std::move(packet)) ? kSuccess : LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not dispatch pointer events to the " "running Flutter application."); } static inline flutter::KeyEventType MapKeyEventType( FlutterKeyEventType event_kind) { switch (event_kind) { case kFlutterKeyEventTypeUp: return flutter::KeyEventType::kUp; case kFlutterKeyEventTypeDown: return flutter::KeyEventType::kDown; case kFlutterKeyEventTypeRepeat: return flutter::KeyEventType::kRepeat; } return flutter::KeyEventType::kUp; } static inline flutter::KeyEventDeviceType MapKeyEventDeviceType( FlutterKeyEventDeviceType event_kind) { switch (event_kind) { case kFlutterKeyEventDeviceTypeKeyboard: return flutter::KeyEventDeviceType::kKeyboard; case kFlutterKeyEventDeviceTypeDirectionalPad: return flutter::KeyEventDeviceType::kDirectionalPad; case kFlutterKeyEventDeviceTypeGamepad: return flutter::KeyEventDeviceType::kGamepad; case kFlutterKeyEventDeviceTypeJoystick: return flutter::KeyEventDeviceType::kJoystick; case kFlutterKeyEventDeviceTypeHdmi: return flutter::KeyEventDeviceType::kHdmi; } return flutter::KeyEventDeviceType::kKeyboard; } // Send a platform message to the framework. // // The `data_callback` will be invoked with `user_data`, and must not be empty. static FlutterEngineResult InternalSendPlatformMessage( FLUTTER_API_SYMBOL(FlutterEngine) engine, const char* channel, const uint8_t* data, size_t size, FlutterDataCallback data_callback, void* user_data) { FlutterEngineResult result; FlutterPlatformMessageResponseHandle* response_handle; result = FlutterPlatformMessageCreateResponseHandle( engine, data_callback, user_data, &response_handle); if (result != kSuccess) { return result; } const FlutterPlatformMessage message = { sizeof(FlutterPlatformMessage), // struct_size channel, // channel data, // message size, // message_size response_handle, // response_handle }; result = FlutterEngineSendPlatformMessage(engine, &message); // Whether `SendPlatformMessage` succeeds or not, the response handle must be // released. FlutterEngineResult release_result = FlutterPlatformMessageReleaseResponseHandle(engine, response_handle); if (result != kSuccess) { return result; } return release_result; } FlutterEngineResult FlutterEngineSendKeyEvent(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterKeyEvent* event, FlutterKeyEventCallback callback, void* user_data) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } if (event == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid key event."); } const char* character = SAFE_ACCESS(event, character, nullptr); flutter::KeyData key_data; key_data.Clear(); key_data.timestamp = static_cast<uint64_t>(SAFE_ACCESS(event, timestamp, 0)); key_data.type = MapKeyEventType( SAFE_ACCESS(event, type, FlutterKeyEventType::kFlutterKeyEventTypeUp)); key_data.physical = SAFE_ACCESS(event, physical, 0); key_data.logical = SAFE_ACCESS(event, logical, 0); key_data.synthesized = SAFE_ACCESS(event, synthesized, false); key_data.device_type = MapKeyEventDeviceType(SAFE_ACCESS( event, device_type, FlutterKeyEventDeviceType::kFlutterKeyEventDeviceTypeKeyboard)); auto packet = std::make_unique<flutter::KeyDataPacket>(key_data, character); struct MessageData { FlutterKeyEventCallback callback; void* user_data; }; MessageData* message_data = new MessageData{.callback = callback, .user_data = user_data}; return InternalSendPlatformMessage( engine, kFlutterKeyDataChannel, packet->data().data(), packet->data().size(), [](const uint8_t* data, size_t size, void* user_data) { auto message_data = std::unique_ptr<MessageData>( reinterpret_cast<MessageData*>(user_data)); if (message_data->callback == nullptr) { return; } bool handled = false; if (size == 1) { handled = *data != 0; } message_data->callback(handled, message_data->user_data); }, message_data); } FlutterEngineResult FlutterEngineSendPlatformMessage( FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessage* flutter_message) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (flutter_message == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid message argument."); } if (SAFE_ACCESS(flutter_message, channel, nullptr) == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Message argument did not specify a valid channel."); } size_t message_size = SAFE_ACCESS(flutter_message, message_size, 0); const uint8_t* message_data = SAFE_ACCESS(flutter_message, message, nullptr); if (message_size != 0 && message_data == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Message size was non-zero but the message data was nullptr."); } const FlutterPlatformMessageResponseHandle* response_handle = SAFE_ACCESS(flutter_message, response_handle, nullptr); fml::RefPtr<flutter::PlatformMessageResponse> response; if (response_handle && response_handle->message) { response = response_handle->message->response(); } std::unique_ptr<flutter::PlatformMessage> message; if (message_size == 0) { message = std::make_unique<flutter::PlatformMessage>( flutter_message->channel, response); } else { message = std::make_unique<flutter::PlatformMessage>( flutter_message->channel, fml::MallocMapping::Copy(message_data, message_size), response); } return reinterpret_cast<flutter::EmbedderEngine*>(engine) ->SendPlatformMessage(std::move(message)) ? kSuccess : LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not send a message to the running " "Flutter application."); } FlutterEngineResult FlutterPlatformMessageCreateResponseHandle( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterDataCallback data_callback, void* user_data, FlutterPlatformMessageResponseHandle** response_out) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } if (data_callback == nullptr || response_out == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Data callback or the response handle was invalid."); } flutter::EmbedderPlatformMessageResponse::Callback response_callback = [user_data, data_callback](const uint8_t* data, size_t size) { data_callback(data, size, user_data); }; auto platform_task_runner = reinterpret_cast<flutter::EmbedderEngine*>(engine) ->GetTaskRunners() .GetPlatformTaskRunner(); auto handle = new FlutterPlatformMessageResponseHandle(); handle->message = std::make_unique<flutter::PlatformMessage>( "", // The channel is empty and unused as the response handle is going // to referenced directly in the |FlutterEngineSendPlatformMessage| // with the container message discarded. fml::MakeRefCounted<flutter::EmbedderPlatformMessageResponse>( std::move(platform_task_runner), response_callback)); *response_out = handle; return kSuccess; } FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterPlatformMessageResponseHandle* response) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (response == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid response handle."); } delete response; return kSuccess; } // Note: This can execute on any thread. FlutterEngineResult FlutterEngineSendPlatformMessageResponse( FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessageResponseHandle* handle, const uint8_t* data, size_t data_length) { if (data_length != 0 && data == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Data size was non zero but the pointer to the data was null."); } auto response = handle->message->response(); if (response) { if (data_length == 0) { response->CompleteEmpty(); } else { response->Complete(std::make_unique<fml::DataMapping>( std::vector<uint8_t>({data, data + data_length}))); } } delete handle; return kSuccess; } FlutterEngineResult __FlutterEngineFlushPendingTasksNow() { fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); return kSuccess; } FlutterEngineResult FlutterEngineRegisterExternalTexture( FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } if (texture_identifier == 0) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Texture identifier was invalid."); } if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->RegisterTexture( texture_identifier)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not register the specified texture."); } return kSuccess; } FlutterEngineResult FlutterEngineUnregisterExternalTexture( FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid."); } if (texture_identifier == 0) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Texture identifier was invalid."); } if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->UnregisterTexture( texture_identifier)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not un-register the specified texture."); } return kSuccess; } FlutterEngineResult FlutterEngineMarkExternalTextureFrameAvailable( FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (texture_identifier == 0) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid texture identifier."); } if (!reinterpret_cast<flutter::EmbedderEngine*>(engine) ->MarkTextureFrameAvailable(texture_identifier)) { return LOG_EMBEDDER_ERROR( kInternalInconsistency, "Could not mark the texture frame as being available."); } return kSuccess; } FlutterEngineResult FlutterEngineUpdateSemanticsEnabled( FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->SetSemanticsEnabled( enabled)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not update semantics state."); } return kSuccess; } FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterAccessibilityFeature flags) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (!reinterpret_cast<flutter::EmbedderEngine*>(engine) ->SetAccessibilityFeatures(flags)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not update accessibility features."); } return kSuccess; } FlutterEngineResult FlutterEngineDispatchSemanticsAction( FLUTTER_API_SYMBOL(FlutterEngine) engine, uint64_t node_id, FlutterSemanticsAction action, const uint8_t* data, size_t data_length) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } auto engine_action = static_cast<flutter::SemanticsAction>(action); if (!reinterpret_cast<flutter::EmbedderEngine*>(engine) ->DispatchSemanticsAction( node_id, engine_action, fml::MallocMapping::Copy(data, data_length))) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not dispatch semantics action."); } return kSuccess; } FlutterEngineResult FlutterEngineOnVsync(FLUTTER_API_SYMBOL(FlutterEngine) engine, intptr_t baton, uint64_t frame_start_time_nanos, uint64_t frame_target_time_nanos) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } TRACE_EVENT0("flutter", "FlutterEngineOnVsync"); auto start_time = fml::TimePoint::FromEpochDelta( fml::TimeDelta::FromNanoseconds(frame_start_time_nanos)); auto target_time = fml::TimePoint::FromEpochDelta( fml::TimeDelta::FromNanoseconds(frame_target_time_nanos)); if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->OnVsyncEvent( baton, start_time, target_time)) { return LOG_EMBEDDER_ERROR( kInternalInconsistency, "Could not notify the running engine instance of a Vsync event."); } return kSuccess; } FlutterEngineResult FlutterEngineReloadSystemFonts( FLUTTER_API_SYMBOL(FlutterEngine) engine) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } TRACE_EVENT0("flutter", "FlutterEngineReloadSystemFonts"); if (!reinterpret_cast<flutter::EmbedderEngine*>(engine) ->ReloadSystemFonts()) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not reload system fonts."); } return kSuccess; } void FlutterEngineTraceEventDurationBegin(const char* name) { fml::tracing::TraceEvent0("flutter", name, /*flow_id_count=*/0, /*flow_ids=*/nullptr); } void FlutterEngineTraceEventDurationEnd(const char* name) { fml::tracing::TraceEventEnd(name); } void FlutterEngineTraceEventInstant(const char* name) { fml::tracing::TraceEventInstant0("flutter", name, /*flow_id_count=*/0, /*flow_ids=*/nullptr); } FlutterEngineResult FlutterEnginePostRenderThreadTask( FLUTTER_API_SYMBOL(FlutterEngine) engine, VoidCallback callback, void* baton) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (callback == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Render thread callback was null."); } auto task = [callback, baton]() { callback(baton); }; return reinterpret_cast<flutter::EmbedderEngine*>(engine) ->PostRenderThreadTask(task) ? kSuccess : LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not post the render thread task."); } uint64_t FlutterEngineGetCurrentTime() { return fml::TimePoint::Now().ToEpochDelta().ToNanoseconds(); } FlutterEngineResult FlutterEngineRunTask(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterTask* task) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } return reinterpret_cast<flutter::EmbedderEngine*>(engine)->RunTask(task) ? kSuccess : LOG_EMBEDDER_ERROR(kInvalidArguments, "Could not run the specified task."); } static bool DispatchJSONPlatformMessage(FLUTTER_API_SYMBOL(FlutterEngine) engine, const rapidjson::Document& document, const std::string& channel_name) { if (channel_name.empty()) { return false; } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); if (!document.Accept(writer)) { return false; } const char* message = buffer.GetString(); if (message == nullptr || buffer.GetSize() == 0) { return false; } auto platform_message = std::make_unique<flutter::PlatformMessage>( channel_name.c_str(), // channel fml::MallocMapping::Copy(message, buffer.GetSize()), // message nullptr // response ); return reinterpret_cast<flutter::EmbedderEngine*>(engine) ->SendPlatformMessage(std::move(platform_message)); } FlutterEngineResult FlutterEngineUpdateLocales(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterLocale** locales, size_t locales_count) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (locales_count == 0) { return kSuccess; } if (locales == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "No locales were specified."); } rapidjson::Document document; auto& allocator = document.GetAllocator(); document.SetObject(); document.AddMember("method", "setLocale", allocator); rapidjson::Value args(rapidjson::kArrayType); args.Reserve(locales_count * 4, allocator); for (size_t i = 0; i < locales_count; ++i) { const FlutterLocale* locale = locales[i]; const char* language_code_str = SAFE_ACCESS(locale, language_code, nullptr); if (language_code_str == nullptr || ::strlen(language_code_str) == 0) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Language code is required but not present in FlutterLocale."); } const char* country_code_str = SAFE_ACCESS(locale, country_code, ""); const char* script_code_str = SAFE_ACCESS(locale, script_code, ""); const char* variant_code_str = SAFE_ACCESS(locale, variant_code, ""); rapidjson::Value language_code, country_code, script_code, variant_code; language_code.SetString(language_code_str, allocator); country_code.SetString(country_code_str ? country_code_str : "", allocator); script_code.SetString(script_code_str ? script_code_str : "", allocator); variant_code.SetString(variant_code_str ? variant_code_str : "", allocator); // Required. args.PushBack(language_code, allocator); args.PushBack(country_code, allocator); args.PushBack(script_code, allocator); args.PushBack(variant_code, allocator); } document.AddMember("args", args, allocator); return DispatchJSONPlatformMessage(engine, document, "flutter/localization") ? kSuccess : LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not send message to update locale of " "a running Flutter application."); } bool FlutterEngineRunsAOTCompiledDartCode(void) { return flutter::DartVM::IsRunningPrecompiledCode(); } FlutterEngineResult FlutterEnginePostDartObject( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterEngineDartPort port, const FlutterEngineDartObject* object) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->IsValid()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine not running."); } if (port == ILLEGAL_PORT) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Attempted to post to an illegal port."); } if (object == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid Dart object to post."); } Dart_CObject dart_object = {}; fml::ScopedCleanupClosure typed_data_finalizer; switch (object->type) { case kFlutterEngineDartObjectTypeNull: dart_object.type = Dart_CObject_kNull; break; case kFlutterEngineDartObjectTypeBool: dart_object.type = Dart_CObject_kBool; dart_object.value.as_bool = object->bool_value; break; case kFlutterEngineDartObjectTypeInt32: dart_object.type = Dart_CObject_kInt32; dart_object.value.as_int32 = object->int32_value; break; case kFlutterEngineDartObjectTypeInt64: dart_object.type = Dart_CObject_kInt64; dart_object.value.as_int64 = object->int64_value; break; case kFlutterEngineDartObjectTypeDouble: dart_object.type = Dart_CObject_kDouble; dart_object.value.as_double = object->double_value; break; case kFlutterEngineDartObjectTypeString: if (object->string_value == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "kFlutterEngineDartObjectTypeString must be " "a null terminated string but was null."); } dart_object.type = Dart_CObject_kString; dart_object.value.as_string = const_cast<char*>(object->string_value); break; case kFlutterEngineDartObjectTypeBuffer: { auto* buffer = SAFE_ACCESS(object->buffer_value, buffer, nullptr); if (buffer == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "kFlutterEngineDartObjectTypeBuffer must " "specify a buffer but found nullptr."); } auto buffer_size = SAFE_ACCESS(object->buffer_value, buffer_size, 0); auto callback = SAFE_ACCESS(object->buffer_value, buffer_collect_callback, nullptr); auto user_data = SAFE_ACCESS(object->buffer_value, user_data, nullptr); // The user has provided a callback, let them manage the lifecycle of // the underlying data. If not, copy it out from the provided buffer. if (callback == nullptr) { dart_object.type = Dart_CObject_kTypedData; dart_object.value.as_typed_data.type = Dart_TypedData_kUint8; dart_object.value.as_typed_data.length = buffer_size; dart_object.value.as_typed_data.values = buffer; } else { struct ExternalTypedDataPeer { void* user_data = nullptr; VoidCallback trampoline = nullptr; }; auto peer = new ExternalTypedDataPeer(); peer->user_data = user_data; peer->trampoline = callback; // This finalizer is set so that in case of failure of the // Dart_PostCObject below, we collect the peer. The embedder is still // responsible for collecting the buffer in case of non-kSuccess // returns from this method. This finalizer must be released in case // of kSuccess returns from this method. typed_data_finalizer.SetClosure([peer]() { // This is the tiny object we use as the peer to the Dart call so // that we can attach the a trampoline to the embedder supplied // callback. In case of error, we need to collect this object lest // we introduce a tiny leak. delete peer; }); dart_object.type = Dart_CObject_kExternalTypedData; dart_object.value.as_external_typed_data.type = Dart_TypedData_kUint8; dart_object.value.as_external_typed_data.length = buffer_size; dart_object.value.as_external_typed_data.data = buffer; dart_object.value.as_external_typed_data.peer = peer; dart_object.value.as_external_typed_data.callback = +[](void* unused_isolate_callback_data, void* peer) { auto typed_peer = reinterpret_cast<ExternalTypedDataPeer*>(peer); typed_peer->trampoline(typed_peer->user_data); delete typed_peer; }; } } break; default: return LOG_EMBEDDER_ERROR( kInvalidArguments, "Invalid FlutterEngineDartObjectType type specified."); } if (!Dart_PostCObject(port, &dart_object)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Could not post the object to the Dart VM."); } // On a successful call, the VM takes ownership of and is responsible for // invoking the finalizer. typed_data_finalizer.Release(); return kSuccess; } FlutterEngineResult FlutterEngineNotifyLowMemoryWarning( FLUTTER_API_SYMBOL(FlutterEngine) raw_engine) { auto engine = reinterpret_cast<flutter::EmbedderEngine*>(raw_engine); if (engine == nullptr || !engine->IsValid()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine was invalid."); } engine->GetShell().NotifyLowMemoryWarning(); rapidjson::Document document; auto& allocator = document.GetAllocator(); document.SetObject(); document.AddMember("type", "memoryPressure", allocator); return DispatchJSONPlatformMessage(raw_engine, document, "flutter/system") ? kSuccess : LOG_EMBEDDER_ERROR( kInternalInconsistency, "Could not dispatch the low memory notification message."); } FlutterEngineResult FlutterEnginePostCallbackOnAllNativeThreads( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterNativeThreadCallback callback, void* user_data) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (callback == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid native thread callback."); } return reinterpret_cast<flutter::EmbedderEngine*>(engine) ->PostTaskOnEngineManagedNativeThreads( [callback, user_data](FlutterNativeThreadType type) { callback(type, user_data); }) ? kSuccess : LOG_EMBEDDER_ERROR(kInvalidArguments, "Internal error while attempting to post " "tasks to all threads."); } namespace { static bool ValidDisplayConfiguration(const FlutterEngineDisplay* displays, size_t display_count) { std::set<FlutterEngineDisplayId> display_ids; for (size_t i = 0; i < display_count; i++) { if (displays[i].single_display && display_count != 1) { return false; } display_ids.insert(displays[i].display_id); } return display_ids.size() == display_count; } } // namespace FlutterEngineResult FlutterEngineNotifyDisplayUpdate( FLUTTER_API_SYMBOL(FlutterEngine) raw_engine, const FlutterEngineDisplaysUpdateType update_type, const FlutterEngineDisplay* embedder_displays, size_t display_count) { if (raw_engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (!ValidDisplayConfiguration(embedder_displays, display_count)) { return LOG_EMBEDDER_ERROR( kInvalidArguments, "Invalid FlutterEngineDisplay configuration specified."); } auto engine = reinterpret_cast<flutter::EmbedderEngine*>(raw_engine); switch (update_type) { case kFlutterEngineDisplaysUpdateTypeStartup: { std::vector<std::unique_ptr<flutter::Display>> displays; const auto* display = embedder_displays; for (size_t i = 0; i < display_count; i++) { displays.push_back(std::make_unique<flutter::Display>( SAFE_ACCESS(display, display_id, i), // SAFE_ACCESS(display, refresh_rate, 0), // SAFE_ACCESS(display, width, 0), // SAFE_ACCESS(display, height, 0), // SAFE_ACCESS(display, device_pixel_ratio, 1))); display = reinterpret_cast<const FlutterEngineDisplay*>( reinterpret_cast<const uint8_t*>(display) + display->struct_size); } engine->GetShell().OnDisplayUpdates(std::move(displays)); return kSuccess; } default: return LOG_EMBEDDER_ERROR( kInvalidArguments, "Invalid FlutterEngineDisplaysUpdateType type specified."); } } FlutterEngineResult FlutterEngineScheduleFrame(FLUTTER_API_SYMBOL(FlutterEngine) engine) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } return reinterpret_cast<flutter::EmbedderEngine*>(engine)->ScheduleFrame() ? kSuccess : LOG_EMBEDDER_ERROR(kInvalidArguments, "Could not schedule frame."); } FlutterEngineResult FlutterEngineSetNextFrameCallback( FLUTTER_API_SYMBOL(FlutterEngine) engine, VoidCallback callback, void* user_data) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle."); } if (callback == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Next frame callback was null."); } flutter::EmbedderEngine* embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine); fml::WeakPtr<flutter::PlatformView> weak_platform_view = embedder_engine->GetShell().GetPlatformView(); if (!weak_platform_view) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, "Platform view unavailable."); } weak_platform_view->SetNextFrameCallback( [callback, user_data]() { callback(user_data); }); return kSuccess; } FlutterEngineResult FlutterEngineGetProcAddresses( FlutterEngineProcTable* table) { if (!table) { return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null table specified."); } #define SET_PROC(member, function) \ if (STRUCT_HAS_MEMBER(table, member)) { \ table->member = &function; \ } SET_PROC(CreateAOTData, FlutterEngineCreateAOTData); SET_PROC(CollectAOTData, FlutterEngineCollectAOTData); SET_PROC(Run, FlutterEngineRun); SET_PROC(Shutdown, FlutterEngineShutdown); SET_PROC(Initialize, FlutterEngineInitialize); SET_PROC(Deinitialize, FlutterEngineDeinitialize); SET_PROC(RunInitialized, FlutterEngineRunInitialized); SET_PROC(SendWindowMetricsEvent, FlutterEngineSendWindowMetricsEvent); SET_PROC(SendPointerEvent, FlutterEngineSendPointerEvent); SET_PROC(SendKeyEvent, FlutterEngineSendKeyEvent); SET_PROC(SendPlatformMessage, FlutterEngineSendPlatformMessage); SET_PROC(PlatformMessageCreateResponseHandle, FlutterPlatformMessageCreateResponseHandle); SET_PROC(PlatformMessageReleaseResponseHandle, FlutterPlatformMessageReleaseResponseHandle); SET_PROC(SendPlatformMessageResponse, FlutterEngineSendPlatformMessageResponse); SET_PROC(RegisterExternalTexture, FlutterEngineRegisterExternalTexture); SET_PROC(UnregisterExternalTexture, FlutterEngineUnregisterExternalTexture); SET_PROC(MarkExternalTextureFrameAvailable, FlutterEngineMarkExternalTextureFrameAvailable); SET_PROC(UpdateSemanticsEnabled, FlutterEngineUpdateSemanticsEnabled); SET_PROC(UpdateAccessibilityFeatures, FlutterEngineUpdateAccessibilityFeatures); SET_PROC(DispatchSemanticsAction, FlutterEngineDispatchSemanticsAction); SET_PROC(OnVsync, FlutterEngineOnVsync); SET_PROC(ReloadSystemFonts, FlutterEngineReloadSystemFonts); SET_PROC(TraceEventDurationBegin, FlutterEngineTraceEventDurationBegin); SET_PROC(TraceEventDurationEnd, FlutterEngineTraceEventDurationEnd); SET_PROC(TraceEventInstant, FlutterEngineTraceEventInstant); SET_PROC(PostRenderThreadTask, FlutterEnginePostRenderThreadTask); SET_PROC(GetCurrentTime, FlutterEngineGetCurrentTime); SET_PROC(RunTask, FlutterEngineRunTask); SET_PROC(UpdateLocales, FlutterEngineUpdateLocales); SET_PROC(RunsAOTCompiledDartCode, FlutterEngineRunsAOTCompiledDartCode); SET_PROC(PostDartObject, FlutterEnginePostDartObject); SET_PROC(NotifyLowMemoryWarning, FlutterEngineNotifyLowMemoryWarning); SET_PROC(PostCallbackOnAllNativeThreads, FlutterEnginePostCallbackOnAllNativeThreads); SET_PROC(NotifyDisplayUpdate, FlutterEngineNotifyDisplayUpdate); SET_PROC(ScheduleFrame, FlutterEngineScheduleFrame); SET_PROC(SetNextFrameCallback, FlutterEngineSetNextFrameCallback); #undef SET_PROC return kSuccess; }
engine/shell/platform/embedder/embedder.cc/0
{ "file_path": "engine/shell/platform/embedder/embedder.cc", "repo_id": "engine", "token_count": 52309 }
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. #include "flutter/shell/platform/embedder/embedder.h" // This file is only present to ensure that the public embedder header can be // cleanly included in a C file.
engine/shell/platform/embedder/embedder_include.c/0
{ "file_path": "engine/shell/platform/embedder/embedder_include.c", "repo_id": "engine", "token_count": 89 }
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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_STRUCT_MACROS_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_STRUCT_MACROS_H_ #include <type_traits> // Checks if the given struct contains a member, whether set or not. #define STRUCT_HAS_MEMBER(pointer, member) \ ((offsetof(std::remove_pointer<decltype(pointer)>::type, member) + \ sizeof(pointer->member) <= \ pointer->struct_size)) #define SAFE_ACCESS(pointer, member, default_value) \ ([=]() { \ if (STRUCT_HAS_MEMBER(pointer, member)) { \ return pointer->member; \ } \ return static_cast<decltype(pointer->member)>((default_value)); \ })() /// Checks if the member exists and is non-null. #define SAFE_EXISTS(pointer, member) \ (SAFE_ACCESS(pointer, member, nullptr) != nullptr) /// Checks if exactly one of member1 or member2 exists and is non-null. #define SAFE_EXISTS_ONE_OF(pointer, member1, member2) \ (SAFE_EXISTS(pointer, member1) != SAFE_EXISTS(pointer, member2)) #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_STRUCT_MACROS_H_
engine/shell/platform/embedder/embedder_struct_macros.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_struct_macros.h", "repo_id": "engine", "token_count": 704 }
381
// Copyright 2013 The Flutter 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_TASK_RUNNER_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_TASK_RUNNER_H_ #include <mutex> #include <unordered_map> #include "flutter/fml/macros.h" #include "flutter/fml/task_runner.h" namespace flutter { //------------------------------------------------------------------------------ /// A task runner which delegates responsibility of task execution to an /// embedder. This is done by managing a dispatch table to the embedder. /// class EmbedderTaskRunner final : public fml::TaskRunner { public: //---------------------------------------------------------------------------- /// @brief A /// struct DispatchTable { //-------------------------------------------------------------------------- /// Delegates responsibility of deferred task execution to the embedder. /// Once the embedder gets the task, it must call /// `EmbedderTaskRunner::PostTask` with the supplied `task_baton` on the /// correct thread after the tasks `target_time` point expires. /// std::function<void(EmbedderTaskRunner* task_runner, uint64_t task_baton, fml::TimePoint target_time)> post_task_callback; //-------------------------------------------------------------------------- /// Asks the embedder if tasks posted to it on this task runner via the /// `post_task_callback` will be executed (after task expiry) on the calling /// thread. /// std::function<bool(void)> runs_task_on_current_thread_callback; }; //---------------------------------------------------------------------------- /// @brief Create a task runner with a dispatch table for delegation of /// task runner responsibility to the embedder. When embedders /// specify task runner dispatch tables that service tasks on the /// same thread, they also must ensure that their /// `embedder_idetifier`s match. This allows the engine to /// determine task runner equality without actually posting tasks /// to the task runner. /// /// @param[in] table The task runner dispatch table. /// @param[in] embedder_identifier The embedder identifier /// EmbedderTaskRunner(DispatchTable table, size_t embedder_identifier); // |fml::TaskRunner| ~EmbedderTaskRunner() override; //---------------------------------------------------------------------------- /// @brief The unique identifier provided by the embedder for the task /// runner. Embedders whose dispatch tables service tasks on the /// same underlying OS thread must ensure that their identifiers /// match. This allows the engine to determine task runner /// equality without posting tasks on the thread. /// /// @return The embedder identifier. /// size_t GetEmbedderIdentifier() const; bool PostTask(uint64_t baton); private: const size_t embedder_identifier_; DispatchTable dispatch_table_; std::mutex tasks_mutex_; uint64_t last_baton_ = 0; std::unordered_map<uint64_t, fml::closure> pending_tasks_; fml::TaskQueueId placeholder_id_; // |fml::TaskRunner| void PostTask(const fml::closure& task) override; // |fml::TaskRunner| void PostTaskForTime(const fml::closure& task, fml::TimePoint target_time) override; // |fml::TaskRunner| void PostDelayedTask(const fml::closure& task, fml::TimeDelta delay) override; // |fml::TaskRunner| bool RunsTasksOnCurrentThread() override; // |fml::TaskRunner| fml::TaskQueueId GetTaskQueueId() override; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTaskRunner); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_TASK_RUNNER_H_
engine/shell/platform/embedder/embedder_task_runner.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_task_runner.h", "repo_id": "engine", "token_count": 1298 }
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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_PROC_TABLE_REPLACEMENT_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_PROC_TABLE_REPLACEMENT_H_ #include "flutter/shell/platform/embedder/embedder.h" // Wraps capturing lambas with non-capturing version that can be assigned to // FlutterEngineProcTable entries (by using statics) to facilitate mocking in // tests of code built on top of the embedder API. // // This should *ONLY* be used in unit tests as it is leaky by design. // // |proc| should be the name of an entry in FlutterEngineProcTable, such as // "Initialize". |mock_impl| should be a lamba that replaces its implementation, // taking the same arguments and returning the same type. #define MOCK_ENGINE_PROC(proc, mock_impl) \ ([&]() { \ static std::function< \ std::remove_pointer_t<decltype(FlutterEngineProcTable::proc)>> \ closure; \ closure = mock_impl; \ static auto non_capturing = [](auto... args) { return closure(args...); }; \ return non_capturing; \ })() #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_PROC_TABLE_REPLACEMENT_H_
engine/shell/platform/embedder/test_utils/proc_table_replacement.h/0
{ "file_path": "engine/shell/platform/embedder/test_utils/proc_table_replacement.h", "repo_id": "engine", "token_count": 776 }
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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_GL_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_GL_H_ #include "flutter/fml/macros.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h" namespace flutter { namespace testing { class EmbedderTestCompositorGL : public EmbedderTestCompositor { public: EmbedderTestCompositorGL(SkISize surface_size, sk_sp<GrDirectContext> context); ~EmbedderTestCompositorGL() override; private: bool UpdateOffscrenComposition(const FlutterLayer** layers, size_t layers_count) override; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositorGL); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_GL_H_
engine/shell/platform/embedder/tests/embedder_test_compositor_gl.h/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_compositor_gl.h", "repo_id": "engine", "token_count": 437 }
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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_VULKAN_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_VULKAN_H_ #include <memory> #include "flutter/shell/platform/embedder/tests/embedder_test_context.h" #include "flutter/testing/test_vulkan_context.h" #include "flutter/vulkan/vulkan_application.h" #include "testing/test_vulkan_surface.h" namespace flutter { namespace testing { class EmbedderTestContextVulkan : public EmbedderTestContext { public: explicit EmbedderTestContextVulkan(std::string assets_path = ""); ~EmbedderTestContextVulkan() override; // |EmbedderTestContext| EmbedderTestContextType GetContextType() const override; // |EmbedderTestContext| size_t GetSurfacePresentCount() const override; // |EmbedderTestContext| void SetupCompositor() override; VkImage GetNextImage(const SkISize& size); bool PresentImage(VkImage image); static void* InstanceProcAddr(void* user_data, FlutterVulkanInstanceHandle instance, const char* name); private: std::unique_ptr<TestVulkanSurface> surface_; SkISize surface_size_ = SkISize::MakeEmpty(); size_t present_count_ = 0; void SetupSurface(SkISize surface_size) override; friend class EmbedderConfigBuilder; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContextVulkan); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_VULKAN_H_
engine/shell/platform/embedder/tests/embedder_test_context_vulkan.h/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_context_vulkan.h", "repo_id": "engine", "token_count": 625 }
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. import("//flutter/testing/testing.gni") import("//flutter/tools/fuchsia/dart/dart_library.gni") import("//flutter/tools/fuchsia/flutter/flutter_component.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") config("zircon_config") { include_dirs = [ "." ] } source_set("zircon") { public_configs = [ ":zircon_config" ] sources = [ "sdk_ext/handle.cc", "sdk_ext/handle.h", "sdk_ext/handle_disposition.cc", "sdk_ext/handle_disposition.h", "sdk_ext/handle_waiter.cc", "sdk_ext/handle_waiter.h", "sdk_ext/natives.cc", "sdk_ext/natives.h", "sdk_ext/system.cc", "sdk_ext/system.h", ] deps = [ "${fuchsia_sdk}/fidl/fuchsia.io", "${fuchsia_sdk}/pkg/async-cpp", "${fuchsia_sdk}/pkg/async-default", "${fuchsia_sdk}/pkg/async-loop-cpp", "${fuchsia_sdk}/pkg/fdio", "${fuchsia_sdk}/pkg/zx", "//flutter/fml", "//flutter/third_party/tonic", ] } dart_library("zircon_lib") { testonly = true package_name = "zircon" language_version = "2.12" source_dir = "lib" sources = [ "src/handle.dart", "src/handle_disposition.dart", "src/handle_waiter.dart", "src/init.dart", "src/system.dart", "src/zd_channel.dart", "src/zd_handle.dart", "zircon.dart", ] } dart_library("zircon_tests_lib") { testonly = true package_name = "zircon_tests" language_version = "2.12" source_dir = "." package_root = "test" sources = [ "zircon_tests.dart" ] deps = [ "//flutter/shell/platform/fuchsia/dart:litetest" ] } flutter_component("zircon_tests_component") { testonly = true main_package = "zircon_tests" component_name = "zircon_tests" main_dart = "zircon_tests.dart" manifest = rebase_path("test/meta/zircon_tests.cml") deps = [ ":zircon_tests_lib" ] } fuchsia_package("zircon_tests_package") { testonly = true package_name = "zircon_tests" deps = [ ":zircon_tests_component" ] } if (enable_unittests) { source_set("tests") { testonly = true deps = [ ":zircon_tests_package" ] } }
engine/shell/platform/fuchsia/dart-pkg/zircon/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/BUILD.gn", "repo_id": "engine", "token_count": 1025 }
386
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "handle_waiter.h" #include <lib/async/default.h> #include "handle.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_args.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_library_natives.h" #include "third_party/tonic/dart_message_handler.h" #include "third_party/tonic/dart_microtask_queue.h" #include "third_party/tonic/logging/dart_invoke.h" using tonic::DartInvokeField; using tonic::DartState; using tonic::ToDart; namespace zircon { namespace dart { IMPLEMENT_WRAPPERTYPEINFO(zircon, HandleWaiter); #define FOR_EACH_BINDING(V) V(HandleWaiter, Cancel) FOR_EACH_BINDING(DART_NATIVE_NO_UI_CHECK_CALLBACK) void HandleWaiter::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } fml::RefPtr<HandleWaiter> HandleWaiter::Create(Handle* handle, zx_signals_t signals, Dart_Handle callback) { return fml::MakeRefCounted<HandleWaiter>(handle, signals, callback); } HandleWaiter::HandleWaiter(Handle* handle, zx_signals_t signals, Dart_Handle callback) : wait_(this, handle->handle(), signals), handle_(handle), callback_(DartState::Current(), callback) { FML_CHECK(handle_ != nullptr); FML_CHECK(handle_->is_valid()); zx_status_t status = wait_.Begin(async_get_default_dispatcher()); FML_DCHECK(status == ZX_OK); } HandleWaiter::~HandleWaiter() { Cancel(); } void HandleWaiter::Cancel() { FML_DCHECK(wait_.is_pending() == !!handle_); if (handle_) { // Cancel the wait. wait_.Cancel(); // Release this object from the handle and clear handle_. handle_->ReleaseWaiter(this); handle_ = nullptr; } FML_DCHECK(!wait_.is_pending()); } void HandleWaiter::OnWaitComplete(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal) { FML_DCHECK(handle_); FML_DCHECK(!callback_.is_empty()); // Hold a reference to this object. fml::RefPtr<HandleWaiter> ref(this); // Remove this waiter from the handle. handle_->ReleaseWaiter(this); // Clear handle_. handle_ = nullptr; auto state = callback_.dart_state().lock(); FML_DCHECK(state); DartState::Scope scope(state); // Put the closure invocation on the microtask queue. Dart_Handle zircon_lib = Dart_LookupLibrary(ToDart("dart:zircon")); FML_DCHECK(!tonic::CheckAndHandleError(zircon_lib)); Dart_Handle owc_type = Dart_GetClass(zircon_lib, ToDart("_OnWaitCompleteClosure")); FML_DCHECK(!tonic::CheckAndHandleError(owc_type)); FML_DCHECK(!callback_.is_empty()); std::vector<Dart_Handle> owc_args{callback_.Release(), ToDart(status), ToDart(signal->observed)}; Dart_Handle owc = Dart_New(owc_type, Dart_Null(), owc_args.size(), owc_args.data()); FML_DCHECK(!tonic::CheckAndHandleError(owc)); Dart_Handle closure = Dart_GetField(owc, ToDart("_closure")); FML_DCHECK(!tonic::CheckAndHandleError(closure)); // TODO(issue#tbd): Use tonic::DartMicrotaskQueue::ScheduleMicrotask() // instead when tonic::DartState gets a microtask queue field. Dart_Handle async_lib = Dart_LookupLibrary(ToDart("dart:async")); FML_DCHECK(!tonic::CheckAndHandleError(async_lib)); std::vector<Dart_Handle> sm_args{closure}; Dart_Handle sm_result = Dart_Invoke(async_lib, ToDart("scheduleMicrotask"), sm_args.size(), sm_args.data()); FML_DCHECK(!tonic::CheckAndHandleError(sm_result)); } } // namespace dart } // namespace zircon
engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.cc", "repo_id": "engine", "token_count": 1666 }
387
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_DART_DL_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_DART_DL_H_ #include "macros.h" #include <stdint.h> #ifdef __cplusplus extern "C" { #endif // Initialize Dart API with dynamic linking. // // Must be called with `NativeApi.initializeApiDLData` from `dart:ffi`, before // using other functions. // // Returns 1 on success. ZIRCON_FFI_EXPORT int zircon_dart_dl_initialize(void* initialize_api_dl_data); #ifdef __cplusplus } // extern "C" #endif #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_DART_DL_H_
engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.h/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.h", "repo_id": "engine", "token_count": 270 }
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_FUCHSIA_DART_RUNNER_DART_RUNNER_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_RUNNER_H_ #include <fuchsia/component/runner/cpp/fidl.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/sys/cpp/component_context.h> #include "dart_test_component_controller.h" #include "runtime/dart/utils/mapped_resource.h" namespace dart_runner { class DartRunner : public fuchsia::component::runner::ComponentRunner { public: explicit DartRunner(sys::ComponentContext* context); ~DartRunner() override; private: // |fuchsia::component::runner::ComponentRunner| implementation: void Start( fuchsia::component::runner::ComponentStartInfo start_info, fidl::InterfaceRequest<fuchsia::component::runner::ComponentController> controller) override; // Add test components to this map to ensure it is kept alive in memory for // the duration of test execution and retrieval of exit code. std::map<DartTestComponentController*, std::shared_ptr<DartTestComponentController>> test_components_; // Not owned by DartRunner. sys::ComponentContext* context_; fidl::BindingSet<fuchsia::component::runner::ComponentRunner> component_runner_bindings_; #if !defined(AOT_RUNTIME) dart_utils::MappedResource vm_snapshot_data_; dart_utils::MappedResource vm_snapshot_instructions_; #endif // Disallow copy and assignment. DartRunner(const DartRunner&) = delete; DartRunner& operator=(const DartRunner&) = delete; }; } // namespace dart_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_RUNNER_H_
engine/shell/platform/fuchsia/dart_runner/dart_runner.h/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/dart_runner.h", "repo_id": "engine", "token_count": 608 }
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 <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/inspect/component/cpp/component.h> #include <lib/trace-provider/provider.h> #include <lib/trace/event.h> #include "dart_runner.h" #include "flutter/fml/logging.h" #include "flutter/fml/platform/fuchsia/log_interest_listener.h" #include "flutter/fml/platform/fuchsia/log_state.h" #include "flutter/fml/trace_event.h" #include "logging.h" #include "platform/utils.h" #include "runtime/dart/utils/build_info.h" #include "runtime/dart/utils/files.h" #include "runtime/dart/utils/root_inspect_node.h" #include "runtime/dart/utils/tempfs.h" #include "third_party/dart/runtime/include/dart_api.h" #if !defined(DART_PRODUCT) // Register native symbol information for the Dart VM's profiler. static void RegisterProfilerSymbols(const char* symbols_path, const char* dso_name) { std::string* symbols = new std::string(); if (dart_utils::ReadFileToString(symbols_path, symbols)) { Dart_AddSymbols(dso_name, symbols->data(), symbols->size()); } else { FML_LOG(ERROR) << "Failed to load " << symbols_path; FML_CHECK(false); } } #endif // !defined(DART_PRODUCT) int main(int argc, const char** argv) { async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); // Setup logging. fml::LogState::Default().SetTags({LOG_TAG}); fml::LogInterestListener listener(fml::LogState::Default().TakeClientEnd(), loop.dispatcher()); listener.AsyncWaitForInterestChanged(); // Create our component context which is served later. auto context = sys::ComponentContext::Create(); dart_utils::RootInspectNode::Initialize(context.get()); auto build_info = dart_utils::RootInspectNode::CreateRootChild("build_info"); dart_utils::BuildInfo::Dump(build_info); dart::SetDartVmNode(std::make_unique<inspect::Node>( dart_utils::RootInspectNode::CreateRootChild("vm"))); std::unique_ptr<trace::TraceProviderWithFdio> provider; { bool already_started; // Use CreateSynchronously to prevent loss of early events. trace::TraceProviderWithFdio::CreateSynchronously( loop.dispatcher(), "dart_runner", &provider, &already_started); } #if !defined(DART_PRODUCT) #if defined(AOT_RUNTIME) RegisterProfilerSymbols("pkg/data/dart_aot_runner.dartprofilersymbols", ""); #else RegisterProfilerSymbols("pkg/data/dart_jit_runner.dartprofilersymbols", ""); #endif // defined(AOT_RUNTIME) #endif // !defined(DART_PRODUCT) dart_runner::DartRunner runner(context.get()); // Wait to serve until we have finished all of our setup. context->outgoing()->ServeFromStartupInfo(); loop.Run(); return 0; }
engine/shell/platform/fuchsia/dart_runner/main.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/main.cc", "repo_id": "engine", "token_count": 1049 }
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. import 'dart:fuchsia.builtin'; String? OnEchoString(String? str) { print('Got echo string: $str'); return str; } void main(List<String> args) { receiveEchoStringCallback = OnEchoString; }
engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/main.dart/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/main.dart", "repo_id": "engine", "token_count": 114 }
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 "accessibility_bridge.h" #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/async/cpp/executor.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/fidl/cpp/interface_request.h> #include <lib/inspect/cpp/hierarchy.h> #include <lib/inspect/cpp/inspector.h> #include <lib/inspect/cpp/reader.h> #include <lib/sys/cpp/testing/service_directory_provider.h> #include <lib/zx/eventpair.h> #include <zircon/status.h> #include <zircon/types.h> #include <memory> #include "flutter/lib/ui/semantics/semantics_node.h" #include "gtest/gtest.h" #include "flutter_runner_fakes.h" namespace flutter_runner_test { namespace { void ExpectNodeHasRole( const fuchsia::accessibility::semantics::Node& node, const std::unordered_map<uint32_t, fuchsia::accessibility::semantics::Role> roles_by_node_id) { ASSERT_TRUE(node.has_node_id()); ASSERT_NE(roles_by_node_id.find(node.node_id()), roles_by_node_id.end()); EXPECT_TRUE(node.has_role()); EXPECT_EQ(node.role(), roles_by_node_id.at(node.node_id())); } } // namespace class AccessibilityBridgeTestDelegate { public: void SetSemanticsEnabled(bool enabled) { enabled_ = enabled; } void DispatchSemanticsAction(int32_t node_id, flutter::SemanticsAction action) { actions.push_back(std::make_pair(node_id, action)); } bool enabled() { return enabled_; } std::vector<std::pair<int32_t, flutter::SemanticsAction>> actions; private: bool enabled_; }; class AccessibilityBridgeTest : public testing::Test { public: AccessibilityBridgeTest() : loop_(&kAsyncLoopConfigAttachToCurrentThread), services_provider_(loop_.dispatcher()), executor_(loop_.dispatcher()) { services_provider_.AddService( semantics_manager_.GetHandler(loop_.dispatcher()), SemanticsManager::Name_); } void RunLoopUntilIdle() { loop_.RunUntilIdle(); loop_.ResetQuit(); } void RunPromiseToCompletion(fpromise::promise<> promise) { bool done = false; executor_.schedule_task( std::move(promise).and_then([&done]() { done = true; })); while (loop_.GetState() == ASYNC_LOOP_RUNNABLE) { if (done) { loop_.ResetQuit(); return; } loop_.Run(zx::deadline_after(zx::duration::infinite()), true); } loop_.ResetQuit(); } protected: void SetUp() override { // Connect to SemanticsManager service. fuchsia::accessibility::semantics::SemanticsManagerHandle semantics_manager; zx_status_t semantics_status = services_provider_.service_directory() ->Connect<fuchsia::accessibility::semantics::SemanticsManager>( semantics_manager.NewRequest()); if (semantics_status != ZX_OK) { FML_LOG(WARNING) << "fuchsia::accessibility::semantics::SemanticsManager connection " "failed: " << zx_status_get_string(semantics_status); } accessibility_delegate_.actions.clear(); inspector_ = std::make_unique<inspect::Inspector>(); flutter_runner::AccessibilityBridge::SetSemanticsEnabledCallback set_semantics_enabled_callback = [this](bool enabled) { accessibility_delegate_.SetSemanticsEnabled(enabled); }; flutter_runner::AccessibilityBridge::DispatchSemanticsActionCallback dispatch_semantics_action_callback = [this](int32_t node_id, flutter::SemanticsAction action) { accessibility_delegate_.DispatchSemanticsAction(node_id, action); }; fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ASSERT_EQ(status, ZX_OK); view_ref_control.reference.replace( ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), &view_ref_control.reference); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); accessibility_bridge_ = std::make_unique<flutter_runner::AccessibilityBridge>( std::move(set_semantics_enabled_callback), std::move(dispatch_semantics_action_callback), std::move(semantics_manager), std::move(view_ref), inspector_->GetRoot().CreateChild("test_node")); RunLoopUntilIdle(); } void TearDown() override { semantics_manager_.ResetTree(); } MockSemanticsManager semantics_manager_; AccessibilityBridgeTestDelegate accessibility_delegate_; std::unique_ptr<flutter_runner::AccessibilityBridge> accessibility_bridge_; // Required to verify inspect metrics. std::unique_ptr<inspect::Inspector> inspector_; private: async::Loop loop_; sys::testing::ServiceDirectoryProvider services_provider_; // Required to retrieve inspect metrics. async::Executor executor_; }; TEST_F(AccessibilityBridgeTest, RegistersViewRef) { EXPECT_TRUE(semantics_manager_.RegisterViewCalled()); } TEST_F(AccessibilityBridgeTest, EnableDisable) { EXPECT_FALSE(accessibility_delegate_.enabled()); std::unique_ptr<fuchsia::accessibility::semantics::SemanticListener> listener( accessibility_bridge_.release()); listener->OnSemanticsModeChanged(true, nullptr); EXPECT_TRUE(accessibility_delegate_.enabled()); } TEST_F(AccessibilityBridgeTest, RequestAnnounce) { accessibility_bridge_->RequestAnnounce("message"); RunLoopUntilIdle(); auto& last_events = semantics_manager_.GetLastEvents(); ASSERT_EQ(last_events.size(), 1u); ASSERT_TRUE(last_events[0].is_announce()); EXPECT_EQ(last_events[0].announce().message(), "message"); } TEST_F(AccessibilityBridgeTest, PopulatesIsKeyboardKeyAttribute) { flutter::SemanticsNode node0; node0.id = 0; node0.flags = static_cast<int>(flutter::SemanticsFlags::kIsKeyboardKey); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_attributes()); EXPECT_TRUE(fuchsia_node.attributes().is_keyboard_key()); } TEST_F(AccessibilityBridgeTest, UpdatesNodeRoles) { flutter::SemanticsNodeUpdates updates; flutter::SemanticsNode node0; node0.id = 0; node0.flags |= static_cast<int>(flutter::SemanticsFlags::kIsButton); node0.childrenInTraversalOrder = {1, 2, 3, 4, 5, 6, 7, 8}; node0.childrenInHitTestOrder = {1, 2, 3, 4, 5, 6, 7, 8}; updates.emplace(0, node0); flutter::SemanticsNode node1; node1.id = 1; node1.flags |= static_cast<int>(flutter::SemanticsFlags::kIsHeader); node1.childrenInTraversalOrder = {}; node1.childrenInHitTestOrder = {}; updates.emplace(1, node1); flutter::SemanticsNode node2; node2.id = 2; node2.flags |= static_cast<int>(flutter::SemanticsFlags::kIsImage); node2.childrenInTraversalOrder = {}; node2.childrenInHitTestOrder = {}; updates.emplace(2, node2); flutter::SemanticsNode node3; node3.id = 3; node3.flags |= static_cast<int>(flutter::SemanticsFlags::kIsTextField); node3.childrenInTraversalOrder = {}; node3.childrenInHitTestOrder = {}; updates.emplace(3, node3); flutter::SemanticsNode node4; node4.childrenInTraversalOrder = {}; node4.childrenInHitTestOrder = {}; node4.id = 4; node4.flags |= static_cast<int>(flutter::SemanticsFlags::kIsSlider); updates.emplace(4, node4); flutter::SemanticsNode node5; node5.childrenInTraversalOrder = {}; node5.childrenInHitTestOrder = {}; node5.id = 5; node5.flags |= static_cast<int>(flutter::SemanticsFlags::kIsLink); updates.emplace(5, node5); flutter::SemanticsNode node6; node6.childrenInTraversalOrder = {}; node6.childrenInHitTestOrder = {}; node6.id = 6; node6.flags |= static_cast<int>(flutter::SemanticsFlags::kHasCheckedState); node6.flags |= static_cast<int>(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup); updates.emplace(6, node6); flutter::SemanticsNode node7; node7.childrenInTraversalOrder = {}; node7.childrenInHitTestOrder = {}; node7.id = 7; node7.flags |= static_cast<int>(flutter::SemanticsFlags::kHasCheckedState); updates.emplace(7, node7); flutter::SemanticsNode node8; node8.childrenInTraversalOrder = {}; node8.childrenInHitTestOrder = {}; node8.id = 8; node8.flags |= static_cast<int>(flutter::SemanticsFlags::kHasToggledState); updates.emplace(7, node8); accessibility_bridge_->AddSemanticsNodeUpdate(std::move(updates), 1.f); RunLoopUntilIdle(); std::unordered_map<uint32_t, fuchsia::accessibility::semantics::Role> roles_by_node_id = { {0u, fuchsia::accessibility::semantics::Role::BUTTON}, {1u, fuchsia::accessibility::semantics::Role::HEADER}, {2u, fuchsia::accessibility::semantics::Role::IMAGE}, {3u, fuchsia::accessibility::semantics::Role::TEXT_FIELD}, {4u, fuchsia::accessibility::semantics::Role::SLIDER}, {5u, fuchsia::accessibility::semantics::Role::LINK}, {6u, fuchsia::accessibility::semantics::Role::RADIO_BUTTON}, {7u, fuchsia::accessibility::semantics::Role::CHECK_BOX}, {8u, fuchsia::accessibility::semantics::Role::TOGGLE_SWITCH}}; EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(8u, semantics_manager_.LastUpdatedNodes().size()); for (const auto& node : semantics_manager_.LastUpdatedNodes()) { ExpectNodeHasRole(node, roles_by_node_id); } EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, DeletesChildrenTransitively) { // Test that when a node is deleted, so are its transitive children. flutter::SemanticsNode node2; node2.id = 2; flutter::SemanticsNode node1; node1.id = 1; node1.childrenInTraversalOrder = {2}; node1.childrenInHitTestOrder = {2}; flutter::SemanticsNode node0; node0.id = 0; node0.childrenInTraversalOrder = {1}; node0.childrenInHitTestOrder = {1}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, {2, node2}, }, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(3U, semantics_manager_.LastUpdatedNodes().size()); EXPECT_EQ(0U, semantics_manager_.LastDeletedNodeIds().size()); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); // Remove the children node0.childrenInTraversalOrder.clear(); node0.childrenInHitTestOrder.clear(); accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, }, 1.f); RunLoopUntilIdle(); EXPECT_EQ(1, semantics_manager_.DeleteCount()); EXPECT_EQ(2, semantics_manager_.UpdateCount()); EXPECT_EQ(2, semantics_manager_.CommitCount()); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); ASSERT_EQ(std::vector<uint32_t>({1, 2}), semantics_manager_.LastDeletedNodeIds()); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, PopulatesRoleButton) { flutter::SemanticsNode node0; node0.id = 0; node0.flags = static_cast<int>(flutter::SemanticsFlags::kIsButton); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_role()); EXPECT_EQ(fuchsia_node.role(), fuchsia::accessibility::semantics::Role::BUTTON); } TEST_F(AccessibilityBridgeTest, PopulatesRoleImage) { flutter::SemanticsNode node0; node0.id = 0; node0.flags = static_cast<int>(flutter::SemanticsFlags::kIsImage); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_role()); EXPECT_EQ(fuchsia_node.role(), fuchsia::accessibility::semantics::Role::IMAGE); } TEST_F(AccessibilityBridgeTest, PopulatesRoleSlider) { flutter::SemanticsNode node0; node0.id = 0; node0.actions |= static_cast<int>(flutter::SemanticsAction::kIncrease); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_role()); EXPECT_EQ(fuchsia_node.role(), fuchsia::accessibility::semantics::Role::SLIDER); } TEST_F(AccessibilityBridgeTest, PopulatesRoleHeader) { flutter::SemanticsNode node0; node0.id = 0; node0.flags = static_cast<int>(flutter::SemanticsFlags::kIsHeader); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_role()); EXPECT_EQ(fuchsia_node.role(), fuchsia::accessibility::semantics::Role::HEADER); } TEST_F(AccessibilityBridgeTest, PopulatesCheckedState) { flutter::SemanticsNode node0; node0.id = 0; // HasCheckedState = true // IsChecked = true // IsSelected = false node0.flags |= static_cast<int>(flutter::SemanticsFlags::kHasCheckedState); node0.flags |= static_cast<int>(flutter::SemanticsFlags::kIsChecked); node0.value = "value"; accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_states()); const auto& states = fuchsia_node.states(); EXPECT_TRUE(states.has_checked_state()); EXPECT_EQ(states.checked_state(), fuchsia::accessibility::semantics::CheckedState::CHECKED); EXPECT_TRUE(states.has_selected()); EXPECT_FALSE(states.selected()); EXPECT_TRUE(states.has_value()); EXPECT_EQ(states.value(), node0.value); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, PopulatesSelectedState) { flutter::SemanticsNode node0; node0.id = 0; // HasCheckedState = false // IsChecked = false // IsSelected = true node0.flags = static_cast<int>(flutter::SemanticsFlags::kIsSelected); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_states()); const auto& states = fuchsia_node.states(); EXPECT_TRUE(states.has_checked_state()); EXPECT_EQ(states.checked_state(), fuchsia::accessibility::semantics::CheckedState::NONE); EXPECT_TRUE(states.has_selected()); EXPECT_TRUE(states.selected()); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, PopulatesToggledState) { flutter::SemanticsNode node0; node0.id = 0; node0.flags |= static_cast<int>(flutter::SemanticsFlags::kHasToggledState); node0.flags |= static_cast<int>(flutter::SemanticsFlags::kIsToggled); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_states()); const auto& states = fuchsia_node.states(); EXPECT_TRUE(states.has_toggled_state()); EXPECT_EQ(states.toggled_state(), fuchsia::accessibility::semantics::ToggledState::ON); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, PopulatesEnabledState) { flutter::SemanticsNode node0; node0.id = 0; // HasEnabledState = true // IsEnabled = true node0.flags |= static_cast<int>(flutter::SemanticsFlags::kHasEnabledState); node0.flags |= static_cast<int>(flutter::SemanticsFlags::kIsEnabled); node0.value = "value"; accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_states()); const auto& states = fuchsia_node.states(); EXPECT_TRUE(states.has_enabled_state()); EXPECT_EQ(states.enabled_state(), fuchsia::accessibility::semantics::EnabledState::ENABLED); EXPECT_TRUE(states.has_value()); EXPECT_EQ(states.value(), node0.value); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, ApplyViewPixelRatioToRoot) { flutter::SemanticsNode node0; node0.id = 0; node0.flags = static_cast<int>(flutter::SemanticsFlags::kIsSelected); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.25f); RunLoopUntilIdle(); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_EQ(fuchsia_node.transform().matrix[0], 0.8f); EXPECT_EQ(fuchsia_node.transform().matrix[5], 0.8f); EXPECT_EQ(fuchsia_node.transform().matrix[10], 1.f); } TEST_F(AccessibilityBridgeTest, DoesNotPopulatesHiddenState) { // Flutter's notion of a hidden node is different from Fuchsia's hidden node. // This test make sures that this state does not get sent. flutter::SemanticsNode node0; node0.id = 0; // HasCheckedState = false // IsChecked = false // IsSelected = false // IsHidden = true node0.flags = static_cast<int>(flutter::SemanticsFlags::kIsHidden); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(1u, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.node_id(), static_cast<unsigned int>(node0.id)); EXPECT_TRUE(fuchsia_node.has_states()); const auto& states = fuchsia_node.states(); EXPECT_TRUE(states.has_checked_state()); EXPECT_EQ(states.checked_state(), fuchsia::accessibility::semantics::CheckedState::NONE); EXPECT_TRUE(states.has_selected()); EXPECT_FALSE(states.selected()); EXPECT_FALSE(states.has_hidden()); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, PopulatesActions) { flutter::SemanticsNode node0; node0.id = 0; node0.actions |= static_cast<int>(flutter::SemanticsAction::kTap); node0.actions |= static_cast<int>(flutter::SemanticsAction::kLongPress); node0.actions |= static_cast<int>(flutter::SemanticsAction::kShowOnScreen); node0.actions |= static_cast<int>(flutter::SemanticsAction::kIncrease); node0.actions |= static_cast<int>(flutter::SemanticsAction::kDecrease); accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(1u, semantics_manager_.LastUpdatedNodes().size()); const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); EXPECT_EQ(fuchsia_node.actions().size(), 5u); EXPECT_EQ(fuchsia_node.actions().at(0u), fuchsia::accessibility::semantics::Action::DEFAULT); EXPECT_EQ(fuchsia_node.actions().at(1u), fuchsia::accessibility::semantics::Action::SECONDARY); EXPECT_EQ(fuchsia_node.actions().at(2u), fuchsia::accessibility::semantics::Action::SHOW_ON_SCREEN); EXPECT_EQ(fuchsia_node.actions().at(3u), fuchsia::accessibility::semantics::Action::INCREMENT); EXPECT_EQ(fuchsia_node.actions().at(4u), fuchsia::accessibility::semantics::Action::DECREMENT); } TEST_F(AccessibilityBridgeTest, TruncatesLargeLabel) { // Test that labels which are too long are truncated. flutter::SemanticsNode node0; node0.id = 0; flutter::SemanticsNode node1; node1.id = 1; flutter::SemanticsNode bad_node; bad_node.id = 2; bad_node.label = std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE + 1, '2'); node0.childrenInTraversalOrder = {1, 2}; node0.childrenInHitTestOrder = {1, 2}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, {2, bad_node}, }, 1.f); RunLoopUntilIdle(); // Nothing to delete, but we should have broken EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(3U, semantics_manager_.LastUpdatedNodes().size()); auto trimmed_node = std::find_if(semantics_manager_.LastUpdatedNodes().begin(), semantics_manager_.LastUpdatedNodes().end(), [id = static_cast<uint32_t>(bad_node.id)]( fuchsia::accessibility::semantics::Node const& node) { return node.node_id() == id; }); ASSERT_NE(trimmed_node, semantics_manager_.LastUpdatedNodes().end()); ASSERT_TRUE(trimmed_node->has_attributes()); EXPECT_EQ( trimmed_node->attributes().label(), std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE, '2')); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, TruncatesLargeToolTip) { // Test that tooltips which are too long are truncated. flutter::SemanticsNode node0; node0.id = 0; flutter::SemanticsNode node1; node1.id = 1; flutter::SemanticsNode bad_node; bad_node.id = 2; bad_node.tooltip = std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE + 1, '2'); node0.childrenInTraversalOrder = {1, 2}; node0.childrenInHitTestOrder = {1, 2}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, {2, bad_node}, }, 1.f); RunLoopUntilIdle(); // Nothing to delete, but we should have broken EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(3U, semantics_manager_.LastUpdatedNodes().size()); auto trimmed_node = std::find_if(semantics_manager_.LastUpdatedNodes().begin(), semantics_manager_.LastUpdatedNodes().end(), [id = static_cast<uint32_t>(bad_node.id)]( fuchsia::accessibility::semantics::Node const& node) { return node.node_id() == id; }); ASSERT_NE(trimmed_node, semantics_manager_.LastUpdatedNodes().end()); ASSERT_TRUE(trimmed_node->has_attributes()); EXPECT_EQ( trimmed_node->attributes().secondary_label(), std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE, '2')); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, TruncatesLargeValue) { // Test that values which are too long are truncated. flutter::SemanticsNode node0; node0.id = 0; flutter::SemanticsNode node1; node1.id = 1; flutter::SemanticsNode bad_node; bad_node.id = 2; bad_node.value = std::string(fuchsia::accessibility::semantics::MAX_VALUE_SIZE + 1, '2'); node0.childrenInTraversalOrder = {1, 2}; node0.childrenInHitTestOrder = {1, 2}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, {2, bad_node}, }, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(3U, semantics_manager_.LastUpdatedNodes().size()); auto trimmed_node = std::find_if(semantics_manager_.LastUpdatedNodes().begin(), semantics_manager_.LastUpdatedNodes().end(), [id = static_cast<uint32_t>(bad_node.id)]( fuchsia::accessibility::semantics::Node const& node) { return node.node_id() == id; }); ASSERT_NE(trimmed_node, semantics_manager_.LastUpdatedNodes().end()); ASSERT_TRUE(trimmed_node->has_states()); EXPECT_EQ( trimmed_node->states().value(), std::string(fuchsia::accessibility::semantics::MAX_VALUE_SIZE, '2')); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, SplitsLargeUpdates) { // Test that labels which are too long are truncated. flutter::SemanticsNode node0; node0.id = 0; flutter::SemanticsNode node1; node1.id = 1; node1.label = std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE, '1'); flutter::SemanticsNode node2; node2.id = 2; node2.label = "2"; flutter::SemanticsNode node3; node3.id = 3; node3.label = "3"; flutter::SemanticsNode node4; node4.id = 4; node4.value = std::string(fuchsia::accessibility::semantics::MAX_VALUE_SIZE, '4'); node0.childrenInTraversalOrder = {1, 2}; node0.childrenInHitTestOrder = {1, 2}; node1.childrenInTraversalOrder = {3, 4}; node1.childrenInHitTestOrder = {3, 4}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, {2, node2}, {3, node3}, {4, node4}, }, 1.f); RunLoopUntilIdle(); // Nothing to delete, but we should have broken into groups (4, 3, 2), (1, 0) EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(2, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_EQ(2U, semantics_manager_.LastUpdatedNodes().size()); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, HandlesCycles) { // Test that cycles don't cause fatal error. flutter::SemanticsNode node0; node0.id = 0; node0.childrenInTraversalOrder.push_back(0); node0.childrenInHitTestOrder.push_back(0); accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, }, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(1, semantics_manager_.UpdateCount()); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); node0.childrenInTraversalOrder = {0, 1}; node0.childrenInHitTestOrder = {0, 1}; flutter::SemanticsNode node1; node1.id = 1; node1.childrenInTraversalOrder = {0}; node1.childrenInHitTestOrder = {0}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, }, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_EQ(2, semantics_manager_.UpdateCount()); EXPECT_EQ(2, semantics_manager_.CommitCount()); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, BatchesLargeMessages) { // Tests that messages get batched appropriately. flutter::SemanticsNode node0; node0.id = 0; flutter::SemanticsNodeUpdates update; const int32_t child_nodes = 100; const int32_t leaf_nodes = 100; for (int32_t i = 1; i < child_nodes + 1; i++) { flutter::SemanticsNode node; node.id = i; node0.childrenInTraversalOrder.push_back(i); node0.childrenInHitTestOrder.push_back(i); for (int32_t j = 0; j < leaf_nodes; j++) { flutter::SemanticsNode leaf_node; int id = (i * child_nodes) + ((j + 1) * leaf_nodes); leaf_node.id = id; leaf_node.label = "A relatively simple label"; node.childrenInTraversalOrder.push_back(id); node.childrenInHitTestOrder.push_back(id); update.insert(std::make_pair(id, std::move(leaf_node))); } update.insert(std::make_pair(i, std::move(node))); } update.insert(std::make_pair(0, std::move(node0))); // Make the semantics manager hold answering to this commit to test the flow // control. This means the second update will not be pushed until the first // one has processed. semantics_manager_.SetShouldHoldCommitResponse(true); accessibility_bridge_->AddSemanticsNodeUpdate(update, 1.f); RunLoopUntilIdle(); EXPECT_EQ(0, semantics_manager_.DeleteCount()); EXPECT_TRUE(6 <= semantics_manager_.UpdateCount() && semantics_manager_.UpdateCount() <= 12); EXPECT_EQ(1, semantics_manager_.CommitCount()); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); int next_update_count = semantics_manager_.UpdateCount() + 1; // Remove the children node0.childrenInTraversalOrder.clear(); node0.childrenInHitTestOrder.clear(); accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, }, 1.f); RunLoopUntilIdle(); // Should still be 0, because the commit was not answered yet. EXPECT_EQ(0, semantics_manager_.DeleteCount()); semantics_manager_.InvokeCommitCallback(); RunLoopUntilIdle(); EXPECT_EQ(1, semantics_manager_.DeleteCount()); EXPECT_EQ(next_update_count, semantics_manager_.UpdateCount()); EXPECT_EQ(2, semantics_manager_.CommitCount()); EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); } TEST_F(AccessibilityBridgeTest, HitTest) { flutter::SemanticsNode node0; node0.id = 0; node0.rect.setLTRB(0, 0, 100, 100); node0.flags |= static_cast<int32_t>(flutter::SemanticsFlags::kIsFocusable); flutter::SemanticsNode node1; node1.id = 1; node1.rect.setLTRB(10, 10, 20, 20); // Setting platform view id ensures this node is considered focusable. node1.platformViewId = 1u; flutter::SemanticsNode node2; node2.id = 2; node2.rect.setLTRB(25, 10, 45, 20); // Setting label ensures this node is considered focusable. node2.label = "label"; flutter::SemanticsNode node3; node3.id = 3; node3.rect.setLTRB(10, 25, 20, 45); // Setting actions to a nonzero value ensures this node is considered // focusable. node3.actions = 1u; flutter::SemanticsNode node4; node4.id = 4; node4.rect.setLTRB(10, 10, 20, 20); node4.transform.setTranslate(20, 20, 0); node4.flags |= static_cast<int32_t>(flutter::SemanticsFlags::kIsFocusable); node0.childrenInTraversalOrder = {1, 2, 3, 4}; node0.childrenInHitTestOrder = {1, 2, 3, 4}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, {2, node2}, {3, node3}, {4, node4}, }, 1.f); RunLoopUntilIdle(); uint32_t hit_node_id; auto callback = [&hit_node_id](fuchsia::accessibility::semantics::Hit hit) { EXPECT_TRUE(hit.has_node_id()); hit_node_id = hit.node_id(); }; // Nodes are: // ---------- // | 1 2 | // | 3 4 | // ---------- accessibility_bridge_->HitTest({1, 1}, callback); EXPECT_EQ(hit_node_id, 0u); accessibility_bridge_->HitTest({15, 15}, callback); EXPECT_EQ(hit_node_id, 1u); accessibility_bridge_->HitTest({30, 15}, callback); EXPECT_EQ(hit_node_id, 2u); accessibility_bridge_->HitTest({15, 30}, callback); EXPECT_EQ(hit_node_id, 3u); accessibility_bridge_->HitTest({30, 30}, callback); EXPECT_EQ(hit_node_id, 4u); } TEST_F(AccessibilityBridgeTest, HitTestWithPixelRatio) { flutter::SemanticsNode node0; node0.id = 0; node0.rect.setLTRB(0, 0, 100, 100); node0.flags |= static_cast<int32_t>(flutter::SemanticsFlags::kIsFocusable); flutter::SemanticsNode node1; node1.id = 1; node1.rect.setLTRB(10, 10, 20, 20); // Setting platform view id ensures this node is considered focusable. node1.platformViewId = 1u; node0.childrenInTraversalOrder = {1}; node0.childrenInHitTestOrder = {1}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, }, // Pick a very small pixel ratio so that a point within the bounds of // the node's root-space coordinates will be well outside the "screen" // bounds of the node. .1f); RunLoopUntilIdle(); uint32_t hit_node_id; auto callback = [&hit_node_id](fuchsia::accessibility::semantics::Hit hit) { EXPECT_TRUE(hit.has_node_id()); hit_node_id = hit.node_id(); }; accessibility_bridge_->HitTest({15, 15}, callback); EXPECT_EQ(hit_node_id, 0u); } TEST_F(AccessibilityBridgeTest, HitTestUnfocusableChild) { flutter::SemanticsNode node0; node0.id = 0; node0.rect.setLTRB(0, 0, 100, 100); flutter::SemanticsNode node1; node1.id = 1; node1.rect.setLTRB(10, 10, 60, 60); flutter::SemanticsNode node2; node2.id = 2; node2.rect.setLTRB(50, 50, 100, 100); node2.flags |= static_cast<int32_t>(flutter::SemanticsFlags::kIsFocusable); node0.childrenInTraversalOrder = {1, 2}; node0.childrenInHitTestOrder = {1, 2}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, {2, node2}, }, 1.f); RunLoopUntilIdle(); uint32_t hit_node_id; auto callback = [&hit_node_id](fuchsia::accessibility::semantics::Hit hit) { EXPECT_TRUE(hit.has_node_id()); hit_node_id = hit.node_id(); }; accessibility_bridge_->HitTest({55, 55}, callback); EXPECT_EQ(hit_node_id, 2u); } TEST_F(AccessibilityBridgeTest, HitTestOverlapping) { // Tests that the first node in hit test order wins, even if a later node // would be able to receive the hit. flutter::SemanticsNode node0; node0.id = 0; node0.rect.setLTRB(0, 0, 100, 100); node0.flags |= static_cast<int32_t>(flutter::SemanticsFlags::kIsFocusable); flutter::SemanticsNode node1; node1.id = 1; node1.rect.setLTRB(0, 0, 100, 100); node1.flags |= static_cast<int32_t>(flutter::SemanticsFlags::kIsFocusable); flutter::SemanticsNode node2; node2.id = 2; node2.rect.setLTRB(25, 10, 45, 20); node2.flags |= static_cast<int32_t>(flutter::SemanticsFlags::kIsFocusable); node0.childrenInTraversalOrder = {1, 2}; node0.childrenInHitTestOrder = {2, 1}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, {2, node2}, }, 1.f); RunLoopUntilIdle(); uint32_t hit_node_id; auto callback = [&hit_node_id](fuchsia::accessibility::semantics::Hit hit) { EXPECT_TRUE(hit.has_node_id()); hit_node_id = hit.node_id(); }; accessibility_bridge_->HitTest({30, 15}, callback); EXPECT_EQ(hit_node_id, 2u); } TEST_F(AccessibilityBridgeTest, Actions) { flutter::SemanticsNode node0; node0.id = 0; flutter::SemanticsNode node1; node1.id = 1; node0.childrenInTraversalOrder = {1}; node0.childrenInHitTestOrder = {1}; accessibility_bridge_->AddSemanticsNodeUpdate( { {0, node0}, {1, node1}, }, 1.f); RunLoopUntilIdle(); auto handled_callback = [](bool handled) { EXPECT_TRUE(handled); }; auto unhandled_callback = [](bool handled) { EXPECT_FALSE(handled); }; accessibility_bridge_->OnAccessibilityActionRequested( 0u, fuchsia::accessibility::semantics::Action::DEFAULT, handled_callback); EXPECT_EQ(accessibility_delegate_.actions.size(), 1u); EXPECT_EQ(accessibility_delegate_.actions.back(), std::make_pair(0, flutter::SemanticsAction::kTap)); accessibility_bridge_->OnAccessibilityActionRequested( 0u, fuchsia::accessibility::semantics::Action::SECONDARY, handled_callback); EXPECT_EQ(accessibility_delegate_.actions.size(), 2u); EXPECT_EQ(accessibility_delegate_.actions.back(), std::make_pair(0, flutter::SemanticsAction::kLongPress)); accessibility_bridge_->OnAccessibilityActionRequested( 0u, fuchsia::accessibility::semantics::Action::SET_FOCUS, unhandled_callback); EXPECT_EQ(accessibility_delegate_.actions.size(), 2u); accessibility_bridge_->OnAccessibilityActionRequested( 0u, fuchsia::accessibility::semantics::Action::SET_VALUE, unhandled_callback); EXPECT_EQ(accessibility_delegate_.actions.size(), 2u); accessibility_bridge_->OnAccessibilityActionRequested( 0u, fuchsia::accessibility::semantics::Action::SHOW_ON_SCREEN, handled_callback); EXPECT_EQ(accessibility_delegate_.actions.size(), 3u); EXPECT_EQ(accessibility_delegate_.actions.back(), std::make_pair(0, flutter::SemanticsAction::kShowOnScreen)); accessibility_bridge_->OnAccessibilityActionRequested( 2u, fuchsia::accessibility::semantics::Action::DEFAULT, unhandled_callback); EXPECT_EQ(accessibility_delegate_.actions.size(), 3u); accessibility_bridge_->OnAccessibilityActionRequested( 0u, fuchsia::accessibility::semantics::Action::INCREMENT, handled_callback); EXPECT_EQ(accessibility_delegate_.actions.size(), 4u); EXPECT_EQ(accessibility_delegate_.actions.back(), std::make_pair(0, flutter::SemanticsAction::kIncrease)); accessibility_bridge_->OnAccessibilityActionRequested( 0u, fuchsia::accessibility::semantics::Action::DECREMENT, handled_callback); EXPECT_EQ(accessibility_delegate_.actions.size(), 5u); EXPECT_EQ(accessibility_delegate_.actions.back(), std::make_pair(0, flutter::SemanticsAction::kDecrease)); } #if !FLUTTER_RELEASE TEST_F(AccessibilityBridgeTest, InspectData) { flutter::SemanticsNodeUpdates updates; flutter::SemanticsNode node0; node0.id = 0; node0.label = "node0"; node0.hint = "node0_hint"; node0.value = "value"; node0.flags |= static_cast<int>(flutter::SemanticsFlags::kIsButton); node0.childrenInTraversalOrder = {1}; node0.childrenInHitTestOrder = {1}; node0.rect.setLTRB(0, 0, 100, 100); updates.emplace(0, node0); flutter::SemanticsNode node1; node1.id = 1; node1.flags |= static_cast<int>(flutter::SemanticsFlags::kIsHeader); node1.childrenInTraversalOrder = {}; node1.childrenInHitTestOrder = {}; updates.emplace(1, node1); accessibility_bridge_->AddSemanticsNodeUpdate(std::move(updates), 1.f); RunLoopUntilIdle(); fpromise::result<inspect::Hierarchy> hierarchy; ASSERT_FALSE(hierarchy.is_ok()); RunPromiseToCompletion( inspect::ReadFromInspector(*inspector_) .then([&hierarchy](fpromise::result<inspect::Hierarchy>& result) { hierarchy = std::move(result); })); ASSERT_TRUE(hierarchy.is_ok()); auto tree_inspect_hierarchy = hierarchy.value().GetByPath({"test_node"}); ASSERT_NE(tree_inspect_hierarchy, nullptr); // TODO(http://fxbug.dev/75841): Rewrite flutter engine accessibility bridge // tests using inspect matchers. The checks bellow verify that the tree was // built, and that it matches the format of the input tree. This will be // updated in the future when test matchers are available to verify individual // property values. const auto& root = tree_inspect_hierarchy->children(); ASSERT_EQ(root.size(), 1u); EXPECT_EQ(root[0].name(), "semantic_tree_root"); const auto& child = root[0].children(); ASSERT_EQ(child.size(), 1u); EXPECT_EQ(child[0].name(), "node_1"); } #endif // !FLUTTER_RELEASE } // namespace flutter_runner_test
engine/shell/platform/fuchsia/flutter/accessibility_bridge_unittest.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/accessibility_bridge_unittest.cc", "repo_id": "engine", "token_count": 16074 }
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. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_CONNECTION_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_CONNECTION_H_ #include <fuchsia/ui/composition/cpp/fidl.h> #include "flutter/fml/closure.h" #include "flutter/fml/macros.h" #include "flutter/fml/time/time_delta.h" #include "flutter/fml/time/time_point.h" #include "vsync_waiter.h" #include <cstdint> #include <mutex> #include <queue> #include <string> namespace flutter_runner { using on_frame_presented_event = std::function<void(fuchsia::scenic::scheduling::FramePresentedInfo)>; // 10ms interval to target vsync is only used until Scenic sends presentation // feedback. static constexpr fml::TimeDelta kInitialFlatlandVsyncOffset = fml::TimeDelta::FromMilliseconds(10); // The component residing on the raster thread that is responsible for // maintaining the Flatland instance connection and presenting updates. class FlatlandConnection final { public: FlatlandConnection(std::string debug_label, fuchsia::ui::composition::FlatlandHandle flatland, fml::closure error_callback, on_frame_presented_event on_frame_presented_callback); ~FlatlandConnection(); void Present(); // Used to implement VsyncWaiter functionality. // Note that these two methods are called from the UI thread while the // rest of the methods on this class are called from the raster thread. void AwaitVsync(FireCallbackCallback callback); void AwaitVsyncForSecondaryCallback(FireCallbackCallback callback); fuchsia::ui::composition::Flatland* flatland() { return flatland_.get(); } fuchsia::ui::composition::TransformId NextTransformId() { return {++next_transform_id_}; } fuchsia::ui::composition::ContentId NextContentId() { return {++next_content_id_}; } void EnqueueAcquireFence(zx::event fence); void EnqueueReleaseFence(zx::event fence); private: void OnError(fuchsia::ui::composition::FlatlandError error); void OnNextFrameBegin( fuchsia::ui::composition::OnNextFrameBeginValues values); void OnFramePresented(fuchsia::scenic::scheduling::FramePresentedInfo info); void DoPresent(); fml::TimePoint GetNextPresentationTime(const fml::TimePoint& now); bool MaybeRunInitialVsyncCallback(const fml::TimePoint& now, FireCallbackCallback& callback); void RunVsyncCallback(const fml::TimePoint& now, FireCallbackCallback& callback); fuchsia::ui::composition::FlatlandPtr flatland_; fml::closure error_callback_; uint64_t next_transform_id_ = 0; uint64_t next_content_id_ = 0; on_frame_presented_event on_frame_presented_callback_; bool present_waiting_for_credit_ = false; // A flow event trace id for following |Flatland::Present| calls into Scenic. uint64_t next_present_trace_id_ = 0; // This struct contains state that is accessed from both from the UI thread // (in AwaitVsync) and the raster thread (in OnNextFrameBegin and Present). // You should always lock mutex_ before touching anything in this struct struct { std::mutex mutex_; std::queue<fml::TimePoint> next_presentation_times_; fml::TimeDelta vsync_interval_ = kInitialFlatlandVsyncOffset; fml::TimeDelta vsync_offset_ = kInitialFlatlandVsyncOffset; fml::TimePoint last_presentation_time_; FireCallbackCallback pending_fire_callback_; uint32_t present_credits_ = 1; bool first_feedback_received_ = false; } threadsafe_state_; std::vector<zx::event> acquire_fences_; std::vector<zx::event> current_present_release_fences_; std::vector<zx::event> previous_present_release_fences_; FML_DISALLOW_COPY_AND_ASSIGN(FlatlandConnection); }; } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_CONNECTION_H_
engine/shell/platform/fuchsia/flutter/flatland_connection.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/flatland_connection.h", "repo_id": "engine", "token_count": 1398 }
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. #include <fuchsia/ui/pointer/cpp/fidl.h> #include <gtest/gtest.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fidl/cpp/binding_set.h> #include <array> #include <optional> #include <vector> #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" #include "pointer_delegate.h" #include "tests/fakes/mouse_source.h" #include "tests/fakes/touch_source.h" #include "tests/pointer_event_utility.h" namespace flutter_runner::testing { using fup_EventPhase = fuchsia::ui::pointer::EventPhase; using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; using fup_TouchIxnId = fuchsia::ui::pointer::TouchInteractionId; using fup_TouchIxnResult = fuchsia::ui::pointer::TouchInteractionResult; using fup_TouchIxnStatus = fuchsia::ui::pointer::TouchInteractionStatus; using fup_TouchPointerSample = fuchsia::ui::pointer::TouchPointerSample; using fup_TouchResponse = fuchsia::ui::pointer::TouchResponse; using fup_TouchResponseType = fuchsia::ui::pointer::TouchResponseType; using fup_ViewParameters = fuchsia::ui::pointer::ViewParameters; using fup_MouseEvent = fuchsia::ui::pointer::MouseEvent; constexpr std::array<std::array<float, 2>, 2> kRect = {{{0, 0}, {20, 20}}}; constexpr std::array<float, 9> kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1}; constexpr fup_TouchIxnId kIxnOne = {.device_id = 1u, .pointer_id = 1u, .interaction_id = 2u}; constexpr uint32_t kMouseDeviceId = 123; constexpr std::array<int64_t, 2> kNoScrollInPhysicalPixelDelta = {0, 0}; const bool kNotPrecisionScroll = false; const bool kPrecisionScroll = true; // Fixture to exercise Flutter runner's implementation for // fuchsia.ui.pointer.TouchSource. class PointerDelegateTest : public ::testing::Test { protected: PointerDelegateTest() : loop_(&kAsyncLoopConfigAttachToCurrentThread) { touch_source_ = std::make_unique<FakeTouchSource>(); mouse_source_ = std::make_unique<FakeMouseSource>(); pointer_delegate_ = std::make_unique<flutter_runner::PointerDelegate>( touch_source_bindings_.AddBinding(touch_source_.get()), mouse_source_bindings_.AddBinding(mouse_source_.get())); } void RunLoopUntilIdle() { loop_.RunUntilIdle(); } std::unique_ptr<FakeTouchSource> touch_source_; std::unique_ptr<FakeMouseSource> mouse_source_; std::unique_ptr<flutter_runner::PointerDelegate> pointer_delegate_; private: async::Loop loop_; fidl::BindingSet<fuchsia::ui::pointer::TouchSource> touch_source_bindings_; fidl::BindingSet<fuchsia::ui::pointer::MouseSource> mouse_source_bindings_; FML_DISALLOW_COPY_AND_ASSIGN(PointerDelegateTest); }; TEST_F(PointerDelegateTest, Data_FuchsiaTimeVersusFlutterTime) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD -> Flutter ADD+DOWN std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(/* in nanoseconds */ 1111789u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .AddResult( {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 2u); EXPECT_EQ((*pointers)[0].time_stamp, /* in microseconds */ 1111u); EXPECT_EQ((*pointers)[1].time_stamp, /* in microseconds */ 1111u); } TEST_F(PointerDelegateTest, Phase_FlutterPhasesAreSynthesized) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD -> Flutter ADD+DOWN std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .AddResult( {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 2u); EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kAdd); EXPECT_EQ((*pointers)[1].change, flutter::PointerData::Change::kDown); // Fuchsia CHANGE -> Flutter MOVE events = TouchEventBuilder::New() .AddTime(2222000u) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 1u); EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kMove); // Fuchsia REMOVE -> Flutter UP+REMOVE events = TouchEventBuilder::New() .AddTime(3333000u) .AddSample(kIxnOne, fup_EventPhase::REMOVE, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 2u); EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kUp); EXPECT_EQ((*pointers)[1].change, flutter::PointerData::Change::kRemove); } TEST_F(PointerDelegateTest, Phase_FuchsiaCancelBecomesFlutterCancel) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD -> Flutter ADD+DOWN std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .AddResult( {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 2u); EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kAdd); EXPECT_EQ((*pointers)[1].change, flutter::PointerData::Change::kDown); // Fuchsia CANCEL -> Flutter CANCEL events = TouchEventBuilder::New() .AddTime(2222000u) .AddSample(kIxnOne, fup_EventPhase::CANCEL, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 1u); EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kCancel); } TEST_F(PointerDelegateTest, Coordinates_CorrectMapping) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD event, with a view parameter that maps the viewport identically // to the view. Then the center point of the viewport should map to the center // of the view, (10.f, 10.f). std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(2222000u) .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, /*viewport*/ {{{0, 0}, {20, 20}}}, /*matrix*/ {1, 0, 0, 0, 1, 0, 0, 0, 1}) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .AddResult( {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 2u); // ADD - DOWN EXPECT_FLOAT_EQ((*pointers)[0].physical_x, 10.f); EXPECT_FLOAT_EQ((*pointers)[0].physical_y, 10.f); pointers = {}; // Fuchsia CHANGE event, with a view parameter that translates the viewport by // (10, 10) within the view. Then the minimal point in the viewport (its // origin) should map to the center of the view, (10.f, 10.f). events = TouchEventBuilder::New() .AddTime(2222000u) .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, /*viewport*/ {{{0, 0}, {20, 20}}}, /*matrix*/ {1, 0, 0, 0, 1, 0, 10, 10, 1}) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {0.f, 0.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 1u); // MOVE EXPECT_FLOAT_EQ((*pointers)[0].physical_x, 10.f); EXPECT_FLOAT_EQ((*pointers)[0].physical_y, 10.f); // Fuchsia CHANGE event, with a view parameter that scales the viewport by // (0.5, 0.5) within the view. Then the maximal point in the viewport should // map to the center of the view, (10.f, 10.f). events = TouchEventBuilder::New() .AddTime(2222000u) .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, /*viewport*/ {{{0, 0}, {20, 20}}}, /*matrix*/ {0.5f, 0, 0, 0, 0.5f, 0, 0, 0, 1}) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {20.f, 20.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 1u); // MOVE EXPECT_FLOAT_EQ((*pointers)[0].physical_x, 10.f); EXPECT_FLOAT_EQ((*pointers)[0].physical_y, 10.f); } TEST_F(PointerDelegateTest, Coordinates_DownEventClampedToView) { const float kSmallDiscrepancy = -0.00003f; std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, kSmallDiscrepancy}) .AddResult( {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers->size(), 2u); const auto& add_event = (*pointers)[0]; EXPECT_FLOAT_EQ(add_event.physical_x, 10.f); EXPECT_FLOAT_EQ(add_event.physical_y, kSmallDiscrepancy); const auto& down_event = (*pointers)[1]; EXPECT_FLOAT_EQ(down_event.physical_x, 10.f); EXPECT_EQ(down_event.physical_y, 0.f); } TEST_F(PointerDelegateTest, Protocol_FirstResponseIsEmpty) { bool called = false; pointer_delegate_->WatchLoop( [&called](std::vector<flutter::PointerData> events) { called = true; }); RunLoopUntilIdle(); // Server gets Watch call. EXPECT_FALSE(called); // No events yet received to forward to client. // Server sees an initial "response" from client, which is empty, by contract. const auto responses = touch_source_->UploadedResponses(); ASSERT_TRUE(responses.has_value()); ASSERT_EQ(responses->size(), 0u); } TEST_F(PointerDelegateTest, Protocol_ResponseMatchesEarlierEvents) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia view parameter only. Empty response. std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .BuildAsVector(); // Fuchsia ptr 1 ADD sample. Yes response. fup_TouchEvent e1 = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample({.device_id = 0u, .pointer_id = 1u, .interaction_id = 3u}, fup_EventPhase::ADD, {10.f, 10.f}) .Build(); events.emplace_back(std::move(e1)); // Fuchsia ptr 2 ADD sample. Yes response. fup_TouchEvent e2 = TouchEventBuilder::New() .AddTime(1111000u) .AddSample({.device_id = 0u, .pointer_id = 2u, .interaction_id = 3u}, fup_EventPhase::ADD, {5.f, 5.f}) .Build(); events.emplace_back(std::move(e2)); // Fuchsia ptr 3 ADD sample. Yes response. fup_TouchEvent e3 = TouchEventBuilder::New() .AddTime(1111000u) .AddSample({.device_id = 0u, .pointer_id = 3u, .interaction_id = 3u}, fup_EventPhase::ADD, {1.f, 1.f}) .Build(); events.emplace_back(std::move(e3)); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); const auto responses = touch_source_->UploadedResponses(); ASSERT_TRUE(responses.has_value()); ASSERT_EQ(responses.value().size(), 4u); // Event 0 did not carry a sample, so no response. EXPECT_FALSE(responses.value()[0].has_response_type()); // Events 1-3 had a sample, must have a response. EXPECT_TRUE(responses.value()[1].has_response_type()); EXPECT_EQ(responses.value()[1].response_type(), fup_TouchResponseType::YES); EXPECT_TRUE(responses.value()[2].has_response_type()); EXPECT_EQ(responses.value()[2].response_type(), fup_TouchResponseType::YES); EXPECT_TRUE(responses.value()[3].has_response_type()); EXPECT_EQ(responses.value()[3].response_type(), fup_TouchResponseType::YES); } TEST_F(PointerDelegateTest, Protocol_LateGrant) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, no grant result - buffer it. std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); EXPECT_EQ(pointers.value().size(), 0u); pointers = {}; // Fuchsia CHANGE, no grant result - buffer it. events = TouchEventBuilder::New() .AddTime(2222000u) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); EXPECT_EQ(pointers.value().size(), 0u); pointers = {}; // Fuchsia result: ownership granted. Buffered pointers released. events = TouchEventBuilder::New() .AddTime(3333000u) .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 3u); // ADD - DOWN - MOVE EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); EXPECT_EQ(pointers.value()[2].change, flutter::PointerData::Change::kMove); pointers = {}; // Fuchsia CHANGE, grant result - release immediately. events = TouchEventBuilder::New() .AddTime(/* in nanoseconds */ 4444000u) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 1u); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kMove); EXPECT_EQ(pointers.value()[0].time_stamp, /* in microseconds */ 4444u); pointers = {}; } TEST_F(PointerDelegateTest, Protocol_LateGrantCombo) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, no grant result - buffer it. std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); EXPECT_EQ(pointers.value().size(), 0u); pointers = {}; // Fuchsia CHANGE, no grant result - buffer it. events = TouchEventBuilder::New() .AddTime(2222000u) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); EXPECT_EQ(pointers.value().size(), 0u); pointers = {}; // Fuchsia CHANGE, with grant result - release buffered events. events = TouchEventBuilder::New() .AddTime(3333000u) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 4u); // ADD - DOWN - MOVE - MOVE EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); EXPECT_EQ(pointers.value()[0].time_stamp, 1111u); EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); EXPECT_EQ(pointers.value()[1].time_stamp, 1111u); EXPECT_EQ(pointers.value()[2].change, flutter::PointerData::Change::kMove); EXPECT_EQ(pointers.value()[2].time_stamp, 2222u); EXPECT_EQ(pointers.value()[3].change, flutter::PointerData::Change::kMove); EXPECT_EQ(pointers.value()[3].time_stamp, 3333u); pointers = {}; } TEST_F(PointerDelegateTest, Protocol_EarlyGrant) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, with grant result - release immediately. std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 2u); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); pointers = {}; // Fuchsia CHANGE, after grant result - release immediately. events = TouchEventBuilder::New() .AddTime(2222000u) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 1u); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kMove); pointers = {}; } TEST_F(PointerDelegateTest, Protocol_LateDeny) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, no grant result - buffer it. std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); EXPECT_EQ(pointers.value().size(), 0u); pointers = {}; // Fuchsia CHANGE, no grant result - buffer it. events = TouchEventBuilder::New() .AddTime(2222000u) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); EXPECT_EQ(pointers.value().size(), 0u); pointers = {}; // Fuchsia result: ownership denied. Buffered pointers deleted. events = TouchEventBuilder::New() .AddTime(3333000u) .AddResult({kIxnOne, fup_TouchIxnStatus::DENIED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 0u); // Do not release to client! pointers = {}; } TEST_F(PointerDelegateTest, Protocol_LateDenyCombo) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, no grant result - buffer it. std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); EXPECT_EQ(pointers.value().size(), 0u); pointers = {}; // Fuchsia CHANGE, no grant result - buffer it. events = TouchEventBuilder::New() .AddTime(2222000u) .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); EXPECT_EQ(pointers.value().size(), 0u); pointers = {}; // Fuchsia result: ownership denied. Buffered pointers deleted. events = TouchEventBuilder::New() .AddTime(3333000u) .AddSample(kIxnOne, fup_EventPhase::CANCEL, {10.f, 10.f}) .AddResult({kIxnOne, fup_TouchIxnStatus::DENIED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 0u); // Do not release to client! pointers = {}; } TEST_F(PointerDelegateTest, Protocol_PointersAreIndependent) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. constexpr fup_TouchIxnId kIxnTwo = { .device_id = 1u, .pointer_id = 2u, .interaction_id = 2u}; // Fuchsia ptr1 ADD and ptr2 ADD, no grant result for either - buffer them. std::vector<fup_TouchEvent> events = TouchEventBuilder::New() .AddTime(1111000u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) .BuildAsVector(); fup_TouchEvent ptr2 = TouchEventBuilder::New() .AddTime(1111000u) .AddSample(kIxnTwo, fup_EventPhase::ADD, {15.f, 15.f}) .Build(); events.emplace_back(std::move(ptr2)); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); EXPECT_EQ(pointers.value().size(), 0u); pointers = {}; // Server grants win to pointer 2. events = TouchEventBuilder::New() .AddTime(2222000u) .AddResult({kIxnTwo, fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); // Note: Fuchsia's device and pointer IDs (both 32 bit) are coerced together // to fit in Flutter's 64-bit device ID. However, Flutter's pointer_identifier // is not set by platform runner code - PointerDataCaptureConverter (PDPC) // sets it. ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 2u); EXPECT_EQ(pointers.value()[0].pointer_identifier, 0); // reserved for PDPC EXPECT_EQ(pointers.value()[0].device, (int64_t)((1ul << 32) | 2u)); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); EXPECT_EQ(pointers.value()[1].pointer_identifier, 0); // reserved for PDPC EXPECT_EQ(pointers.value()[1].device, (int64_t)((1ul << 32) | 2u)); EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); pointers = {}; // Server grants win to pointer 1. events = TouchEventBuilder::New() .AddTime(3333000u) .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) .BuildAsVector(); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 2u); EXPECT_EQ(pointers.value()[0].pointer_identifier, 0); // reserved for PDPC EXPECT_EQ(pointers.value()[0].device, (int64_t)((1ul << 32) | 1u)); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); EXPECT_EQ(pointers.value()[1].pointer_identifier, 0); // reserved for PDPC EXPECT_EQ(pointers.value()[1].device, (int64_t)((1ul << 32) | 1u)); EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); pointers = {}; } TEST_F(PointerDelegateTest, MouseWheel_TickBased) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. std::vector<fup_MouseEvent> events = MouseEventBuilder() .AddTime(1111789u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {0, 1}, kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) .BuildAsVector(); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 1u); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); EXPECT_EQ(pointers.value()[0].signal_kind, flutter::PointerData::SignalKind::kScroll); EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); EXPECT_EQ(pointers.value()[0].buttons, 0); EXPECT_EQ(pointers.value()[0].scroll_delta_x, 0); EXPECT_EQ(pointers.value()[0].scroll_delta_y, -20); pointers = {}; // receive a horizontal scroll events = MouseEventBuilder() .AddTime(1111789u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {1, 0}, kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) .BuildAsVector(); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 1u); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); EXPECT_EQ(pointers.value()[0].signal_kind, flutter::PointerData::SignalKind::kScroll); EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); EXPECT_EQ(pointers.value()[0].buttons, 0); EXPECT_EQ(pointers.value()[0].scroll_delta_x, 20); EXPECT_EQ(pointers.value()[0].scroll_delta_y, 0); pointers = {}; } TEST_F(PointerDelegateTest, MouseWheel_PixelBased) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. std::vector<fup_MouseEvent> events = MouseEventBuilder() .AddTime(1111789u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {0, 1}, {0, 120}, kNotPrecisionScroll) .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) .BuildAsVector(); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 1u); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); EXPECT_EQ(pointers.value()[0].signal_kind, flutter::PointerData::SignalKind::kScroll); EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); EXPECT_EQ(pointers.value()[0].buttons, 0); EXPECT_EQ(pointers.value()[0].scroll_delta_x, 0); EXPECT_EQ(pointers.value()[0].scroll_delta_y, -120); pointers = {}; // receive a horizontal scroll events = MouseEventBuilder() .AddTime(1111789u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {1, 0}, {120, 0}, kNotPrecisionScroll) .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) .BuildAsVector(); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 1u); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); EXPECT_EQ(pointers.value()[0].signal_kind, flutter::PointerData::SignalKind::kScroll); EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); EXPECT_EQ(pointers.value()[0].buttons, 0); EXPECT_EQ(pointers.value()[0].scroll_delta_x, 120); EXPECT_EQ(pointers.value()[0].scroll_delta_y, 0); pointers = {}; } TEST_F(PointerDelegateTest, MouseWheel_TouchpadPixelBased) { std::optional<std::vector<flutter::PointerData>> pointers; pointer_delegate_->WatchLoop( [&pointers](std::vector<flutter::PointerData> events) { pointers = std::move(events); }); RunLoopUntilIdle(); // Server gets watch call. std::vector<fup_MouseEvent> events = MouseEventBuilder() .AddTime(1111789u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {0, 1}, {0, 120}, kPrecisionScroll) .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) .BuildAsVector(); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 1u); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); EXPECT_EQ(pointers.value()[0].signal_kind, flutter::PointerData::SignalKind::kScroll); EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); EXPECT_EQ(pointers.value()[0].buttons, 0); EXPECT_EQ(pointers.value()[0].scroll_delta_x, 0); EXPECT_EQ(pointers.value()[0].scroll_delta_y, -120); pointers = {}; // receive a horizontal scroll events = MouseEventBuilder() .AddTime(1111789u) .AddViewParameters(kRect, kRect, kIdentity) .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {1, 0}, {120, 0}, kPrecisionScroll) .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) .BuildAsVector(); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_TRUE(pointers.has_value()); ASSERT_EQ(pointers.value().size(), 1u); EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); EXPECT_EQ(pointers.value()[0].signal_kind, flutter::PointerData::SignalKind::kScroll); EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); EXPECT_EQ(pointers.value()[0].buttons, 0); EXPECT_EQ(pointers.value()[0].scroll_delta_x, 120); EXPECT_EQ(pointers.value()[0].scroll_delta_y, 0); pointers = {}; } } // namespace flutter_runner::testing
engine/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc", "repo_id": "engine", "token_count": 13993 }
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_FLUTTER_SOFTWARE_SURFACE_PRODUCER_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_PRODUCER_H_ #include <fuchsia/sysmem/cpp/fidl.h> #include <fuchsia/ui/composition/cpp/fidl.h> #include <unordered_map> #include "flutter/fml/macros.h" #include "software_surface.h" namespace flutter_runner { class SoftwareSurfaceProducer final : public SurfaceProducer { public: // Only keep 12 surfaces at a time. static constexpr int kMaxSurfaces = 12; // If a surface doesn't get used for 3 or more generations, we discard it. static constexpr int kMaxSurfaceAge = 3; explicit SoftwareSurfaceProducer(); ~SoftwareSurfaceProducer() override; bool IsValid() const { return valid_; } // |SurfaceProducer| GrDirectContext* gr_context() const override { return nullptr; } // |SurfaceProducer| std::unique_ptr<SurfaceProducerSurface> ProduceOffscreenSurface( const SkISize& size) override; // |SurfaceProducer| std::unique_ptr<SurfaceProducerSurface> ProduceSurface( const SkISize& size) override; // |SurfaceProducer| void SubmitSurfaces( std::vector<std::unique_ptr<SurfaceProducerSurface>> surfaces) override; private: void SubmitSurface(std::unique_ptr<SurfaceProducerSurface> surface); std::unique_ptr<SoftwareSurface> CreateSurface(const SkISize& size); void RecycleSurface(std::unique_ptr<SoftwareSurface> surface); void RecyclePendingSurface(uintptr_t surface_key); void AgeAndCollectOldBuffers(); void TraceStats(); fuchsia::sysmem::AllocatorSyncPtr sysmem_allocator_; fuchsia::ui::composition::AllocatorPtr flatland_allocator_; // These surfaces are available for re-use. std::vector<std::unique_ptr<SoftwareSurface>> available_surfaces_; // These surfaces have been written to, but scenic is not finished reading // from them yet. std::unordered_map<uintptr_t, std::unique_ptr<SoftwareSurface>> pending_surfaces_; size_t trace_surfaces_created_ = 0; size_t trace_surfaces_reused_ = 0; bool valid_ = false; FML_DISALLOW_COPY_AND_ASSIGN(SoftwareSurfaceProducer); }; } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_PRODUCER_H_
engine/shell/platform/fuchsia/flutter/software_surface_producer.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/software_surface_producer.h", "repo_id": "engine", "token_count": 826 }
395
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_H_ #include <fuchsia/math/cpp/fidl.h> #include <fuchsia/scenic/scheduling/cpp/fidl.h> #include <fuchsia/sysmem/cpp/fidl.h> #include <fuchsia/ui/composition/cpp/fidl.h> #include <fuchsia/ui/composition/cpp/fidl_test_base.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/async/dispatcher.h> #include <lib/fidl/cpp/binding.h> #include <lib/fidl/cpp/interface_request.h> #include <cstdint> #include <functional> #include <string> #include <unordered_map> #include <vector> #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" #include "fake_flatland_types.h" namespace flutter_runner::testing { // A lightweight fake implementation of the Flatland API. // // The fake has no side effects besides mutating its own internal state // according to the rules of interacting with the Flatland API. It makes that // internal state available for inspection by a test. // // Thus it allows tests to do a few things that would be difficult using either // a mock implementation or the real implementation: // + It allows the user to hook `Present` invocations and respond with // stubbed-out `FuturePresentationTimes`, but more crucially it mimics the // real Flatland behavior of only processing commands when a `Present` is // invoked. // + It allows the user to inspect a snapshot of the scene graph at any moment // in time, via the `SceneGraph()` accessor. // + It stores the various Flatland transforms and content generated by // commands into a std::unordered_map, and also correctly manages the // transform and content lifetimes via reference counting. This allows a // given transform or content to stay alive if its parent still holds a // reference to it, in the same way the real Flatland implementation would. // + The resources returned by `SceneGraph()` that the test uses for // inspection are decoupled from the resources managed internally by the // `FakeFlatland` itself -- they are a snapshot of the scene graph at that // moment in time, with all snapshot state being cloned from the underlying // scene graph state. This allows the `FakeFlatland` and test to naturally // use `shared_ptr` for reference counting and mimic the real Flatland // behavior exactly, instead of an awkward index-based API. // + TODO(fxb/85619): Allow injecting {touch,mouse,focus,views} events using // the ViewBoundProtocols and {ParentViewport,ChildView}Watcher. // + TODO(fxb/85619): Error handling / flatland disconnection is still WIP. // FakeFlatland will likely generate a CHECK in any place where the real // Flatland would disconnect or send a FlatlandError. // // The fake deliberately does not attempt to handle certain aspects of the real // Flatland implemntation which are complex or burdensome to implement: // +Rendering/interacting with Vulkan in any way // +Cross-flatland links between Views and Viewports. class FakeFlatland : public fuchsia::ui::composition::testing::Allocator_TestBase, public fuchsia::ui::composition::testing::Flatland_TestBase { public: using PresentHandler = std::function<void(fuchsia::ui::composition::PresentArgs)>; FakeFlatland(); ~FakeFlatland() override; bool is_allocator_connected() const { return allocator_binding_.is_bound(); } bool is_flatland_connected() const { return flatland_binding_.is_bound(); } const std::string& debug_name() const { return debug_name_; } const FakeGraph& graph() { return current_graph_; } // Bind this instance's Flatland FIDL channel to the `dispatcher` and allow // processing of incoming FIDL requests. // // This can only be called once. fuchsia::ui::composition::AllocatorHandle ConnectAllocator( async_dispatcher_t* dispatcher = nullptr); // Bind this instance's Allocator FIDL channel to the `dispatcher` and allow // processing of incoming FIDL requests. // // This can only be called once. fuchsia::ui::composition::FlatlandHandle ConnectFlatland( async_dispatcher_t* dispatcher = nullptr); // Disconnect the Flatland's FIDL channel with an error. // TODO(fxb/85619): Call this internally upon command error, instead of // CHECK'ing. void Disconnect(fuchsia::ui::composition::FlatlandError error); // Set a handler for `Present`-related FIDL calls' return values. void SetPresentHandler(PresentHandler present_handler); // Fire an `OnNextFrameBegin` event. Call this first after a `Present` in // order to give additional present tokens to the client and simulate scenic's // normal event flow. void FireOnNextFrameBeginEvent( fuchsia::ui::composition::OnNextFrameBeginValues on_next_frame_begin_values); // Fire an `OnFramePresented` event. Call this second after a `Present` in // order to inform the client of retured frames and simulate scenic's normal // event flow. void FireOnFramePresentedEvent( fuchsia::scenic::scheduling::FramePresentedInfo frame_presented_info); private: struct ParentViewportWatcher : public fuchsia::ui::composition::testing:: ParentViewportWatcher_TestBase { public: 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); ParentViewportWatcher(ParentViewportWatcher&& other); ~ParentViewportWatcher() override; // |fuchsia::ui::composition::testing::ParentViewportWatcher_TestBase| void NotImplemented_(const std::string& name) override; // |fuchsia::ui::composition::ParentViewportWatcher| void GetLayout(GetLayoutCallback callback) override; // |fuchsia::ui::composition::ParentViewportWatcher| void GetStatus(GetStatusCallback callback) override; fuchsia::ui::views::ViewCreationToken view_token; fuchsia::ui::views::ViewIdentityOnCreation view_identity; fuchsia::ui::composition::ViewBoundProtocols view_protocols; fidl::Binding<fuchsia::ui::composition::ParentViewportWatcher> parent_viewport_watcher; }; struct ChildViewWatcher : public fuchsia::ui::composition::testing::ChildViewWatcher_TestBase { public: ChildViewWatcher( fuchsia::ui::views::ViewportCreationToken viewport_token, fidl::InterfaceRequest<fuchsia::ui::composition::ChildViewWatcher> child_view_watcher, async_dispatcher_t* dispatcher); ChildViewWatcher(ChildViewWatcher&& other); ~ChildViewWatcher() override; // |fuchsia::ui::composition::testing::ChildViewWatcher_TestBase| void NotImplemented_(const std::string& name) override; // |fuchsia::ui::composition::ChildViewWatcher| void GetStatus(GetStatusCallback callback) override; fuchsia::ui::views::ViewportCreationToken viewport_token; fidl::Binding<fuchsia::ui::composition::ChildViewWatcher> child_view_watcher; }; struct ImageBinding { fuchsia::ui::composition::BufferCollectionImportToken import_token; }; struct BufferCollectionBinding { fuchsia::ui::composition::BufferCollectionExportToken export_token; fuchsia::sysmem::BufferCollectionTokenHandle sysmem_token; fuchsia::ui::composition::RegisterBufferCollectionUsage usage; }; struct GraphBindings { std::optional<std::pair<zx_koid_t, ParentViewportWatcher>> viewport_watcher; std::unordered_map<zx_koid_t, ChildViewWatcher> view_watchers; std::unordered_map<zx_koid_t, ImageBinding> images; std::unordered_map<zx_koid_t, BufferCollectionBinding> buffer_collections; }; // |fuchsia::ui::composition::testing::Allocator_TestBase| // |fuchsia::ui::composition::testing::Flatland_TestBase| void NotImplemented_(const std::string& name) override; // |fuchsia::ui::composition::testing::Allocator| void RegisterBufferCollection( fuchsia::ui::composition::RegisterBufferCollectionArgs args, RegisterBufferCollectionCallback callback) override; // |fuchsia::ui::composition::Flatland| void Present(fuchsia::ui::composition::PresentArgs args) override; // |fuchsia::ui::composition::Flatland| void CreateView( fuchsia::ui::views::ViewCreationToken token, fidl::InterfaceRequest<fuchsia::ui::composition::ParentViewportWatcher> parent_viewport_watcher) override; // |fuchsia::ui::composition::Flatland| void 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) override; // |fuchsia::ui::composition::Flatland| void CreateTransform( fuchsia::ui::composition::TransformId transform_id) override; // |fuchsia::ui::composition::Flatland| void SetTranslation(fuchsia::ui::composition::TransformId transform_id, fuchsia::math::Vec translation) override; // |fuchsia::ui::composition::Flatland| void SetScale(fuchsia::ui::composition::TransformId transform_id, fuchsia::math::VecF scale) override; // |fuchsia::ui::composition::Flatland| void SetOrientation( fuchsia::ui::composition::TransformId transform_id, fuchsia::ui::composition::Orientation orientation) override; // |fuchsia::ui::composition::Flatland| void SetOpacity(fuchsia::ui::composition::TransformId transform_id, float value) override; // |fuchsia::ui::composition::Flatland| void SetClipBoundary(fuchsia::ui::composition::TransformId transform_id, std::unique_ptr<fuchsia::math::Rect> bounds) override; // TODO(fxbug.dev/89111): Re-enable once SDK rolls. // // |fuchsia::ui::composition::Flatland| // void SetImageOpacity(fuchsia::ui::composition::ContentId image_id, // float opacity) override; // |fuchsia::ui::composition::Flatland| void AddChild( fuchsia::ui::composition::TransformId parent_transform_id, fuchsia::ui::composition::TransformId child_transform_id) override; // |fuchsia::ui::composition::Flatland| void RemoveChild( fuchsia::ui::composition::TransformId parent_transform_id, fuchsia::ui::composition::TransformId child_transform_id) override; // |fuchsia::ui::composition::Flatland| void SetContent(fuchsia::ui::composition::TransformId transform_id, fuchsia::ui::composition::ContentId content_id) override; // |fuchsia::ui::composition::Flatland| void SetRootTransform( fuchsia::ui::composition::TransformId transform_id) override; // |fuchsia::ui::composition::Flatland| void 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) override; // |fuchsia::ui::composition::Flatland| void CreateImage( fuchsia::ui::composition::ContentId image_id, fuchsia::ui::composition::BufferCollectionImportToken import_token, uint32_t vmo_index, fuchsia::ui::composition::ImageProperties properties) override; // |fuchsia::ui::composition::Flatland| void SetImageSampleRegion(fuchsia::ui::composition::ContentId image_id, fuchsia::math::RectF rect) override; // |fuchsia::ui::composition::Flatland| void SetImageDestinationSize(fuchsia::ui::composition::ContentId image_id, fuchsia::math::SizeU size) override; // |fuchsia::ui::composition::Flatland| void SetImageBlendingFunction( fuchsia::ui::composition::ContentId image_id, fuchsia::ui::composition::BlendMode blend_mode) override; // |fuchsia::ui::composition::Flatland| void SetViewportProperties( fuchsia::ui::composition::ContentId viewport_id, fuchsia::ui::composition::ViewportProperties properties) override; // |fuchsia::ui::composition::Flatland| void ReleaseTransform( fuchsia::ui::composition::TransformId transform_id) override; // |fuchsia::ui::composition::Flatland| void ReleaseViewport(fuchsia::ui::composition::ContentId viewport_id, ReleaseViewportCallback callback) override; // |fuchsia::ui::composition::Flatland| void ReleaseImage(fuchsia::ui::composition::ContentId image_id) override; // |fuchsia::ui::composition::Flatland| void SetHitRegions( fuchsia::ui::composition::TransformId transform_id, std::vector<fuchsia::ui::composition::HitRegion> regions) override; // |fuchsia::ui::composition::Flatland| void SetInfiniteHitRegion( fuchsia::ui::composition::TransformId transform_id, fuchsia::ui::composition::HitTestInteraction hit_test) override; // |fuchsia::ui::composition::Flatland| void Clear() override; // |fuchsia::ui::composition::Flatland| void SetDebugName(std::string debug_name) override; fidl::Binding<fuchsia::ui::composition::Allocator> allocator_binding_; fidl::Binding<fuchsia::ui::composition::Flatland> flatland_binding_; GraphBindings graph_bindings_; PresentHandler present_handler_; FakeGraph pending_graph_; FakeGraph current_graph_; // This map is used to cache parent refs for `AddChild` and `RemoveChild`. // // Ideally we would like to map weak(child) -> weak(parent), but std::weak_ptr // cannot be the Key for an associative container. Instead we key on the raw // parent pointer and store pair(weak(parent), weak(child)) in the map. std::unordered_map< FakeGraph::TransformIdKey, std::pair<std::weak_ptr<FakeTransform>, std::weak_ptr<FakeTransform>>> parents_map_; std::string debug_name_; FML_DISALLOW_COPY_AND_ASSIGN(FakeFlatland); }; } // namespace flutter_runner::testing #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_H_
engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.h", "repo_id": "engine", "token_count": 5036 }
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. import("//flutter/tools/fuchsia/dart/dart_library.gni") import("//flutter/tools/fuchsia/flutter/flutter_component.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") dart_library("lib") { package_name = "parent-view" sources = [ "parent_view.dart" ] deps = [ "//flutter/shell/platform/fuchsia/dart:args", "//flutter/shell/platform/fuchsia/dart:vector_math", ] } flutter_component("component") { main_package = "parent-view" component_name = "parent-view" main_dart = "parent_view.dart" manifest = rebase_path("meta/parent-view.cml") deps = [ ":lib" ] } fuchsia_package("package") { package_name = "parent-view" deps = [ ":component" ] }
engine/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/BUILD.gn", "repo_id": "engine", "token_count": 348 }
397
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This is an instrumented test application. It has a single field, is // able to receive keyboard input from the test fixture, and is able to report // back the contents of its text field to the test fixture. import 'dart:convert'; import 'dart:typed_data'; import 'dart:ui'; // Corresponds to the USB HID values provided in fidl.fuchsia.input // https://fuchsia.dev/reference/fidl/fuchsia.input final Map<int, String> hidToKey = { 458977: 'LEFT_SHIFT', // Keyboard Left Shift 458792: 'ENTER', // Keyboard Enter (Return) 458782: 'KEY_1', // Keyboard 1 and ! 458763: 'H', // Keyboard h and H 458760: 'E', // Keyboard e and E 458767: 'L', // Keyboard l and L 458770: 'O', // Keyboard o and O 458778: 'W', // Keyboard w and W 458773: 'R', // Keyboard r and R 458759: 'D', // Keyboard d and D }; int main() { final bool soundNullSafety = <int?>[null] is! List<int>; print('Launching text-input-view. Sound null safety: $soundNullSafety'); TestApp app = TestApp(); app.run(); return 0; } class TestApp { static const _yellow = Color.fromARGB(255, 255, 255, 0); Color _backgroundColor = _yellow; void run() { // Set up window callbacks window.onPlatformMessage = (String name, ByteData? data, PlatformMessageResponseCallback? callback) { this.decodeAndReportPlatformMessage(name, data!); }; window.onMetricsChanged = () { window.scheduleFrame(); }; window.onBeginFrame = (Duration duration) { this.beginFrame(duration); }; window.scheduleFrame(); } void beginFrame(Duration duration) { // Convert physical screen size of device to values final pixelRatio = window.devicePixelRatio; final size = window.physicalSize / pixelRatio; final physicalBounds = Offset.zero & size * pixelRatio; final windowBounds = Offset.zero & size; // Set up a Canvas that uses the screen size final recorder = PictureRecorder(); final canvas = Canvas(recorder, physicalBounds); canvas.scale(pixelRatio, pixelRatio); // Draw something final paint = Paint()..color = this._backgroundColor; canvas.drawRect(windowBounds, paint); // Build the scene final picture = recorder.endRecording(); final sceneBuilder = SceneBuilder() ..pushClipRect(physicalBounds) ..addPicture(Offset.zero, picture) ..pop(); window.render(sceneBuilder.build()); } void decodeAndReportPlatformMessage(String name, ByteData data) async { final buffer = data.buffer; var list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); var decoded = utf8.decode(list); var decodedJson = json.decode(decoded); print('received ${name} platform message: ${decodedJson}'); if (name == "flutter/keyevent" && decodedJson["type"] == "keydown") { if (hidToKey[decodedJson["hidUsage"]] != null) { _reportTextInput(hidToKey[decodedJson["hidUsage"]!]!); } } window.scheduleFrame(); } void _reportTextInput(String text) { print('text-input-view reporting keyboard input to KeyboardInputListener'); final message = utf8 .encode(json.encode({ 'method': 'KeyboardInputListener.ReportTextInput', 'text': text, })) .buffer .asByteData(); PlatformDispatcher.instance .sendPlatformMessage('fuchsia/input_test', message, null); } }
engine/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/lib/text_input_view.dart/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/lib/text_input_view.dart", "repo_id": "engine", "token_count": 1238 }
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. #include "check_view.h" #include "flutter/fml/logging.h" namespace fuchsia_test_utils { bool CheckViewExistsInSnapshot( const fuchsia::ui::observation::geometry::ViewTreeSnapshot& snapshot, zx_koid_t view_ref_koid) { if (!snapshot.has_views()) { return false; } auto snapshot_count = std::count_if(snapshot.views().begin(), snapshot.views().end(), [view_ref_koid](const auto& view) { return view.view_ref_koid() == view_ref_koid; }); return snapshot_count > 0; } bool CheckViewExistsInUpdates( const std::vector<fuchsia::ui::observation::geometry::ViewTreeSnapshot>& updates, zx_koid_t view_ref_koid) { auto update_count = std::count_if( updates.begin(), updates.end(), [view_ref_koid](auto& snapshot) { return CheckViewExistsInSnapshot(snapshot, view_ref_koid); }); return update_count > 0; } } // namespace fuchsia_test_utils
engine/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.cc", "repo_id": "engine", "token_count": 460 }
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 "text_delegate.h" #include <fuchsia/ui/input/cpp/fidl.h> #include <fuchsia/ui/input3/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <gtest/gtest.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fidl/cpp/binding.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/zx/eventpair.h> #include "tests/fakes/platform_message.h" #include "flutter/lib/ui/window/platform_message.h" #include <memory> namespace flutter_runner::testing { // Convert a |PlatformMessage| to string for ease of testing. static std::string MessageToString(PlatformMessage& message) { const char* data = reinterpret_cast<const char*>(message.data().GetMapping()); return std::string(data, message.data().GetSize()); } // Fake |KeyboardService| implementation. Only responsibility is to remember // what it was called with. class FakeKeyboardService : public fuchsia::ui::input3::Keyboard { public: // |fuchsia.ui.input3/Keyboard.AddListener| virtual void AddListener( fuchsia::ui::views::ViewRef, fidl::InterfaceHandle<fuchsia::ui::input3::KeyboardListener> listener, fuchsia::ui::input3::Keyboard::AddListenerCallback callback) { listener_ = listener.Bind(); callback(); } fidl::InterfacePtr<fuchsia::ui::input3::KeyboardListener> listener_; }; // Fake ImeService implementation. Only responsibility is to remember what // it was called with. class FakeImeService : public fuchsia::ui::input::ImeService { public: virtual void GetInputMethodEditor( fuchsia::ui::input::KeyboardType keyboard_type, fuchsia::ui::input::InputMethodAction action, fuchsia::ui::input::TextInputState input_state, fidl::InterfaceHandle<fuchsia::ui::input::InputMethodEditorClient> client, fidl::InterfaceRequest<fuchsia::ui::input::InputMethodEditor> ime) { keyboard_type_ = std::move(keyboard_type); action_ = std::move(action); input_state_ = std::move(input_state); client_ = client.Bind(); ime_ = std::move(ime); } virtual void ShowKeyboard() { keyboard_shown_ = true; } virtual void HideKeyboard() { keyboard_shown_ = false; } bool IsKeyboardShown() { return keyboard_shown_; } bool keyboard_shown_ = false; fuchsia::ui::input::KeyboardType keyboard_type_; fuchsia::ui::input::InputMethodAction action_; fuchsia::ui::input::TextInputState input_state_; fidl::InterfacePtr<fuchsia::ui::input::InputMethodEditorClient> client_; fidl::InterfaceRequest<fuchsia::ui::input::InputMethodEditor> ime_; }; class TextDelegateTest : public ::testing::Test { protected: TextDelegateTest() : loop_(&kAsyncLoopConfigAttachToCurrentThread), keyboard_service_binding_(&keyboard_service_), ime_service_binding_(&ime_service_) { fidl::InterfaceHandle<fuchsia::ui::input3::Keyboard> keyboard_handle; auto keyboard_request = keyboard_handle.NewRequest(); keyboard_service_binding_.Bind(keyboard_request.TakeChannel()); fidl::InterfaceHandle<fuchsia::ui::input::ImeService> ime_service_handle; ime_service_binding_.Bind(ime_service_handle.NewRequest().TakeChannel()); fuchsia::ui::views::ViewRefControl view_ref_control; fuchsia::ui::views::ViewRef view_ref; auto status = zx::eventpair::create( /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); ZX_ASSERT(status == ZX_OK); view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); text_delegate_ = std::make_unique<TextDelegate>( std::move(view_ref), std::move(ime_service_handle), std::move(keyboard_handle), // Should this be accessed through a weak pointer? [this](std::unique_ptr<flutter::PlatformMessage> message) { last_message_ = std::move(message); }); // TextDelegate has some async initialization that needs to happen. RunLoopUntilIdle(); } // Runs the event loop until all scheduled events are spent. void RunLoopUntilIdle() { loop_.RunUntilIdle(); } void TearDown() override { loop_.Quit(); ASSERT_EQ(loop_.ResetQuit(), 0); } async::Loop loop_; FakeKeyboardService keyboard_service_; fidl::Binding<fuchsia::ui::input3::Keyboard> keyboard_service_binding_; FakeImeService ime_service_; fidl::Binding<fuchsia::ui::input::ImeService> ime_service_binding_; // Unit under test. std::unique_ptr<TextDelegate> text_delegate_; std::unique_ptr<flutter::PlatformMessage> last_message_; }; // Goes through several steps of a text edit protocol. These are hard to test // in isolation because the text edit protocol depends on the correct method // invocation sequence. The text editor is initialized with the editing // parameters, and we verify that the correct input action is parsed out. We // then exercise showing and hiding the keyboard, as well as a text state // update. TEST_F(TextDelegateTest, ActivateIme) { auto fake_platform_message_response = FakePlatformMessageResponse::Create(); { // Initialize the editor. Without this initialization, the protocol code // will crash. const auto set_client_msg = R"( { "method": "TextInput.setClient", "args": [ 7, { "inputType": { "name": "TextInputType.multiline", "signed":null, "decimal":null }, "readOnly": false, "obscureText": false, "autocorrect":true, "smartDashesType":"1", "smartQuotesType":"1", "enableSuggestions":true, "enableInteractiveSelection":true, "actionLabel":null, "inputAction":"TextInputAction.newline", "textCapitalization":"TextCapitalization.none", "keyboardAppearance":"Brightness.dark", "enableIMEPersonalizedLearning":true, "enableDeltaModel":false } ] } )"; auto message = fake_platform_message_response->WithMessage( kTextInputChannel, set_client_msg); text_delegate_->HandleFlutterTextInputChannelPlatformMessage( std::move(message)); RunLoopUntilIdle(); EXPECT_EQ(ime_service_.action_, fuchsia::ui::input::InputMethodAction::NEWLINE); EXPECT_FALSE(ime_service_.IsKeyboardShown()); } { // Verify that showing keyboard results in the correct platform effect. const auto set_client_msg = R"( { "method": "TextInput.show" } )"; auto message = fake_platform_message_response->WithMessage( kTextInputChannel, set_client_msg); text_delegate_->HandleFlutterTextInputChannelPlatformMessage( std::move(message)); RunLoopUntilIdle(); EXPECT_TRUE(ime_service_.IsKeyboardShown()); } { // Verify that hiding keyboard results in the correct platform effect. const auto set_client_msg = R"( { "method": "TextInput.hide" } )"; auto message = fake_platform_message_response->WithMessage( kTextInputChannel, set_client_msg); text_delegate_->HandleFlutterTextInputChannelPlatformMessage( std::move(message)); RunLoopUntilIdle(); EXPECT_FALSE(ime_service_.IsKeyboardShown()); } { // Update the editing state from the Fuchsia platform side. fuchsia::ui::input::TextInputState state = { .revision = 42, .text = "Foo", .selection = fuchsia::ui::input::TextSelection{}, .composing = fuchsia::ui::input::TextRange{}, }; auto input_event = std::make_unique<fuchsia::ui::input::InputEvent>(); ime_service_.client_->DidUpdateState(std::move(state), std::move(input_event)); RunLoopUntilIdle(); EXPECT_EQ( R"({"method":"TextInputClient.updateEditingState","args":[7,{"text":"Foo","selectionBase":0,"selectionExtent":0,"selectionAffinity":"TextAffinity.upstream","selectionIsDirectional":true,"composingBase":-1,"composingExtent":-1}]})", MessageToString(*last_message_)); } { // Notify Flutter that the action key has been pressed. ime_service_.client_->OnAction(fuchsia::ui::input::InputMethodAction::DONE); RunLoopUntilIdle(); EXPECT_EQ( R"({"method":"TextInputClient.performAction","args":[7,"TextInputAction.done"]})", MessageToString(*last_message_)); } } // Hands a few typical |KeyEvent|s to the text delegate. Regular key events are // handled, "odd" key events are rejected (not handled). "Handling" a key event // means converting it to an appropriate |PlatformMessage| and forwarding it. TEST_F(TextDelegateTest, OnAction) { { // A sensible key event is converted into a platform message. fuchsia::ui::input3::KeyEvent key_event; *key_event.mutable_type() = fuchsia::ui::input3::KeyEventType::PRESSED; *key_event.mutable_key() = fuchsia::input::Key::A; key_event.mutable_key_meaning()->set_codepoint('a'); fuchsia::ui::input3::KeyEventStatus status; keyboard_service_.listener_->OnKeyEvent( std::move(key_event), [&status](fuchsia::ui::input3::KeyEventStatus s) { status = std::move(s); }); RunLoopUntilIdle(); EXPECT_EQ(fuchsia::ui::input3::KeyEventStatus::HANDLED, status); EXPECT_EQ( R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":97,"modifiers":0})", MessageToString(*last_message_)); } { // SYNC event is not handled. // This is currently expected, though we may need to change that behavior. fuchsia::ui::input3::KeyEvent key_event; *key_event.mutable_type() = fuchsia::ui::input3::KeyEventType::SYNC; fuchsia::ui::input3::KeyEventStatus status; keyboard_service_.listener_->OnKeyEvent( std::move(key_event), [&status](fuchsia::ui::input3::KeyEventStatus s) { status = std::move(s); }); RunLoopUntilIdle(); EXPECT_EQ(fuchsia::ui::input3::KeyEventStatus::NOT_HANDLED, status); } { // CANCEL event is not handled. // This is currently expected, though we may need to change that behavior. fuchsia::ui::input3::KeyEvent key_event; *key_event.mutable_type() = fuchsia::ui::input3::KeyEventType::CANCEL; fuchsia::ui::input3::KeyEventStatus status; keyboard_service_.listener_->OnKeyEvent( std::move(key_event), [&status](fuchsia::ui::input3::KeyEventStatus s) { status = std::move(s); }); RunLoopUntilIdle(); EXPECT_EQ(fuchsia::ui::input3::KeyEventStatus::NOT_HANDLED, status); } } } // namespace flutter_runner::testing
engine/shell/platform/fuchsia/flutter/text_delegate_unittests.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/text_delegate_unittests.cc", "repo_id": "engine", "token_count": 4073 }
400
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_BUILD_INFO_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_BUILD_INFO_H_ #include "root_inspect_node.h" namespace dart_utils { class BuildInfo { public: static const char* DartSdkGitRevision(); static const char* DartSdkSemanticVersion(); static const char* FlutterEngineGitRevision(); static const char* FuchsiaSdkVersion(); /// Appends the above properties to the specified node on the inspect tree for /// the duration of the node's lifetime. static void Dump(inspect::Node& node); }; } // namespace dart_utils #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_BUILD_INFO_H_
engine/shell/platform/fuchsia/runtime/dart/utils/build_info.h/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/build_info.h", "repo_id": "engine", "token_count": 293 }
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. #include "vmo.h" #include <fcntl.h> #include <sys/stat.h> #include <fuchsia/io/cpp/fidl.h> #include <fuchsia/mem/cpp/fidl.h> #include <lib/fdio/directory.h> #include <lib/fdio/io.h> #include <zircon/status.h> #include <ios> #include "flutter/fml/logging.h" namespace { bool VmoFromFd(int fd, bool executable, fuchsia::mem::Buffer* buffer) { if (!buffer) { FML_LOG(FATAL) << "Invalid buffer pointer"; } struct stat stat_struct; if (fstat(fd, &stat_struct) == -1) { FML_LOG(ERROR) << "fstat failed: " << strerror(errno); return false; } zx_handle_t result = ZX_HANDLE_INVALID; zx_status_t status; if (executable) { status = fdio_get_vmo_exec(fd, &result); } else { status = fdio_get_vmo_copy(fd, &result); } if (status != ZX_OK) { FML_LOG(ERROR) << (executable ? "fdio_get_vmo_exec" : "fdio_get_vmo_copy") << " failed: " << zx_status_get_string(status); return false; } buffer->vmo = zx::vmo(result); buffer->size = stat_struct.st_size; return true; } } // namespace namespace dart_utils { bool VmoFromFilename(const std::string& filename, bool executable, fuchsia::mem::Buffer* buffer) { // Note: the implementation here cannot be shared with VmoFromFilenameAt // because fdio_open_fd_at does not aim to provide POSIX compatibility, and // thus does not handle AT_FDCWD as dirfd. auto flags = fuchsia::io::OpenFlags::RIGHT_READABLE; if (executable) { flags |= fuchsia::io::OpenFlags::RIGHT_EXECUTABLE; } int fd; const zx_status_t status = fdio_open_fd(filename.c_str(), static_cast<uint32_t>(flags), &fd); if (status != ZX_OK) { FML_LOG(ERROR) << "fdio_open_fd(\"" << filename << "\", " << std::hex << static_cast<uint32_t>(flags) << ") failed: " << zx_status_get_string(status); return false; } bool result = VmoFromFd(fd, executable, buffer); close(fd); return result; } bool VmoFromFilenameAt(int dirfd, const std::string& filename, bool executable, fuchsia::mem::Buffer* buffer) { auto flags = fuchsia::io::OpenFlags::RIGHT_READABLE; if (executable) { flags |= fuchsia::io::OpenFlags::RIGHT_EXECUTABLE; } int fd; const zx_status_t status = fdio_open_fd_at(dirfd, filename.c_str(), static_cast<uint32_t>(flags), &fd); if (status != ZX_OK) { FML_LOG(ERROR) << "fdio_open_fd_at(" << dirfd << ", \"" << filename << "\", " << std::hex << static_cast<uint32_t>(flags) << ") failed: " << zx_status_get_string(status); return false; } bool result = VmoFromFd(fd, executable, buffer); close(fd); return result; } zx_status_t IsSizeValid(const fuchsia::mem::Buffer& buffer, bool* is_valid) { size_t vmo_size; zx_status_t status = buffer.vmo.get_size(&vmo_size); if (status == ZX_OK) { *is_valid = vmo_size >= buffer.size; } else { *is_valid = false; } return status; } } // namespace dart_utils
engine/shell/platform/fuchsia/runtime/dart/utils/vmo.cc/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/vmo.cc", "repo_id": "engine", "token_count": 1451 }
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 <memory> #include <string> #include "flutter/shell/platform/glfw/client_wrapper/include/flutter/plugin_registrar_glfw.h" #include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h" #include "gtest/gtest.h" namespace flutter { namespace { // A test plugin that tries to access registrar state during destruction and // reports it out via a flag provided at construction. class TestPlugin : public Plugin { public: // registrar_valid_at_destruction will be set at destruction to indicate // whether or not |registrar->window()| was non-null. TestPlugin(PluginRegistrarGlfw* registrar, bool* registrar_valid_at_destruction) : registrar_(registrar), registrar_valid_at_destruction_(registrar_valid_at_destruction) {} virtual ~TestPlugin() { *registrar_valid_at_destruction_ = registrar_->window() != nullptr; } private: PluginRegistrarGlfw* registrar_; bool* registrar_valid_at_destruction_; }; } // namespace TEST(PluginRegistrarGlfwTest, GetView) { testing::ScopedStubFlutterGlfwApi scoped_api_stub( std::make_unique<testing::StubFlutterGlfwApi>()); PluginRegistrarGlfw registrar( reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1)); EXPECT_NE(registrar.window(), nullptr); } // Tests that the registrar runs plugin destructors before its own teardown. TEST(PluginRegistrarGlfwTest, PluginDestroyedBeforeRegistrar) { auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); bool registrar_valid_at_destruction = false; { PluginRegistrarGlfw registrar(dummy_registrar_handle); auto plugin = std::make_unique<TestPlugin>(&registrar, &registrar_valid_at_destruction); registrar.AddPlugin(std::move(plugin)); } EXPECT_TRUE(registrar_valid_at_destruction); } } // namespace flutter
engine/shell/platform/glfw/client_wrapper/plugin_registrar_glfw_unittests.cc/0
{ "file_path": "engine/shell/platform/glfw/client_wrapper/plugin_registrar_glfw_unittests.cc", "repo_id": "engine", "token_count": 751 }
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. #ifndef FLUTTER_SHELL_PLATFORM_GLFW_PUBLIC_FLUTTER_GLFW_H_ #define FLUTTER_SHELL_PLATFORM_GLFW_PUBLIC_FLUTTER_GLFW_H_ #include <stddef.h> #include <stdint.h> #include "flutter_export.h" #include "flutter_messenger.h" #include "flutter_plugin_registrar.h" #if defined(__cplusplus) extern "C" { #endif // Indicates that any value is acceptable for an otherwise required property. extern const int32_t kFlutterDesktopDontCare; // Opaque reference to a Flutter window controller. typedef struct FlutterDesktopWindowControllerState* FlutterDesktopWindowControllerRef; // Opaque reference to a Flutter window. typedef struct FlutterDesktopWindow* FlutterDesktopWindowRef; // Opaque reference to a Flutter engine instance. typedef struct FlutterDesktopEngineState* FlutterDesktopEngineRef; // Properties representing a generic rectangular size. typedef struct { int32_t width; int32_t height; } FlutterDesktopSize; // Properties for configuring a Flutter engine instance. typedef struct { // The path to the flutter_assets folder for the application to be run. // This can either be an absolute path, or on Windows or Linux, a path // relative to the directory containing the executable. const char* assets_path; // The path to the icudtl.dat file for the version of Flutter you are using. // This can either be an absolute path, or on Windows or Linux, a path // relative to the directory containing the executable. const char* icu_data_path; // The path to the libapp.so file for the application to be run. // This can either be an absolute path or a path relative to the directory // containing the executable. const char* aot_library_path; // The switches to pass to the Flutter engine. // // See: https://github.com/flutter/engine/blob/main/shell/common/switches.h // for details. Not all arguments will apply to desktop. const char** switches; // The number of elements in |switches|. size_t switches_count; } FlutterDesktopEngineProperties; // Properties for configuring the initial settings of a Flutter window. typedef struct { // The display title. const char* title; // Width in screen coordinates. int32_t width; // Height in screen coordinates. int32_t height; // Whether or not the user is prevented from resizing the window. // Reversed so that the default for a cleared struct is to allow resizing. bool prevent_resize; } FlutterDesktopWindowProperties; // Sets up the library's graphic context. Must be called before any other // methods. // // Note: Internally, this library uses GLFW, which does not support multiple // copies within the same process. Internally this calls glfwInit, which will // fail if you have called glfwInit elsewhere in the process. FLUTTER_EXPORT bool FlutterDesktopInit(); // Tears down library state. Must be called before the process terminates. FLUTTER_EXPORT void FlutterDesktopTerminate(); // Creates a Window running a Flutter Application. // // FlutterDesktopInit() must be called prior to this function. // // This will set up and run an associated Flutter engine using the settings in // |engine_properties|. // // Returns a null pointer in the event of an error. Otherwise, the pointer is // valid until FlutterDesktopDestroyWindow is called. // Note that calling FlutterDesktopCreateWindow without later calling // FlutterDesktopDestroyWindow on the returned reference is a memory leak. FLUTTER_EXPORT FlutterDesktopWindowControllerRef FlutterDesktopCreateWindow( const FlutterDesktopWindowProperties& window_properties, const FlutterDesktopEngineProperties& engine_properties); // Shuts down the engine instance associated with |controller|, and cleans up // associated state. // // |controller| is no longer valid after this call. FLUTTER_EXPORT void FlutterDesktopDestroyWindow( FlutterDesktopWindowControllerRef controller); // Waits for and processes the next event before |timeout_milliseconds|. // // If |timeout_milliseconds| is zero, it will wait for the next event // indefinitely. A non-zero timeout is needed only if processing unrelated to // the event loop is necessary (e.g., to handle events from another source). // // Returns false if the window should be closed as a result of the last event // processed. FLUTTER_EXPORT bool FlutterDesktopRunWindowEventLoopWithTimeout( FlutterDesktopWindowControllerRef controller, uint32_t timeout_milliseconds); // Returns the window handle for the window associated with // FlutterDesktopWindowControllerRef. // // Its lifetime is the same as the |controller|'s. FLUTTER_EXPORT FlutterDesktopWindowRef FlutterDesktopGetWindow( FlutterDesktopWindowControllerRef controller); // Returns the handle for the engine running in // FlutterDesktopWindowControllerRef. // // Its lifetime is the same as the |controller|'s. FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopGetEngine( FlutterDesktopWindowControllerRef controller); // Returns the plugin registrar handle for the plugin with the given name. // // The name must be unique across the application. FLUTTER_EXPORT FlutterDesktopPluginRegistrarRef FlutterDesktopGetPluginRegistrar(FlutterDesktopEngineRef engine, const char* plugin_name); // Enables or disables hover tracking. // // If hover is enabled, mouse movement will send hover events to the Flutter // engine, rather than only tracking the mouse while the button is pressed. // Defaults to on. FLUTTER_EXPORT void FlutterDesktopWindowSetHoverEnabled( FlutterDesktopWindowRef flutter_window, bool enabled); // Sets the displayed title for |flutter_window|. FLUTTER_EXPORT void FlutterDesktopWindowSetTitle( FlutterDesktopWindowRef flutter_window, const char* title); // Sets the displayed icon for |flutter_window|. // // The pixel format is 32-bit RGBA. The provided image data only needs to be // valid for the duration of the call to this method. Pass a nullptr to revert // to the default icon. FLUTTER_EXPORT void FlutterDesktopWindowSetIcon( FlutterDesktopWindowRef flutter_window, uint8_t* pixel_data, int width, int height); // Gets the position and size of |flutter_window| in screen coordinates. FLUTTER_EXPORT void FlutterDesktopWindowGetFrame( FlutterDesktopWindowRef flutter_window, int* x, int* y, int* width, int* height); // Sets the position and size of |flutter_window| in screen coordinates. FLUTTER_EXPORT void FlutterDesktopWindowSetFrame( FlutterDesktopWindowRef flutter_window, int x, int y, int width, int height); // Returns the scale factor--the number of pixels per screen coordinate--for // |flutter_window|. FLUTTER_EXPORT double FlutterDesktopWindowGetScaleFactor( FlutterDesktopWindowRef flutter_window); // Forces a specific pixel ratio for Flutter rendering in |flutter_window|, // rather than one computed automatically from screen information. // // To clear a previously set override, pass an override value of zero. FLUTTER_EXPORT void FlutterDesktopWindowSetPixelRatioOverride( FlutterDesktopWindowRef flutter_window, double pixel_ratio); // Sets the min/max size of |flutter_window| in screen coordinates. Use // kFlutterDesktopDontCare for any dimension you wish to leave unconstrained. FLUTTER_EXPORT void FlutterDesktopWindowSetSizeLimits( FlutterDesktopWindowRef flutter_window, FlutterDesktopSize minimum_size, FlutterDesktopSize maximum_size); // Runs an instance of a headless Flutter engine. // // Returns a null pointer in the event of an error. FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopRunEngine( const FlutterDesktopEngineProperties& properties); // Waits for and processes the next event before |timeout_milliseconds|. // // If |timeout_milliseconds| is zero, it will wait for the next event // indefinitely. A non-zero timeout is needed only if processing unrelated to // the event loop is necessary (e.g., to handle events from another source). FLUTTER_EXPORT void FlutterDesktopRunEngineEventLoopWithTimeout( FlutterDesktopEngineRef engine, uint32_t timeout_milliseconds); // Shuts down the given engine instance. Returns true if the shutdown was // successful. |engine_ref| is no longer valid after this call. FLUTTER_EXPORT bool FlutterDesktopShutDownEngine( FlutterDesktopEngineRef engine); // Returns the window associated with this registrar's engine instance. // // This is a GLFW shell-specific extension to flutter_plugin_registrar.h FLUTTER_EXPORT FlutterDesktopWindowRef FlutterDesktopPluginRegistrarGetWindow( FlutterDesktopPluginRegistrarRef registrar); // Enables input blocking on the given channel. // // If set, then the Flutter window will disable input callbacks // while waiting for the handler for messages on that channel to run. This is // useful if handling the message involves showing a modal window, for instance. // // This must be called after FlutterDesktopSetMessageHandler, as setting a // handler on a channel will reset the input blocking state back to the // default of disabled. // // This is a GLFW shell-specific extension to flutter_plugin_registrar.h FLUTTER_EXPORT void FlutterDesktopPluginRegistrarEnableInputBlocking( FlutterDesktopPluginRegistrarRef registrar, const char* channel); #if defined(__cplusplus) } // extern "C" #endif #endif // FLUTTER_SHELL_PLATFORM_GLFW_PUBLIC_FLUTTER_GLFW_H_
engine/shell/platform/glfw/public/flutter_glfw.h/0
{ "file_path": "engine/shell/platform/glfw/public/flutter_glfw.h", "repo_id": "engine", "token_count": 2699 }
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. #include "flutter/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h" #include <gmodule.h> struct _FlBasicMessageChannel { GObject parent_instance; // Messenger to communicate on. FlBinaryMessenger* messenger; // TRUE if the channel has been closed. gboolean channel_closed; // Channel name. gchar* name; // Codec to en/decode messages. FlMessageCodec* codec; // Function called when a message is received. FlBasicMessageChannelMessageHandler message_handler; gpointer message_handler_data; GDestroyNotify message_handler_destroy_notify; }; struct _FlBasicMessageChannelResponseHandle { GObject parent_instance; FlBinaryMessengerResponseHandle* response_handle; }; G_DEFINE_TYPE(FlBasicMessageChannel, fl_basic_message_channel, G_TYPE_OBJECT) G_DEFINE_TYPE(FlBasicMessageChannelResponseHandle, fl_basic_message_channel_response_handle, G_TYPE_OBJECT) static void fl_basic_message_channel_response_handle_dispose(GObject* object) { FlBasicMessageChannelResponseHandle* self = FL_BASIC_MESSAGE_CHANNEL_RESPONSE_HANDLE(object); g_clear_object(&self->response_handle); G_OBJECT_CLASS(fl_basic_message_channel_response_handle_parent_class) ->dispose(object); } static void fl_basic_message_channel_response_handle_class_init( FlBasicMessageChannelResponseHandleClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_basic_message_channel_response_handle_dispose; } static void fl_basic_message_channel_response_handle_init( FlBasicMessageChannelResponseHandle* self) {} static FlBasicMessageChannelResponseHandle* fl_basic_message_channel_response_handle_new( FlBinaryMessengerResponseHandle* response_handle) { FlBasicMessageChannelResponseHandle* self = FL_BASIC_MESSAGE_CHANNEL_RESPONSE_HANDLE(g_object_new( fl_basic_message_channel_response_handle_get_type(), nullptr)); self->response_handle = FL_BINARY_MESSENGER_RESPONSE_HANDLE(g_object_ref(response_handle)); return self; } // Called when a binary message is received on this channel. static void message_cb(FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, FlBinaryMessengerResponseHandle* response_handle, gpointer user_data) { FlBasicMessageChannel* self = FL_BASIC_MESSAGE_CHANNEL(user_data); if (self->message_handler == nullptr) { fl_binary_messenger_send_response(messenger, response_handle, nullptr, nullptr); return; } g_autoptr(GError) error = nullptr; g_autoptr(FlValue) message_value = fl_message_codec_decode_message(self->codec, message, &error); if (message_value == nullptr) { g_warning("Failed to decode message: %s", error->message); fl_binary_messenger_send_response(messenger, response_handle, nullptr, nullptr); } g_autoptr(FlBasicMessageChannelResponseHandle) handle = fl_basic_message_channel_response_handle_new(response_handle); self->message_handler(self, message_value, handle, self->message_handler_data); } // Called when a response is received to a sent message. static void message_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { GTask* task = G_TASK(user_data); g_task_return_pointer(task, result, g_object_unref); } // Called when the channel handler is closed. static void channel_closed_cb(gpointer user_data) { g_autoptr(FlBasicMessageChannel) self = FL_BASIC_MESSAGE_CHANNEL(user_data); self->channel_closed = TRUE; // Disconnect handler. if (self->message_handler_destroy_notify != nullptr) { self->message_handler_destroy_notify(self->message_handler_data); } self->message_handler = nullptr; self->message_handler_data = nullptr; self->message_handler_destroy_notify = nullptr; } static void fl_basic_message_channel_dispose(GObject* object) { FlBasicMessageChannel* self = FL_BASIC_MESSAGE_CHANNEL(object); if (self->messenger != nullptr) { fl_binary_messenger_set_message_handler_on_channel( self->messenger, self->name, nullptr, nullptr, nullptr); } g_clear_object(&self->messenger); g_clear_pointer(&self->name, g_free); g_clear_object(&self->codec); if (self->message_handler_destroy_notify != nullptr) { self->message_handler_destroy_notify(self->message_handler_data); } self->message_handler = nullptr; self->message_handler_data = nullptr; self->message_handler_destroy_notify = nullptr; G_OBJECT_CLASS(fl_basic_message_channel_parent_class)->dispose(object); } static void fl_basic_message_channel_class_init( FlBasicMessageChannelClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_basic_message_channel_dispose; } static void fl_basic_message_channel_init(FlBasicMessageChannel* self) {} G_MODULE_EXPORT FlBasicMessageChannel* fl_basic_message_channel_new( FlBinaryMessenger* messenger, const gchar* name, FlMessageCodec* codec) { g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr); g_return_val_if_fail(name != nullptr, nullptr); g_return_val_if_fail(FL_IS_MESSAGE_CODEC(codec), nullptr); FlBasicMessageChannel* self = FL_BASIC_MESSAGE_CHANNEL( g_object_new(fl_basic_message_channel_get_type(), nullptr)); self->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger)); self->name = g_strdup(name); self->codec = FL_MESSAGE_CODEC(g_object_ref(codec)); fl_binary_messenger_set_message_handler_on_channel( self->messenger, self->name, message_cb, g_object_ref(self), channel_closed_cb); return self; } G_MODULE_EXPORT void fl_basic_message_channel_set_message_handler( FlBasicMessageChannel* self, FlBasicMessageChannelMessageHandler handler, gpointer user_data, GDestroyNotify destroy_notify) { g_return_if_fail(FL_IS_BASIC_MESSAGE_CHANNEL(self)); // Don't set handler if channel closed. if (self->channel_closed) { if (handler != nullptr) { g_warning( "Attempted to set message handler on a closed FlBasicMessageChannel"); } if (destroy_notify != nullptr) { destroy_notify(user_data); } return; } if (self->message_handler_destroy_notify != nullptr) { self->message_handler_destroy_notify(self->message_handler_data); } self->message_handler = handler; self->message_handler_data = user_data; self->message_handler_destroy_notify = destroy_notify; } G_MODULE_EXPORT gboolean fl_basic_message_channel_respond( FlBasicMessageChannel* self, FlBasicMessageChannelResponseHandle* response_handle, FlValue* message, GError** error) { g_return_val_if_fail(FL_IS_BASIC_MESSAGE_CHANNEL(self), FALSE); g_return_val_if_fail(response_handle != nullptr, FALSE); g_return_val_if_fail(response_handle->response_handle != nullptr, FALSE); g_autoptr(GBytes) data = fl_message_codec_encode_message(self->codec, message, error); if (data == nullptr) { return FALSE; } gboolean result = fl_binary_messenger_send_response( self->messenger, response_handle->response_handle, data, error); g_clear_object(&response_handle->response_handle); return result; } G_MODULE_EXPORT void fl_basic_message_channel_send(FlBasicMessageChannel* self, FlValue* message, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_return_if_fail(FL_IS_BASIC_MESSAGE_CHANNEL(self)); g_autoptr(GTask) task = callback != nullptr ? g_task_new(self, cancellable, callback, user_data) : nullptr; g_autoptr(GError) error = nullptr; g_autoptr(GBytes) data = fl_message_codec_encode_message(self->codec, message, &error); if (data == nullptr) { if (task != nullptr) { g_task_return_error(task, error); } return; } fl_binary_messenger_send_on_channel( self->messenger, self->name, data, cancellable, callback != nullptr ? message_response_cb : nullptr, g_steal_pointer(&task)); } G_MODULE_EXPORT FlValue* fl_basic_message_channel_send_finish( FlBasicMessageChannel* self, GAsyncResult* result, GError** error) { g_return_val_if_fail(FL_IS_BASIC_MESSAGE_CHANNEL(self), nullptr); g_return_val_if_fail(g_task_is_valid(result, self), nullptr); g_autoptr(GTask) task = G_TASK(result); GAsyncResult* r = G_ASYNC_RESULT(g_task_propagate_pointer(task, nullptr)); g_autoptr(GBytes) message = fl_binary_messenger_send_on_channel_finish(self->messenger, r, error); if (message == nullptr) { return nullptr; } return fl_message_codec_decode_message(self->codec, message, error); }
engine/shell/platform/linux/fl_basic_message_channel.cc/0
{ "file_path": "engine/shell/platform/linux/fl_basic_message_channel.cc", "repo_id": "engine", "token_count": 3622 }
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. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_GNOME_SETTINGS_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_GNOME_SETTINGS_H_ #include "flutter/shell/platform/linux/fl_settings.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlGnomeSettings, fl_gnome_settings, FL, GNOME_SETTINGS, GObject); /** * fl_gnome_settings_new: * * Creates a new settings instance for GNOME. * * Returns: a new #FlSettings. */ FlSettings* fl_gnome_settings_new(); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_GNOME_SETTINGS_H_
engine/shell/platform/linux/fl_gnome_settings.h/0
{ "file_path": "engine/shell/platform/linux/fl_gnome_settings.h", "repo_id": "engine", "token_count": 343 }
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. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_RESPONDER_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_RESPONDER_H_ #include <gdk/gdk.h> #include <cinttypes> #include "flutter/shell/platform/linux/fl_key_event.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" G_BEGIN_DECLS typedef struct _FlKeyboardManager FlKeyboardManager; /** * FlKeyResponderAsyncCallback: * @event: whether the event has been handled. * @user_data: the same value as user_data sent by * #fl_key_responder_handle_event. * * The signature for a callback with which a #FlKeyResponder asynchronously * reports whether the responder handles the event. **/ typedef void (*FlKeyResponderAsyncCallback)(bool handled, gpointer user_data); #define FL_TYPE_KEY_RESPONDER fl_key_responder_get_type() G_DECLARE_INTERFACE(FlKeyResponder, fl_key_responder, FL, KEY_RESPONDER, GObject); /** * FlKeyResponder: * * An interface for a responder that can process a key event and decides * asynchronously whether to handle an event. * * To use this class, add it with #fl_keyboard_manager_add_responder. */ struct _FlKeyResponderInterface { GTypeInterface g_iface; /** * FlKeyResponder::handle_event: * * The implementation of #fl_key_responder_handle_event. */ void (*handle_event)(FlKeyResponder* responder, FlKeyEvent* event, uint64_t specified_logical_key, FlKeyResponderAsyncCallback callback, gpointer user_data); }; /** * fl_key_responder_handle_event: * @responder: the #FlKeyResponder self. * @event: the event to be handled. Must not be null. The object is managed * by callee and must not be assumed available after this function. * @callback: the callback to report the result. It should be called exactly * once. Must not be null. * @user_data: a value that will be sent back in the callback. Can be null. * * Let the responder handle an event, expecting the responder to report * whether to handle the event. The result will be reported by invoking * `callback` exactly once, which might happen after * `fl_key_responder_handle_event` or during it. */ void fl_key_responder_handle_event(FlKeyResponder* responder, FlKeyEvent* event, FlKeyResponderAsyncCallback callback, gpointer user_data, uint64_t specified_logical_key = 0); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_RESPONDER_H_
engine/shell/platform/linux/fl_key_responder.h/0
{ "file_path": "engine/shell/platform/linux/fl_key_responder.h", "repo_id": "engine", "token_count": 1153 }
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. #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h" #include <gmodule.h> G_DEFINE_QUARK(fl_method_response_error_quark, fl_method_response_error) struct _FlMethodSuccessResponse { FlMethodResponse parent_instance; FlValue* result; }; struct _FlMethodErrorResponse { FlMethodResponse parent_instance; gchar* code; gchar* message; FlValue* details; }; struct _FlMethodNotImplementedResponse { FlMethodResponse parent_instance; }; G_DEFINE_TYPE(FlMethodResponse, fl_method_response, G_TYPE_OBJECT) G_DEFINE_TYPE(FlMethodSuccessResponse, fl_method_success_response, fl_method_response_get_type()) G_DEFINE_TYPE(FlMethodErrorResponse, fl_method_error_response, fl_method_response_get_type()) G_DEFINE_TYPE(FlMethodNotImplementedResponse, fl_method_not_implemented_response, fl_method_response_get_type()) static void fl_method_response_class_init(FlMethodResponseClass* klass) {} static void fl_method_response_init(FlMethodResponse* self) {} static void fl_method_success_response_dispose(GObject* object) { FlMethodSuccessResponse* self = FL_METHOD_SUCCESS_RESPONSE(object); g_clear_pointer(&self->result, fl_value_unref); G_OBJECT_CLASS(fl_method_success_response_parent_class)->dispose(object); } static void fl_method_success_response_class_init( FlMethodSuccessResponseClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_method_success_response_dispose; } static void fl_method_success_response_init(FlMethodSuccessResponse* self) {} static void fl_method_error_response_dispose(GObject* object) { FlMethodErrorResponse* self = FL_METHOD_ERROR_RESPONSE(object); g_clear_pointer(&self->code, g_free); g_clear_pointer(&self->message, g_free); g_clear_pointer(&self->details, fl_value_unref); G_OBJECT_CLASS(fl_method_error_response_parent_class)->dispose(object); } static void fl_method_error_response_class_init( FlMethodErrorResponseClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_method_error_response_dispose; } static void fl_method_error_response_init(FlMethodErrorResponse* self) {} static void fl_method_not_implemented_response_class_init( FlMethodNotImplementedResponseClass* klass) {} static void fl_method_not_implemented_response_init( FlMethodNotImplementedResponse* self) {} G_MODULE_EXPORT FlValue* fl_method_response_get_result(FlMethodResponse* self, GError** error) { if (FL_IS_METHOD_SUCCESS_RESPONSE(self)) { return fl_method_success_response_get_result( FL_METHOD_SUCCESS_RESPONSE(self)); } if (FL_IS_METHOD_ERROR_RESPONSE(self)) { const gchar* code = fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(self)); const gchar* message = fl_method_error_response_get_message(FL_METHOD_ERROR_RESPONSE(self)); FlValue* details = fl_method_error_response_get_details(FL_METHOD_ERROR_RESPONSE(self)); g_autofree gchar* details_text = nullptr; if (details != nullptr) { details_text = fl_value_to_string(details); } g_autoptr(GString) error_message = g_string_new(""); g_string_append_printf(error_message, "Remote code returned error %s", code); if (message != nullptr) { g_string_append_printf(error_message, ": %s", message); } if (details_text != nullptr) { g_string_append_printf(error_message, " %s", details_text); } g_set_error_literal(error, FL_METHOD_RESPONSE_ERROR, FL_METHOD_RESPONSE_ERROR_REMOTE_ERROR, error_message->str); return nullptr; } else if (FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(self)) { g_set_error(error, FL_METHOD_RESPONSE_ERROR, FL_METHOD_RESPONSE_ERROR_NOT_IMPLEMENTED, "Requested method is not implemented"); return nullptr; } else { g_set_error(error, FL_METHOD_RESPONSE_ERROR, FL_METHOD_RESPONSE_ERROR_FAILED, "Unknown response type"); return nullptr; } } G_MODULE_EXPORT FlMethodSuccessResponse* fl_method_success_response_new( FlValue* result) { FlMethodSuccessResponse* self = FL_METHOD_SUCCESS_RESPONSE( g_object_new(fl_method_success_response_get_type(), nullptr)); if (result != nullptr) { self->result = fl_value_ref(result); } return self; } G_MODULE_EXPORT FlValue* fl_method_success_response_get_result( FlMethodSuccessResponse* self) { g_return_val_if_fail(FL_IS_METHOD_SUCCESS_RESPONSE(self), nullptr); return self->result; } G_MODULE_EXPORT FlMethodErrorResponse* fl_method_error_response_new( const gchar* code, const gchar* message, FlValue* details) { g_return_val_if_fail(code != nullptr, nullptr); FlMethodErrorResponse* self = FL_METHOD_ERROR_RESPONSE( g_object_new(fl_method_error_response_get_type(), nullptr)); self->code = g_strdup(code); self->message = g_strdup(message); self->details = details != nullptr ? fl_value_ref(details) : nullptr; return self; } G_MODULE_EXPORT const gchar* fl_method_error_response_get_code( FlMethodErrorResponse* self) { g_return_val_if_fail(FL_IS_METHOD_ERROR_RESPONSE(self), nullptr); return self->code; } G_MODULE_EXPORT const gchar* fl_method_error_response_get_message( FlMethodErrorResponse* self) { g_return_val_if_fail(FL_IS_METHOD_ERROR_RESPONSE(self), nullptr); return self->message; } G_MODULE_EXPORT FlValue* fl_method_error_response_get_details( FlMethodErrorResponse* self) { g_return_val_if_fail(FL_IS_METHOD_ERROR_RESPONSE(self), nullptr); return self->details; } G_MODULE_EXPORT FlMethodNotImplementedResponse* fl_method_not_implemented_response_new() { return FL_METHOD_NOT_IMPLEMENTED_RESPONSE( g_object_new(fl_method_not_implemented_response_get_type(), nullptr)); }
engine/shell/platform/linux/fl_method_response.cc/0
{ "file_path": "engine/shell/platform/linux/fl_method_response.cc", "repo_id": "engine", "token_count": 2406 }
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. #include "flutter/shell/platform/linux/fl_renderer_gdk.h" struct _FlRendererGdk { FlRenderer parent_instance; // Window being rendered on. GdkWindow* window; // Main OpenGL rendering context. GdkGLContext* main_context; // Secondary OpenGL rendering context. GdkGLContext* resource_context; }; G_DEFINE_TYPE(FlRendererGdk, fl_renderer_gdk, fl_renderer_get_type()) // Implements FlRenderer::make_current. static void fl_renderer_gdk_make_current(FlRenderer* renderer) { FlRendererGdk* self = FL_RENDERER_GDK(renderer); gdk_gl_context_make_current(self->main_context); } // Implements FlRenderer::make_resource_current. static void fl_renderer_gdk_make_resource_current(FlRenderer* renderer) { FlRendererGdk* self = FL_RENDERER_GDK(renderer); gdk_gl_context_make_current(self->resource_context); } // Implements FlRenderer::clear_current. static void fl_renderer_gdk_clear_current(FlRenderer* renderer) { gdk_gl_context_clear_current(); } static void fl_renderer_gdk_dispose(GObject* object) { FlRendererGdk* self = FL_RENDERER_GDK(object); g_clear_object(&self->main_context); g_clear_object(&self->resource_context); G_OBJECT_CLASS(fl_renderer_gdk_parent_class)->dispose(object); } static void fl_renderer_gdk_class_init(FlRendererGdkClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_renderer_gdk_dispose; FL_RENDERER_CLASS(klass)->make_current = fl_renderer_gdk_make_current; FL_RENDERER_CLASS(klass)->make_resource_current = fl_renderer_gdk_make_resource_current; FL_RENDERER_CLASS(klass)->clear_current = fl_renderer_gdk_clear_current; } static void fl_renderer_gdk_init(FlRendererGdk* self) {} FlRendererGdk* fl_renderer_gdk_new(GdkWindow* window) { FlRendererGdk* self = FL_RENDERER_GDK(g_object_new(fl_renderer_gdk_get_type(), nullptr)); self->window = window; return self; } gboolean fl_renderer_gdk_create_contexts(FlRendererGdk* self, GError** error) { self->main_context = gdk_window_create_gl_context(self->window, error); if (self->main_context == nullptr) { return FALSE; } if (!gdk_gl_context_realize(self->main_context, error)) { return FALSE; } self->resource_context = gdk_window_create_gl_context(self->window, error); if (self->resource_context == nullptr) { return FALSE; } if (!gdk_gl_context_realize(self->resource_context, error)) { return FALSE; } return TRUE; } GdkGLContext* fl_renderer_gdk_get_context(FlRendererGdk* self) { g_return_val_if_fail(FL_IS_RENDERER_GDK(self), nullptr); return self->main_context; }
engine/shell/platform/linux/fl_renderer_gdk.cc/0
{ "file_path": "engine/shell/platform/linux/fl_renderer_gdk.cc", "repo_id": "engine", "token_count": 1048 }
409
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_settings_portal.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "flutter/testing/testing.h" #include <glib.h> #include "gmock/gmock.h" #include "gtest/gtest.h" TEST(FlSettingsPortalTest, ClockFormat) { g_autoptr(GVariantDict) settings = g_variant_dict_new(nullptr); g_autoptr(FlSettings) portal = FL_SETTINGS(fl_settings_portal_new_with_values(settings)); EXPECT_EQ(fl_settings_get_clock_format(portal), FL_CLOCK_FORMAT_24H); g_variant_dict_insert_value(settings, "org.gnome.desktop.interface::clock-format", g_variant_new_string("24h")); EXPECT_EQ(fl_settings_get_clock_format(portal), FL_CLOCK_FORMAT_24H); g_variant_dict_insert_value(settings, "org.gnome.desktop.interface::clock-format", g_variant_new_string("12h")); EXPECT_EQ(fl_settings_get_clock_format(portal), FL_CLOCK_FORMAT_12H); g_variant_dict_insert_value(settings, "org.gnome.desktop.interface::clock-format", g_variant_new_string("unknown")); EXPECT_EQ(fl_settings_get_clock_format(portal), FL_CLOCK_FORMAT_24H); } TEST(FlSettingsPortalTest, ColorScheme) { g_autoptr(GVariantDict) settings = g_variant_dict_new(nullptr); g_autoptr(FlSettings) portal = FL_SETTINGS(fl_settings_portal_new_with_values(settings)); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_LIGHT); g_variant_dict_insert_value(settings, "org.freedesktop.appearance::color-scheme", g_variant_new_uint32(1)); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_DARK); g_variant_dict_insert_value(settings, "org.freedesktop.appearance::color-scheme", g_variant_new_uint32(2)); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_LIGHT); g_variant_dict_insert_value(settings, "org.freedesktop.appearance::color-scheme", g_variant_new_uint32(123)); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_LIGHT); // color-scheme takes precedence over gtk-theme g_variant_dict_insert_value(settings, "org.gnome.desktop.interface::gtk-theme", g_variant_new_string("Yaru-dark")); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_LIGHT); } TEST(FlSettingsPortalTest, GtkTheme) { g_autoptr(GVariantDict) settings = g_variant_dict_new(nullptr); g_autoptr(FlSettings) portal = FL_SETTINGS(fl_settings_portal_new_with_values(settings)); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_LIGHT); g_variant_dict_insert_value(settings, "org.gnome.desktop.interface::gtk-theme", g_variant_new_string("Yaru-dark")); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_DARK); g_variant_dict_insert_value(settings, "org.gnome.desktop.interface::gtk-theme", g_variant_new_string("Yaru")); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_LIGHT); g_variant_dict_insert_value(settings, "org.gnome.desktop.interface::gtk-theme", g_variant_new_string("Adwaita")); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_LIGHT); g_variant_dict_insert_value(settings, "org.gnome.desktop.interface::gtk-theme", g_variant_new_string("Adwaita-dark")); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_DARK); // color-scheme takes precedence over gtk-theme g_variant_dict_insert_value(settings, "org.freedesktop.appearance::color-scheme", g_variant_new_uint32(2)); EXPECT_EQ(fl_settings_get_color_scheme(portal), FL_COLOR_SCHEME_LIGHT); } TEST(FlSettingsPortalTest, EnableAnimations) { g_autoptr(GVariantDict) settings = g_variant_dict_new(nullptr); g_autoptr(FlSettings) portal = FL_SETTINGS(fl_settings_portal_new_with_values(settings)); EXPECT_TRUE(fl_settings_get_enable_animations(portal)); g_variant_dict_insert_value(settings, "org.gnome.desktop.interface::enable-animations", g_variant_new_boolean(false)); EXPECT_FALSE(fl_settings_get_enable_animations(portal)); } TEST(FlSettingsPortalTest, HighContrast) { g_autoptr(GVariantDict) settings = g_variant_dict_new(nullptr); g_autoptr(FlSettings) portal = FL_SETTINGS(fl_settings_portal_new_with_values(settings)); EXPECT_FALSE(fl_settings_get_high_contrast(portal)); g_variant_dict_insert_value(settings, "org.gnome.desktop.a11y.interface::high-contrast", g_variant_new_boolean(true)); EXPECT_TRUE(fl_settings_get_high_contrast(portal)); } TEST(FlSettingsPortalTest, TextScalingFactor) { g_autoptr(GVariantDict) settings = g_variant_dict_new(nullptr); g_autoptr(FlSettings) portal = FL_SETTINGS(fl_settings_portal_new_with_values(settings)); EXPECT_EQ(fl_settings_get_text_scaling_factor(portal), 1.0); g_variant_dict_insert_value( settings, "org.gnome.desktop.interface::text-scaling-factor", g_variant_new_double(1.5)); EXPECT_EQ(fl_settings_get_text_scaling_factor(portal), 1.5); }
engine/shell/platform/linux/fl_settings_portal_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_settings_portal_test.cc", "repo_id": "engine", "token_count": 2828 }
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_LINUX_FL_TEXTURE_GL_PRIVATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXTURE_GL_PRIVATE_H_ #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_gl.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h" G_BEGIN_DECLS /** * fl_texture_gl_populate: * @texture: an #FlTextureGL. * @width: width of the texture. * @height: height of the texture. * @opengl_texture: (out): return an #FlutterOpenGLTexture. * @error: (allow-none): #GError location to store the error occurring, or * %NULL to ignore. * * Attempts to populate the specified @opengl_texture with texture details * such as the name, width, height and the pixel format. * * Returns: %TRUE on success. */ gboolean fl_texture_gl_populate(FlTextureGL* texture, uint32_t width, uint32_t height, FlutterOpenGLTexture* opengl_texture, GError** error); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXTURE_GL_PRIVATE_H_
engine/shell/platform/linux/fl_texture_gl_private.h/0
{ "file_path": "engine/shell/platform/linux/fl_texture_gl_private.h", "repo_id": "engine", "token_count": 547 }
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. #include "key_mapping.h" #include <gmodule.h> #include <algorithm> #include <vector> #include "gtest/gtest.h" bool operator==(const LayoutGoal& a, const LayoutGoal& b) { return a.keycode == b.keycode && a.logical_key == b.logical_key && a.mandatory == b.mandatory; } // Spot check some expected values so that we know that some classes of key // aren't excluded. TEST(KeyMappingTest, HasExpectedValues) { // Has Space EXPECT_NE(std::find(layout_goals.begin(), layout_goals.end(), LayoutGoal{0x41, 0x20, false}), layout_goals.end()); // Has Digit0 EXPECT_NE(std::find(layout_goals.begin(), layout_goals.end(), LayoutGoal{0x13, 0x30, true}), layout_goals.end()); // Has KeyA EXPECT_NE(std::find(layout_goals.begin(), layout_goals.end(), LayoutGoal{0x26, 0x61, true}), layout_goals.end()); // Has Equal EXPECT_NE(std::find(layout_goals.begin(), layout_goals.end(), LayoutGoal{0x15, 0x3d, false}), layout_goals.end()); // Has IntlBackslash EXPECT_NE(std::find(layout_goals.begin(), layout_goals.end(), LayoutGoal{0x5e, 0x200000020, false}), layout_goals.end()); }
engine/shell/platform/linux/key_mapping_test.cc/0
{ "file_path": "engine/shell/platform/linux/key_mapping_test.cc", "repo_id": "engine", "token_count": 631 }
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. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRY_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRY_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_plugin_registrar.h" G_BEGIN_DECLS G_MODULE_EXPORT G_DECLARE_INTERFACE(FlPluginRegistry, fl_plugin_registry, FL, PLUGIN_REGISTRY, GObject) /** * FlPluginRegistry: * * #FlPluginRegistry vends #FlPluginRegistrar objects for named plugins. */ struct _FlPluginRegistryInterface { GTypeInterface g_iface; /** * FlPluginRegistry::get_registrar_for_plugin: * @registry: an #FlPluginRegistry. * @name: plugin name. * * Gets the plugin registrar for the plugin with @name. * * Returns: (transfer full): an #FlPluginRegistrar. */ FlPluginRegistrar* (*get_registrar_for_plugin)(FlPluginRegistry* registry, const gchar* name); }; /** * fl_plugin_registry_get_registrar_for_plugin: * @registry: an #FlPluginRegistry. * @name: plugin name. * * Gets the plugin registrar for the plugin with @name. * * Returns: (transfer full): an #FlPluginRegistrar. */ FlPluginRegistrar* fl_plugin_registry_get_registrar_for_plugin( FlPluginRegistry* registry, const gchar* name); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRY_H_
engine/shell/platform/linux/public/flutter_linux/fl_plugin_registry.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_plugin_registry.h", "repo_id": "engine", "token_count": 756 }
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/testing/mock_binary_messenger.h" #include "flutter/shell/platform/linux/testing/mock_binary_messenger_response_handle.h" using namespace flutter::testing; G_DECLARE_FINAL_TYPE(FlMockBinaryMessenger, fl_mock_binary_messenger, FL, MOCK_BINARY_MESSENGER, GObject) struct _FlMockBinaryMessenger { GObject parent_instance; MockBinaryMessenger* mock; }; static FlBinaryMessenger* fl_mock_binary_messenger_new( MockBinaryMessenger* mock) { FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER( g_object_new(fl_mock_binary_messenger_get_type(), nullptr)); self->mock = mock; return FL_BINARY_MESSENGER(self); } MockBinaryMessenger::MockBinaryMessenger() : instance_(fl_mock_binary_messenger_new(this)) {} MockBinaryMessenger::~MockBinaryMessenger() { if (FL_IS_BINARY_MESSENGER(instance_)) { g_clear_object(&instance_); } } MockBinaryMessenger::operator FlBinaryMessenger*() { return instance_; } bool MockBinaryMessenger::HasMessageHandler(const gchar* channel) const { return message_handlers_.at(channel) != nullptr; } void MockBinaryMessenger::SetMessageHandler( const gchar* channel, FlBinaryMessengerMessageHandler handler, gpointer user_data) { message_handlers_[channel] = handler; user_datas_[channel] = user_data; } void MockBinaryMessenger::ReceiveMessage(const gchar* channel, GBytes* message) { FlBinaryMessengerMessageHandler handler = message_handlers_[channel]; if (response_handles_[channel] == nullptr) { response_handles_[channel] = FL_BINARY_MESSENGER_RESPONSE_HANDLE( fl_mock_binary_messenger_response_handle_new()); } handler(instance_, channel, message, response_handles_[channel], user_datas_[channel]); } static void fl_mock_binary_messenger_iface_init( FlBinaryMessengerInterface* iface); G_DEFINE_TYPE_WITH_CODE( FlMockBinaryMessenger, fl_mock_binary_messenger, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE(fl_binary_messenger_get_type(), fl_mock_binary_messenger_iface_init)) static void fl_mock_binary_messenger_class_init( FlMockBinaryMessengerClass* klass) {} static void fl_mock_binary_messenger_set_message_handler_on_channel( FlBinaryMessenger* messenger, const gchar* channel, FlBinaryMessengerMessageHandler handler, gpointer user_data, GDestroyNotify destroy_notify) { g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(messenger)); FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); self->mock->SetMessageHandler(channel, handler, user_data); self->mock->fl_binary_messenger_set_message_handler_on_channel( messenger, channel, handler, user_data, destroy_notify); } static gboolean fl_mock_binary_messenger_send_response( FlBinaryMessenger* messenger, FlBinaryMessengerResponseHandle* response_handle, GBytes* response, GError** error) { g_return_val_if_fail(FL_IS_MOCK_BINARY_MESSENGER(messenger), false); FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); return self->mock->fl_binary_messenger_send_response( messenger, response_handle, response, error); } static void fl_mock_binary_messenger_send_on_channel( FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(messenger)); FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); self->mock->fl_binary_messenger_send_on_channel( messenger, channel, message, cancellable, callback, user_data); } static GBytes* fl_mock_binary_messenger_send_on_channel_finish( FlBinaryMessenger* messenger, GAsyncResult* result, GError** error) { g_return_val_if_fail(FL_IS_MOCK_BINARY_MESSENGER(messenger), nullptr); FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); return self->mock->fl_binary_messenger_send_on_channel_finish(messenger, result, error); } static void fl_mock_binary_messenger_resize_channel( FlBinaryMessenger* messenger, const gchar* channel, int64_t new_size) { g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(messenger)); FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); self->mock->fl_binary_messenger_resize_channel(messenger, channel, new_size); } static void fl_mock_binary_messenger_set_warns_on_channel_overflow( FlBinaryMessenger* messenger, const gchar* channel, bool warns) { g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(messenger)); FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); self->mock->fl_binary_messenger_set_warns_on_channel_overflow(messenger, channel, warns); } static void fl_mock_binary_messenger_iface_init( FlBinaryMessengerInterface* iface) { iface->set_message_handler_on_channel = fl_mock_binary_messenger_set_message_handler_on_channel; iface->send_response = fl_mock_binary_messenger_send_response; iface->send_on_channel = fl_mock_binary_messenger_send_on_channel; iface->send_on_channel_finish = fl_mock_binary_messenger_send_on_channel_finish; iface->resize_channel = fl_mock_binary_messenger_resize_channel; iface->set_warns_on_channel_overflow = fl_mock_binary_messenger_set_warns_on_channel_overflow; } static void fl_mock_binary_messenger_init(FlMockBinaryMessenger* self) {}
engine/shell/platform/linux/testing/mock_binary_messenger.cc/0
{ "file_path": "engine/shell/platform/linux/testing/mock_binary_messenger.cc", "repo_id": "engine", "token_count": 2401 }
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/testing/mock_text_input_plugin.h" struct _FlMockTextInputPlugin { FlTextInputPlugin parent_instance; gboolean (*filter_keypress)(FlTextInputPlugin* self, FlKeyEvent* event); }; G_DEFINE_TYPE(FlMockTextInputPlugin, fl_mock_text_input_plugin, fl_text_input_plugin_get_type()) static gboolean mock_text_input_plugin_filter_keypress(FlTextInputPlugin* self, FlKeyEvent* event) { FlMockTextInputPlugin* mock_self = FL_MOCK_TEXT_INPUT_PLUGIN(self); if (mock_self->filter_keypress) { return mock_self->filter_keypress(self, event); } return FALSE; } static void fl_mock_text_input_plugin_class_init( FlMockTextInputPluginClass* klass) { FL_TEXT_INPUT_PLUGIN_CLASS(klass)->filter_keypress = mock_text_input_plugin_filter_keypress; } static void fl_mock_text_input_plugin_init(FlMockTextInputPlugin* self) {} // Creates a mock text_input_plugin FlMockTextInputPlugin* fl_mock_text_input_plugin_new( gboolean (*filter_keypress)(FlTextInputPlugin* self, FlKeyEvent* event)) { FlMockTextInputPlugin* self = FL_MOCK_TEXT_INPUT_PLUGIN( g_object_new(fl_mock_text_input_plugin_get_type(), nullptr)); self->filter_keypress = filter_keypress; return self; }
engine/shell/platform/linux/testing/mock_text_input_plugin.cc/0
{ "file_path": "engine/shell/platform/linux/testing/mock_text_input_plugin.cc", "repo_id": "engine", "token_count": 585 }
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. #include <memory> #include <string> #include "flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h" #include "flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h" #include "gtest/gtest.h" namespace flutter { namespace { // Stub implementation to validate calls to the API. class TestFlutterWindowsApi : public testing::StubFlutterWindowsApi { public: // |flutter::testing::StubFlutterWindowsApi| FlutterDesktopEngineRef EngineCreate( const FlutterDesktopEngineProperties& engine_properties) { create_called_ = true; // dart_entrypoint_argv is only guaranteed to exist until this method // returns, so copy it here for unit test validation dart_entrypoint_arguments_.clear(); for (int i = 0; i < engine_properties.dart_entrypoint_argc; i++) { dart_entrypoint_arguments_.push_back( std::string(engine_properties.dart_entrypoint_argv[i])); } return reinterpret_cast<FlutterDesktopEngineRef>(1); } // |flutter::testing::StubFlutterWindowsApi| bool EngineRun(const char* entry_point) override { run_called_ = true; return true; } // |flutter::testing::StubFlutterWindowsApi| bool EngineDestroy() override { destroy_called_ = true; return true; } // |flutter::testing::StubFlutterWindowsApi| uint64_t EngineProcessMessages() override { return 99; } // |flutter::testing::StubFlutterWindowsApi| void EngineSetNextFrameCallback(VoidCallback callback, void* user_data) override { next_frame_callback_ = callback; next_frame_user_data_ = user_data; } // |flutter::testing::StubFlutterWindowsApi| void EngineReloadSystemFonts() override { reload_fonts_called_ = true; } // |flutter::testing::StubFlutterWindowsApi| bool EngineProcessExternalWindowMessage(FlutterDesktopEngineRef engine, HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result) override { last_external_message_ = message; return false; } bool create_called() { return create_called_; } bool run_called() { return run_called_; } bool destroy_called() { return destroy_called_; } bool reload_fonts_called() { return reload_fonts_called_; } const std::vector<std::string>& dart_entrypoint_arguments() { return dart_entrypoint_arguments_; } bool has_next_frame_callback() { return next_frame_callback_ != nullptr; } void run_next_frame_callback() { next_frame_callback_(next_frame_user_data_); next_frame_callback_ = nullptr; } UINT last_external_message() { return last_external_message_; } private: bool create_called_ = false; bool run_called_ = false; bool destroy_called_ = false; bool reload_fonts_called_ = false; std::vector<std::string> dart_entrypoint_arguments_; VoidCallback next_frame_callback_ = nullptr; void* next_frame_user_data_ = nullptr; UINT last_external_message_ = 0; }; } // namespace TEST(FlutterEngineTest, CreateDestroy) { testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestFlutterWindowsApi>()); auto test_api = static_cast<TestFlutterWindowsApi*>(scoped_api_stub.stub()); { FlutterEngine engine(DartProject(L"fake/project/path")); engine.Run(); EXPECT_EQ(test_api->create_called(), true); EXPECT_EQ(test_api->run_called(), true); EXPECT_EQ(test_api->destroy_called(), false); } // Destroying should implicitly shut down if it hasn't been done manually. EXPECT_EQ(test_api->destroy_called(), true); } TEST(FlutterEngineTest, CreateDestroyWithCustomEntrypoint) { testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestFlutterWindowsApi>()); auto test_api = static_cast<TestFlutterWindowsApi*>(scoped_api_stub.stub()); { DartProject project(L"fake/project/path"); project.set_dart_entrypoint("customEntrypoint"); FlutterEngine engine(project); engine.Run(); EXPECT_EQ(test_api->create_called(), true); EXPECT_EQ(test_api->run_called(), true); EXPECT_EQ(test_api->destroy_called(), false); } // Destroying should implicitly shut down if it hasn't been done manually. EXPECT_EQ(test_api->destroy_called(), true); } TEST(FlutterEngineTest, ExplicitShutDown) { testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestFlutterWindowsApi>()); auto test_api = static_cast<TestFlutterWindowsApi*>(scoped_api_stub.stub()); FlutterEngine engine(DartProject(L"fake/project/path")); engine.Run(); EXPECT_EQ(test_api->create_called(), true); EXPECT_EQ(test_api->run_called(), true); EXPECT_EQ(test_api->destroy_called(), false); engine.ShutDown(); EXPECT_EQ(test_api->destroy_called(), true); } TEST(FlutterEngineTest, ProcessMessages) { testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestFlutterWindowsApi>()); auto test_api = static_cast<TestFlutterWindowsApi*>(scoped_api_stub.stub()); FlutterEngine engine(DartProject(L"fake/project/path")); engine.Run(); std::chrono::nanoseconds next_event_time = engine.ProcessMessages(); EXPECT_EQ(next_event_time.count(), 99); } TEST(FlutterEngineTest, ReloadFonts) { testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestFlutterWindowsApi>()); auto test_api = static_cast<TestFlutterWindowsApi*>(scoped_api_stub.stub()); FlutterEngine engine(DartProject(L"fake/project/path")); engine.Run(); engine.ReloadSystemFonts(); EXPECT_TRUE(test_api->reload_fonts_called()); } TEST(FlutterEngineTest, GetMessenger) { DartProject project(L"data"); testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestFlutterWindowsApi>()); auto test_api = static_cast<TestFlutterWindowsApi*>(scoped_api_stub.stub()); FlutterEngine engine(DartProject(L"fake/project/path")); EXPECT_NE(engine.messenger(), nullptr); } TEST(FlutterEngineTest, DartEntrypointArgs) { testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestFlutterWindowsApi>()); auto test_api = static_cast<TestFlutterWindowsApi*>(scoped_api_stub.stub()); DartProject project(L"data"); std::vector<std::string> arguments = {"one", "two"}; project.set_dart_entrypoint_arguments(arguments); FlutterEngine engine(project); const std::vector<std::string>& arguments_ref = test_api->dart_entrypoint_arguments(); ASSERT_EQ(2, arguments_ref.size()); EXPECT_TRUE(arguments[0] == arguments_ref[0]); EXPECT_TRUE(arguments[1] == arguments_ref[1]); } TEST(FlutterEngineTest, SetNextFrameCallback) { DartProject project(L"data"); testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestFlutterWindowsApi>()); auto test_api = static_cast<TestFlutterWindowsApi*>(scoped_api_stub.stub()); FlutterEngine engine(DartProject(L"fake/project/path")); bool success = false; engine.SetNextFrameCallback([&success]() { success = true; }); EXPECT_TRUE(test_api->has_next_frame_callback()); test_api->run_next_frame_callback(); EXPECT_TRUE(success); } TEST(FlutterEngineTest, ProcessExternalWindowMessage) { testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestFlutterWindowsApi>()); auto test_api = static_cast<TestFlutterWindowsApi*>(scoped_api_stub.stub()); FlutterEngine engine(DartProject(L"fake/project/path")); engine.ProcessExternalWindowMessage(reinterpret_cast<HWND>(1), 1234, 0, 0); EXPECT_EQ(test_api->last_external_message(), 1234); } } // namespace flutter
engine/shell/platform/windows/client_wrapper/flutter_engine_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/client_wrapper/flutter_engine_unittests.cc", "repo_id": "engine", "token_count": 2948 }
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. #include "flutter/shell/platform/windows/compositor_software.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" namespace flutter { CompositorSoftware::CompositorSoftware(FlutterWindowsEngine* engine) : engine_(engine) {} bool CompositorSoftware::CreateBackingStore( const FlutterBackingStoreConfig& config, FlutterBackingStore* result) { size_t size = config.size.width * config.size.height * 4; void* allocation = std::calloc(size, sizeof(uint8_t)); if (!allocation) { return false; } result->type = kFlutterBackingStoreTypeSoftware; result->software.allocation = allocation; result->software.height = config.size.height; result->software.row_bytes = config.size.width * 4; result->software.user_data = nullptr; result->software.destruction_callback = [](void* user_data) { // Backing store destroyed in `CompositorSoftware::CollectBackingStore`, set // on FlutterCompositor.collect_backing_store_callback during engine start. }; return true; } bool CompositorSoftware::CollectBackingStore(const FlutterBackingStore* store) { std::free(const_cast<void*>(store->software.allocation)); return true; } bool CompositorSoftware::Present(FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { FlutterWindowsView* view = engine_->view(view_id); if (!view) { return false; } // Clear the view if there are no layers to present. if (layers_count == 0) { return view->ClearSoftwareBitmap(); } // TODO: Support compositing layers and platform views. // See: https://github.com/flutter/flutter/issues/31713 FML_DCHECK(layers_count == 1); FML_DCHECK(layers[0]->offset.x == 0 && layers[0]->offset.y == 0); FML_DCHECK(layers[0]->type == kFlutterLayerContentTypeBackingStore); FML_DCHECK(layers[0]->backing_store->type == kFlutterBackingStoreTypeSoftware); const auto& backing_store = layers[0]->backing_store->software; return view->PresentSoftwareBitmap( backing_store.allocation, backing_store.row_bytes, backing_store.height); } } // namespace flutter
engine/shell/platform/windows/compositor_software.cc/0
{ "file_path": "engine/shell/platform/windows/compositor_software.cc", "repo_id": "engine", "token_count": 826 }
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/windows/egl/manager.h" #include <vector> #include "flutter/fml/logging.h" #include "flutter/shell/platform/windows/egl/egl.h" namespace flutter { namespace egl { int Manager::instance_count_ = 0; std::unique_ptr<Manager> Manager::Create(bool enable_impeller) { std::unique_ptr<Manager> manager; manager.reset(new Manager(enable_impeller)); if (!manager->IsValid()) { return nullptr; } return std::move(manager); } Manager::Manager(bool enable_impeller) { ++instance_count_; if (!InitializeDisplay()) { return; } if (!InitializeConfig(enable_impeller)) { return; } if (!InitializeContexts()) { return; } is_valid_ = true; } Manager::~Manager() { CleanUp(); --instance_count_; } bool Manager::InitializeDisplay() { // These are preferred display attributes and request ANGLE's D3D11 // renderer. eglInitialize will only succeed with these attributes if the // hardware supports D3D11 Feature Level 10_0+. const EGLint d3d11_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that will // enable ANGLE to automatically call the IDXGIDevice3::Trim method on // behalf of the application when it gets suspended. EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE, // This extension allows angle to render directly on a D3D swapchain // in the correct orientation on D3D11. EGL_EXPERIMENTAL_PRESENT_PATH_ANGLE, EGL_EXPERIMENTAL_PRESENT_PATH_FAST_ANGLE, EGL_NONE, }; // These are used to request ANGLE's D3D11 renderer, with D3D11 Feature // Level 9_3. const EGLint d3d11_fl_9_3_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, 9, EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, 3, EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE, EGL_NONE, }; // These attributes request D3D11 WARP (software rendering fallback) in case // hardware-backed D3D11 is unavailable. const EGLint d3d11_warp_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE, EGL_NONE, }; std::vector<const EGLint*> display_attributes_configs = { d3d11_display_attributes, d3d11_fl_9_3_display_attributes, d3d11_warp_display_attributes, }; PFNEGLGETPLATFORMDISPLAYEXTPROC egl_get_platform_display_EXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>( ::eglGetProcAddress("eglGetPlatformDisplayEXT")); if (!egl_get_platform_display_EXT) { LogEGLError("eglGetPlatformDisplayEXT not available"); return false; } // Attempt to initialize ANGLE's renderer in order of: D3D11, D3D11 Feature // Level 9_3 and finally D3D11 WARP. for (auto config : display_attributes_configs) { bool is_last = (config == display_attributes_configs.back()); display_ = egl_get_platform_display_EXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, config); if (display_ == EGL_NO_DISPLAY) { if (is_last) { LogEGLError("Failed to get a compatible EGLdisplay"); return false; } // Try the next config. continue; } if (::eglInitialize(display_, nullptr, nullptr) == EGL_FALSE) { if (is_last) { LogEGLError("Failed to initialize EGL via ANGLE"); return false; } // Try the next config. continue; } return true; } FML_UNREACHABLE(); } bool Manager::InitializeConfig(bool enable_impeller) { const EGLint config_attributes[] = {EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_STENCIL_SIZE, 8, EGL_NONE}; const EGLint impeller_config_attributes[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 0, EGL_STENCIL_SIZE, 8, EGL_SAMPLE_BUFFERS, 1, EGL_SAMPLES, 4, EGL_NONE}; const EGLint impeller_config_attributes_no_msaa[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 0, EGL_STENCIL_SIZE, 8, EGL_NONE}; EGLBoolean result; EGLint num_config = 0; if (enable_impeller) { // First try the MSAA configuration. result = ::eglChooseConfig(display_, impeller_config_attributes, &config_, 1, &num_config); if (result == EGL_TRUE && num_config > 0) { return true; } // Next fall back to disabled MSAA. result = ::eglChooseConfig(display_, impeller_config_attributes_no_msaa, &config_, 1, &num_config); if (result == EGL_TRUE && num_config == 0) { return true; } } else { result = ::eglChooseConfig(display_, config_attributes, &config_, 1, &num_config); if (result == EGL_TRUE && num_config > 0) { return true; } } LogEGLError("Failed to choose EGL config"); return false; } bool Manager::InitializeContexts() { const EGLint context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; auto const render_context = ::eglCreateContext(display_, config_, EGL_NO_CONTEXT, context_attributes); if (render_context == EGL_NO_CONTEXT) { LogEGLError("Failed to create EGL render context"); return false; } auto const resource_context = ::eglCreateContext(display_, config_, render_context, context_attributes); if (resource_context == EGL_NO_CONTEXT) { LogEGLError("Failed to create EGL resource context"); return false; } render_context_ = std::make_unique<Context>(display_, render_context); resource_context_ = std::make_unique<Context>(display_, resource_context); return true; } bool Manager::InitializeDevice() { const auto query_display_attrib_EXT = reinterpret_cast<PFNEGLQUERYDISPLAYATTRIBEXTPROC>( ::eglGetProcAddress("eglQueryDisplayAttribEXT")); const auto query_device_attrib_EXT = reinterpret_cast<PFNEGLQUERYDEVICEATTRIBEXTPROC>( ::eglGetProcAddress("eglQueryDeviceAttribEXT")); if (query_display_attrib_EXT == nullptr || query_device_attrib_EXT == nullptr) { return false; } EGLAttrib egl_device = 0; EGLAttrib angle_device = 0; auto result = query_display_attrib_EXT(display_, EGL_DEVICE_EXT, &egl_device); if (result != EGL_TRUE) { return false; } result = query_device_attrib_EXT(reinterpret_cast<EGLDeviceEXT>(egl_device), EGL_D3D11_DEVICE_ANGLE, &angle_device); if (result != EGL_TRUE) { return false; } resolved_device_ = reinterpret_cast<ID3D11Device*>(angle_device); return true; } void Manager::CleanUp() { EGLBoolean result = EGL_FALSE; // Needs to be reset before destroying the contexts. resolved_device_.Reset(); // Needs to be reset before destroying the EGLDisplay. render_context_.reset(); resource_context_.reset(); if (display_ != EGL_NO_DISPLAY) { // Display is reused between instances so only terminate display // if destroying last instance if (instance_count_ == 1) { ::eglTerminate(display_); } display_ = EGL_NO_DISPLAY; } } bool Manager::IsValid() const { return is_valid_; } std::unique_ptr<WindowSurface> Manager::CreateWindowSurface(HWND hwnd, size_t width, size_t height) { if (!hwnd || !is_valid_) { return nullptr; } // Disable ANGLE's automatic surface resizing and provide an explicit size. // The surface will need to be destroyed and re-created if the HWND is // resized. const EGLint surface_attributes[] = {EGL_FIXED_SIZE_ANGLE, EGL_TRUE, EGL_WIDTH, static_cast<EGLint>(width), EGL_HEIGHT, static_cast<EGLint>(height), EGL_NONE}; auto const surface = ::eglCreateWindowSurface( display_, config_, static_cast<EGLNativeWindowType>(hwnd), surface_attributes); if (surface == EGL_NO_SURFACE) { LogEGLError("Surface creation failed."); return nullptr; } return std::make_unique<WindowSurface>(display_, render_context_->GetHandle(), surface, width, height); } bool Manager::HasContextCurrent() { return ::eglGetCurrentContext() != EGL_NO_CONTEXT; } EGLSurface Manager::CreateSurfaceFromHandle(EGLenum handle_type, EGLClientBuffer handle, const EGLint* attributes) const { return ::eglCreatePbufferFromClientBuffer(display_, handle_type, handle, config_, attributes); } bool Manager::GetDevice(ID3D11Device** device) { if (!resolved_device_) { if (!InitializeDevice()) { return false; } } resolved_device_.CopyTo(device); return (resolved_device_ != nullptr); } Context* Manager::render_context() const { return render_context_.get(); } Context* Manager::resource_context() const { return resource_context_.get(); } } // namespace egl } // namespace flutter
engine/shell/platform/windows/egl/manager.cc/0
{ "file_path": "engine/shell/platform/windows/egl/manager.cc", "repo_id": "engine", "token_count": 4424 }
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_WINDOWS_FLUTTER_DESKTOP_MESSENGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_DESKTOP_MESSENGER_H_ #include <atomic> #include <mutex> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/public/flutter_messenger.h" namespace flutter { class FlutterWindowsEngine; /// A messenger object used to invoke platform messages. /// /// On Windows, the message handler is essentially the |FlutterWindowsEngine|, /// this allows a handle to the |FlutterWindowsEngine| that will become /// invalidated if the |FlutterWindowsEngine| is destroyed. class FlutterDesktopMessenger { public: FlutterDesktopMessenger() = default; /// Convert to FlutterDesktopMessengerRef. FlutterDesktopMessengerRef ToRef() { return reinterpret_cast<FlutterDesktopMessengerRef>(this); } /// Convert from FlutterDesktopMessengerRef. static FlutterDesktopMessenger* FromRef(FlutterDesktopMessengerRef ref) { return reinterpret_cast<FlutterDesktopMessenger*>(ref); } /// Getter for the engine field. flutter::FlutterWindowsEngine* GetEngine() const { return engine; } /// Setter for the engine field. /// Thread-safe. void SetEngine(flutter::FlutterWindowsEngine* arg_engine) { std::scoped_lock lock(mutex_); engine = arg_engine; } /// Increments the reference count. /// /// Thread-safe. FlutterDesktopMessenger* AddRef() { ref_count_.fetch_add(1); return this; } /// Decrements the reference count and deletes the object if the count has /// gone to zero. /// /// Thread-safe. void Release() { int32_t old_count = ref_count_.fetch_sub(1); if (old_count <= 1) { delete this; } } /// Returns the mutex associated with the |FlutterDesktopMessenger|. /// /// This mutex is used to synchronize reading or writing state inside the /// |FlutterDesktopMessenger| (ie |engine|). std::mutex& GetMutex() { return mutex_; } private: // The engine that owns this state object. flutter::FlutterWindowsEngine* engine = nullptr; std::mutex mutex_; std::atomic<int32_t> ref_count_ = 0; FML_DISALLOW_COPY_AND_ASSIGN(FlutterDesktopMessenger); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_DESKTOP_MESSENGER_H_
engine/shell/platform/windows/flutter_desktop_messenger.h/0
{ "file_path": "engine/shell/platform/windows/flutter_desktop_messenger.h", "repo_id": "engine", "token_count": 799 }
419