text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @TestOn('browser') library; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine/dom.dart'; import 'package:ui/src/engine/view_embedder/embedding_strategy/custom_element_embedding_strategy.dart'; import 'package:ui/src/engine/view_embedder/embedding_strategy/embedding_strategy.dart'; import 'package:ui/src/engine/view_embedder/embedding_strategy/full_page_embedding_strategy.dart'; void main() { internalBootstrapBrowserTest(() => doTests); } void doTests() { group('Factory', () { test('Creates a FullPage instance when hostElement is null', () async { final EmbeddingStrategy strategy = EmbeddingStrategy.create(); expect(strategy, isA<FullPageEmbeddingStrategy>()); }); test('Creates a CustomElement instance when hostElement is not null', () async { final DomElement element = createDomElement('some-random-element'); final EmbeddingStrategy strategy = EmbeddingStrategy.create( hostElement: element, ); expect(strategy, isA<CustomElementEmbeddingStrategy>()); }); }); }
engine/lib/web_ui/test/engine/view_embedder/embedding_strategy/embedding_strategy_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/view_embedder/embedding_strategy/embedding_strategy_test.dart", "repo_id": "engine", "token_count": 432 }
271
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart' hide BackdropFilterEngineLayer, ClipRectEngineLayer; import 'package:ui/ui.dart'; import 'package:web_engine_tester/golden_tester.dart'; import '../../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); setUp(() async { debugShowClipLayers = true; SurfaceSceneBuilder.debugForgetFrameScene(); for (final DomNode scene in domDocument.querySelectorAll('flt-scene')) { scene.remove(); } }); // The black circle on the left should not be blurred since it is outside // the clip boundary around backdrop filter. However there should be only // one red dot since the other one should be blurred by filter. test('Background should only blur at ancestor clip boundary', () async { const Rect region = Rect.fromLTWH(0, 0, 190, 130); final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); final Picture backgroundPicture = _drawBackground(region); builder.addPicture(Offset.zero, backgroundPicture); builder.pushClipRect( const Rect.fromLTRB(10, 10, 180, 120), ); final Picture circles1 = _drawTestPictureWithCircles(region, 30, 30); builder.addPicture(Offset.zero, circles1); builder.pushClipRect( const Rect.fromLTRB(60, 10, 180, 120), ); builder.pushBackdropFilter(ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0)); final Picture circles2 = _drawTestPictureWithCircles(region, 90, 30); builder.addPicture(Offset.zero, circles2); builder.pop(); builder.pop(); builder.pop(); domDocument.body!.append(builder .build() .webOnlyRootElement!); await matchGoldenFile('backdrop_filter_clip.png', region: region); }); test('Background should only blur at ancestor clip boundary after move', () async { const Rect region = Rect.fromLTWH(0, 0, 190, 130); final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); final Picture backgroundPicture = _drawBackground(region); builder.addPicture(Offset.zero, backgroundPicture); final ClipRectEngineLayer clipEngineLayer = builder.pushClipRect( const Rect.fromLTRB(10, 10, 180, 120), ); final Picture circles1 = _drawTestPictureWithCircles(region, 30, 30); builder.addPicture(Offset.zero, circles1); final ClipRectEngineLayer clipEngineLayer2 = builder.pushClipRect( const Rect.fromLTRB(60, 10, 180, 120), ); final BackdropFilterEngineLayer oldBackdropFilterLayer = builder.pushBackdropFilter(ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0)); final Picture circles2 = _drawTestPictureWithCircles(region, 90, 30); builder.addPicture(Offset.zero, circles2); builder.pop(); builder.pop(); builder.pop(); builder.build(); // Now reparent filter layer in next scene. final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder(); builder2.addPicture(Offset.zero, backgroundPicture); builder2.pushClipRect( const Rect.fromLTRB(10, 10, 180, 120), oldLayer: clipEngineLayer ); builder2.addPicture(Offset.zero, circles1); builder2.pushClipRect( const Rect.fromLTRB(10, 75, 180, 120), oldLayer: clipEngineLayer2 ); builder2.pushBackdropFilter(ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), oldLayer: oldBackdropFilterLayer); builder2.addPicture(Offset.zero, circles2); builder2.pop(); builder2.pop(); builder2.pop(); domDocument.body!.append(builder2 .build() .webOnlyRootElement!); await matchGoldenFile('backdrop_filter_clip_moved.png', region: region); }); // The blur filter should be applied to the background inside the clip even // though there are no children of the backdrop filter. test('Background should blur even if child does not paint', () async { const Rect region = Rect.fromLTWH(0, 0, 190, 130); final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); final Picture backgroundPicture = _drawBackground(region); builder.addPicture(Offset.zero, backgroundPicture); builder.pushClipRect( const Rect.fromLTRB(10, 10, 180, 120), ); final Picture circles1 = _drawTestPictureWithCircles(region, 30, 30); builder.addPicture(Offset.zero, circles1); builder.pushClipRect( const Rect.fromLTRB(60, 10, 180, 120), ); builder.pushBackdropFilter(ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0)); builder.pop(); builder.pop(); builder.pop(); domDocument.body!.append(builder .build() .webOnlyRootElement!); await matchGoldenFile('backdrop_filter_no_child_rendering.png', region: region); }); test('colorFilter as imageFilter', () async { const Rect region = Rect.fromLTWH(0, 0, 190, 130); final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); final Picture backgroundPicture = _drawBackground(region); builder.addPicture(Offset.zero, backgroundPicture); builder.pushClipRect( const Rect.fromLTRB(10, 10, 180, 120), ); final Picture circles1 = _drawTestPictureWithCircles(region, 30, 30); // current background color is light green, apply a light yellow colorFilter const ColorFilter colorFilter = ColorFilter.mode( Color(0xFFFFFFB1), BlendMode.modulate ); builder.pushBackdropFilter(colorFilter); builder.addPicture(Offset.zero, circles1); builder.pop(); domDocument.body!.append(builder .build() .webOnlyRootElement!); await matchGoldenFile('backdrop_filter_colorFilter_as_imageFilter.png', region: region); }); } Picture _drawTestPictureWithCircles(Rect region, double offsetX, double offsetY) { final EnginePictureRecorder recorder = PictureRecorder() as EnginePictureRecorder; final RecordingCanvas canvas = recorder.beginRecording(region); canvas.drawCircle( Offset(offsetX + 10, offsetY + 10), 10, SurfacePaint()..style = PaintingStyle.fill); canvas.drawCircle( Offset(offsetX + 60, offsetY + 10), 10, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromRGBO(255, 0, 0, 1)); canvas.drawCircle( Offset(offsetX + 10, offsetY + 60), 10, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromRGBO(0, 255, 0, 1)); canvas.drawCircle( Offset(offsetX + 60, offsetY + 60), 10, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromRGBO(0, 0, 255, 1)); return recorder.endRecording(); } Picture _drawBackground(Rect region) { final EnginePictureRecorder recorder = PictureRecorder() as EnginePictureRecorder; final RecordingCanvas canvas = recorder.beginRecording(region); canvas.drawRect( region.deflate(8.0), SurfacePaint() ..style = PaintingStyle.fill ..color = const Color(0xFFE0FFE0) ); return recorder.endRecording(); }
engine/lib/web_ui/test/html/compositing/backdrop_filter_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/compositing/backdrop_filter_golden_test.dart", "repo_id": "engine", "token_count": 2572 }
272
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import 'package:web_engine_tester/golden_tester.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const Rect region = Rect.fromLTWH(0, 0, 300, 300); late BitmapCanvas canvas; setUp(() { canvas = BitmapCanvas(region, RenderStrategy()); }); tearDown(() { canvas.rootElement.remove(); }); test('draws stroke joins', () async { paintStrokeJoins(canvas); domDocument.body!.append(canvas.rootElement); await matchGoldenFile('canvas_stroke_joins.png', region: region); }); } void paintStrokeJoins(BitmapCanvas canvas) { canvas.drawRect(const Rect.fromLTRB(0, 0, 300, 300), SurfacePaintData() ..color = 0xFFFFFFFF ..style = PaintingStyle.fill); // white Offset start = const Offset(20, 10); Offset mid = const Offset(120, 10); Offset end = const Offset(120, 20); final List<StrokeCap> strokeCaps = <StrokeCap>[StrokeCap.butt, StrokeCap.round, StrokeCap.square]; for (final StrokeCap cap in strokeCaps) { final List<StrokeJoin> joints = <StrokeJoin>[StrokeJoin.miter, StrokeJoin.bevel, StrokeJoin.round]; const List<Color> colors = <Color>[ Color(0xFFF44336), Color(0xFF4CAF50), Color(0xFF2196F3)]; // red, green, blue for (int i = 0; i < joints.length; i++) { final StrokeJoin join = joints[i]; final Color color = colors[i % colors.length]; final Path path = Path(); path.moveTo(start.dx, start.dy); path.lineTo(mid.dx, mid.dy); path.lineTo(end.dx, end.dy); canvas.drawPath(path, SurfacePaintData() ..style = PaintingStyle.stroke ..strokeWidth = 4 ..color = color.value ..strokeJoin = join ..strokeCap = cap); start = start.translate(0, 20); mid = mid.translate(0, 20); end = end.translate(0, 20); } } }
engine/lib/web_ui/test/html/drawing/canvas_stroke_joins_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/drawing/canvas_stroke_joins_golden_test.dart", "repo_id": "engine", "token_count": 868 }
273
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import '../../common/test_initialization.dart'; import 'helper.dart'; import 'text_goldens.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { final EngineGoldenTester goldenTester = await EngineGoldenTester.initialize( viewportSize: const Size(600, 600), ); setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); testEachCanvas('draws paragraphs with placeholders', (EngineCanvas canvas) { const Rect screenRect = Rect.fromLTWH(0, 0, 600, 600); final RecordingCanvas recordingCanvas = RecordingCanvas(screenRect); Offset offset = Offset.zero; for (final PlaceholderAlignment placeholderAlignment in PlaceholderAlignment.values) { _paintTextWithPlaceholder( recordingCanvas, offset, before: 'Lorem ipsum', after: 'dolor sit amet, consectetur.', placeholderAlignment: placeholderAlignment, ); offset = offset.translate(0.0, 80.0); } recordingCanvas.endRecording(); recordingCanvas.apply(canvas, screenRect); return goldenTester.diffCanvasScreenshot(canvas, 'text_with_placeholders'); }); testEachCanvas('text alignment and placeholders', (EngineCanvas canvas) { const Rect screenRect = Rect.fromLTWH(0, 0, 600, 600); final RecordingCanvas recordingCanvas = RecordingCanvas(screenRect); Offset offset = Offset.zero; _paintTextWithPlaceholder( recordingCanvas, offset, before: 'Lorem', after: 'ipsum.', textAlignment: TextAlign.start, ); offset = offset.translate(0.0, 80.0); _paintTextWithPlaceholder( recordingCanvas, offset, before: 'Lorem', after: 'ipsum.', textAlignment: TextAlign.center, ); offset = offset.translate(0.0, 80.0); _paintTextWithPlaceholder( recordingCanvas, offset, before: 'Lorem', after: 'ipsum.', textAlignment: TextAlign.end, ); recordingCanvas.endRecording(); recordingCanvas.apply(canvas, screenRect); return goldenTester.diffCanvasScreenshot(canvas, 'text_align_with_placeholders'); }); } const Size placeholderSize = Size(80.0, 50.0); void _paintTextWithPlaceholder( RecordingCanvas canvas, Offset offset, { required String before, required String after, PlaceholderAlignment placeholderAlignment = PlaceholderAlignment.baseline, TextAlign textAlignment = TextAlign.left, }) { // First let's draw the paragraph. final Paragraph paragraph = _createParagraphWithPlaceholder( before, after, placeholderAlignment, textAlignment, ); canvas.drawParagraph(paragraph, offset); // Then fill the placeholders. final TextBox placeholderBox = paragraph.getBoxesForPlaceholders().single; canvas.drawRect( placeholderBox.toRect().shift(offset), SurfacePaint()..color = red, ); } Paragraph _createParagraphWithPlaceholder( String before, String after, PlaceholderAlignment placeholderAlignment, TextAlign textAlignment, ) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(textAlign: textAlignment)); builder .pushStyle(TextStyle(color: black, fontFamily: 'Roboto', fontSize: 14)); builder.addText(before); builder.addPlaceholder( placeholderSize.width, placeholderSize.height, placeholderAlignment, baselineOffset: 40.0, baseline: TextBaseline.alphabetic, ); builder.pushStyle(TextStyle(color: blue, fontFamily: 'Roboto', fontSize: 14)); builder.addText(after); return builder.build()..layout(const ParagraphConstraints(width: 200.0)); }
engine/lib/web_ui/test/html/paragraph/text_placeholders_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/paragraph/text_placeholders_golden_test.dart", "repo_id": "engine", "token_count": 1385 }
274
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:ui/src/engine.dart'; /// 50x50 pixel flutter logo image that contains alpha ramps and colors /// specifically to transparency and blending. const String _flutterLogoBase64 = 'iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAAXNSR0IArs4c6QAAAKRlWElm' 'TU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgExAAIAAAAg' 'AAAAWodpAAQAAAABAAAAegAAAAAAAABIAAAAAQAAAEgAAAABQWRvYmUgUGhvdG9zaG9wIENT' 'NiAoTWFjaW50b3NoKQAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAMqADAAQAAAABAAAAMgAA' 'AABWBXsWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAEemlUWHRYTUw6Y29tLmFkb2JlLnhtcAAA' 'AAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENv' 'cmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5' 'OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjph' 'Ym91dD0iIgogICAgICAgICAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94' 'YXAvMS4wL21tLyIKICAgICAgICAgICAgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5j' 'b20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiCiAgICAgICAgICAgIHhtbG5zOnhtcD0i' 'aHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIKICAgICAgICAgICAgeG1sbnM6dGlmZj0i' 'aHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8eG1wTU06SW5zdGFu' 'Y2VJRD54bXAuaWlkOjMyOERERjc5ODRCRjExRUE5QUE4OEM5NTZDREM5QkUyPC94bXBNTTp' 'JbnN0YW5jZUlEPgogICAgICAgICA8eG1wTU06RG9jdW1lbnRJRD54bXAuZGlkOjMyOERERj' 'dBODRCRjExRUE5QUE4OEM5NTZDREM5QkUyPC94bXBNTTpEb2N1bWVudElEPgogICAgICAgI' 'CA8eG1wTU06T3JpZ2luYWxEb2N1bWVudElEPnhtcC5kaWQ6MDE4MDExNzQwNzIwNjgxMTgy' 'MkFBQjU0OEFBMDMwM0E8L3htcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD4KICAgICAgICAgPHht' 'cE1NOkRlcml2ZWRGcm9tIHJkZjpwYXJzZVR5cGU9IlJlc291cmNlIj4KICAgICAgICAgICA' 'gPHN0UmVmOmluc3RhbmNlSUQ+eG1wLmlpZDowNDgwMTE3NDA3MjA2ODExODIyQUFCNTQ4QU' 'EwMzAzQTwvc3RSZWY6aW5zdGFuY2VJRD4KICAgICAgICAgICAgPHN0UmVmOmRvY3VtZW50SU' 'Q+eG1wLmRpZDowMTgwMTE3NDA3MjA2ODExODIyQUFCNTQ4QUEwMzAzQTwvc3RSZWY6ZG9jd' 'W1lbnRJRD4KICAgICAgICAgPC94bXBNTTpEZXJpdmVkRnJvbT4KICAgICAgICAgPHhtcDpD' 'cmVhdG9yVG9vbD5BZG9iZSBQaG90b3Nob3AgQ1M2IChNYWNpbnRvc2gpPC94bXA6Q3JlYXRv' 'clRvb2w+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb2' '4+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhP' 'gr/+ApQAAAQNUlEQVRoBbVaDYxdRRWemTv3vt2WbrctpRYxtCVU4io1LomElrjYWnbbgtr2' 'CbISwGpR0UBUjD8YHyZCNCqIP5GmtLWSAn3SVYqw7PbnFUQFXGOMRUFlW9G2gKalu/veu38' 'zfufce3ff275dWtBJ5s7cuTPnnO+cM2d+3pN2urDiVSHEVCFuOpgT35vVIuaLV8Tgtw8Icf' 'PZkZgntDggrhNCbhHCuihD9J402Y4OLUulqNy1+iwvFIscaaqRMWqyQRofIxFH2ohpwqjDc' 't/OZyyYSTAVHQUtSoVIfPiL7xWu3i2i0KA7PnFmstpaEVMLBnHm1rFHhEbiQZ9PKtl83pPF' 'YnB0xVVne2HlKcdz5wgTC62cZLwlGdJUSxXtWnngFItIOhdzj3xeiWIxzrpPVmpAZg4EJjc' 'tAcmqazqNxjnJVwEOnKjDhMmuX+/KDRuCoeVXn9EcDf/K0c4cEwYBBmgBjSUJZVbnJiuh9' '1BZ4ZnYREpNucgtPfAMW7VYjHjM7Ldlg1MaJxYaxlnNzVCUP4THrLRTdRiVWVaEcQ54fpu2' 'JoTTl9rid+3tBCL8a1d3S1M0/ARAnGWiyEcfjK+xaB0Icg0ZQXGekEoo4V0qdwNEatVR+q8' '8O6kCqZ+Wx0QPD6jgeTop72Xxd26Yx0/xYlJAFmJa4xdZO74kcwIgPpObF//rce3qhSYMAw' 'zIpaqsEYSqaE0Kcmso04F/q/fr/uKeE0AQm5OwCCwqvCzn90MzMHEbsijsJ4f1RBuysFCa' 'TGUaA0C1bGKjKufFh/Zo111kopAsQXQnTABAvu9IR6OiunX/jocagpiQQv0HDYJkhiS1Jc' 'V+Lupe0g71BRg7mNjsbmHnml7t6IswJ3wog9xpggR4Uhh4mFTapTjwCb17xzbblgSJCQa9' 'ZvOkIXGy0SkIjihh5+odcKfl6cSeBAQoSrinhYm1qwDi887uHXdbml/7i2MKnYzxBN9eFx' 'ArCgqWYBDBpWu2wp0+aAKOTll0m4AdQbBGuZ4DELcCxHfINcXAwIRBhAmdxGQ/ZSAEQogC' '0w861/7Q9dyrGQTNqwkTzxaAEBFAaBOa7zq7dhTIqqJUogk/2XQ6uck+Ie8GH9i7O0oKjI3' 'ftfabAPEpE/i00mPFz1IDmZKmUHmua6J4g7O753NMq9hGobDBADRaK7NcaJuNbkLMoaV5gn' 'RqFunocGjr4XeuvcXT7heMXyWXIPLMiHk0FEsEsIQXh/F9zq6fX8/9CgWsxYWG4Zy/1zzmz' 'n2e6U9VpMPGacIP47vbdqzaAxvCYEX+RtfRd2Jix8IaGq/qdJoteCkBdPCldnNxFO9EiL2' 'cmmsDRdrtJIv3X+Rdc/6TQRiQAoj3qPyTGGuMNhhj/7QhCDrz61zlEAjonbwCIGrTOBD4xC' 'BsFO3R/T2vCQKupCSiGkpsYcU25NORg7Q9eu6Fg7POu+lOMWN6kxyB65EUWXpNIAmIYlBen' 'r/CddRGG4UEAiHUJrvAGmIZ0bQMEGJhiehpZ/Gi94n+nmTxzPZP4zqnr5mGSa7lyE3UDnB' 'UiJmtrUJUA+u2NktaySEHPTjVazRrTUvb1ZWjnWz10vzKZi3vp9ULoacxiHpr+ADhYa/1p' '8PD8zpkoWDYNTG/xrEY/5pJRuWx9GNoDBhjl18ul7EJULzFoBBYmyYEwpZ49FG/0pV/T07Z' 'h0l+YwlJaolaKmk9VWegHJ1DdHpBTZ1+8Vt+c0eFN5SYXw2GTNREpNJ9P0qJzVgSVFDWA8g' 'INASSudPIijUXuNbsojkFrYR1IGrppdZAE0A4HhR4WLkti+XPtxwjWhcMDJwKiEy2sTLlVc' 'uyZp5zvxPmSAbC78q/TRtbgiV1DEcHYneU0GgFNACC1IemUCkFEOaoEqctlo9sOZLRGpPo/' '1ers0jG+Njy/HzHmCeUElPh5yE6aZadHg1B4GCklItwU45k08Wy76eDGa3/jei1TDOK9W2' 'jQHgyYmIPL/3wnGkqfsJx5EwTxwECRmKJ+nFsCSKJ5gjLFIGIY6kvyT123/4sSOCjPJVcEi' 'WW55g4lk63TOjXLnlgttgd7fhAa5OuPgk/fzOBwHCP3b8WBDWkcwLfAULCPSWCSW6Z91jxab' 'YEgkTBpmvMKUC5RF7CUa1VtNJ5pkGqFaT+s04ORhvCwY5rm07zjpccxznHhFEV3Wg7bngC0J' 'h6GqQxCok43SkRW3mZ7r2/lFoCIAqqIJPtx3K7fOp0QWfoydM/8Xn1S6vVzXNu9ntF75xO0Z' 'mNsbRI0mgc7vlJ9WSyjwnF1zbUfJZ3fJfWDk53URmvCQjqjmU1nc/ULUkSNzfQuMLNSGzVlb' 'qv+HA6J/y8zTsAwVv8lfHSexGx3zsim4fQPwunqI4JwHXI1wIuj5/RL5eY86f+Otj31c6mTr' 'o0mIOcbUcgDAHBZjIZnxLhHYbQe3EeWOLO6NeOWgwQw+iTA3AIkvQb8yLGQJToYAQUjo6ts0' '73bX8guz1JLcEgVkXLtjrK6Q5tSCvz3FHLMpnkQQIlWiZvBWPpisA/duvXf3v7FtEhvp52' 'HQPCwmRWyZRB73CNDpwH7PLV/8FqBxFZ97Ryk6gpnaxg5CSkxRyaYoy4ESA28ekOtyckU0E' 'UmPqqeOkPYK6rQxMeBxtsKhOmia8k9XFWiRylWlUgbnu6+R8F0GoBH+qe5URaFiUJ91yted' 'C+2Kq+HWutMT3KUdNgPbgW+SSW8vpMExFhlkDILzt9D97F84sWu4S2gnrtqnjZ7VKpGyIT0f' '2lQxrJMt5JO2nmCw36FmuAcEJz1/bcL7+C79ibHKM+pLTaDFWTTKPg6uoKvs2+q/p7VsMQvT' 'D1DHSukHsBJM0FIgYQ0ldStUTWfMPp+9ntPA7WJBAdogPbCBGvsku/BDG/iHu2oxhDWiRmpI' 'AYQoAO5awuqa3iKDFdhXbjTm/fjeDPboCoReNGQaA9fZdp2xgtsGH6fPbmczNGymDRZRhUQn' 'UmBKxAWxlBHxxmGmPvcPt6biENi/R0RyBKshQttUtuALvbsB/7NyihyygI0ABjChDImKoRWQ' 'FtFSy4s5zAbtvplT6O/mJADIwGBLyOAsEcI2GjRLGkAIl60gY2JCPtPMAWu9IkDBewMMcrMe' 'A3YNQK34ab2Qosejri8I+dXT2fpf50ZqfTXbttdwnEvOicaw6Yl+4oi+rLjlUkOBNHRxKYB' 'E8si0WT2iAERcZZOrA7dub2daMu8ohq7aKdvlMiRVCdAWCK8ThugyIQSfGe0IL0iUXwkRODo' 'WuZnTvL0puyCjr9Iz7QAacVN4Fbnf6eT1JHW8ANSgpiQA6EC6IFq+FyP8BN+n9eEEeiEVnF' 'tbuC8BYMUhAQiN6BLgEhzUzHyN6HcvvWEk0K2UWOlPQ2mjIgMeYtA8KXpMzeUyuTpdki2VC' 'Jicur/C+3HcWEXQlBDkN7jwDEtdSH5gWdLcgSBGK+Pfd9WBDvRph71REKBzZrB+3hqCICEF' 'YQnMAkIFDSnCvD3VsB4okFB5rX4N122A5dlA1v3OuFz0DAAuRaRBd2G811QPBR0Lmc3ayv5' '2VldCe2UeuonUHgLqvNtnkE4hx7zkUw8T3wAdwa2ypOKwYzPoyFiV4Qh7A1qAHDmpMj6DcN' 'IH4/52/hmu+f+6hPIMg1iX6DlAEJMW+5DhdDCdciS3Od3pN8wjaeCLKbJdehB+md3alQiF' 'NLBPPtwkU4c2zGygJCxoeGcPUqcQam5VuJEPP8gDgsFoi52MNoeKmhfdt0x8q/tLwi8pvO' 'e3IonV+TnVPoG+UIkx3GQ+IYQnakOjKVaWoIhL7RTSKH2DbcPcGdUu2FC+yCc42JtkB4zB' 'U7hJ4uaAa8XIIwgdEAU4EMg+KInC/mRtq6LdLEL055VV1535l7/r0errkBVs2EaFCSiKTtD' 'AwDgbK4KzZfKYgxJMmXBpTqmmgni0PiPDvvPBk7GyH0TAwsI5TiB5w6xWAY9I8nxVEf7jZN' 'TvEWSOdwa1V//P7mPxxotwLziwWsY0EvtI5A+dhfWPqVaSfybGS6RSGjyAP/PCTmf+w2MfuM' 'aeI4lkefGKXphDmSfRhXMmAbOXOxZM2AiY+DOKYDbvKtCGBxMGOGXNJ7bGTgKeWPhH82T93' 'bdYRAEM0Bub2G/Tgu9a9kDXLJzCqoS3oHD4nfXlCX+J7mkwNCoRHuf9D9+14o7CaAyAEQX' 'Sv5VCLeBtiIMBPYLmHoaNyiDcaV4mePlje8Y9G06++5O5HzQ7HIb69d+JLm+if5DB0lKFe' 'w5HHJ75JAMEDwIZ5JPjkgoADksdgr9KAc7MeK/DVw8gDCxx4NHgTCsAATNSCsXJwsnw/K2' 'z8TlO98Z6wXRkfiYdXe3L35W0RKFAEG6xHXGz/IA+goQfdaTeBH9WY+xBnrsxUYAPFMrDQ' 'ZMYwdly7BBETIBJiHsFP+NgRvggWqWMwpI3oBmMj5Vj7nl39xvV/5xrt85/zAt1W4obWHs' 'OAvabpq0y1MFQGkARiyBCVypz3IjyD3wgMeQ/nwSLn6lMi5EWIvpocEIALFwHz2fXQ6+YR' 'whc40+eOzo7OvwvRchw0JXaZBKTn8RvycrfReJ6ufXizkhcmSaHCKhPWgPEVXSrOMUL/wt1' '33vYQpxTuOq8nrpM8FC5u683dh0SqDP8kxKv+pWYSY0BmcNoSIZAf1wW04Nf0E95dNiMJlg' 'KgGu7v94NoLq84FcdUGsIVUsFbq7zguIigcQgC8tKl780eJXJI4eGcvXMIKKst79+7lZaJ9f' 'Xeuis0sZKAzPeaNHc2nDoTYJGBoyZD/kINbrWl60Kq/5oJf5YcrH1tStctUNdROJdJuFf' 'eSVei7CgCcMZbc5hDm1grvqs15tkbh1jrtMgtEFQrFlH/0o1fY5Q5VeIWniZ9k0ISpOb8' '+IMyJLUM18aJ+blP49BW9w99Z5oUXNg+FWlWMlVV4DJUVSAMtphlC4NcICptHsIG9PNd9T' 'xfmCs2XE8AwcTyKbc8ykMMWgZAOfpJ3z2QZZMP59QMhLmSZNPq89O4HNsYt7uPWiTUCJB1x' 'y7AENomU+VcA/BKQvBNAjIQmASY2l+srN1+cgDnRxTIwSakoaJQ5SzpiEKAkvzEgRL0m+lS' '3fnQjzn/PQEsKAQCLphgBGGQLUJSTd2onUABCIF9WNrrMvWLTu0QBR+zJwjJub2ENuiAhA' 'NiEZtmOvHEg48Hcv24z/ABnGUnniFeh46HxGYCGpDVDCDzD+M0Ll14KkyDuyn3knrfWKia' 'xQs2TNtcYC08YwrpFgOiaCVmB1v8ykTbZQnu19/zgSmXs6QjKFHKZD52U6pIBJPoGc+G6i' 'koVGq9PFK/5FyISxuA7p7R+7c1vEqGzAusRBQwk2j0mabSSNbzhMgPTsVe7Zx54O85TYz9b' 'G7q0QYqx43NQp5J+DyaxgBqC4d9IEn9j8Z8VxRvogo76E5ik7C7gmmjkHXjFDz64oKFxDs5' 'rMQ4IqP4fUo0219/tijMXppoFq1LKbmHySy2/PY/v9H50hhEz8KvE0RkS2xhsP8YlvvGZ3S' 'yapiT0mk/DqjIsBcr/Atffr8/hCjApAAAAAElFTkSuQmCC'; HtmlImage createFlutterLogoTestImage() { return HtmlImage( createDomHTMLImageElement() ..src = 'data:text/plain;base64,$_flutterLogoBase64', 50, 50, ); }
engine/lib/web_ui/test/html/testimage.dart/0
{ "file_path": "engine/lib/web_ui/test/html/testimage.dart", "repo_id": "engine", "token_count": 6353 }
275
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/ui.dart'; import 'package:web_engine_tester/golden_tester.dart'; import '../common/test_initialization.dart'; import 'utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, setUpTestViewDimensions: false, ); const Rect region = Rect.fromLTWH(0, 0, 300, 300); test('draw arc', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder, region); canvas.drawArc( const Rect.fromLTRB(100, 100, 200, 200), math.pi / 3.0, 4.0 * math.pi / 3.0, false, Paint() ..style = PaintingStyle.stroke ..strokeWidth = 3.0 ..color = const Color(0xFFFF00FF) ); await drawPictureUsingCurrentRenderer(recorder.endRecording()); await matchGoldenFile('ui_canvas_draw_arc.png', region: region); }); test('draw circle', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder, region); canvas.drawCircle( const Offset(150, 150), 50, Paint() ..style = PaintingStyle.stroke ..strokeWidth = 3.0 ..color = const Color(0xFFFF0000) ); await drawPictureUsingCurrentRenderer(recorder.endRecording()); await matchGoldenFile('ui_canvas_draw_circle.png', region: region); }); test('draw oval', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder, region); canvas.drawOval( const Rect.fromLTRB(100, 125, 200, 175), Paint() ..style = PaintingStyle.stroke ..strokeWidth = 3.0 ..color = const Color(0xFF00FFFF) ); await drawPictureUsingCurrentRenderer(recorder.endRecording()); await matchGoldenFile('ui_canvas_draw_oval.png', region: region); }); }
engine/lib/web_ui/test/ui/canvas_curves_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/canvas_curves_golden_test.dart", "repo_id": "engine", "token_count": 813 }
276
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/ui.dart'; import '../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); test('Should be able to build and layout a paragraph', () { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle()); builder.addText('Hello'); final Paragraph paragraph = builder.build(); expect(paragraph, isNotNull); paragraph.layout(const ParagraphConstraints(width: 800.0)); expect(paragraph.width, isNonZero); expect(paragraph.height, isNonZero); }); test('the presence of foreground style should not throw', () { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle()); builder.pushStyle(TextStyle( foreground: Paint()..color = const Color(0xFFABCDEF), )); builder.addText('hi'); expect(() => builder.build(), returnsNormally); }); }
engine/lib/web_ui/test/ui/paragraph_builder_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/paragraph_builder_test.dart", "repo_id": "engine", "token_count": 399 }
277
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/ui.dart' as ui; import 'package:web_engine_tester/golden_tester.dart'; import '../common/test_initialization.dart'; import 'utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('Vertices', () { setUpUnitTests(withImplicitView: true, setUpTestViewDimensions: false); test('can be constructed, drawn, and disposed of', () { final ui.Vertices vertices = _testVertices(); expect(vertices.debugDisposed, isFalse); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas( recorder, const ui.Rect.fromLTRB(0, 0, 100, 100) ); canvas.drawVertices( vertices, ui.BlendMode.srcOver, ui.Paint(), ); vertices.dispose(); expect(vertices.debugDisposed, isTrue); }); }); test('Vertices are not anti-aliased by default', () async { const ui.Rect region = ui.Rect.fromLTRB(0, 0, 500, 500); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder, region); final ui.Vertices vertices = ui.Vertices.raw( ui.VertexMode.triangles, Float32List.fromList(_circularVertices), indices: Uint16List.fromList(_circularVertexIndices), ); canvas.scale(3.0, 3.0); canvas.drawVertices( vertices, ui.BlendMode.srcOver, ui.Paint()..color = const ui.Color(0xFFFF0000), ); await drawPictureUsingCurrentRenderer(recorder.endRecording()); await matchGoldenFile('ui_vertices_antialiased.png', region: region); }, skip: isHtml); // https://github.com/flutter/flutter/issues/127454 } ui.Vertices _testVertices() { return ui.Vertices( ui.VertexMode.triangles, const <ui.Offset>[ ui.Offset.zero, ui.Offset(10, 10), ui.Offset(0, 20), ], textureCoordinates: const <ui.Offset>[ ui.Offset.zero, ui.Offset(10, 10), ui.Offset(0, 20), ], colors: const <ui.Color>[ ui.Color.fromRGBO(255, 0, 0, 1.0), ui.Color.fromRGBO(0, 255, 0, 1.0), ui.Color.fromRGBO(0, 0, 255, 1.0), ], indices: <int>[0, 1, 2], ); } const List<double> _circularVertices = <double>[ 14.530723571777344, 18.18381690979004, 14.530723571777344, 18.624177932739258, 14.538220405578613, 18.40399742126465, 14.445072174072266, 17.765277862548828, 14.445072174072266, 19.04271697998047, 14.282388687133789, 17.38067626953125, 14.282388687133789, 19.427318572998047, 14.051292419433594, 17.038639068603516, 14.051292419433594, 19.76935577392578, 13.76040267944336, 16.747783660888672, 13.76040267944336, 20.06021499633789, 13.418340682983398, 16.5167236328125, 13.418340682983398, 20.291275024414062, 13.033727645874023, 20.45391845703125, 13.03372573852539, 16.354080200195312, 12.615180015563965, 20.539527893066406, 12.6151762008667, 16.268470764160156, 12.395000457763672, 20.547000885009766, 12.394994735717773, 16.260997772216797, 12.394994735717773, 20.546998977661133, 12.174847602844238, 16.268516540527344, 12.174847602844238, 20.539480209350586, 11.75637149810791, 16.354188919067383, 11.75637149810791, 20.45380973815918, 11.371832847595215, 16.516868591308594, 11.371832847595215, 20.291126251220703, 11.029844284057617, 16.747943878173828, 11.029844284057617, 20.06005096435547, 10.739023208618164, 17.038795471191406, 10.739023208618164, 19.76919937133789, 10.507984161376953, 17.380809783935547, 10.507984161376953, 19.427188873291016, 10.345342636108398, 17.765365600585938, 10.345342636108398, 19.042633056640625, 10.259716033935547, 18.183849334716797, 10.259716033935547, 18.6241455078125, 10.25222110748291, 18.40399742126465, ]; const List<int> _circularVertexIndices = <int>[ 0, 1, 2, 3, 1, 0, 3, 4, 1, 5, 4, 3, 5, 6, 4, 7, 6, 5, 7, 8, 6, 9, 8, 7, 9, 10, 8, 11, 10, 9, 11, 12, 10, 11, 13, 12, 14, 13, 11, 14, 15, 13, 16, 15, 14, 16, 17, 15, 18, 17, 16, 18, 19, 17, 20, 19, 18, 20, 21, 19, 22, 21, 20, 22, 23, 21, 24, 23, 22, 24, 25, 23, 26, 25, 24, 26, 27, 25, 28, 27, 26, 28, 29, 27, 30, 29, 28, 30, 31, 29, 32, 31, 30, 32, 33, 31, 34, 33, 32, 34, 35, 33, 35, 34, 36 ];
engine/lib/web_ui/test/ui/vertices_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/vertices_test.dart", "repo_id": "engine", "token_count": 2346 }
278
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "dart_timestamp_provider.h" #include "dart_tools_api.h" namespace flutter { DartTimestampProvider::DartTimestampProvider() = default; DartTimestampProvider::~DartTimestampProvider() = default; int64_t DartTimestampProvider::ConvertToNanos(int64_t ticks, int64_t frequency) { int64_t nano_seconds = (ticks / frequency) * kNanosPerSecond; int64_t leftover_ticks = ticks % frequency; int64_t leftover_nanos = (leftover_ticks * kNanosPerSecond) / frequency; return nano_seconds + leftover_nanos; } fml::TimePoint DartTimestampProvider::Now() { const int64_t ticks = Dart_TimelineGetTicks(); const int64_t frequency = Dart_TimelineGetTicksFrequency(); // optimization for the most common case. if (frequency != kNanosPerSecond) { return fml::TimePoint::FromTicks(ConvertToNanos(ticks, frequency)); } else { return fml::TimePoint::FromTicks(ticks); } } fml::TimePoint DartTimelineTicksSinceEpoch() { return DartTimestampProvider::Instance().Now(); } } // namespace flutter
engine/runtime/dart_timestamp_provider.cc/0
{ "file_path": "engine/runtime/dart_timestamp_provider.cc", "repo_id": "engine", "token_count": 433 }
279
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_RUNTIME_SERVICE_PROTOCOL_H_ #define FLUTTER_RUNTIME_SERVICE_PROTOCOL_H_ #include <map> #include <set> #include <string> #include <string_view> #include "flutter/fml/compiler_specific.h" #include "flutter/fml/macros.h" #include "flutter/fml/synchronization/atomic_object.h" #include "flutter/fml/synchronization/shared_mutex.h" #include "flutter/fml/task_runner.h" #include "rapidjson/document.h" namespace flutter { class ServiceProtocol { public: static const std::string_view kScreenshotExtensionName; static const std::string_view kScreenshotSkpExtensionName; static const std::string_view kRunInViewExtensionName; static const std::string_view kFlushUIThreadTasksExtensionName; static const std::string_view kSetAssetBundlePathExtensionName; static const std::string_view kGetDisplayRefreshRateExtensionName; static const std::string_view kGetSkSLsExtensionName; static const std::string_view kEstimateRasterCacheMemoryExtensionName; static const std::string_view kRenderFrameWithRasterStatsExtensionName; static const std::string_view kReloadAssetFonts; class Handler { public: struct Description { int64_t isolate_port = 0 /* illegal port by default. */; std::string isolate_name; Description() {} Description(int64_t p_isolate_port, std::string p_isolate_name) : isolate_port(p_isolate_port), isolate_name(std::move(p_isolate_name)) {} void Write(Handler* handler, rapidjson::Value& value, rapidjson::MemoryPoolAllocator<>& allocator) const; }; using ServiceProtocolMap = std::map<std::string_view, std::string_view>; virtual fml::RefPtr<fml::TaskRunner> GetServiceProtocolHandlerTaskRunner( std::string_view method) const = 0; virtual Description GetServiceProtocolDescription() const = 0; virtual bool HandleServiceProtocolMessage( std::string_view method, // one if the extension names specified above. const ServiceProtocolMap& params, rapidjson::Document* response) = 0; }; ServiceProtocol(); ~ServiceProtocol(); void ToggleHooks(bool set); void AddHandler(Handler* handler, const Handler::Description& description); void RemoveHandler(Handler* handler); void SetHandlerDescription(Handler* handler, const Handler::Description& description); private: const std::set<std::string_view> endpoints_; std::unique_ptr<fml::SharedMutex> handlers_mutex_; std::map<Handler*, fml::AtomicObject<Handler::Description>> handlers_; [[nodiscard]] static bool HandleMessage(const char* method, const char** param_keys, const char** param_values, intptr_t num_params, void* user_data, const char** json_object); [[nodiscard]] static bool HandleMessage( std::string_view method, const Handler::ServiceProtocolMap& params, ServiceProtocol* service_protocol, rapidjson::Document* response); [[nodiscard]] bool HandleMessage(std::string_view method, const Handler::ServiceProtocolMap& params, rapidjson::Document* response) const; [[nodiscard]] bool HandleListViewsMethod(rapidjson::Document* response) const; FML_DISALLOW_COPY_AND_ASSIGN(ServiceProtocol); }; } // namespace flutter #endif // FLUTTER_RUNTIME_SERVICE_PROTOCOL_H_
engine/runtime/service_protocol.h/0
{ "file_path": "engine/runtime/service_protocol.h", "repo_id": "engine", "token_count": 1465 }
280
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "context_options.h" #include "gtest/gtest.h" namespace flutter { namespace testing { TEST(ContextOptionsTest, OpenGLDisablesStencilBuffers) { auto options = MakeDefaultContextOptions(flutter::ContextType::kRender, GrBackendApi::kOpenGL); EXPECT_TRUE(options.fAvoidStencilBuffers); } } // namespace testing } // namespace flutter
engine/shell/common/context_options_unittests.cc/0
{ "file_path": "engine/shell/common/context_options_unittests.cc", "repo_id": "engine", "token_count": 202 }
281
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/common/shell_test.h" #include "flutter/testing/testing.h" // CREATE_NATIVE_ENTRY is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) namespace flutter { namespace testing { // Throughout these tests, the choice of time unit is irrelevant as long as all // times have the same units. using UnitlessTime = int; // Signature of a generator function that takes the frame index as input and // returns the time of that frame. using Generator = std::function<UnitlessTime(int)>; //---------------------------------------------------------------------------- /// Simulate n input events where the i-th one is delivered at delivery_time(i). /// /// Simulation results will be written into events_consumed_at_frame whose /// length will be equal to the number of frames drawn. Each element in the /// vector is the number of input events consumed up to that frame. (We can't /// return such vector because ASSERT_TRUE requires return type of void.) /// /// We assume (and check) that the delivery latency is some base latency plus a /// random latency where the random latency must be within one frame: /// /// 1. latency = delivery_time(i) - j * frame_time = base_latency + /// random_latency /// 2. 0 <= base_latency, 0 <= random_latency < frame_time /// /// We also assume that there will be at least one input event per frame if /// there were no latency. Let j = floor( (delivery_time(i) - base_latency) / /// frame_time ) be the frame index if there were no latency. Then the set of j /// should be all integers from 0 to continuous_frame_count - 1 for some /// integer continuous_frame_count. /// /// (Note that there coulds be multiple input events within one frame.) /// /// The test here is insensitive to the choice of time unit as long as /// delivery_time and frame_time are in the same unit. static void TestSimulatedInputEvents( ShellTest* fixture, int num_events, UnitlessTime base_latency, Generator delivery_time, UnitlessTime frame_time, std::vector<UnitlessTime>& events_consumed_at_frame, bool restart_engine = false) { ///// Begin constructing shell /////////////////////////////////////////////// auto settings = fixture->CreateSettingsForFixture(); std::unique_ptr<Shell> shell = fixture->CreateShell({ .settings = settings, .platform_view_create_callback = ShellTestPlatformViewBuilder({ .simulate_vsync = true, }), }); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("onPointerDataPacketMain"); // The following 4 variables are only accessed in the UI thread by // nativeOnPointerDataPacket and nativeOnBeginFrame between their // initializations and `shell.reset()`. events_consumed_at_frame.clear(); bool will_draw_new_frame = true; int events_consumed = 0; int frame_drawn = 0; auto nativeOnPointerDataPacket = [&events_consumed_at_frame, &will_draw_new_frame, &events_consumed, &frame_drawn](Dart_NativeArguments args) { events_consumed += 1; if (will_draw_new_frame) { frame_drawn += 1; will_draw_new_frame = false; events_consumed_at_frame.push_back(events_consumed); } else { events_consumed_at_frame.back() = events_consumed; } }; fixture->AddNativeCallback("NativeOnPointerDataPacket", CREATE_NATIVE_ENTRY(nativeOnPointerDataPacket)); ASSERT_TRUE(configuration.IsValid()); fixture->RunEngine(shell.get(), std::move(configuration)); if (restart_engine) { auto new_configuration = RunConfiguration::InferFromSettings(settings); new_configuration.SetEntrypoint("onPointerDataPacketMain"); ASSERT_TRUE(new_configuration.IsValid()); fixture->RestartEngine(shell.get(), std::move(new_configuration)); } ///// End constructing shell ///////////////////////////////////////////////// ASSERT_GE(base_latency, 0); // Check that delivery_time satisfies our assumptions. int continuous_frame_count = 0; for (int i = 0; i < num_events; i += 1) { // j is the frame index of event i if there were no latency. int j = static_cast<int>((delivery_time(i) - base_latency) / frame_time); if (j == continuous_frame_count) { continuous_frame_count += 1; } double random_latency = delivery_time(i) - j * frame_time - base_latency; ASSERT_GE(random_latency, 0); ASSERT_LT(random_latency, frame_time); // If there were no latency, there should be at least one event per frame. // Hence j should never skip any integer less than continuous_frame_count. ASSERT_LT(j, continuous_frame_count); } // This has to be running on a different thread than Platform thread to avoid // dead locks. auto simulation = std::async(std::launch::async, [&]() { // i is the input event's index. // j is the frame's index. for (int i = 0, j = 0; i < num_events; j += 1) { double t = j * frame_time; while (i < num_events && delivery_time(i) <= t) { ShellTest::DispatchFakePointerData(shell.get()); i += 1; } ShellTest::VSyncFlush(shell.get(), &will_draw_new_frame); } // Finally, issue a vsync for the pending event that may be generated duing // the last vsync. ShellTest::VSyncFlush(shell.get(), &will_draw_new_frame); }); simulation.wait(); TaskRunners task_runners = fixture->GetTaskRunnersForFixture(); fml::AutoResetWaitableEvent latch; task_runners.GetPlatformTaskRunner()->PostTask([&shell, &latch]() mutable { shell.reset(); latch.Signal(); }); latch.Wait(); // Make sure that all events have been consumed so // https://github.com/flutter/flutter/issues/40863 won't happen again. ASSERT_EQ(events_consumed_at_frame.back(), num_events); } void CreateSimulatedPointerData(PointerData& data, PointerData::Change change, double dx, double dy) { data.time_stamp = 0; data.change = change; data.kind = PointerData::DeviceKind::kTouch; data.signal_kind = PointerData::SignalKind::kNone; data.device = 0; data.pointer_identifier = 0; data.physical_x = dx; data.physical_y = dy; data.physical_delta_x = 0.0; data.physical_delta_y = 0.0; data.buttons = 0; data.obscured = 0; data.synthesized = 0; data.pressure = 0.0; data.pressure_min = 0.0; data.pressure_max = 0.0; data.distance = 0.0; data.distance_max = 0.0; data.size = 0.0; data.radius_major = 0.0; data.radius_minor = 0.0; data.radius_min = 0.0; data.radius_max = 0.0; data.orientation = 0.0; data.tilt = 0.0; data.platformData = 0; data.scroll_delta_x = 0.0; data.scroll_delta_y = 0.0; } TEST_F(ShellTest, MissAtMostOneFrameForIrregularInputEvents) { // We don't use `constexpr int frame_time` here because MSVC doesn't handle // it well with lambda capture. UnitlessTime frame_time = 10; UnitlessTime base_latency = 0.5 * frame_time; Generator extreme = [frame_time, base_latency](int i) { return static_cast<UnitlessTime>( i * frame_time + base_latency + (i % 2 == 0 ? 0.1 * frame_time : 0.9 * frame_time)); }; constexpr int n = 40; std::vector<int> events_consumed_at_frame; TestSimulatedInputEvents(this, n, base_latency, extreme, frame_time, events_consumed_at_frame); int frame_drawn = events_consumed_at_frame.size(); ASSERT_GE(frame_drawn, n - 1); // Make sure that it also works after an engine restart. TestSimulatedInputEvents(this, n, base_latency, extreme, frame_time, events_consumed_at_frame, true /* restart_engine */); int frame_drawn_after_restart = events_consumed_at_frame.size(); ASSERT_GE(frame_drawn_after_restart, n - 1); } TEST_F(ShellTest, DelayAtMostOneEventForFasterThanVSyncInputEvents) { // We don't use `constexpr int frame_time` here because MSVC doesn't handle // it well with lambda capture. UnitlessTime frame_time = 10; UnitlessTime base_latency = 0.2 * frame_time; Generator double_sampling = [frame_time, base_latency](int i) { return static_cast<UnitlessTime>(i * 0.5 * frame_time + base_latency); }; constexpr int n = 40; std::vector<int> events_consumed_at_frame; TestSimulatedInputEvents(this, n, base_latency, double_sampling, frame_time, events_consumed_at_frame); // Draw one extra frame due to delaying a pending packet for the next frame. int frame_drawn = events_consumed_at_frame.size(); ASSERT_EQ(frame_drawn, n / 2 + 1); for (int i = 0; i < n / 2; i += 1) { ASSERT_GE(events_consumed_at_frame[i], 2 * i - 1); } } TEST_F(ShellTest, HandlesActualIphoneXsInputEvents) { // Actual delivery times measured on iPhone Xs, in the unit of frame_time // (16.67ms for 60Hz). static constexpr double iphone_xs_times[] = {0.15, 1.0773046874999999, 2.1738720703124996, 3.0579052734374996, 4.0890087890624995, 5.0952685546875, 6.1251708984375, 7.1253076171875, 8.125927734374999, 9.37248046875, 10.133950195312499, 11.161201171875, 12.226992187499999, 13.1443798828125, 14.440327148437499, 15.091684570312498, 16.138681640625, 17.126469726562497, 18.1592431640625, 19.371372070312496, 20.033774414062496, 21.021782226562497, 22.070053710937497, 23.325541992187496, 24.119648437499997, 25.084262695312496, 26.077866210937497, 27.036547851562496, 28.035073242187497, 29.081411132812498, 30.066064453124998, 31.089360351562497, 32.086142578125, 33.4618798828125, 34.14697265624999, 35.0513525390625, 36.136025390624994, 37.1618408203125, 38.144472656249995, 39.201123046875, 40.4339501953125, 41.1552099609375, 42.102128906249995, 43.0426318359375, 44.070131835937495, 45.08862304687499, 46.091469726562494}; constexpr int n = sizeof(iphone_xs_times) / sizeof(iphone_xs_times[0]); // We don't use `constexpr int frame_time` here because MSVC doesn't handle // it well with lambda capture. UnitlessTime frame_time = 10000; double base_latency_f = 0.0; for (int i = 0; i < 10; i++) { base_latency_f += 0.1; // Everything is converted to int to avoid floating point error in // TestSimulatedInputEvents. UnitlessTime base_latency = static_cast<UnitlessTime>(base_latency_f * frame_time); Generator iphone_xs_generator = [frame_time, base_latency](int i) { return base_latency + static_cast<UnitlessTime>(iphone_xs_times[i] * frame_time); }; std::vector<int> events_consumed_at_frame; TestSimulatedInputEvents(this, n, base_latency, iphone_xs_generator, frame_time, events_consumed_at_frame); int frame_drawn = events_consumed_at_frame.size(); ASSERT_GE(frame_drawn, n - 1); } } TEST_F(ShellTest, CanCorrectlyPipePointerPacket) { // Sets up shell with test fixture. auto settings = CreateSettingsForFixture(); std::unique_ptr<Shell> shell = CreateShell({ .settings = settings, .platform_view_create_callback = ShellTestPlatformViewBuilder({ .simulate_vsync = true, }), }); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("onPointerDataPacketMain"); // Sets up native handler. fml::AutoResetWaitableEvent reportLatch; std::vector<int64_t> result_sequence; auto nativeOnPointerDataPacket = [&reportLatch, &result_sequence]( Dart_NativeArguments args) { Dart_Handle exception = nullptr; result_sequence = tonic::DartConverter<std::vector<int64_t>>::FromArguments( args, 0, exception); reportLatch.Signal(); }; // Starts engine. AddNativeCallback("NativeOnPointerDataPacket", CREATE_NATIVE_ENTRY(nativeOnPointerDataPacket)); ASSERT_TRUE(configuration.IsValid()); RunEngine(shell.get(), std::move(configuration)); // Starts test. auto packet = std::make_unique<PointerDataPacket>(6); PointerData data; CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0.0, 0.0); packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kHover, 3.0, 0.0); packet->SetPointerData(1, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 3.0, 0.0); packet->SetPointerData(2, data); CreateSimulatedPointerData(data, PointerData::Change::kMove, 3.0, 4.0); packet->SetPointerData(3, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 3.0, 4.0); packet->SetPointerData(4, data); CreateSimulatedPointerData(data, PointerData::Change::kRemove, 3.0, 4.0); packet->SetPointerData(5, data); ShellTest::DispatchPointerData(shell.get(), std::move(packet)); ShellTest::VSyncFlush(shell.get()); reportLatch.Wait(); size_t expect_length = 6; ASSERT_EQ(result_sequence.size(), expect_length); ASSERT_EQ(PointerData::Change(result_sequence[0]), PointerData::Change::kAdd); ASSERT_EQ(PointerData::Change(result_sequence[1]), PointerData::Change::kHover); ASSERT_EQ(PointerData::Change(result_sequence[2]), PointerData::Change::kDown); ASSERT_EQ(PointerData::Change(result_sequence[3]), PointerData::Change::kMove); ASSERT_EQ(PointerData::Change(result_sequence[4]), PointerData::Change::kUp); ASSERT_EQ(PointerData::Change(result_sequence[5]), PointerData::Change::kRemove); // Cleans up shell. ASSERT_TRUE(DartVMRef::IsInstanceRunning()); DestroyShell(std::move(shell)); ASSERT_FALSE(DartVMRef::IsInstanceRunning()); } TEST_F(ShellTest, CanCorrectlySynthesizePointerPacket) { // Sets up shell with test fixture. auto settings = CreateSettingsForFixture(); std::unique_ptr<Shell> shell = CreateShell({ .settings = settings, .platform_view_create_callback = ShellTestPlatformViewBuilder({ .simulate_vsync = true, }), }); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("onPointerDataPacketMain"); // Sets up native handler. fml::AutoResetWaitableEvent reportLatch; std::vector<int64_t> result_sequence; auto nativeOnPointerDataPacket = [&reportLatch, &result_sequence]( Dart_NativeArguments args) { Dart_Handle exception = nullptr; result_sequence = tonic::DartConverter<std::vector<int64_t>>::FromArguments( args, 0, exception); reportLatch.Signal(); }; // Starts engine. AddNativeCallback("NativeOnPointerDataPacket", CREATE_NATIVE_ENTRY(nativeOnPointerDataPacket)); ASSERT_TRUE(configuration.IsValid()); RunEngine(shell.get(), std::move(configuration)); // Starts test. auto packet = std::make_unique<PointerDataPacket>(4); PointerData data; CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0.0, 0.0); packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 3.0, 0.0); packet->SetPointerData(1, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 3.0, 4.0); packet->SetPointerData(2, data); CreateSimulatedPointerData(data, PointerData::Change::kRemove, 3.0, 4.0); packet->SetPointerData(3, data); ShellTest::DispatchPointerData(shell.get(), std::move(packet)); ShellTest::VSyncFlush(shell.get()); reportLatch.Wait(); size_t expect_length = 6; ASSERT_EQ(result_sequence.size(), expect_length); ASSERT_EQ(PointerData::Change(result_sequence[0]), PointerData::Change::kAdd); // The pointer data packet converter should synthesize a hover event. ASSERT_EQ(PointerData::Change(result_sequence[1]), PointerData::Change::kHover); ASSERT_EQ(PointerData::Change(result_sequence[2]), PointerData::Change::kDown); // The pointer data packet converter should synthesize a move event. ASSERT_EQ(PointerData::Change(result_sequence[3]), PointerData::Change::kMove); ASSERT_EQ(PointerData::Change(result_sequence[4]), PointerData::Change::kUp); ASSERT_EQ(PointerData::Change(result_sequence[5]), PointerData::Change::kRemove); // Cleans up shell. ASSERT_TRUE(DartVMRef::IsInstanceRunning()); DestroyShell(std::move(shell)); ASSERT_FALSE(DartVMRef::IsInstanceRunning()); } } // namespace testing } // namespace flutter // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/shell/common/input_events_unittests.cc/0
{ "file_path": "engine/shell/common/input_events_unittests.cc", "repo_id": "engine", "token_count": 8293 }
282
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/common/run_configuration.h" #include <sstream> #include <utility> #include "flutter/assets/directory_asset_bundle.h" #include "flutter/common/graphics/persistent_cache.h" #include "flutter/fml/file.h" #include "flutter/fml/unique_fd.h" #include "flutter/runtime/dart_vm.h" #include "flutter/runtime/isolate_configuration.h" namespace flutter { RunConfiguration RunConfiguration::InferFromSettings( const Settings& settings, const fml::RefPtr<fml::TaskRunner>& io_worker, IsolateLaunchType launch_type) { auto asset_manager = std::make_shared<AssetManager>(); if (fml::UniqueFD::traits_type::IsValid(settings.assets_dir)) { asset_manager->PushBack(std::make_unique<DirectoryAssetBundle>( fml::Duplicate(settings.assets_dir), true)); } asset_manager->PushBack(std::make_unique<DirectoryAssetBundle>( fml::OpenDirectory(settings.assets_path.c_str(), false, fml::FilePermission::kRead), true)); return {IsolateConfiguration::InferFromSettings(settings, asset_manager, io_worker, launch_type), asset_manager}; } RunConfiguration::RunConfiguration( std::unique_ptr<IsolateConfiguration> configuration) : RunConfiguration(std::move(configuration), std::make_shared<AssetManager>()) { PersistentCache::SetAssetManager(asset_manager_); } RunConfiguration::RunConfiguration( std::unique_ptr<IsolateConfiguration> configuration, std::shared_ptr<AssetManager> asset_manager) : isolate_configuration_(std::move(configuration)), asset_manager_(std::move(asset_manager)) { PersistentCache::SetAssetManager(asset_manager_); } RunConfiguration::RunConfiguration(RunConfiguration&&) = default; RunConfiguration::~RunConfiguration() = default; bool RunConfiguration::IsValid() const { return asset_manager_ && isolate_configuration_; } bool RunConfiguration::AddAssetResolver( std::unique_ptr<AssetResolver> resolver) { if (!resolver || !resolver->IsValid()) { return false; } asset_manager_->PushBack(std::move(resolver)); return true; } void RunConfiguration::SetEntrypoint(std::string entrypoint) { entrypoint_ = std::move(entrypoint); } void RunConfiguration::SetEntrypointAndLibrary(std::string entrypoint, std::string library) { SetEntrypoint(std::move(entrypoint)); entrypoint_library_ = std::move(library); } void RunConfiguration::SetEntrypointArgs( std::vector<std::string> entrypoint_args) { entrypoint_args_ = std::move(entrypoint_args); } std::shared_ptr<AssetManager> RunConfiguration::GetAssetManager() const { return asset_manager_; } const std::string& RunConfiguration::GetEntrypoint() const { return entrypoint_; } const std::string& RunConfiguration::GetEntrypointLibrary() const { return entrypoint_library_; } const std::vector<std::string>& RunConfiguration::GetEntrypointArgs() const { return entrypoint_args_; } std::unique_ptr<IsolateConfiguration> RunConfiguration::TakeIsolateConfiguration() { return std::move(isolate_configuration_); } } // namespace flutter
engine/shell/common/run_configuration.cc/0
{ "file_path": "engine/shell/common/run_configuration.cc", "repo_id": "engine", "token_count": 1167 }
283
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_H_ #define FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_H_ #include "flutter/shell/common/platform_view.h" #include "flutter/shell/common/shell_test_external_view_embedder.h" #include "flutter/shell/common/vsync_waiters_test.h" namespace flutter { namespace testing { class ShellTestPlatformView : public PlatformView { public: enum class BackendType { kDefaultBackend = 0, kGLBackend, kVulkanBackend, kMetalBackend, }; static std::unique_ptr<ShellTestPlatformView> Create( PlatformView::Delegate& delegate, const TaskRunners& task_runners, const std::shared_ptr<ShellTestVsyncClock>& vsync_clock, const CreateVsyncWaiter& create_vsync_waiter, BackendType backend, const std::shared_ptr<ShellTestExternalViewEmbedder>& shell_test_external_view_embedder, const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch); virtual void SimulateVSync() = 0; protected: ShellTestPlatformView(PlatformView::Delegate& delegate, const TaskRunners& task_runners) : PlatformView(delegate, task_runners) {} FML_DISALLOW_COPY_AND_ASSIGN(ShellTestPlatformView); }; // Create a ShellTestPlatformView from configuration struct. class ShellTestPlatformViewBuilder { public: struct Config { bool simulate_vsync = false; std::shared_ptr<ShellTestExternalViewEmbedder> shell_test_external_view_embedder = nullptr; ShellTestPlatformView::BackendType rendering_backend = ShellTestPlatformView::BackendType::kDefaultBackend; }; explicit ShellTestPlatformViewBuilder(Config config); ~ShellTestPlatformViewBuilder() = default; // Override operator () to make this class assignable to std::function. std::unique_ptr<PlatformView> operator()(Shell& shell); private: Config config_; }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_H_
engine/shell/common/shell_test_platform_view.h/0
{ "file_path": "engine/shell/common/shell_test_platform_view.h", "repo_id": "engine", "token_count": 767 }
284
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_COMMON_SNAPSHOT_SURFACE_PRODUCER_H_ #define FLUTTER_SHELL_COMMON_SNAPSHOT_SURFACE_PRODUCER_H_ #include <memory> #include "flutter/flow/surface.h" namespace flutter { class SnapshotSurfaceProducer { public: virtual ~SnapshotSurfaceProducer() = default; virtual std::unique_ptr<Surface> CreateSnapshotSurface() = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_COMMON_SNAPSHOT_SURFACE_PRODUCER_H_
engine/shell/common/snapshot_surface_producer.h/0
{ "file_path": "engine/shell/common/snapshot_surface_producer.h", "repo_id": "engine", "token_count": 219 }
285
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_COMMON_VSYNC_WAITERS_TEST_H_ #define FLUTTER_SHELL_COMMON_VSYNC_WAITERS_TEST_H_ #define FML_USED_ON_EMBEDDER #include <utility> #include "flutter/shell/common/shell.h" namespace flutter { namespace testing { using CreateVsyncWaiter = std::function<std::unique_ptr<VsyncWaiter>()>; class ShellTestVsyncClock { public: /// Simulate that a vsync signal is triggered. void SimulateVSync(); /// A future that will return the index the next vsync signal. std::future<int> NextVSync(); private: std::mutex mutex_; std::vector<std::promise<int>> vsync_promised_; size_t vsync_issued_ = 0; }; class ShellTestVsyncWaiter : public VsyncWaiter { public: ShellTestVsyncWaiter(const TaskRunners& task_runners, std::shared_ptr<ShellTestVsyncClock> clock) : VsyncWaiter(task_runners), clock_(std::move(clock)) {} protected: void AwaitVSync() override; private: std::shared_ptr<ShellTestVsyncClock> clock_; }; class ConstantFiringVsyncWaiter : public VsyncWaiter { public: // both of these are set in the past so as to fire immediately. static constexpr fml::TimePoint kFrameBeginTime = fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromSeconds(0)); static constexpr fml::TimePoint kFrameTargetTime = fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromSeconds(100)); explicit ConstantFiringVsyncWaiter(const TaskRunners& task_runners) : VsyncWaiter(task_runners) {} protected: void AwaitVSync() override; }; class TestRefreshRateReporter final : public VariableRefreshRateReporter { public: explicit TestRefreshRateReporter(double refresh_rate); void UpdateRefreshRate(double refresh_rate); // |RefreshRateReporter| double GetRefreshRate() const override; private: double refresh_rate_; }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_COMMON_VSYNC_WAITERS_TEST_H_
engine/shell/common/vsync_waiters_test.h/0
{ "file_path": "engine/shell/common/vsync_waiters_test.h", "repo_id": "engine", "token_count": 719 }
286
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/gpu/gpu_surface_metal_skia.h" #import <Metal/Metal.h> #import <QuartzCore/QuartzCore.h> #include <utility> #include "flutter/common/graphics/persistent_cache.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/platform/darwin/cf_utils.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" #include "flutter/fml/trace_event.h" #include "flutter/shell/gpu/gpu_surface_metal_delegate.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkColorType.h" #include "third_party/skia/include/core/SkMatrix.h" #include "third_party/skia/include/core/SkRect.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/core/SkSurfaceProps.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" #include "third_party/skia/include/ports/SkCFObject.h" static_assert(!__has_feature(objc_arc), "ARC must be disabled."); namespace flutter { namespace { sk_sp<SkSurface> CreateSurfaceFromMetalTexture(GrDirectContext* context, id<MTLTexture> texture, GrSurfaceOrigin origin, MsaaSampleCount sample_cnt, SkColorType color_type, sk_sp<SkColorSpace> color_space, const SkSurfaceProps* props, SkSurfaces::TextureReleaseProc release_proc, SkSurface::ReleaseContext release_context) { GrMtlTextureInfo info; info.fTexture.reset([texture retain]); GrBackendTexture backend_texture(texture.width, texture.height, skgpu::Mipmapped::kNo, info); return SkSurfaces::WrapBackendTexture( context, backend_texture, origin, static_cast<int>(sample_cnt), color_type, std::move(color_space), props, release_proc, release_context); } } // namespace GPUSurfaceMetalSkia::GPUSurfaceMetalSkia(GPUSurfaceMetalDelegate* delegate, sk_sp<GrDirectContext> context, MsaaSampleCount msaa_samples, bool render_to_surface) : delegate_(delegate), render_target_type_(delegate->GetRenderTargetType()), context_(std::move(context)), msaa_samples_(msaa_samples), render_to_surface_(render_to_surface) { // If this preference is explicitly set, we allow for disabling partial repaint. NSNumber* disablePartialRepaint = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTDisablePartialRepaint"]; if (disablePartialRepaint != nil) { disable_partial_repaint_ = disablePartialRepaint.boolValue; } } GPUSurfaceMetalSkia::~GPUSurfaceMetalSkia() = default; // |Surface| bool GPUSurfaceMetalSkia::IsValid() { return context_ != nullptr; } void GPUSurfaceMetalSkia::PrecompileKnownSkSLsIfNecessary() { auto* current_context = GetContext(); if (current_context == precompiled_sksl_context_) { // Known SkSLs have already been prepared in this context. return; } precompiled_sksl_context_ = current_context; flutter::PersistentCache::GetCacheForProcess()->PrecompileKnownSkSLs(precompiled_sksl_context_); } // |Surface| std::unique_ptr<SurfaceFrame> GPUSurfaceMetalSkia::AcquireFrame(const SkISize& frame_size) { if (!IsValid()) { FML_LOG(ERROR) << "Metal surface was invalid."; return nullptr; } if (frame_size.isEmpty()) { FML_LOG(ERROR) << "Metal surface was asked for an empty frame."; return nullptr; } if (!render_to_surface_) { return std::make_unique<SurfaceFrame>( nullptr, SurfaceFrame::FramebufferInfo(), [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { return true; }, frame_size); } PrecompileKnownSkSLsIfNecessary(); switch (render_target_type_) { case MTLRenderTargetType::kCAMetalLayer: return AcquireFrameFromCAMetalLayer(frame_size); case MTLRenderTargetType::kMTLTexture: return AcquireFrameFromMTLTexture(frame_size); default: FML_CHECK(false) << "Unknown MTLRenderTargetType type."; } return nullptr; } std::unique_ptr<SurfaceFrame> GPUSurfaceMetalSkia::AcquireFrameFromCAMetalLayer( const SkISize& frame_info) { auto layer = delegate_->GetCAMetalLayer(frame_info); if (!layer) { FML_LOG(ERROR) << "Invalid CAMetalLayer given by the embedder."; return nullptr; } auto* mtl_layer = (CAMetalLayer*)layer; // Get the drawable eagerly, we will need texture object to identify target framebuffer fml::scoped_nsprotocol<id<CAMetalDrawable>> drawable( reinterpret_cast<id<CAMetalDrawable>>([[mtl_layer nextDrawable] retain])); if (!drawable.get()) { FML_LOG(ERROR) << "Could not obtain drawable from the metal layer."; return nullptr; } auto surface = CreateSurfaceFromMetalTexture(context_.get(), drawable.get().texture, kTopLeft_GrSurfaceOrigin, // origin msaa_samples_, // sample count kBGRA_8888_SkColorType, // color type nullptr, // colorspace nullptr, // surface properties nullptr, // release proc nullptr // release context ); if (!surface) { FML_LOG(ERROR) << "Could not create the SkSurface from the CAMetalLayer."; return nullptr; } auto submit_callback = [this, drawable](const SurfaceFrame& surface_frame, DlCanvas* canvas) -> bool { TRACE_EVENT0("flutter", "GPUSurfaceMetal::Submit"); if (canvas == nullptr) { FML_DLOG(ERROR) << "Canvas not available."; return false; } { TRACE_EVENT0("flutter", "SkCanvas::Flush"); canvas->Flush(); } if (!disable_partial_repaint_) { uintptr_t texture = reinterpret_cast<uintptr_t>(drawable.get().texture); for (auto& entry : damage_) { if (entry.first != texture) { // Accumulate damage for other framebuffers if (surface_frame.submit_info().frame_damage) { entry.second.join(*surface_frame.submit_info().frame_damage); } } } // Reset accumulated damage for current framebuffer damage_[texture] = SkIRect::MakeEmpty(); } return delegate_->PresentDrawable(drawable); }; SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true; if (!disable_partial_repaint_) { // Provide accumulated damage to rasterizer (area in current framebuffer that lags behind // front buffer) uintptr_t texture = reinterpret_cast<uintptr_t>(drawable.get().texture); auto i = damage_.find(texture); if (i != damage_.end()) { framebuffer_info.existing_damage = i->second; } framebuffer_info.supports_partial_repaint = true; } return std::make_unique<SurfaceFrame>(std::move(surface), framebuffer_info, submit_callback, frame_info); } std::unique_ptr<SurfaceFrame> GPUSurfaceMetalSkia::AcquireFrameFromMTLTexture( const SkISize& frame_info) { GPUMTLTextureInfo texture = delegate_->GetMTLTexture(frame_info); id<MTLTexture> mtl_texture = (id<MTLTexture>)(texture.texture); if (!mtl_texture) { FML_LOG(ERROR) << "Invalid MTLTexture given by the embedder."; return nullptr; } sk_sp<SkSurface> surface = CreateSurfaceFromMetalTexture( context_.get(), mtl_texture, kTopLeft_GrSurfaceOrigin, msaa_samples_, kBGRA_8888_SkColorType, nullptr, nullptr, static_cast<SkSurfaces::TextureReleaseProc>(texture.destruction_callback), texture.destruction_context); if (!surface) { FML_LOG(ERROR) << "Could not create the SkSurface from the metal texture."; return nullptr; } auto submit_callback = [texture = texture, delegate = delegate_]( const SurfaceFrame& surface_frame, DlCanvas* canvas) -> bool { TRACE_EVENT0("flutter", "GPUSurfaceMetal::PresentTexture"); if (canvas == nullptr) { FML_DLOG(ERROR) << "Canvas not available."; return false; } { TRACE_EVENT0("flutter", "SkCanvas::Flush"); canvas->Flush(); } return delegate->PresentTexture(texture); }; SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true; return std::make_unique<SurfaceFrame>(std::move(surface), framebuffer_info, submit_callback, frame_info); } // |Surface| SkMatrix GPUSurfaceMetalSkia::GetRootTransformation() const { // This backend does not currently support root surface transformations. Just // return identity. return {}; } // |Surface| GrDirectContext* GPUSurfaceMetalSkia::GetContext() { return context_.get(); } // |Surface| std::unique_ptr<GLContextResult> GPUSurfaceMetalSkia::MakeRenderContextCurrent() { // A context may either be necessary to render to the surface or to snapshot an offscreen // surface. Either way, SkSL precompilation must be attempted. PrecompileKnownSkSLsIfNecessary(); // This backend has no such concept. return std::make_unique<GLContextDefaultResult>(true); } bool GPUSurfaceMetalSkia::AllowsDrawingWhenGpuDisabled() const { return delegate_->AllowsDrawingWhenGpuDisabled(); } } // namespace flutter
engine/shell/gpu/gpu_surface_metal_skia.mm/0
{ "file_path": "engine/shell/gpu/gpu_surface_metal_skia.mm", "repo_id": "engine", "token_count": 4303 }
287
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/android_context_gl_impeller.h" #include "flutter/impeller/renderer/backend/gles/context_gles.h" #include "flutter/impeller/renderer/backend/gles/proc_table_gles.h" #include "flutter/impeller/renderer/backend/gles/reactor_gles.h" #include "flutter/impeller/toolkit/egl/context.h" #include "flutter/impeller/toolkit/egl/surface.h" #include "impeller/entity/gles/entity_shaders_gles.h" #include "impeller/entity/gles/framebuffer_blend_shaders_gles.h" #if IMPELLER_ENABLE_3D // This include was turned to an error since it breaks GN. #include "impeller/scene/shaders/gles/scene_shaders_gles.h" // nogncheck #endif // IMPELLER_ENABLE_3D namespace flutter { class AndroidContextGLImpeller::ReactorWorker final : public impeller::ReactorGLES::Worker { public: ReactorWorker() = default; // |impeller::ReactorGLES::Worker| ~ReactorWorker() override = default; // |impeller::ReactorGLES::Worker| bool CanReactorReactOnCurrentThreadNow( const impeller::ReactorGLES& reactor) const override { impeller::ReaderLock lock(mutex_); auto found = reactions_allowed_.find(std::this_thread::get_id()); if (found == reactions_allowed_.end()) { return false; } return found->second; } void SetReactionsAllowedOnCurrentThread(bool allowed) { impeller::WriterLock lock(mutex_); reactions_allowed_[std::this_thread::get_id()] = allowed; } private: mutable impeller::RWMutex mutex_; std::map<std::thread::id, bool> reactions_allowed_ IPLR_GUARDED_BY(mutex_); FML_DISALLOW_COPY_AND_ASSIGN(ReactorWorker); }; static std::shared_ptr<impeller::Context> CreateImpellerContext( const std::shared_ptr<impeller::ReactorGLES::Worker>& worker, bool enable_gpu_tracing) { auto proc_table = std::make_unique<impeller::ProcTableGLES>( impeller::egl::CreateProcAddressResolver()); if (!proc_table->IsValid()) { FML_LOG(ERROR) << "Could not create OpenGL proc table."; return nullptr; } std::vector<std::shared_ptr<fml::Mapping>> shader_mappings = { std::make_shared<fml::NonOwnedMapping>( impeller_entity_shaders_gles_data, impeller_entity_shaders_gles_length), std::make_shared<fml::NonOwnedMapping>( impeller_framebuffer_blend_shaders_gles_data, impeller_framebuffer_blend_shaders_gles_length), #if IMPELLER_ENABLE_3D std::make_shared<fml::NonOwnedMapping>( impeller_scene_shaders_gles_data, impeller_scene_shaders_gles_length), #endif // IMPELLER_ENABLE_3D }; auto context = impeller::ContextGLES::Create( std::move(proc_table), shader_mappings, enable_gpu_tracing); if (!context) { FML_LOG(ERROR) << "Could not create OpenGLES Impeller Context."; return nullptr; } if (!context->AddReactorWorker(worker).has_value()) { FML_LOG(ERROR) << "Could not add reactor worker."; return nullptr; } FML_LOG(IMPORTANT) << "Using the Impeller rendering backend (OpenGLES)."; return context; } AndroidContextGLImpeller::AndroidContextGLImpeller( std::unique_ptr<impeller::egl::Display> display, bool enable_gpu_tracing) : AndroidContext(AndroidRenderingAPI::kImpellerOpenGLES), reactor_worker_(std::shared_ptr<ReactorWorker>(new ReactorWorker())), display_(std::move(display)) { if (!display_ || !display_->IsValid()) { FML_DLOG(ERROR) << "Could not create context with invalid EGL display."; return; } impeller::egl::ConfigDescriptor desc; desc.api = impeller::egl::API::kOpenGLES2; desc.color_format = impeller::egl::ColorFormat::kRGBA8888; desc.depth_bits = impeller::egl::DepthBits::kZero; desc.stencil_bits = impeller::egl::StencilBits::kEight; desc.samples = impeller::egl::Samples::kFour; desc.surface_type = impeller::egl::SurfaceType::kWindow; std::unique_ptr<impeller::egl::Config> onscreen_config = display_->ChooseConfig(desc); if (!onscreen_config) { // Fallback for Android emulator. desc.samples = impeller::egl::Samples::kOne; onscreen_config = display_->ChooseConfig(desc); if (onscreen_config) { FML_LOG(INFO) << "Warning: This device doesn't support MSAA for onscreen " "framebuffers. Falling back to a single sample."; } else { FML_DLOG(ERROR) << "Could not choose onscreen config."; return; } } desc.surface_type = impeller::egl::SurfaceType::kPBuffer; auto offscreen_config = display_->ChooseConfig(desc); if (!offscreen_config) { FML_DLOG(ERROR) << "Could not choose offscreen config."; return; } auto onscreen_context = display_->CreateContext(*onscreen_config, nullptr); if (!onscreen_context) { FML_DLOG(ERROR) << "Could not create onscreen context."; return; } auto offscreen_context = display_->CreateContext(*offscreen_config, onscreen_context.get()); if (!offscreen_context) { FML_DLOG(ERROR) << "Could not create offscreen context."; return; } // Creating the impeller::Context requires a current context, which requires // some surface. auto offscreen_surface = display_->CreatePixelBufferSurface(*offscreen_config, 1u, 1u); if (!offscreen_context->MakeCurrent(*offscreen_surface)) { FML_DLOG(ERROR) << "Could not make offscreen context current."; return; } auto impeller_context = CreateImpellerContext(reactor_worker_, enable_gpu_tracing); if (!impeller_context) { FML_DLOG(ERROR) << "Could not create Impeller context."; return; } if (!offscreen_context->ClearCurrent()) { FML_DLOG(ERROR) << "Could not clear offscreen context."; return; } // Setup context listeners. impeller::egl::Context::LifecycleListener listener = [worker = reactor_worker_](impeller::egl ::Context::LifecycleEvent event) { switch (event) { case impeller::egl::Context::LifecycleEvent::kDidMakeCurrent: worker->SetReactionsAllowedOnCurrentThread(true); break; case impeller::egl::Context::LifecycleEvent::kWillClearCurrent: worker->SetReactionsAllowedOnCurrentThread(false); break; } }; if (!onscreen_context->AddLifecycleListener(listener).has_value() || !offscreen_context->AddLifecycleListener(listener).has_value()) { FML_DLOG(ERROR) << "Could not add lifecycle listeners"; } onscreen_config_ = std::move(onscreen_config); offscreen_config_ = std::move(offscreen_config); onscreen_context_ = std::move(onscreen_context); offscreen_context_ = std::move(offscreen_context); SetImpellerContext(impeller_context); is_valid_ = true; } AndroidContextGLImpeller::~AndroidContextGLImpeller() = default; bool AndroidContextGLImpeller::IsValid() const { return is_valid_; } bool AndroidContextGLImpeller::ResourceContextClearCurrent() { if (!offscreen_context_) { return false; } return offscreen_context_->ClearCurrent(); } bool AndroidContextGLImpeller::ResourceContextMakeCurrent( impeller::egl::Surface* offscreen_surface) { if (!offscreen_context_ || !offscreen_surface) { return false; } return offscreen_context_->MakeCurrent(*offscreen_surface); } std::unique_ptr<impeller::egl::Surface> AndroidContextGLImpeller::CreateOffscreenSurface() { return display_->CreatePixelBufferSurface(*offscreen_config_, 1u, 1u); } bool AndroidContextGLImpeller::OnscreenContextMakeCurrent( impeller::egl::Surface* onscreen_surface) { if (!onscreen_surface || !onscreen_context_) { return false; } return onscreen_context_->MakeCurrent(*onscreen_surface); } bool AndroidContextGLImpeller::OnscreenContextClearCurrent() { if (!onscreen_context_) { return false; } return onscreen_context_->ClearCurrent(); } std::unique_ptr<impeller::egl::Surface> AndroidContextGLImpeller::CreateOnscreenSurface(EGLNativeWindowType window) { return display_->CreateWindowSurface(*onscreen_config_, window); } } // namespace flutter
engine/shell/platform/android/android_context_gl_impeller.cc/0
{ "file_path": "engine/shell/platform/android/android_context_gl_impeller.cc", "repo_id": "engine", "token_count": 2994 }
288
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_IMAGE_GENERATOR_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_IMAGE_GENERATOR_H_ #include <jni.h> #include "flutter/fml/memory/ref_ptr.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/fml/task_runner.h" #include "flutter/lib/ui/painting/image_generator.h" namespace flutter { class AndroidImageGenerator : public ImageGenerator { private: explicit AndroidImageGenerator(sk_sp<SkData> buffer); public: ~AndroidImageGenerator(); // |ImageGenerator| const SkImageInfo& GetInfo() override; // |ImageGenerator| unsigned int GetFrameCount() const override; // |ImageGenerator| unsigned int GetPlayCount() const override; // |ImageGenerator| const ImageGenerator::FrameInfo GetFrameInfo( unsigned int frame_index) override; // |ImageGenerator| SkISize GetScaledDimensions(float desired_scale) override; // |ImageGenerator| bool GetPixels(const SkImageInfo& info, void* pixels, size_t row_bytes, unsigned int frame_index, std::optional<unsigned int> prior_frame) override; void DecodeImage(); static bool Register(JNIEnv* env); static std::shared_ptr<ImageGenerator> MakeFromData( sk_sp<SkData> data, const fml::RefPtr<fml::TaskRunner>& task_runner); static void NativeImageHeaderCallback(JNIEnv* env, jclass jcaller, jlong generator_pointer, int width, int height); private: sk_sp<SkData> data_; sk_sp<SkData> software_decoded_data_; SkImageInfo image_info_; /// Blocks until the header of the image has been decoded and the image /// dimensions have been determined. fml::ManualResetWaitableEvent header_decoded_latch_; /// Blocks until the image has been fully decoded. fml::ManualResetWaitableEvent fully_decoded_latch_; void DoDecodeImage(); bool IsValidImageData(); FML_DISALLOW_COPY_ASSIGN_AND_MOVE(AndroidImageGenerator); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_IMAGE_GENERATOR_H_
engine/shell/platform/android/android_image_generator.h/0
{ "file_path": "engine/shell/platform/android/android_image_generator.h", "repo_id": "engine", "token_count": 956 }
289
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/image_external_texture_gl.h" #include <android/hardware_buffer_jni.h> #include <android/sensor.h> #include "flutter/common/graphics/texture.h" #include "flutter/impeller/core/formats.h" #include "flutter/impeller/display_list/dl_image_impeller.h" #include "flutter/impeller/toolkit/android/hardware_buffer.h" #include "flutter/impeller/toolkit/egl/image.h" #include "flutter/impeller/toolkit/gles/texture.h" #include "third_party/skia/include/core/SkAlphaType.h" #include "third_party/skia/include/core/SkColorType.h" #include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h" #include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" namespace flutter { ImageExternalTextureGL::ImageExternalTextureGL( int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& image_texture_entry, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) : ImageExternalTexture(id, image_texture_entry, jni_facade) {} void ImageExternalTextureGL::Attach(PaintContext& context) { if (state_ == AttachmentState::kUninitialized) { // TODO(johnmccurtchan): We currently display the first frame after an // attach-detach cycle as blank. There seems to be an issue on some // devices where ImageReaders/Images from before the detach aren't // valid after the attach. According to Android folks this doesn't // match the spec. Revisit this in the future. // See https://github.com/flutter/flutter/issues/142978 and // https://github.com/flutter/flutter/issues/139039. state_ = AttachmentState::kAttached; } } void ImageExternalTextureGL::UpdateImage(JavaLocalRef& hardware_buffer, const SkRect& bounds, PaintContext& context) { AHardwareBuffer* latest_hardware_buffer = AHardwareBufferFor(hardware_buffer); std::optional<HardwareBufferKey> key = impeller::android::HardwareBuffer::GetSystemUniqueID( latest_hardware_buffer); auto existing_image = image_lru_.FindImage(key); if (existing_image != nullptr) { dl_image_ = existing_image; return; } auto egl_image = CreateEGLImage(latest_hardware_buffer); if (!egl_image.is_valid()) { return; } dl_image_ = CreateDlImage(context, bounds, key, std::move(egl_image)); if (key.has_value()) { gl_entries_.erase(image_lru_.AddImage(dl_image_, key.value())); } } void ImageExternalTextureGL::ProcessFrame(PaintContext& context, const SkRect& bounds) { JavaLocalRef image = AcquireLatestImage(); if (image.is_null()) { return; } JavaLocalRef hardware_buffer = HardwareBufferFor(image); UpdateImage(hardware_buffer, bounds, context); CloseHardwareBuffer(hardware_buffer); } void ImageExternalTextureGL::Detach() { image_lru_.Clear(); gl_entries_.clear(); } impeller::UniqueEGLImageKHR ImageExternalTextureGL::CreateEGLImage( AHardwareBuffer* hardware_buffer) { if (hardware_buffer == nullptr) { return impeller::UniqueEGLImageKHR(); } EGLDisplay display = eglGetCurrentDisplay(); FML_CHECK(display != EGL_NO_DISPLAY); EGLClientBuffer client_buffer = impeller::android::GetProcTable().eglGetNativeClientBufferANDROID( hardware_buffer); FML_DCHECK(client_buffer != nullptr); if (client_buffer == nullptr) { FML_LOG(ERROR) << "eglGetNativeClientBufferAndroid returned null."; return impeller::UniqueEGLImageKHR(); } impeller::EGLImageKHRWithDisplay maybe_image = impeller::EGLImageKHRWithDisplay{ eglCreateImageKHR(display, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, client_buffer, 0), display}; return impeller::UniqueEGLImageKHR(maybe_image); } ImageExternalTextureGLSkia::ImageExternalTextureGLSkia( const std::shared_ptr<AndroidContextGLSkia>& context, int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& image_texture_entry, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) : ImageExternalTextureGL(id, image_texture_entry, jni_facade) {} void ImageExternalTextureGLSkia::Attach(PaintContext& context) { if (state_ == AttachmentState::kUninitialized) { // After this call state_ will be AttachmentState::kAttached and egl_image_ // will have been created if we still have an Image associated with us. ImageExternalTextureGL::Attach(context); } } void ImageExternalTextureGLSkia::Detach() { ImageExternalTextureGL::Detach(); } void ImageExternalTextureGLSkia::BindImageToTexture( const impeller::UniqueEGLImageKHR& image, GLuint tex) { if (!image.is_valid() || tex == 0) { return; } glBindTexture(GL_TEXTURE_EXTERNAL_OES, tex); glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, (GLeglImageOES)image.get().image); } sk_sp<flutter::DlImage> ImageExternalTextureGLSkia::CreateDlImage( PaintContext& context, const SkRect& bounds, std::optional<HardwareBufferKey> id, impeller::UniqueEGLImageKHR&& egl_image) { GLuint texture_name; glGenTextures(1, &texture_name); auto gl_texture = impeller::GLTexture{texture_name}; impeller::UniqueGLTexture unique_texture; unique_texture.reset(gl_texture); BindImageToTexture(egl_image, unique_texture.get().texture_name); GrGLTextureInfo textureInfo = { GL_TEXTURE_EXTERNAL_OES, unique_texture.get().texture_name, GL_RGBA8_OES}; auto backendTexture = GrBackendTextures::MakeGL(1, 1, skgpu::Mipmapped::kNo, textureInfo); gl_entries_[id.value_or(0)] = GlEntry{.egl_image = std::move(egl_image), .texture = std::move(unique_texture)}; return DlImage::Make(SkImages::BorrowTextureFrom( context.gr_context, backendTexture, kTopLeft_GrSurfaceOrigin, kRGBA_8888_SkColorType, kPremul_SkAlphaType, nullptr)); } ImageExternalTextureGLImpeller::ImageExternalTextureGLImpeller( const std::shared_ptr<impeller::ContextGLES>& context, int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& image_textury_entry, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) : ImageExternalTextureGL(id, image_textury_entry, jni_facade), impeller_context_(context) {} void ImageExternalTextureGLImpeller::Detach() {} void ImageExternalTextureGLImpeller::Attach(PaintContext& context) { if (state_ == AttachmentState::kUninitialized) { ImageExternalTextureGL::Attach(context); } } sk_sp<flutter::DlImage> ImageExternalTextureGLImpeller::CreateDlImage( PaintContext& context, const SkRect& bounds, std::optional<HardwareBufferKey> id, impeller::UniqueEGLImageKHR&& egl_image) { impeller::TextureDescriptor desc; desc.type = impeller::TextureType::kTextureExternalOES; desc.storage_mode = impeller::StorageMode::kDevicePrivate; desc.format = impeller::PixelFormat::kR8G8B8A8UNormInt; desc.size = {static_cast<int>(bounds.width()), static_cast<int>(bounds.height())}; desc.mip_count = 1; auto texture = std::make_shared<impeller::TextureGLES>( impeller_context_->GetReactor(), desc, impeller::TextureGLES::IsWrapped::kWrapped); texture->SetCoordinateSystem( impeller::TextureCoordinateSystem::kUploadFromHost); if (!texture->Bind()) { return nullptr; } // Associate the hardware buffer image with the texture. glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, (GLeglImageOES)egl_image.get().image); gl_entries_[id.value_or(0)] = GlEntry{ .egl_image = std::move(egl_image), }; return impeller::DlImageImpeller::Make(texture); } } // namespace flutter
engine/shell/platform/android/image_external_texture_gl.cc/0
{ "file_path": "engine/shell/platform/android/image_external_texture_gl.cc", "repo_id": "engine", "token_count": 3000 }
290
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.app; import androidx.annotation.CallSuper; import com.google.android.play.core.splitcompat.SplitCompatApplication; import io.flutter.FlutterInjector; import io.flutter.embedding.engine.deferredcomponents.PlayStoreDeferredComponentManager; /** * Flutter's extension of {@link SplitCompatApplication} that injects a {@link * PlayStoreDeferredComponentManager} with {@link FlutterInjector} to enable Split AOT Flutter apps. * * <p>To use this class, either have your custom application class extend * FlutterPlayStoreSplitApplication or use it directly in the app's AndroidManifest.xml by adding * the following line: * * <pre>{@code * <manifest * ... * <application * android:name="io.flutter.app.FlutterPlayStoreSplitApplication" * ...> * </application> * </manifest> * }</pre> * * This class is meant to be used with the Google Play store. Custom non-play store applications do * not need to extend SplitCompatApplication and should inject a custom {@link * io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager} implementation like so: * * <pre>{@code * FlutterInjector.setInstance( * new FlutterInjector.Builder().setDeferredComponentManager(yourCustomManager).build()); * }</pre> */ public class FlutterPlayStoreSplitApplication extends SplitCompatApplication { @Override @CallSuper public void onCreate() { super.onCreate(); // Create and inject a PlayStoreDeferredComponentManager, which is the default manager for // interacting with the Google Play Store. PlayStoreDeferredComponentManager deferredComponentManager = new PlayStoreDeferredComponentManager(this, null); FlutterInjector.setInstance( new FlutterInjector.Builder() .setDeferredComponentManager(deferredComponentManager) .build()); } }
engine/shell/platform/android/io/flutter/app/FlutterPlayStoreSplitApplication.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/app/FlutterPlayStoreSplitApplication.java", "repo_id": "engine", "token_count": 611 }
291
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.android; import android.view.KeyEvent; import androidx.annotation.NonNull; import io.flutter.embedding.engine.systemchannels.KeyEventChannel; /** * A {@link KeyboardManager.Responder} of {@link KeyboardManager} that handles events by sending the * raw information through the method channel. * * <p>This class corresponds to the RawKeyboard API in the framework. */ public class KeyChannelResponder implements KeyboardManager.Responder { private static final String TAG = "KeyChannelResponder"; @NonNull private final KeyEventChannel keyEventChannel; @NonNull private final KeyboardManager.CharacterCombiner characterCombiner = new KeyboardManager.CharacterCombiner(); public KeyChannelResponder(@NonNull KeyEventChannel keyEventChannel) { this.keyEventChannel = keyEventChannel; } @Override public void handleEvent( @NonNull KeyEvent keyEvent, @NonNull OnKeyEventHandledCallback onKeyEventHandledCallback) { final int action = keyEvent.getAction(); if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_UP) { // There is theoretically a KeyEvent.ACTION_MULTIPLE, but theoretically // that isn't sent by Android anymore, so this is just for protection in // case the theory is wrong. onKeyEventHandledCallback.onKeyEventHandled(false); return; } final Character complexCharacter = characterCombiner.applyCombiningCharacterToBaseCharacter(keyEvent.getUnicodeChar()); KeyEventChannel.FlutterKeyEvent flutterEvent = new KeyEventChannel.FlutterKeyEvent(keyEvent, complexCharacter); final boolean isKeyUp = action != KeyEvent.ACTION_DOWN; keyEventChannel.sendFlutterKeyEvent( flutterEvent, isKeyUp, (isEventHandled) -> onKeyEventHandledCallback.onKeyEventHandled(isEventHandled)); } }
engine/shell/platform/android/io/flutter/embedding/android/KeyChannelResponder.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/android/KeyChannelResponder.java", "repo_id": "engine", "token_count": 611 }
292
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import java.util.*; /** * Arguments that can be delivered to the Flutter shell when it is created. * * <p>The term "shell" refers to the native code that adapts Flutter to different platforms. * Flutter's Android Java code initializes a native "shell" and passes these arguments to that * native shell when it is initialized. See {@link * io.flutter.embedding.engine.loader.FlutterLoader#ensureInitializationComplete(Context, String[])} * for more information. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class FlutterShellArgs { public static final String ARG_KEY_TRACE_STARTUP = "trace-startup"; public static final String ARG_TRACE_STARTUP = "--trace-startup"; public static final String ARG_KEY_START_PAUSED = "start-paused"; public static final String ARG_START_PAUSED = "--start-paused"; public static final String ARG_KEY_DISABLE_SERVICE_AUTH_CODES = "disable-service-auth-codes"; public static final String ARG_DISABLE_SERVICE_AUTH_CODES = "--disable-service-auth-codes"; public static final String ARG_KEY_ENDLESS_TRACE_BUFFER = "endless-trace-buffer"; public static final String ARG_ENDLESS_TRACE_BUFFER = "--endless-trace-buffer"; public static final String ARG_KEY_USE_TEST_FONTS = "use-test-fonts"; public static final String ARG_USE_TEST_FONTS = "--use-test-fonts"; public static final String ARG_KEY_ENABLE_DART_PROFILING = "enable-dart-profiling"; public static final String ARG_ENABLE_DART_PROFILING = "--enable-dart-profiling"; public static final String ARG_KEY_ENABLE_SOFTWARE_RENDERING = "enable-software-rendering"; public static final String ARG_ENABLE_SOFTWARE_RENDERING = "--enable-software-rendering"; public static final String ARG_KEY_SKIA_DETERMINISTIC_RENDERING = "skia-deterministic-rendering"; public static final String ARG_SKIA_DETERMINISTIC_RENDERING = "--skia-deterministic-rendering"; public static final String ARG_KEY_TRACE_SKIA = "trace-skia"; public static final String ARG_TRACE_SKIA = "--trace-skia"; public static final String ARG_KEY_TRACE_SKIA_ALLOWLIST = "trace-skia-allowlist"; public static final String ARG_TRACE_SKIA_ALLOWLIST = "--trace-skia-allowlist="; public static final String ARG_KEY_TRACE_SYSTRACE = "trace-systrace"; public static final String ARG_TRACE_SYSTRACE = "--trace-systrace"; public static final String ARG_KEY_TRACE_TO_FILE = "trace-to-file"; public static final String ARG_TRACE_TO_FILE = "--trace-to-file"; public static final String ARG_KEY_ENABLE_IMPELLER = "enable-impeller"; public static final String ARG_ENABLE_IMPELLER = "--enable-impeller"; public static final String ARG_KEY_ENABLE_VULKAN_VALIDATION = "enable-vulkan-validation"; public static final String ARG_ENABLE_VULKAN_VALIDATION = "--enable-vulkan-validation"; public static final String ARG_KEY_DUMP_SHADER_SKP_ON_SHADER_COMPILATION = "dump-skp-on-shader-compilation"; public static final String ARG_DUMP_SHADER_SKP_ON_SHADER_COMPILATION = "--dump-skp-on-shader-compilation"; public static final String ARG_KEY_CACHE_SKSL = "cache-sksl"; public static final String ARG_CACHE_SKSL = "--cache-sksl"; public static final String ARG_KEY_PURGE_PERSISTENT_CACHE = "purge-persistent-cache"; public static final String ARG_PURGE_PERSISTENT_CACHE = "--purge-persistent-cache"; public static final String ARG_KEY_VERBOSE_LOGGING = "verbose-logging"; public static final String ARG_VERBOSE_LOGGING = "--verbose-logging"; public static final String ARG_KEY_VM_SERVICE_PORT = "vm-service-port"; public static final String ARG_VM_SERVICE_PORT = "--vm-service-port="; // TODO(bkonyi): remove once flutter_tools no longer uses this option. // See https://github.com/dart-lang/sdk/issues/50233 public static final String ARG_KEY_OBSERVATORY_PORT = "observatory-port"; public static final String ARG_KEY_DART_FLAGS = "dart-flags"; public static final String ARG_DART_FLAGS = "--dart-flags"; public static final String ARG_KEY_MSAA_SAMPLES = "msaa-samples"; public static final String ARG_MSAA_SAMPLES = "--msaa-samples"; @NonNull public static FlutterShellArgs fromIntent(@NonNull Intent intent) { // Before adding more entries to this list, consider that arbitrary // Android applications can generate intents with extra data and that // there are many security-sensitive args in the binary. // TODO(mattcarroll): I left this warning as-is, but we should clarify what exactly this warning // is warning against. ArrayList<String> args = new ArrayList<>(); if (intent.getBooleanExtra(ARG_KEY_TRACE_STARTUP, false)) { args.add(ARG_TRACE_STARTUP); } if (intent.getBooleanExtra(ARG_KEY_START_PAUSED, false)) { args.add(ARG_START_PAUSED); } int vmServicePort = intent.getIntExtra(ARG_KEY_VM_SERVICE_PORT, 0); if (vmServicePort > 0) { args.add(ARG_VM_SERVICE_PORT + Integer.toString(vmServicePort)); } else { // TODO(bkonyi): remove once flutter_tools no longer uses this option. // See https://github.com/dart-lang/sdk/issues/50233 vmServicePort = intent.getIntExtra(ARG_KEY_OBSERVATORY_PORT, 0); if (vmServicePort > 0) { args.add(ARG_VM_SERVICE_PORT + Integer.toString(vmServicePort)); } } if (intent.getBooleanExtra(ARG_KEY_DISABLE_SERVICE_AUTH_CODES, false)) { args.add(ARG_DISABLE_SERVICE_AUTH_CODES); } if (intent.getBooleanExtra(ARG_KEY_ENDLESS_TRACE_BUFFER, false)) { args.add(ARG_ENDLESS_TRACE_BUFFER); } if (intent.getBooleanExtra(ARG_KEY_USE_TEST_FONTS, false)) { args.add(ARG_USE_TEST_FONTS); } if (intent.getBooleanExtra(ARG_KEY_ENABLE_DART_PROFILING, false)) { args.add(ARG_ENABLE_DART_PROFILING); } if (intent.getBooleanExtra(ARG_KEY_ENABLE_SOFTWARE_RENDERING, false)) { args.add(ARG_ENABLE_SOFTWARE_RENDERING); } if (intent.getBooleanExtra(ARG_KEY_SKIA_DETERMINISTIC_RENDERING, false)) { args.add(ARG_SKIA_DETERMINISTIC_RENDERING); } if (intent.getBooleanExtra(ARG_KEY_TRACE_SKIA, false)) { args.add(ARG_TRACE_SKIA); } String traceSkiaAllowlist = intent.getStringExtra(ARG_KEY_TRACE_SKIA_ALLOWLIST); if (traceSkiaAllowlist != null) { args.add(ARG_TRACE_SKIA_ALLOWLIST + traceSkiaAllowlist); } if (intent.getBooleanExtra(ARG_KEY_TRACE_SYSTRACE, false)) { args.add(ARG_TRACE_SYSTRACE); } if (intent.hasExtra(ARG_KEY_TRACE_TO_FILE)) { args.add(ARG_TRACE_TO_FILE + "=" + intent.getStringExtra(ARG_KEY_TRACE_TO_FILE)); } if (intent.getBooleanExtra(ARG_KEY_ENABLE_IMPELLER, false)) { args.add(ARG_ENABLE_IMPELLER); } if (intent.getBooleanExtra(ARG_KEY_ENABLE_VULKAN_VALIDATION, false)) { args.add(ARG_ENABLE_VULKAN_VALIDATION); } if (intent.getBooleanExtra(ARG_KEY_DUMP_SHADER_SKP_ON_SHADER_COMPILATION, false)) { args.add(ARG_DUMP_SHADER_SKP_ON_SHADER_COMPILATION); } if (intent.getBooleanExtra(ARG_KEY_CACHE_SKSL, false)) { args.add(ARG_CACHE_SKSL); } if (intent.getBooleanExtra(ARG_KEY_PURGE_PERSISTENT_CACHE, false)) { args.add(ARG_PURGE_PERSISTENT_CACHE); } if (intent.getBooleanExtra(ARG_KEY_VERBOSE_LOGGING, false)) { args.add(ARG_VERBOSE_LOGGING); } final int msaaSamples = intent.getIntExtra("msaa-samples", 0); if (msaaSamples > 1) { args.add("--msaa-samples=" + Integer.toString(msaaSamples)); } // NOTE: all flags provided with this argument are subject to filtering // based on a list of allowed flags in shell/common/switches.cc. If any // flag provided is not allowed, the process will immediately terminate. if (intent.hasExtra(ARG_KEY_DART_FLAGS)) { args.add(ARG_DART_FLAGS + "=" + intent.getStringExtra(ARG_KEY_DART_FLAGS)); } return new FlutterShellArgs(args); } @NonNull private Set<String> args; /** * Creates a set of Flutter shell arguments from a given {@code String[]} array. The given * arguments are automatically de-duplicated. */ public FlutterShellArgs(@NonNull String[] args) { this.args = new HashSet<>(Arrays.asList(args)); } /** * Creates a set of Flutter shell arguments from a given {@code List<String>}. The given arguments * are automatically de-duplicated. */ public FlutterShellArgs(@NonNull List<String> args) { this.args = new HashSet<>(args); } /** Creates a set of Flutter shell arguments from a given {@code Set<String>}. */ public FlutterShellArgs(@NonNull Set<String> args) { this.args = new HashSet<>(args); } /** * Adds the given {@code arg} to this set of arguments. * * @param arg argument to add */ public void add(@NonNull String arg) { args.add(arg); } /** * Removes the given {@code arg} from this set of arguments. * * @param arg argument to remove */ public void remove(@NonNull String arg) { args.remove(arg); } /** * Returns a new {@code String[]} array which contains each of the arguments within this {@code * FlutterShellArgs}. * * @return array of arguments */ @NonNull public String[] toArray() { String[] argsArray = new String[args.size()]; return args.toArray(argsArray); } }
engine/shell/platform/android/io/flutter/embedding/engine/FlutterShellArgs.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/FlutterShellArgs.java", "repo_id": "engine", "token_count": 3636 }
293
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.plugins.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.Lifecycle; import io.flutter.embedding.android.ExclusiveAppComponent; /** * Control surface through which an {@link android.app.Activity} attaches to a {@link * io.flutter.embedding.engine.FlutterEngine}. * * <p>An {@link android.app.Activity} that contains a {@link * io.flutter.embedding.android.FlutterView} and associated {@link * io.flutter.embedding.engine.FlutterEngine} should coordinate itself with the {@link * io.flutter.embedding.engine.FlutterEngine}'s {@code ActivityControlSurface}. * * <ol> * <li>Once an {@link android.app.Activity} is created, and its associated {@link * io.flutter.embedding.engine.FlutterEngine} is executing Dart code, the {@link * android.app.Activity} should invoke {@link #attachToActivity( ExclusiveAppComponent, * Lifecycle)}. At this point the {@link io.flutter.embedding.engine.FlutterEngine} is * considered "attached" to the {@link android.app.Activity} and all {@link ActivityAware} * plugins are given access to the {@link android.app.Activity}. * <li>Just before an attached {@link android.app.Activity} is destroyed for configuration change * purposes, that {@link android.app.Activity} should invoke {@link * #detachFromActivityForConfigChanges()}, giving each {@link ActivityAware} plugin an * opportunity to clean up its references before the {@link android.app.Activity is * destroyed}. * <li>When an {@link android.app.Activity} is destroyed for non-configuration-change purposes, or * when the {@link android.app.Activity} is no longer interested in displaying a {@link * io.flutter.embedding.engine.FlutterEngine}'s content, the {@link android.app.Activity} * should invoke {@link #detachFromActivity()}. * <li>When a {@link android.app.Activity} is being attached while an existing {@link * ExclusiveAppComponent} is already attached, the existing {@link ExclusiveAppComponent} is * given a chance to detach first via {@link ExclusiveAppComponent#detachFromFlutterEngine()} * before the new activity attaches. * </ol> * * The attached {@link android.app.Activity} should also forward all {@link android.app.Activity} * calls that this {@code ActivityControlSurface} supports, e.g., {@link * #onRequestPermissionsResult(int, String[], int[])}. These forwarded calls are made available to * all {@link ActivityAware} plugins that are added to the attached {@link * io.flutter.embedding.engine.FlutterEngine}. */ public interface ActivityControlSurface { /** * Call this method from the {@link ExclusiveAppComponent} that is displaying the visual content * of the {@link io.flutter.embedding.engine.FlutterEngine} that is associated with this {@code * ActivityControlSurface}. * * <p>Once an {@link ExclusiveAppComponent} is created, and its associated {@link * io.flutter.embedding.engine.FlutterEngine} is executing Dart code, the {@link * ExclusiveAppComponent} should invoke this method. At that point the {@link * io.flutter.embedding.engine.FlutterEngine} is considered "attached" to the {@link * ExclusiveAppComponent} and all {@link ActivityAware} plugins are given access to the {@link * ExclusiveAppComponent}'s {@link android.app.Activity}. */ void attachToActivity( @NonNull ExclusiveAppComponent<Activity> exclusiveActivity, @NonNull Lifecycle lifecycle); /** * Call this method from the {@link android.app.Activity} that is attached to this {@code * ActivityControlSurfaces}'s {@link io.flutter.embedding.engine.FlutterEngine} when the {@link * android.app.Activity} is about to be destroyed due to configuration changes. * * <p>This method gives each {@link ActivityAware} plugin an opportunity to clean up its * references before the {@link android.app.Activity is destroyed}. */ void detachFromActivityForConfigChanges(); /** * Call this method from the {@link android.app.Activity} that is attached to this {@code * ActivityControlSurfaces}'s {@link io.flutter.embedding.engine.FlutterEngine} when the {@link * android.app.Activity} is about to be destroyed for non-configuration-change reasons. * * <p>This method gives each {@link ActivityAware} plugin an opportunity to clean up its * references before the {@link android.app.Activity is destroyed}. */ void detachFromActivity(); /** * Call this method from the {@link android.app.Activity} that is attached to this {@code * ActivityControlSurface}'s {@link io.flutter.embedding.engine.FlutterEngine} and the associated * method in the {@link Activity} is invoked. * * <p>Returns true if one or more plugins utilized this permission result. */ boolean onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResult); /** * Call this method from the {@link android.app.Activity} that is attached to this {@code * ActivityControlSurface}'s {@link io.flutter.embedding.engine.FlutterEngine} and the associated * method in the {@link Activity} is invoked. * * <p>Returns true if one or more plugins utilized this {@link android.app.Activity} result. */ boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data); /** * Call this method from the {@link android.app.Activity} that is attached to this {@code * ActivityControlSurface}'s {@link io.flutter.embedding.engine.FlutterEngine} and the associated * method in the {@link Activity} is invoked. */ void onNewIntent(@NonNull Intent intent); /** * Call this method from the {@link android.app.Activity} that is attached to this {@code * ActivityControlSurface}'s {@link io.flutter.embedding.engine.FlutterEngine} and the associated * method in the {@link Activity} is invoked. */ void onUserLeaveHint(); /** * Call this method from the {@link android.app.Activity} or {@code Fragment} that is attached to * this {@code ActivityControlSurface}'s {@link io.flutter.embedding.engine.FlutterEngine} when * the associated method is invoked in the {@link android.app.Activity} or {@code Fragment}. */ void onSaveInstanceState(@NonNull Bundle bundle); /** * Call this method from the {@link android.app.Activity} or {@code Fragment} that is attached to * this {@code ActivityControlSurface}'s {@link io.flutter.embedding.engine.FlutterEngine} when * {@link android.app.Activity#onCreate(Bundle)} or {@code Fragment#onCreate(Bundle)} is invoked * in the {@link android.app.Activity} or {@code Fragment}. */ void onRestoreInstanceState(@Nullable Bundle bundle); }
engine/shell/platform/android/io/flutter/embedding/engine/plugins/activity/ActivityControlSurface.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/activity/ActivityControlSurface.java", "repo_id": "engine", "token_count": 2145 }
294
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.renderer; /** * Listener invoked when Flutter starts and stops rendering pixels to an Android {@code View} * hierarchy. */ public interface FlutterUiDisplayListener { /** * Flutter started painting pixels to an Android {@code View} hierarchy. * * <p>This method will not be invoked if this listener is added after the {@link FlutterRenderer} * has started painting pixels. */ void onFlutterUiDisplayed(); /** Flutter stopped painting pixels to an Android {@code View} hierarchy. */ void onFlutterUiNoLongerDisplayed(); }
engine/shell/platform/android/io/flutter/embedding/engine/renderer/FlutterUiDisplayListener.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/renderer/FlutterUiDisplayListener.java", "repo_id": "engine", "token_count": 211 }
295
package io.flutter.embedding.engine.systemchannels; import static io.flutter.Build.API_LEVELS; import android.annotation.SuppressLint; import android.os.Build; import android.util.DisplayMetrics; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.UiThread; 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.JSONMessageCodec; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; public class SettingsChannel { private static final String TAG = "SettingsChannel"; public static final String CHANNEL_NAME = "flutter/settings"; private static final String TEXT_SCALE_FACTOR = "textScaleFactor"; private static final String NATIVE_SPELL_CHECK_SERVICE_DEFINED = "nativeSpellCheckServiceDefined"; private static final String BRIEFLY_SHOW_PASSWORD = "brieflyShowPassword"; private static final String ALWAYS_USE_24_HOUR_FORMAT = "alwaysUse24HourFormat"; private static final String PLATFORM_BRIGHTNESS = "platformBrightness"; private static final String CONFIGURATION_ID = "configurationId"; // When hasNonlinearTextScalingSupport() returns false, this will not be initialized. private static final ConfigurationQueue CONFIGURATION_QUEUE = new ConfigurationQueue(); @NonNull public final BasicMessageChannel<Object> channel; public SettingsChannel(@NonNull DartExecutor dartExecutor) { this.channel = new BasicMessageChannel<>(dartExecutor, CHANNEL_NAME, JSONMessageCodec.INSTANCE); } @SuppressLint("AnnotateVersionCheck") public static boolean hasNonlinearTextScalingSupport() { return Build.VERSION.SDK_INT >= API_LEVELS.API_34; } // This method will only be called on Flutter's UI thread. public static DisplayMetrics getPastDisplayMetrics(int configId) { assert hasNonlinearTextScalingSupport(); final ConfigurationQueue.SentConfiguration configuration = CONFIGURATION_QUEUE.getConfiguration(configId); return configuration == null ? null : configuration.displayMetrics; } @NonNull public MessageBuilder startMessage() { return new MessageBuilder(channel); } public static class MessageBuilder { @NonNull private final BasicMessageChannel<Object> channel; @NonNull private Map<String, Object> message = new HashMap<>(); @Nullable private DisplayMetrics displayMetrics; MessageBuilder(@NonNull BasicMessageChannel<Object> channel) { this.channel = channel; } @NonNull public MessageBuilder setDisplayMetrics(@NonNull DisplayMetrics displayMetrics) { this.displayMetrics = displayMetrics; return this; } @NonNull public MessageBuilder setTextScaleFactor(float textScaleFactor) { message.put(TEXT_SCALE_FACTOR, textScaleFactor); return this; } @NonNull public MessageBuilder setNativeSpellCheckServiceDefined( boolean nativeSpellCheckServiceDefined) { message.put(NATIVE_SPELL_CHECK_SERVICE_DEFINED, nativeSpellCheckServiceDefined); return this; } @NonNull public MessageBuilder setBrieflyShowPassword(@NonNull boolean brieflyShowPassword) { message.put(BRIEFLY_SHOW_PASSWORD, brieflyShowPassword); return this; } @NonNull public MessageBuilder setUse24HourFormat(boolean use24HourFormat) { message.put(ALWAYS_USE_24_HOUR_FORMAT, use24HourFormat); return this; } @NonNull public MessageBuilder setPlatformBrightness(@NonNull PlatformBrightness brightness) { message.put(PLATFORM_BRIGHTNESS, brightness.name); return this; } public void send() { Log.v( TAG, "Sending message: \n" + "textScaleFactor: " + message.get(TEXT_SCALE_FACTOR) + "\n" + "alwaysUse24HourFormat: " + message.get(ALWAYS_USE_24_HOUR_FORMAT) + "\n" + "platformBrightness: " + message.get(PLATFORM_BRIGHTNESS)); final DisplayMetrics metrics = this.displayMetrics; if (!hasNonlinearTextScalingSupport() || metrics == null) { channel.send(message); return; } final ConfigurationQueue.SentConfiguration sentConfiguration = new ConfigurationQueue.SentConfiguration(metrics); final BasicMessageChannel.Reply deleteCallback = CONFIGURATION_QUEUE.enqueueConfiguration(sentConfiguration); message.put(CONFIGURATION_ID, sentConfiguration.generationNumber); channel.send(message, deleteCallback); } } /** * The brightness mode of the host platform. * * <p>The {@code name} property is the serialized representation of each brightness mode when * communicated via message channel. */ public enum PlatformBrightness { light("light"), dark("dark"); @NonNull public String name; PlatformBrightness(@NonNull String name) { this.name = name; } } /** * A FIFO queue that maintains generations of configurations that are potentially used by the * Flutter application. * * <p>Platform configurations needed by the Flutter app (for example, text scale factor) are * retrived on the platform thread, serialized and sent to the Flutter application running on the * Flutter UI thread. However, configurations exposed as functions that take parameters are * typically not serializable. To allow the Flutter app to access these configurations, one * possible solution is to create dart bindings that allow the Flutter framework to invoke these * functions via JNI synchronously. To ensure the serialized configuration and these functions * represent the same set of configurations at any given time, a "generation" id is used in these * synchronous calls, to keep them consistent with the serialized configuration that the Flutter * app most recently received and is currently using. * * <p>A unique generation identifier is generated by the {@link SettingsChannel} and associated * with a configuration when it sends a serialized configuration to the Flutter framework. This * queue keeps different generations of configurations that could be used by the Flutter * framework, and cleans up old configurations that the Flutter framework no longer uses. When the * Flutter framework invokes a function to access the configuration with a generation identifier, * this queue finds the configuration with that identifier and also cleans up configurations that * are no longer needed. * * <p>This mechanism is only needed because {@code TypedValue#applyDimension} does not take the * current text scale factor as an input. Once the AndroidX API that allows us to query the scaled * font size with a pure function is available, we can scrap this class and make the * implementation much simpler. */ @VisibleForTesting public static class ConfigurationQueue { private final ConcurrentLinkedQueue<SentConfiguration> sentQueue = new ConcurrentLinkedQueue<>(); // The current SentConfiguration the Flutter application is using, according // to the most recent getConfiguration call. // // This instance variable will only be accessed by getConfiguration, on // Flutter's UI thread. private SentConfiguration currentConfiguration; /** * Returns the {@link SentConfiguration} associated with the given {@code configGeneration}, and * removes configurations older than the returned configurations from the queue as they are no * longer needed. */ public SentConfiguration getConfiguration(int configGeneration) { if (currentConfiguration == null) { currentConfiguration = sentQueue.poll(); } // Remove the older entries, up to the entry associated with // configGeneration. Here we assume the generationNumber never overflows. while (currentConfiguration != null && currentConfiguration.generationNumber < configGeneration) { currentConfiguration = sentQueue.poll(); } if (currentConfiguration == null) { Log.e( TAG, "Cannot find config with generation: " + String.valueOf(configGeneration) + ", after exhausting the queue."); return null; } else if (currentConfiguration.generationNumber != configGeneration) { Log.e( TAG, "Cannot find config with generation: " + String.valueOf(configGeneration) + ", the oldest config is now: " + String.valueOf(currentConfiguration.generationNumber)); return null; } return currentConfiguration; } private SentConfiguration previousEnqueuedConfiguration; /** * Adds the most recently sent {@link SentConfiguration} to the queue. * * @return a {@link BasicMessageChannel.Reply} whose {@code reply} method must be called when * the embedder receives the reply for the sent configuration, to properly clean up older * configurations in the queue. */ @UiThread @Nullable public BasicMessageChannel.Reply enqueueConfiguration(SentConfiguration config) { sentQueue.add(config); final SentConfiguration configurationToRemove = previousEnqueuedConfiguration; previousEnqueuedConfiguration = config; return configurationToRemove == null ? null : new BasicMessageChannel.Reply() { @UiThread @Override public void reply(Object reply) { // Removes the SentConfiguration sent right before `config`. Since // platform messages are also FIFO older messages will be removed // before newer ones. sentQueue.remove(configurationToRemove); if (!sentQueue.isEmpty()) { Log.e( TAG, "The queue becomes empty after removing config generation " + String.valueOf(configurationToRemove.generationNumber)); } } }; } public static class SentConfiguration { private static int nextConfigGeneration = Integer.MIN_VALUE; @NonNull public final int generationNumber; @NonNull private final DisplayMetrics displayMetrics; public SentConfiguration(@NonNull DisplayMetrics displayMetrics) { this.generationNumber = nextConfigGeneration++; this.displayMetrics = displayMetrics; } } } }
engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/SettingsChannel.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/SettingsChannel.java", "repo_id": "engine", "token_count": 3522 }
296
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.common; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import io.flutter.BuildConfig; import io.flutter.Log; import io.flutter.plugin.common.BinaryMessenger.BinaryMessageHandler; import io.flutter.plugin.common.BinaryMessenger.BinaryReply; import java.nio.ByteBuffer; /** * A named channel for communicating with the Flutter application using asynchronous method calls. * * <p>Incoming method calls are decoded from binary on receipt, and Java results are encoded into * binary before being transmitted back to Flutter. The {@link MethodCodec} used must be compatible * with the one used by the Flutter application. This can be achieved by creating a <a * href="https://api.flutter.dev/flutter/services/MethodChannel-class.html">MethodChannel</a> * counterpart of this channel on the Dart side. The Java type of method call arguments and results * is {@code Object}, but only values supported by the specified {@link MethodCodec} can be used. * * <p>The logical identity of the channel is given by its name. Identically named channels will * interfere with each other's communication. */ public class MethodChannel { private static final String TAG = "MethodChannel#"; private final BinaryMessenger messenger; private final String name; private final MethodCodec codec; private final BinaryMessenger.TaskQueue taskQueue; /** * Creates a new channel associated with the specified {@link BinaryMessenger} and with the * specified name and the standard {@link MethodCodec}. * * @param messenger a {@link BinaryMessenger}. * @param name a channel name String. */ public MethodChannel(@NonNull BinaryMessenger messenger, @NonNull String name) { this(messenger, name, StandardMethodCodec.INSTANCE); } /** * Creates a new channel associated with the specified {@link BinaryMessenger} and with the * specified name and {@link MethodCodec}. * * @param messenger a {@link BinaryMessenger}. * @param name a channel name String. * @param codec a {@link MessageCodec}. */ public MethodChannel( @NonNull BinaryMessenger messenger, @NonNull String name, @NonNull MethodCodec codec) { this(messenger, name, codec, null); } /** * Creates a new channel associated with the specified {@link BinaryMessenger} and with the * specified name and {@link MethodCodec}. * * @param messenger a {@link BinaryMessenger}. * @param name a channel name String. * @param codec a {@link MessageCodec}. * @param taskQueue a {@link BinaryMessenger.TaskQueue} that specifies what thread will execute * the handler. Specifying null means execute on the platform thread. See also {@link * BinaryMessenger#makeBackgroundTaskQueue()}. */ public MethodChannel( @NonNull BinaryMessenger messenger, @NonNull String name, @NonNull MethodCodec codec, @Nullable BinaryMessenger.TaskQueue taskQueue) { if (BuildConfig.DEBUG) { if (messenger == null) { Log.e(TAG, "Parameter messenger must not be null."); } if (name == null) { Log.e(TAG, "Parameter name must not be null."); } if (codec == null) { Log.e(TAG, "Parameter codec must not be null."); } } this.messenger = messenger; this.name = name; this.codec = codec; this.taskQueue = taskQueue; } /** * Invokes a method on this channel, expecting no result. * * @param method the name String of the method. * @param arguments the arguments for the invocation, possibly null. */ @UiThread public void invokeMethod(@NonNull String method, @Nullable Object arguments) { invokeMethod(method, arguments, null); } /** * Invokes a method on this channel, optionally expecting a result. * * <p>Any uncaught exception thrown by the result callback will be caught and logged. * * @param method the name String of the method. * @param arguments the arguments for the invocation, possibly null. * @param callback a {@link Result} callback for the invocation result, or null. */ @UiThread public void invokeMethod( @NonNull String method, @Nullable Object arguments, @Nullable Result callback) { messenger.send( name, codec.encodeMethodCall(new MethodCall(method, arguments)), callback == null ? null : new IncomingResultHandler(callback)); } /** * Registers a method call handler on this channel. * * <p>Overrides any existing handler registration for (the name of) this channel. * * <p>If no handler has been registered, any incoming method call on this channel will be handled * silently by sending a null reply. This results in a <a * href="https://api.flutter.dev/flutter/services/MissingPluginException-class.html">MissingPluginException</a> * on the Dart side, unless an <a * href="https://api.flutter.dev/flutter/services/OptionalMethodChannel-class.html">OptionalMethodChannel</a> * is used. * * @param handler a {@link MethodCallHandler}, or null to deregister. */ @UiThread public void setMethodCallHandler(final @Nullable MethodCallHandler handler) { // We call the 2 parameter variant specifically to avoid breaking changes in // mock verify calls. // See https://github.com/flutter/flutter/issues/92582. if (taskQueue != null) { messenger.setMessageHandler( name, handler == null ? null : new IncomingMethodCallHandler(handler), taskQueue); } else { messenger.setMessageHandler( name, handler == null ? null : new IncomingMethodCallHandler(handler)); } } /** * Adjusts the number of messages that will get buffered when sending messages to channels that * aren't fully set up yet. For example, the engine isn't running yet or the channel's message * handler isn't set up on the Dart side yet. */ public void resizeChannelBuffer(int newSize) { BasicMessageChannel.resizeChannelBuffer(messenger, name, newSize); } /** * Toggles whether the channel should show warning messages when discarding messages due to * overflow. When 'warns' is false the channel is expected to overflow and warning messages will * not be shown. */ public void setWarnsOnChannelOverflow(boolean warns) { BasicMessageChannel.setWarnsOnChannelOverflow(messenger, name, warns); } /** A handler of incoming method calls. */ public interface MethodCallHandler { /** * Handles the specified method call received from Flutter. * * <p>Handler implementations must submit a result for all incoming calls, by making a single * call on the given {@link Result} callback. Failure to do so will result in lingering Flutter * result handlers. The result may be submitted asynchronously and on any thread. Calls to * unknown or unimplemented methods should be handled using {@link Result#notImplemented()}. * * <p>Any uncaught exception thrown by this method will be caught by the channel implementation * and logged, and an error result will be sent back to Flutter. * * <p>The handler is called on the platform thread (Android main thread) by default, or * otherwise on the thread specified by the {@link BinaryMessenger.TaskQueue} provided to the * associated {@link MethodChannel} when it was created. See also <a * href="https://github.com/flutter/flutter/wiki/The-Engine-architecture#threading">Threading in * the Flutter Engine</a>. * * @param call A {@link MethodCall}. * @param result A {@link Result} used for submitting the result of the call. */ @UiThread void onMethodCall(@NonNull MethodCall call, @NonNull Result result); } /** * Method call result callback. Supports dual use: Implementations of methods to be invoked by * Flutter act as clients of this interface for sending results back to Flutter. Invokers of * Flutter methods provide implementations of this interface for handling results received from * Flutter. * * <p>All methods of this class can be invoked on any thread. */ public interface Result { /** * Handles a successful result. * * @param result The result, possibly null. The result must be an Object type supported by the * codec. For instance, if you are using {@link StandardMessageCodec} (default), please see * its documentation on what types are supported. */ void success(@Nullable Object result); /** * Handles an error result. * * @param errorCode An error code String. * @param errorMessage A human-readable error message String, possibly null. * @param errorDetails Error details, possibly null. The details must be an Object type * supported by the codec. For instance, if you are using {@link StandardMessageCodec} * (default), please see its documentation on what types are supported. */ void error( @NonNull String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails); /** Handles a call to an unimplemented method. */ void notImplemented(); } private final class IncomingResultHandler implements BinaryReply { private final Result callback; IncomingResultHandler(Result callback) { this.callback = callback; } @Override @UiThread public void reply(ByteBuffer reply) { try { if (reply == null) { callback.notImplemented(); } else { try { callback.success(codec.decodeEnvelope(reply)); } catch (FlutterException e) { callback.error(e.code, e.getMessage(), e.details); } } } catch (RuntimeException e) { Log.e(TAG + name, "Failed to handle method call result", e); } } } private final class IncomingMethodCallHandler implements BinaryMessageHandler { private final MethodCallHandler handler; IncomingMethodCallHandler(MethodCallHandler handler) { this.handler = handler; } @Override @UiThread public void onMessage(ByteBuffer message, final BinaryReply reply) { final MethodCall call = codec.decodeMethodCall(message); try { handler.onMethodCall( call, new Result() { @Override public void success(Object result) { reply.reply(codec.encodeSuccessEnvelope(result)); } @Override public void error(String errorCode, String errorMessage, Object errorDetails) { reply.reply(codec.encodeErrorEnvelope(errorCode, errorMessage, errorDetails)); } @Override public void notImplemented() { reply.reply(null); } }); } catch (RuntimeException e) { Log.e(TAG + name, "Failed to handle method call", e); reply.reply( codec.encodeErrorEnvelopeWithStacktrace( "error", e.getMessage(), null, Log.getStackTraceString(e))); } } } }
engine/shell/platform/android/io/flutter/plugin/common/MethodChannel.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/common/MethodChannel.java", "repo_id": "engine", "token_count": 3704 }
297
package io.flutter.plugin.platform; import static io.flutter.Build.API_LEVELS; import android.annotation.TargetApi; import android.graphics.ImageFormat; import android.hardware.HardwareBuffer; import android.media.Image; import android.media.ImageReader; import android.os.Build; import android.os.Handler; import android.view.Surface; import io.flutter.Log; import io.flutter.view.TextureRegistry.ImageTextureEntry; @TargetApi(API_LEVELS.API_29) public class ImageReaderPlatformViewRenderTarget implements PlatformViewRenderTarget { private ImageTextureEntry textureEntry; private ImageReader reader; private int bufferWidth = 0; private int bufferHeight = 0; private static final String TAG = "ImageReaderPlatformViewRenderTarget"; private static final int MAX_IMAGES = 4; private void closeReader() { if (this.reader != null) { // Push a null image, forcing the texture entry to close any cached images. textureEntry.pushImage(null); // Close the reader, which also closes any produced images. this.reader.close(); this.reader = null; } } private final Handler onImageAvailableHandler = new Handler(); private final ImageReader.OnImageAvailableListener onImageAvailableListener = new ImageReader.OnImageAvailableListener() { @Override public void onImageAvailable(ImageReader reader) { Image image = null; try { image = reader.acquireLatestImage(); } catch (IllegalStateException e) { Log.e(TAG, "onImageAvailable acquireLatestImage failed: " + e.toString()); } if (image == null) { return; } textureEntry.pushImage(image); } }; @TargetApi(API_LEVELS.API_33) protected ImageReader createImageReader33() { final ImageReader.Builder builder = new ImageReader.Builder(bufferWidth, bufferHeight); // Allow for double buffering. builder.setMaxImages(MAX_IMAGES); // Use PRIVATE image format so that we can support video decoding. // TODO(johnmccutchan): Should we always use PRIVATE here? It may impact our ability to read // back texture data. If we don't always want to use it, how do we decide when to use it or not? // Perhaps PlatformViews can indicate if they may contain DRM'd content. I need to investigate // how PRIVATE impacts our ability to take screenshots or capture the output of Flutter // application. builder.setImageFormat(ImageFormat.PRIVATE); // Hint that consumed images will only be read by GPU. builder.setUsage(HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE); final ImageReader reader = builder.build(); reader.setOnImageAvailableListener(this.onImageAvailableListener, onImageAvailableHandler); return reader; } @TargetApi(API_LEVELS.API_29) protected ImageReader createImageReader29() { final ImageReader reader = ImageReader.newInstance( bufferWidth, bufferHeight, ImageFormat.PRIVATE, MAX_IMAGES, HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE); reader.setOnImageAvailableListener(this.onImageAvailableListener, onImageAvailableHandler); return reader; } protected ImageReader createImageReader() { if (Build.VERSION.SDK_INT >= API_LEVELS.API_33) { return createImageReader33(); } else if (Build.VERSION.SDK_INT >= API_LEVELS.API_29) { return createImageReader29(); } throw new UnsupportedOperationException( "ImageReaderPlatformViewRenderTarget requires API version 29+"); } public ImageReaderPlatformViewRenderTarget(ImageTextureEntry textureEntry) { if (Build.VERSION.SDK_INT < API_LEVELS.API_29) { throw new UnsupportedOperationException( "ImageReaderPlatformViewRenderTarget requires API version 29+"); } this.textureEntry = textureEntry; } public void resize(int width, int height) { if (this.reader != null && bufferWidth == width && bufferHeight == height) { // No size change. return; } closeReader(); bufferWidth = width; bufferHeight = height; this.reader = createImageReader(); } public int getWidth() { return this.bufferWidth; } public int getHeight() { return this.bufferHeight; } public long getId() { return this.textureEntry.id(); } public void release() { closeReader(); // textureEntry has a finalizer attached. textureEntry = null; } public boolean isReleased() { return this.textureEntry == null; } public Surface getSurface() { return this.reader.getSurface(); } }
engine/shell/platform/android/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTarget.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTarget.java", "repo_id": "engine", "token_count": 1565 }
298
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.platform; import static android.view.View.OnFocusChangeListener; import static io.flutter.Build.API_LEVELS; import android.annotation.TargetApi; import android.content.Context; import android.hardware.display.DisplayManager; import android.hardware.display.VirtualDisplay; import android.os.Build; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.ViewTreeObserver; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; class VirtualDisplayController { private static String TAG = "VirtualDisplayController"; private static VirtualDisplay.Callback callback = new VirtualDisplay.Callback() { @Override public void onPaused() {} @Override public void onResumed() {} }; public static VirtualDisplayController create( Context context, AccessibilityEventsDelegate accessibilityEventsDelegate, PlatformView view, PlatformViewRenderTarget renderTarget, int width, int height, int viewId, Object createParams, OnFocusChangeListener focusChangeListener) { if (width == 0 || height == 0) { return null; } DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); final DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // Virtual Display crashes for some PlatformViews if the width or height is bigger // than the physical screen size. We have tried to clamp or scale down the size to prevent // the crash, but both solutions lead to unwanted behavior because the // AndroidPlatformView(https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/platform_view.dart#L677) widget doesn't // scale or clamp, which leads to a mismatch between the size of the widget and the size of // virtual display. // This mismatch leads to some test failures: https://github.com/flutter/flutter/issues/106750 // TODO(cyanglaz): find a way to prevent the crash without introducing size mistach betewen // virtual display and AndroidPlatformView widget. // https://github.com/flutter/flutter/issues/93115 renderTarget.resize(width, height); int flags = 0; VirtualDisplay virtualDisplay = displayManager.createVirtualDisplay( "flutter-vd#" + viewId, width, height, metrics.densityDpi, renderTarget.getSurface(), flags, callback, null /* handler */); if (virtualDisplay == null) { return null; } VirtualDisplayController controller = new VirtualDisplayController( context, accessibilityEventsDelegate, virtualDisplay, view, renderTarget, focusChangeListener, viewId, createParams); return controller; } @VisibleForTesting SingleViewPresentation presentation; private final Context context; private final AccessibilityEventsDelegate accessibilityEventsDelegate; private final int densityDpi; private final int viewId; private final PlatformViewRenderTarget renderTarget; private final OnFocusChangeListener focusChangeListener; private VirtualDisplay virtualDisplay; private VirtualDisplayController( Context context, AccessibilityEventsDelegate accessibilityEventsDelegate, VirtualDisplay virtualDisplay, PlatformView view, PlatformViewRenderTarget renderTarget, OnFocusChangeListener focusChangeListener, int viewId, Object createParams) { this.context = context; this.accessibilityEventsDelegate = accessibilityEventsDelegate; this.renderTarget = renderTarget; this.focusChangeListener = focusChangeListener; this.viewId = viewId; this.virtualDisplay = virtualDisplay; this.densityDpi = context.getResources().getDisplayMetrics().densityDpi; presentation = new SingleViewPresentation( context, this.virtualDisplay.getDisplay(), view, accessibilityEventsDelegate, viewId, focusChangeListener); presentation.show(); } public int getRenderTargetWidth() { if (renderTarget != null) { return renderTarget.getWidth(); } return 0; } public int getRenderTargetHeight() { if (renderTarget != null) { return renderTarget.getHeight(); } return 0; } public void resize(final int width, final int height, final Runnable onNewSizeFrameAvailable) { // When 'hot reload', although the resize method is triggered, the size of the native View has // not changed. if (width == getRenderTargetWidth() && height == getRenderTargetHeight()) { getView().postDelayed(onNewSizeFrameAvailable, 0); return; } if (Build.VERSION.SDK_INT >= API_LEVELS.API_31) { resize31(getView(), width, height, onNewSizeFrameAvailable); return; } boolean isFocused = getView().isFocused(); final SingleViewPresentation.PresentationState presentationState = presentation.detachState(); // We detach the surface to prevent it being destroyed when releasing the vd. virtualDisplay.setSurface(null); virtualDisplay.release(); final DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); renderTarget.resize(width, height); int flags = 0; virtualDisplay = displayManager.createVirtualDisplay( "flutter-vd#" + viewId, width, height, densityDpi, renderTarget.getSurface(), flags, callback, null /* handler */); final View embeddedView = getView(); // There's a bug in Android version older than O where view tree observer onDrawListeners don't // get properly // merged when attaching to window, as a workaround we register the on draw listener after the // view is attached. embeddedView.addOnAttachStateChangeListener( new View.OnAttachStateChangeListener() { @Override public void onViewAttachedToWindow(View v) { OneTimeOnDrawListener.schedule( embeddedView, new Runnable() { @Override public void run() { // We need some delay here until the frame propagates through the vd surface to // the texture, // 128ms was picked pretty arbitrarily based on trial and error. // As long as we invoke the runnable after a new frame is available we avoid the // scaling jank // described in: https://github.com/flutter/flutter/issues/19572 // We should ideally run onNewSizeFrameAvailable ASAP to make the embedded view // more responsive // following a resize. embeddedView.postDelayed(onNewSizeFrameAvailable, 128); } }); embeddedView.removeOnAttachStateChangeListener(this); } @Override public void onViewDetachedFromWindow(View v) {} }); // Create a new SingleViewPresentation and show() it before we cancel() the existing // presentation. Calling show() and cancel() in this order fixes // https://github.com/flutter/flutter/issues/26345 and maintains seamless transition // of the contents of the presentation. SingleViewPresentation newPresentation = new SingleViewPresentation( context, virtualDisplay.getDisplay(), accessibilityEventsDelegate, presentationState, focusChangeListener, isFocused); newPresentation.show(); presentation.cancel(); presentation = newPresentation; } public void dispose() { // Fix rare crash on HuaWei device described in: https://github.com/flutter/engine/pull/9192 presentation.cancel(); presentation.detachState(); virtualDisplay.release(); renderTarget.release(); } // On Android versions 31+ resizing of a Virtual Display's Presentation is natively supported. @TargetApi(API_LEVELS.API_31) private void resize31( View embeddedView, int width, int height, final Runnable onNewSizeFrameAvailable) { renderTarget.resize(width, height); virtualDisplay.resize(width, height, densityDpi); // Must update the surface to match the renderTarget's current surface. virtualDisplay.setSurface(renderTarget.getSurface()); embeddedView.postDelayed(onNewSizeFrameAvailable, 0); } /** See {@link PlatformView#onFlutterViewAttached(View)} */ /*package*/ void onFlutterViewAttached(@NonNull View flutterView) { if (presentation == null || presentation.getView() == null) { return; } presentation.getView().onFlutterViewAttached(flutterView); } /** See {@link PlatformView#onFlutterViewDetached()} */ /*package*/ void onFlutterViewDetached() { if (presentation == null || presentation.getView() == null) { return; } presentation.getView().onFlutterViewDetached(); } /*package*/ void onInputConnectionLocked() { if (presentation == null || presentation.getView() == null) { return; } presentation.getView().onInputConnectionLocked(); } /*package*/ void onInputConnectionUnlocked() { if (presentation == null || presentation.getView() == null) { return; } presentation.getView().onInputConnectionUnlocked(); } public View getView() { if (presentation == null) return null; PlatformView platformView = presentation.getView(); return platformView.getView(); } /** Dispatches a motion event to the presentation for this controller. */ public void dispatchTouchEvent(MotionEvent event) { if (presentation == null) return; presentation.dispatchTouchEvent(event); } static class OneTimeOnDrawListener implements ViewTreeObserver.OnDrawListener { static void schedule(View view, Runnable runnable) { OneTimeOnDrawListener listener = new OneTimeOnDrawListener(view, runnable); view.getViewTreeObserver().addOnDrawListener(listener); } final View mView; Runnable mOnDrawRunnable; OneTimeOnDrawListener(View view, Runnable onDrawRunnable) { this.mView = view; this.mOnDrawRunnable = onDrawRunnable; } @Override public void onDraw() { if (mOnDrawRunnable == null) { return; } mOnDrawRunnable.run(); mOnDrawRunnable = null; mView.post( new Runnable() { @Override public void run() { mView.getViewTreeObserver().removeOnDrawListener(OneTimeOnDrawListener.this); } }); } } }
engine/shell/platform/android/io/flutter/plugin/platform/VirtualDisplayController.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/VirtualDisplayController.java", "repo_id": "engine", "token_count": 4032 }
299
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.view; import android.graphics.SurfaceTexture; import android.media.Image; import android.view.Surface; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; // TODO(mattcarroll): re-evalute docs in this class and add nullability annotations. /** * Registry of backend textures used with a single {@link FlutterView} instance. Entries may be * embedded into the Flutter view using the <a * href="https://api.flutter.dev/flutter/widgets/Texture-class.html">Texture</a> widget. */ public interface TextureRegistry { /** * Creates and registers a SurfaceProducer texture managed by the Flutter engine. * * @return A SurfaceProducer. */ @NonNull SurfaceProducer createSurfaceProducer(); /** * Creates and registers a SurfaceTexture managed by the Flutter engine. * * @return A SurfaceTextureEntry. */ @NonNull SurfaceTextureEntry createSurfaceTexture(); /** * Registers a SurfaceTexture managed by the Flutter engine. * * @return A SurfaceTextureEntry. */ @NonNull SurfaceTextureEntry registerSurfaceTexture(@NonNull SurfaceTexture surfaceTexture); /** * Creates and registers a texture managed by the Flutter engine. * * @return a ImageTextureEntry. */ @NonNull ImageTextureEntry createImageTexture(); /** * Callback invoked when memory is low. * * <p>Invoke this from {@link android.app.Activity#onTrimMemory(int)}. */ default void onTrimMemory(int level) {} /** An entry in the texture registry. */ interface TextureEntry { /** @return The identity of this texture. */ long id(); /** Deregisters and releases all resources . */ void release(); } /** Uses a Surface to populate the texture. */ @Keep interface SurfaceProducer extends TextureEntry { /** Specify the size of this texture in physical pixels */ void setSize(int width, int height); /** @return The currently specified width (physical pixels) */ int getWidth(); /** @return The currently specified height (physical pixels) */ int getHeight(); /** * Get a Surface that can be used to update the texture contents. * * <p>NOTE: You should not cache the returned surface but instead invoke getSurface each time * you need to draw. The surface may change when the texture is resized or has its format * changed. * * @return a Surface to use for a drawing target for various APIs. */ Surface getSurface(); void scheduleFrame(); }; /** A registry entry for a managed SurfaceTexture. */ @Keep interface SurfaceTextureEntry extends TextureEntry { /** @return The managed SurfaceTexture. */ @NonNull SurfaceTexture surfaceTexture(); /** Set a listener that will be notified when the most recent image has been consumed. */ default void setOnFrameConsumedListener(@Nullable OnFrameConsumedListener listener) {} /** Set a listener that will be notified when a memory pressure warning was forward. */ default void setOnTrimMemoryListener(@Nullable OnTrimMemoryListener listener) {} } @Keep interface ImageTextureEntry extends TextureEntry { /** * Next paint will update texture to use the contents of image. * * <p>NOTE: Caller should not call Image.close() on the pushed image. * * <p>NOTE: In the case that multiple calls to PushFrame occur before the next paint only the * last frame pushed will be used (dropping the missed frames). */ void pushImage(Image image); } /** Listener invoked when the most recent image has been consumed. */ interface OnFrameConsumedListener { /** * This method will to be invoked when the most recent image from the image stream has been * consumed. */ void onFrameConsumed(); } /** Listener invoked when a memory pressure warning was forward. */ interface OnTrimMemoryListener { /** This method will be invoked when a memory pressure warning was forward. */ void onTrimMemory(int level); } @Keep interface ImageConsumer { /** * Retrieve the last Image produced. Drops all previously produced images. * * <p>NOTE: Caller must call Image.close() on returned image. * * @return Image or null. */ @Nullable public Image acquireLatestImage(); } @Keep interface GLTextureConsumer { /** * Retrieve the last GL texture produced. * * @return SurfaceTexture. */ @NonNull public SurfaceTexture getSurfaceTexture(); } }
engine/shell/platform/android/io/flutter/view/TextureRegistry.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/view/TextureRegistry.java", "repo_id": "engine", "token_count": 1423 }
300
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_DELEGATE_PLATFORM_VIEW_ANDROID_DELEGATE_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_DELEGATE_PLATFORM_VIEW_ANDROID_DELEGATE_H_ #include <memory> #include <string> #include <vector> #include "flutter/shell/common/platform_view.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" namespace flutter { class PlatformViewAndroidDelegate { public: explicit PlatformViewAndroidDelegate( std::shared_ptr<PlatformViewAndroidJNI> jni_facade); void UpdateSemantics( const flutter::SemanticsNodeUpdates& update, const flutter::CustomAccessibilityActionUpdates& actions); private: const std::shared_ptr<PlatformViewAndroidJNI> jni_facade_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_DELEGATE_PLATFORM_VIEW_ANDROID_DELEGATE_H_
engine/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h/0
{ "file_path": "engine/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h", "repo_id": "engine", "token_count": 391 }
301
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/surface_texture_external_texture_gl.h" #include <utility> #include "flutter/display_list/effects/dl_color_source.h" #include "impeller/display_list/dl_image_impeller.h" #include "shell/platform/android/surface_texture_external_texture.h" #include "third_party/skia/include/core/SkAlphaType.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkColorType.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h" #include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" namespace flutter { SurfaceTextureExternalTextureGL::SurfaceTextureExternalTextureGL( int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& surface_texture, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) : SurfaceTextureExternalTexture(id, surface_texture, jni_facade) {} SurfaceTextureExternalTextureGL::~SurfaceTextureExternalTextureGL() { if (texture_name_ != 0) { glDeleteTextures(1, &texture_name_); } } void SurfaceTextureExternalTextureGL::ProcessFrame(PaintContext& context, const SkRect& bounds) { if (state_ == AttachmentState::kUninitialized) { // Generate the texture handle. glGenTextures(1, &texture_name_); Attach(texture_name_); } FML_CHECK(state_ == AttachmentState::kAttached); // Updates the texture contents and transformation matrix. Update(); // Create a GrGLTextureInfo textureInfo = {GL_TEXTURE_EXTERNAL_OES, texture_name_, GL_RGBA8_OES}; auto backendTexture = GrBackendTextures::MakeGL(1, 1, skgpu::Mipmapped::kNo, textureInfo); dl_image_ = DlImage::Make(SkImages::BorrowTextureFrom( context.gr_context, backendTexture, kTopLeft_GrSurfaceOrigin, kRGBA_8888_SkColorType, kPremul_SkAlphaType, nullptr)); } void SurfaceTextureExternalTextureGL::Detach() { SurfaceTextureExternalTexture::Detach(); if (texture_name_ != 0) { glDeleteTextures(1, &texture_name_); texture_name_ = 0; } } SurfaceTextureExternalTextureImpellerGL:: SurfaceTextureExternalTextureImpellerGL( const std::shared_ptr<impeller::ContextGLES>& context, int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& surface_texture, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) : SurfaceTextureExternalTexture(id, surface_texture, jni_facade), impeller_context_(context) {} SurfaceTextureExternalTextureImpellerGL:: ~SurfaceTextureExternalTextureImpellerGL() {} void SurfaceTextureExternalTextureImpellerGL::ProcessFrame( PaintContext& context, const SkRect& bounds) { if (state_ == AttachmentState::kUninitialized) { // Generate the texture handle. impeller::TextureDescriptor desc; desc.type = impeller::TextureType::kTextureExternalOES; desc.storage_mode = impeller::StorageMode::kDevicePrivate; desc.format = impeller::PixelFormat::kR8G8B8A8UNormInt; desc.size = {static_cast<int>(bounds.width()), static_cast<int>(bounds.height())}; desc.mip_count = 1; texture_ = std::make_shared<impeller::TextureGLES>( impeller_context_->GetReactor(), desc, impeller::TextureGLES::IsWrapped::kWrapped); texture_->SetCoordinateSystem( impeller::TextureCoordinateSystem::kUploadFromHost); auto maybe_handle = texture_->GetGLHandle(); if (!maybe_handle.has_value()) { FML_LOG(ERROR) << "Could not get GL handle from impeller::TextureGLES!"; return; } Attach(maybe_handle.value()); } FML_CHECK(state_ == AttachmentState::kAttached); // Updates the texture contents and transformation matrix. Update(); dl_image_ = impeller::DlImageImpeller::Make(texture_); } void SurfaceTextureExternalTextureImpellerGL::Detach() { SurfaceTextureExternalTexture::Detach(); texture_.reset(); } } // namespace flutter
engine/shell/platform/android/surface_texture_external_texture_gl.cc/0
{ "file_path": "engine/shell/platform/android/surface_texture_external_texture_gl.cc", "repo_id": "engine", "token_count": 1595 }
302
package io.flutter.embedding.android; import android.content.Intent; import androidx.annotation.NonNull; import org.robolectric.Robolectric; import org.robolectric.android.controller.ActivityController; /** * Creates a {@code FlutterActivity} for use by test code that do not sit within the {@code * io.flutter.embedding.android} package, and offers public access to some package private * properties of {@code FlutterActivity} for testing purposes. */ public class RobolectricFlutterActivity { /** * Creates a {@code FlutterActivity} that is controlled by Robolectric, which otherwise can not be * done in a test outside of the io.flutter.embedding.android package. */ @NonNull public static FlutterActivity createFlutterActivity(@NonNull Intent intent) { ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); return flutterActivity; } /** * Returns a given {@code FlutterActivity}'s {@code BackgroundMode} for use by tests that do not * sit in the {@code io.flutter.embedding.android} package. */ @NonNull public static FlutterActivityLaunchConfigs.BackgroundMode getBackgroundMode( @NonNull FlutterActivity activity) { return activity.getBackgroundMode(); } }
engine/shell/platform/android/test/io/flutter/embedding/android/RobolectricFlutterActivity.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/android/RobolectricFlutterActivity.java", "repo_id": "engine", "token_count": 423 }
303
package io.flutter.embedding.engine.mutatorsstack; import static android.view.View.OnFocusChangeListener; import static junit.framework.TestCase.*; import static org.mockito.Mockito.*; import android.content.Context; import android.graphics.Matrix; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.accessibility.AccessibilityEvent; import android.widget.FrameLayout; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.android.AndroidTouchProcessor; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.annotation.Config; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class FlutterMutatorViewTest { private final Context ctx = ApplicationProvider.getApplicationContext(); @Test public void canDragViews() { final AndroidTouchProcessor touchProcessor = mock(AndroidTouchProcessor.class); final FlutterMutatorView view = new FlutterMutatorView(ctx, 1.0f, touchProcessor); final FlutterMutatorsStack mutatorStack = mock(FlutterMutatorsStack.class); assertTrue(view.onInterceptTouchEvent(mock(MotionEvent.class))); { view.readyToDisplay(mutatorStack, /*left=*/ 1, /*top=*/ 2, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 3, /*top=*/ 4, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 5, /*top=*/ 6, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(3, 4); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 7, /*top=*/ 8, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(7, 8); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } } @Test public void focusChangeListener_hasFocus() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(true); final FlutterMutatorView view = new FlutterMutatorView(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { return viewTreeObserver; } @Override public boolean hasFocus() { return true; } }; final OnFocusChangeListener focusListener = mock(OnFocusChangeListener.class); view.setOnDescendantFocusChangeListener(focusListener); final ArgumentCaptor<ViewTreeObserver.OnGlobalFocusChangeListener> focusListenerCaptor = ArgumentCaptor.forClass(ViewTreeObserver.OnGlobalFocusChangeListener.class); verify(viewTreeObserver).addOnGlobalFocusChangeListener(focusListenerCaptor.capture()); focusListenerCaptor.getValue().onGlobalFocusChanged(null, null); verify(focusListener).onFocusChange(view, true); } @Test public void focusChangeListener_doesNotHaveFocus() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(true); final FlutterMutatorView view = new FlutterMutatorView(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { return viewTreeObserver; } @Override public boolean hasFocus() { return false; } }; final OnFocusChangeListener focusListener = mock(OnFocusChangeListener.class); view.setOnDescendantFocusChangeListener(focusListener); final ArgumentCaptor<ViewTreeObserver.OnGlobalFocusChangeListener> focusListenerCaptor = ArgumentCaptor.forClass(ViewTreeObserver.OnGlobalFocusChangeListener.class); verify(viewTreeObserver).addOnGlobalFocusChangeListener(focusListenerCaptor.capture()); focusListenerCaptor.getValue().onGlobalFocusChanged(null, null); verify(focusListener).onFocusChange(view, false); } @Test public void focusChangeListener_viewTreeObserverIsAliveFalseDoesNotThrow() { final FlutterMutatorView view = new FlutterMutatorView(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(false); return viewTreeObserver; } }; view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); } @Test public void setOnDescendantFocusChangeListener_keepsSingleListener() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(true); final FlutterMutatorView view = new FlutterMutatorView(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { return viewTreeObserver; } }; assertNull(view.activeFocusListener); view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); assertNotNull(view.activeFocusListener); final ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener = view.activeFocusListener; view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); assertNotNull(view.activeFocusListener); verify(viewTreeObserver, times(1)).removeOnGlobalFocusChangeListener(activeFocusListener); } @Test public void unsetOnDescendantFocusChangeListener_removesActiveListener() { final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); when(viewTreeObserver.isAlive()).thenReturn(true); final FlutterMutatorView view = new FlutterMutatorView(ctx) { @Override public ViewTreeObserver getViewTreeObserver() { return viewTreeObserver; } }; assertNull(view.activeFocusListener); view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); assertNotNull(view.activeFocusListener); final ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener = view.activeFocusListener; view.unsetOnDescendantFocusChangeListener(); assertNull(view.activeFocusListener); view.unsetOnDescendantFocusChangeListener(); verify(viewTreeObserver, times(1)).removeOnGlobalFocusChangeListener(activeFocusListener); } @Test @Config( shadows = { ShadowViewGroup.class, }) public void ignoreAccessibilityEvents() { final FlutterMutatorView wrapperView = new FlutterMutatorView(ctx); final View embeddedView = mock(View.class); wrapperView.addView(embeddedView); when(embeddedView.getImportantForAccessibility()) .thenReturn(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); final boolean eventSent = wrapperView.requestSendAccessibilityEvent(embeddedView, mock(AccessibilityEvent.class)); assertFalse(eventSent); } @Implements(ViewGroup.class) public static class ShadowViewGroup extends org.robolectric.shadows.ShadowViewGroup { @Implementation protected boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { return true; } } @Implements(FrameLayout.class) public static class ShadowFrameLayout extends io.flutter.plugin.platform.PlatformViewWrapperTest.ShadowViewGroup {} }
engine/shell/platform/android/test/io/flutter/embedding/engine/mutatorsstack/FlutterMutatorViewTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/mutatorsstack/FlutterMutatorViewTest.java", "repo_id": "engine", "token_count": 3193 }
304
package io.flutter.plugin.common; import static org.junit.Assert.assertNull; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class BinaryCodecTest { @Test public void decodeNull() { assertNull(BinaryCodec.INSTANCE.decodeMessage(null)); } }
engine/shell/platform/android/test/io/flutter/plugin/common/BinaryCodecTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/common/BinaryCodecTest.java", "repo_id": "engine", "token_count": 152 }
305
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.platform; import static android.os.Looper.getMainLooper; import static io.flutter.embedding.engine.systemchannels.PlatformViewsChannel.PlatformViewTouch; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import static org.robolectric.Shadows.shadowOf; import android.app.Presentation; import android.content.Context; import android.content.MutableContextWrapper; import android.content.res.AssetManager; import android.graphics.SurfaceTexture; import android.media.Image; import android.util.SparseArray; import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewParent; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import androidx.annotation.NonNull; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.android.FlutterImageView; import io.flutter.embedding.android.FlutterSurfaceView; import io.flutter.embedding.android.FlutterView; import io.flutter.embedding.android.MotionEventTracker; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.FlutterOverlaySurface; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorView; import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorsStack; import io.flutter.embedding.engine.renderer.FlutterRenderer; import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; import io.flutter.embedding.engine.systemchannels.PlatformViewsChannel; import io.flutter.embedding.engine.systemchannels.PlatformViewsChannel.PlatformViewTouch; import io.flutter.embedding.engine.systemchannels.SettingsChannel; import io.flutter.embedding.engine.systemchannels.TextInputChannel; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.StandardMessageCodec; import io.flutter.plugin.common.StandardMethodCodec; import io.flutter.plugin.localization.LocalizationPlugin; import io.flutter.view.TextureRegistry; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.annotation.Config; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.shadows.ShadowDialog; import org.robolectric.shadows.ShadowSurfaceView; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class PlatformViewsControllerTest { // An implementation of PlatformView that counts invocations of its lifecycle callbacks. class CountingPlatformView implements PlatformView { static final String VIEW_TYPE_ID = "CountingPlatformView"; private View view; public CountingPlatformView(Context context) { view = new SurfaceView(context); } public int disposeCalls = 0; public int attachCalls = 0; public int detachCalls = 0; @Override public void dispose() { // We have been removed from the view hierarhy before the call to dispose. assertNull(view.getParent()); disposeCalls++; } @Override public View getView() { return view; } @Override public void onFlutterViewAttached(View flutterView) { attachCalls++; } @Override public void onFlutterViewDetached() { detachCalls++; } } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void itRemovesPlatformViewBeforeDiposeIsCalled() { PlatformViewsController platformViewsController = new PlatformViewsController(); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Get the platform view registry. PlatformViewRegistry registry = platformViewsController.getRegistry(); // Register a factory for our platform view. registry.registerViewFactory( CountingPlatformView.VIEW_TYPE_ID, new PlatformViewFactory(StandardMessageCodec.INSTANCE) { @Override public PlatformView create(Context context, int viewId, Object args) { return new CountingPlatformView(context); } }); // Create the platform view. int viewId = 0; final PlatformViewsChannel.PlatformViewCreationRequest request = new PlatformViewsChannel.PlatformViewCreationRequest( viewId, CountingPlatformView.VIEW_TYPE_ID, 0, 0, 128, 128, View.LAYOUT_DIRECTION_LTR, null); PlatformView pView = platformViewsController.createPlatformView(request, true); assertTrue(pView instanceof CountingPlatformView); CountingPlatformView cpv = (CountingPlatformView) pView; platformViewsController.configureForTextureLayerComposition(pView, request); assertEquals(0, cpv.disposeCalls); platformViewsController.disposePlatformView(viewId); assertEquals(1, cpv.disposeCalls); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void itNotifiesPlatformViewsOfEngineAttachmentAndDetachment() { PlatformViewsController platformViewsController = new PlatformViewsController(); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Get the platform view registry. PlatformViewRegistry registry = platformViewsController.getRegistry(); // Register a factory for our platform view. registry.registerViewFactory( CountingPlatformView.VIEW_TYPE_ID, new PlatformViewFactory(StandardMessageCodec.INSTANCE) { @Override public PlatformView create(Context context, int viewId, Object args) { return new CountingPlatformView(context); } }); // Create the platform view. int viewId = 0; final PlatformViewsChannel.PlatformViewCreationRequest request = new PlatformViewsChannel.PlatformViewCreationRequest( viewId, CountingPlatformView.VIEW_TYPE_ID, 0, 0, 128, 128, View.LAYOUT_DIRECTION_LTR, null); PlatformView pView = platformViewsController.createPlatformView(request, true); assertTrue(pView instanceof CountingPlatformView); CountingPlatformView cpv = (CountingPlatformView) pView; assertEquals(1, cpv.attachCalls); assertEquals(0, cpv.detachCalls); assertEquals(0, cpv.disposeCalls); platformViewsController.detachFromView(); assertEquals(1, cpv.attachCalls); assertEquals(1, cpv.detachCalls); assertEquals(0, cpv.disposeCalls); platformViewsController.disposePlatformView(viewId); } @Ignore @Test public void itCancelsOldPresentationOnResize() { // Setup test structure. // Create a fake View that represents the View that renders a Flutter UI. View fakeFlutterView = new View(ApplicationProvider.getApplicationContext()); // Create fake VirtualDisplayControllers. This requires internal knowledge of // PlatformViewsController. We know that all PlatformViewsController does is // forward view attachment/detachment calls to it's VirtualDisplayControllers. // // TODO(mattcarroll): once PlatformViewsController is refactored into testable // pieces, remove this test and avoid verifying private behavior. VirtualDisplayController fakeVdController1 = mock(VirtualDisplayController.class); SingleViewPresentation presentation = fakeVdController1.presentation; fakeVdController1.resize(10, 10, null); assertEquals(fakeVdController1.presentation != presentation, true); assertEquals(presentation.isShowing(), false); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void virtualDisplay_handlesResizeResponseWithoutContext() { final int platformViewId = 0; FlutterView fakeFlutterView = new FlutterView(ApplicationProvider.getApplicationContext()); VirtualDisplayController fakeVdController = mock(VirtualDisplayController.class); PlatformViewsController platformViewsController = new PlatformViewsController(); platformViewsController.vdControllers.put(platformViewId, fakeVdController); platformViewsController.attachToView(fakeFlutterView); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); resize(jni, platformViewsController, platformViewId, 10.0, 20.0); ArgumentCaptor<Runnable> resizeCallbackCaptor = ArgumentCaptor.forClass(Runnable.class); verify(fakeVdController, times(1)).resize(anyInt(), anyInt(), resizeCallbackCaptor.capture()); // Simulate a detach call before the resize completes. platformViewsController.detach(); // Trigger the callback to ensure that it doesn't crash. resizeCallbackCaptor.getValue().run(); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void virtualDisplay_ensureDisposeVirtualDisplayController() { final int platformViewId = 0; FlutterView fakeFlutterView = new FlutterView(ApplicationProvider.getApplicationContext()); VirtualDisplayController fakeVdController = mock(VirtualDisplayController.class); PlatformViewsController platformViewsController = new PlatformViewsController(); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); platformViewsController.attachToView(fakeFlutterView); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); Context context = ApplicationProvider.getApplicationContext(); View androidView = new View(context); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); platformViewsController.vdControllers.put(platformViewId, fakeVdController); // Simulate dispose call from the framework. disposePlatformView(jni, platformViewsController, platformViewId); // Ensure VirtualDisplayController.dispose() is called verify(fakeVdController, times(1)).dispose(); } @Test public void itUsesActionEventTypeFromFrameworkEventForVirtualDisplays() { MotionEventTracker motionEventTracker = MotionEventTracker.getInstance(); PlatformViewsController platformViewsController = new PlatformViewsController(); MotionEvent original = MotionEvent.obtain( 100, // downTime 100, // eventTime 1, // action 0, // x 0, // y 0 // metaState ); // track an event that will later get passed to us from framework MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original); PlatformViewTouch frameWorkTouch = new PlatformViewTouch( 0, // viewId original.getDownTime(), original.getEventTime(), 2, // action 1, // pointerCount Arrays.asList(Arrays.asList(0, 0)), // pointer properties Arrays.asList(Arrays.asList(0., 1., 2., 3., 4., 5., 6., 7., 8.)), // pointer coords original.getMetaState(), original.getButtonState(), original.getXPrecision(), original.getYPrecision(), original.getDeviceId(), original.getEdgeFlags(), original.getSource(), original.getFlags(), motionEventId.getId()); MotionEvent resolvedEvent = platformViewsController.toMotionEvent( 1, // density frameWorkTouch, true // usingVirtualDisplays ); assertEquals(resolvedEvent.getAction(), frameWorkTouch.action); assertNotEquals(resolvedEvent.getAction(), original.getAction()); } @Test public void itUsesActionEventTypeFromFrameworkEventAsActionChanged() { MotionEventTracker motionEventTracker = MotionEventTracker.getInstance(); PlatformViewsController platformViewsController = new PlatformViewsController(); MotionEvent original = MotionEvent.obtain( 10, // downTime 10, // eventTime 261, // action 0, // x 0, // y 0 // metaState ); MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original); PlatformViewTouch frameWorkTouch = new PlatformViewTouch( 0, // viewId original.getDownTime(), original.getEventTime(), 0, // action 1, // pointerCount Arrays.asList(Arrays.asList(0, 0)), // pointer properties Arrays.asList(Arrays.asList(0., 1., 2., 3., 4., 5., 6., 7., 8.)), // pointer coords original.getMetaState(), original.getButtonState(), original.getXPrecision(), original.getYPrecision(), original.getDeviceId(), original.getEdgeFlags(), original.getSource(), original.getFlags(), motionEventId.getId()); MotionEvent resolvedEvent = platformViewsController.toMotionEvent( 1, // density frameWorkTouch, false // usingVirtualDisplays ); assertEquals(resolvedEvent.getAction(), original.getAction()); assertNotEquals(resolvedEvent.getAction(), frameWorkTouch.action); } @Ignore @Test public void itUsesActionEventTypeFromMotionEventForHybridPlatformViews() { MotionEventTracker motionEventTracker = MotionEventTracker.getInstance(); PlatformViewsController platformViewsController = new PlatformViewsController(); MotionEvent original = MotionEvent.obtain( 100, // downTime 100, // eventTime 1, // action 0, // x 0, // y 0 // metaState ); // track an event that will later get passed to us from framework MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original); PlatformViewTouch frameWorkTouch = new PlatformViewTouch( 0, // viewId original.getDownTime(), original.getEventTime(), 2, // action 1, // pointerCount Arrays.asList(Arrays.asList(0, 0)), // pointer properties Arrays.asList(Arrays.asList(0., 1., 2., 3., 4., 5., 6., 7., 8.)), // pointer coords original.getMetaState(), original.getButtonState(), original.getXPrecision(), original.getYPrecision(), original.getDeviceId(), original.getEdgeFlags(), original.getSource(), original.getFlags(), motionEventId.getId()); MotionEvent resolvedEvent = platformViewsController.toMotionEvent( /*density=*/ 1, frameWorkTouch, /*usingVirtualDisplay=*/ false); assertEquals(resolvedEvent.getAction(), frameWorkTouch.action); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void getPlatformViewById_hybridComposition() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); platformViewsController.initializePlatformViewIfNeeded(platformViewId); View resultAndroidView = platformViewsController.getPlatformViewById(platformViewId); assertNotNull(resultAndroidView); assertEquals(resultAndroidView, androidView); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createPlatformViewMessage_initializesAndroidView() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(mock(View.class)); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); verify(viewFactory, times(1)).create(any(), eq(platformViewId), any()); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createPlatformViewMessage_wrapsContextForVirtualDisplay() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(mock(View.class)); ArgumentCaptor<Context> passedContext = ArgumentCaptor.forClass(Context.class); when(viewFactory.create(passedContext.capture(), eq(platformViewId), any())) .thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); assertTrue(passedContext.getValue() instanceof MutableContextWrapper); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createPlatformViewMessage_doesNotWrapContextForHybrid() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(mock(View.class)); ArgumentCaptor<Context> passedContext = ArgumentCaptor.forClass(Context.class); when(viewFactory.create(passedContext.capture(), eq(platformViewId), any())) .thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); assertFalse(passedContext.getValue() instanceof MutableContextWrapper); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createPlatformViewMessage_setsAndroidViewLayoutDirection() { PlatformViewsController platformViewsController = new PlatformViewsController(); platformViewsController.setSoftwareRendering(true); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); verify(androidView, times(1)).setLayoutDirection(0); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createPlatformViewMessage_setsAndroidViewSize() { PlatformViewsController platformViewsController = new PlatformViewsController(); platformViewsController.setSoftwareRendering(true); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); ArgumentCaptor<FrameLayout.LayoutParams> layoutParamsCaptor = ArgumentCaptor.forClass(FrameLayout.LayoutParams.class); verify(androidView, times(2)).setLayoutParams(layoutParamsCaptor.capture()); List<FrameLayout.LayoutParams> capturedLayoutParams = layoutParamsCaptor.getAllValues(); assertEquals(capturedLayoutParams.get(0).width, 1); assertEquals(capturedLayoutParams.get(0).height, 1); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createPlatformViewMessage_disablesAccessibility() { PlatformViewsController platformViewsController = new PlatformViewsController(); platformViewsController.setSoftwareRendering(true); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); verify(androidView, times(1)) .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createPlatformViewMessage_throwsIfViewIsNull() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(null); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); assertEquals(ShadowFlutterJNI.getResponses().size(), 1); assertThrows( IllegalStateException.class, () -> { platformViewsController.initializePlatformViewIfNeeded(platformViewId); }); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createHybridPlatformViewMessage_throwsIfViewIsNull() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(null); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); assertEquals(ShadowFlutterJNI.getResponses().size(), 1); assertThrows( IllegalStateException.class, () -> { platformViewsController.initializePlatformViewIfNeeded(platformViewId); }); } @Test @Config( shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class, ShadowPresentation.class}) public void onDetachedFromJNI_clearsPlatformViewContext() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); SurfaceView pv = mock(SurfaceView.class); when(pv.getContext()).thenReturn(mock(MutableContextWrapper.class)); when(pv.getLayoutParams()).thenReturn(new LayoutParams(1, 1)); when(platformView.getView()).thenReturn(pv); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); assertFalse(platformViewsController.contextToEmbeddedView.isEmpty()); platformViewsController.onDetachedFromJNI(); assertTrue(platformViewsController.contextToEmbeddedView.isEmpty()); } @Test @Config( shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class, ShadowPresentation.class}) public void onPreEngineRestart_clearsPlatformViewContext() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); SurfaceView pv = mock(SurfaceView.class); when(pv.getContext()).thenReturn(mock(MutableContextWrapper.class)); when(pv.getLayoutParams()).thenReturn(new LayoutParams(1, 1)); when(platformView.getView()).thenReturn(pv); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); assertFalse(platformViewsController.contextToEmbeddedView.isEmpty()); platformViewsController.onDetachedFromJNI(); assertTrue(platformViewsController.contextToEmbeddedView.isEmpty()); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createPlatformViewMessage_throwsIfViewHasParent() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); View androidView = mock(View.class); when(androidView.getParent()).thenReturn(mock(ViewParent.class)); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); assertEquals(ShadowFlutterJNI.getResponses().size(), 1); assertThrows( IllegalStateException.class, () -> { platformViewsController.initializePlatformViewIfNeeded(platformViewId); }); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void createHybridPlatformViewMessage_throwsIfViewHasParent() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); View androidView = mock(View.class); when(androidView.getParent()).thenReturn(mock(ViewParent.class)); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); assertEquals(ShadowFlutterJNI.getResponses().size(), 1); assertThrows( IllegalStateException.class, () -> { platformViewsController.initializePlatformViewIfNeeded(platformViewId); }); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void setPlatformViewDirection_throwIfPlatformViewNotFound() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); final View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); verify(androidView, never()).setLayoutDirection(anyInt()); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); assertEquals(ShadowFlutterJNI.getResponses().size(), 1); // Simulate set direction call from the framework. setLayoutDirection(jni, platformViewsController, platformViewId, 1); verify(androidView, times(1)).setLayoutDirection(1); // The limit value of reply message will be equal to 2 if the layout direction is set // successfully, otherwise it will be much more than 2 due to the reply message contains // an error message wrapped with exception detail information. assertEquals(ShadowFlutterJNI.getResponses().get(0).limit(), 2); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void resizeAndroidView() { PlatformViewsController platformViewsController = new PlatformViewsController(); platformViewsController.setSoftwareRendering(true); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); final View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); reset(androidView); when(androidView.getLayoutParams()).thenReturn(new FrameLayout.LayoutParams(0, 0)); // Simulate a resize call from the framework. resize(jni, platformViewsController, platformViewId, 10.0, 20.0); ArgumentCaptor<FrameLayout.LayoutParams> layoutParamsCaptor = ArgumentCaptor.forClass(FrameLayout.LayoutParams.class); verify(androidView, times(1)).setLayoutParams(layoutParamsCaptor.capture()); assertEquals(layoutParamsCaptor.getValue().width, 10); assertEquals(layoutParamsCaptor.getValue().height, 20); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void disposeAndroidView_hybridComposition() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); Context context = ApplicationProvider.getApplicationContext(); View androidView = new View(context); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); platformViewsController.initializePlatformViewIfNeeded(platformViewId); assertNotNull(androidView.getParent()); assertTrue(androidView.getParent() instanceof FlutterMutatorView); // Simulate dispose call from the framework. disposePlatformView(jni, platformViewsController, platformViewId); assertNull(androidView.getParent()); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); platformViewsController.initializePlatformViewIfNeeded(platformViewId); assertNotNull(androidView.getParent()); assertTrue(androidView.getParent() instanceof FlutterMutatorView); verify(platformView, times(1)).dispose(); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void disposeNullAndroidView() { PlatformViewsController platformViewsController = new PlatformViewsController(); int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); attach(jni, platformViewsController); // Simulate create call from the framework. createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); platformViewsController.initializePlatformViewIfNeeded(platformViewId); when(platformView.getView()).thenReturn(null); // Simulate dispose call from the framework. disposePlatformView(jni, platformViewsController, platformViewId); verify(platformView, times(1)).dispose(); } @Test @Config( shadows = { ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class }) public void onEndFrame_destroysOverlaySurfaceAfterFrameOnFlutterSurfaceView() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(mock(View.class)); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); attach(jni, platformViewsController); jni.onFirstFrame(); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); // Produce a frame that displays a platform view and an overlay surface. platformViewsController.onBeginFrame(); platformViewsController.onDisplayPlatformView( platformViewId, /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10, /* viewWidth=*/ 10, /* viewHeight=*/ 10, /* mutatorsStack=*/ new FlutterMutatorsStack()); final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); when(overlayImageView.acquireLatestImage()).thenReturn(true); final FlutterOverlaySurface overlaySurface = platformViewsController.createOverlaySurface(overlayImageView); platformViewsController.onDisplayOverlaySurface( overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); platformViewsController.onEndFrame(); // Simulate first frame from the framework. jni.onFirstFrame(); verify(overlayImageView, never()).detachFromRenderer(); // Produce a frame that doesn't display platform views. platformViewsController.onBeginFrame(); platformViewsController.onEndFrame(); shadowOf(getMainLooper()).idle(); verify(overlayImageView, times(1)).detachFromRenderer(); } @Test @Config(shadows = {ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class}) public void onEndFrame_removesPlatformView() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); final View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); attach(jni, platformViewsController); jni.onFirstFrame(); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); // Simulate first frame from the framework. jni.onFirstFrame(); platformViewsController.onBeginFrame(); platformViewsController.onEndFrame(); verify(androidView, never()).setVisibility(View.GONE); final ViewParent parentView = mock(ViewParent.class); when(androidView.getParent()).thenReturn(parentView); } @Test @Config( shadows = { ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class }) public void onEndFrame_removesPlatformViewParent() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); final View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); final FlutterView flutterView = attach(jni, platformViewsController); jni.onFirstFrame(); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); platformViewsController.initializePlatformViewIfNeeded(platformViewId); assertEquals(flutterView.getChildCount(), 2); // Simulate first frame from the framework. jni.onFirstFrame(); platformViewsController.onBeginFrame(); platformViewsController.onEndFrame(); // Simulate dispose call from the framework. disposePlatformView(jni, platformViewsController, platformViewId); assertEquals(flutterView.getChildCount(), 1); } @Test @Config( shadows = { ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class }) public void detach_destroysOverlaySurfaces() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(mock(View.class)); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); attach(jni, platformViewsController); jni.onFirstFrame(); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); // Produce a frame that displays a platform view and an overlay surface. platformViewsController.onBeginFrame(); platformViewsController.onDisplayPlatformView( platformViewId, /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10, /* viewWidth=*/ 10, /* viewHeight=*/ 10, /* mutatorsStack=*/ new FlutterMutatorsStack()); final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); when(overlayImageView.acquireLatestImage()).thenReturn(true); final FlutterOverlaySurface overlaySurface = platformViewsController.createOverlaySurface(overlayImageView); // This is OK. platformViewsController.onDisplayOverlaySurface( overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); platformViewsController.detach(); verify(overlayImageView, times(1)).closeImageReader(); verify(overlayImageView, times(1)).detachFromRenderer(); } @Test @Config(shadows = {ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class}) public void detachFromView_removesAndDestroysOverlayViews() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(mock(View.class)); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); attach(jni, platformViewsController); final FlutterView flutterView = mock(FlutterView.class); platformViewsController.attachToView(flutterView); final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); when(overlayImageView.acquireLatestImage()).thenReturn(true); final FlutterOverlaySurface overlaySurface = platformViewsController.createOverlaySurface(overlayImageView); platformViewsController.onDisplayOverlaySurface( overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); platformViewsController.detachFromView(); verify(overlayImageView, times(1)).closeImageReader(); verify(overlayImageView, times(1)).detachFromRenderer(); verify(flutterView, times(1)).removeView(overlayImageView); } @Test @Config(shadows = {ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class}) public void destroyOverlaySurfaces_doesNotThrowIfFlutterViewIsDetached() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(mock(View.class)); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); attach(jni, platformViewsController); final FlutterView flutterView = mock(FlutterView.class); platformViewsController.attachToView(flutterView); final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); when(overlayImageView.acquireLatestImage()).thenReturn(true); final FlutterOverlaySurface overlaySurface = platformViewsController.createOverlaySurface(overlayImageView); platformViewsController.onDisplayOverlaySurface( overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); platformViewsController.detachFromView(); platformViewsController.destroyOverlaySurfaces(); verify(overlayImageView, times(1)).closeImageReader(); verify(overlayImageView, times(1)).detachFromRenderer(); } @Test @Config(shadows = {ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class}) public void destroyOverlaySurfaces_doesNotRemoveOverlayView() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); when(platformView.getView()).thenReturn(mock(View.class)); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); attach(jni, platformViewsController); final FlutterView flutterView = mock(FlutterView.class); platformViewsController.attachToView(flutterView); final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); when(overlayImageView.acquireLatestImage()).thenReturn(true); final FlutterOverlaySurface overlaySurface = platformViewsController.createOverlaySurface(overlayImageView); platformViewsController.onDisplayOverlaySurface( overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); platformViewsController.destroyOverlaySurfaces(); verify(flutterView, never()).removeView(overlayImageView); } @Test public void checkInputConnectionProxy_falseIfViewIsNull() { final PlatformViewsController platformViewsController = new PlatformViewsController(); boolean shouldProxying = platformViewsController.checkInputConnectionProxy(null); assertFalse(shouldProxying); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void convertPlatformViewRenderSurfaceAsDefault() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); final View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); final FlutterView flutterView = attach(jni, platformViewsController); jni.onFirstFrame(); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); // Produce a frame that displays a platform view and an overlay surface. platformViewsController.onBeginFrame(); platformViewsController.onDisplayPlatformView( platformViewId, /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10, /* viewWidth=*/ 10, /* viewHeight=*/ 10, /* mutatorsStack=*/ new FlutterMutatorsStack()); assertEquals(flutterView.getChildCount(), 3); final View view = flutterView.getChildAt(1); assertTrue(view instanceof FlutterImageView); // Simulate dispose call from the framework. disposePlatformView(jni, platformViewsController, platformViewId); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void dontConverRenderSurfaceWhenFlagIsTrue() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); final View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); final FlutterView flutterView = attach(jni, platformViewsController); jni.onFirstFrame(); // Simulate setting render surface conversion flag. synchronizeToNativeViewHierarchy(jni, platformViewsController, false); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); // Produce a frame that displays a platform view and an overlay surface. platformViewsController.onBeginFrame(); platformViewsController.onDisplayPlatformView( platformViewId, /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10, /* viewWidth=*/ 10, /* viewHeight=*/ 10, /* mutatorsStack=*/ new FlutterMutatorsStack()); assertEquals(flutterView.getChildCount(), 2); assertTrue(!(flutterView.getChildAt(0) instanceof PlatformOverlayView)); assertTrue(flutterView.getChildAt(1) instanceof FlutterMutatorView); // Simulate dispose call from the framework. disposePlatformView(jni, platformViewsController, platformViewId); } @Test @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) public void reattachToFlutterView() { PlatformViewsController platformViewsController = new PlatformViewsController(); platformViewsController.setSoftwareRendering(true); int platformViewId = 100; assertNull(platformViewsController.getPlatformViewById(platformViewId)); PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); PlatformView platformView = mock(PlatformView.class); View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); FlutterJNI jni = new FlutterJNI(); FlutterView initFlutterView = mock(FlutterView.class); attachToFlutterView(jni, platformViewsController, initFlutterView); createPlatformView( jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); verify(initFlutterView, times(1)).addView(any(PlatformViewWrapper.class)); platformViewsController.detachFromView(); verify(initFlutterView, times(1)).removeView(any(PlatformViewWrapper.class)); FlutterView newFlutterView = mock(FlutterView.class); platformViewsController.attachToView(newFlutterView); verify(newFlutterView, times(1)).addView(any(PlatformViewWrapper.class)); } @Config( shadows = { ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class }) public void revertImageViewAndRemoveImageView() { final PlatformViewsController platformViewsController = new PlatformViewsController(); final int platformViewId = 0; assertNull(platformViewsController.getPlatformViewById(platformViewId)); final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); final PlatformView platformView = mock(PlatformView.class); final View androidView = mock(View.class); when(platformView.getView()).thenReturn(androidView); when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); final FlutterJNI jni = new FlutterJNI(); jni.attachToNative(); final FlutterView flutterView = attach(jni, platformViewsController); jni.onFirstFrame(); // Simulate create call from the framework. createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); // The simulation creates an Overlay on top of the PlatformView // This is going to be called `flutterView.convertToImageView` platformViewsController.createOverlaySurface(); platformViewsController.onDisplayOverlaySurface(platformViewId, 0, 0, 10, 10); // This will contain three views: Background ImageView、PlatformView、Overlay ImageView assertEquals(flutterView.getChildCount(), 3); FlutterImageView imageView = flutterView.getCurrentImageSurface(); // Make sure the ImageView is inside the current FlutterView. assertTrue(imageView != null); assertTrue(flutterView.indexOfChild(imageView) != -1); // Make sure the overlayView is inside the current FlutterView assertTrue(platformViewsController.getOverlayLayerViews().size() != 0); PlatformOverlayView overlayView = platformViewsController.getOverlayLayerViews().get(0); assertTrue(overlayView != null); assertTrue(flutterView.indexOfChild(overlayView) != -1); // Simulate in a new frame, there's no PlatformView, which is called // `flutterView.revertImageView`. And register a `FlutterUiDisplayListener` callback. // During callback execution it will invoke `flutterImageView.detachFromRenderer()`. platformViewsController.onBeginFrame(); platformViewsController.onEndFrame(); // Invoke all registered `FlutterUiDisplayListener` callback jni.onFirstFrame(); assertEquals(null, flutterView.getCurrentImageSurface()); // Make sure the background ImageVIew is not in the FlutterView assertTrue(flutterView.indexOfChild(imageView) == -1); // Make sure the overlay ImageVIew is not in the FlutterView assertTrue(flutterView.indexOfChild(overlayView) == -1); } private static ByteBuffer encodeMethodCall(MethodCall call) { final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeMethodCall(call); buffer.rewind(); return buffer; } private static void createPlatformView( FlutterJNI jni, PlatformViewsController platformViewsController, int platformViewId, String viewType, boolean hybrid) { final Map<String, Object> args = new HashMap<>(); args.put("hybrid", hybrid); args.put("id", platformViewId); args.put("viewType", viewType); args.put("direction", 0); args.put("width", 1.0); args.put("height", 1.0); final MethodCall platformCreateMethodCall = new MethodCall("create", args); jni.handlePlatformMessage( "flutter/platform_views", encodeMethodCall(platformCreateMethodCall), /*replyId=*/ 0, /*messageData=*/ 0); } private static void setLayoutDirection( FlutterJNI jni, PlatformViewsController platformViewsController, int platformViewId, int direction) { final Map<String, Object> args = new HashMap<>(); args.put("id", platformViewId); args.put("direction", direction); final MethodCall platformSetDirectionMethodCall = new MethodCall("setDirection", args); jni.handlePlatformMessage( "flutter/platform_views", encodeMethodCall(platformSetDirectionMethodCall), /*replyId=*/ 0, /*messageData=*/ 0); } private static void resize( FlutterJNI jni, PlatformViewsController platformViewsController, int platformViewId, double width, double height) { final Map<String, Object> args = new HashMap<>(); args.put("id", platformViewId); args.put("width", width); args.put("height", height); final MethodCall platformResizeMethodCall = new MethodCall("resize", args); jni.handlePlatformMessage( "flutter/platform_views", encodeMethodCall(platformResizeMethodCall), /*replyId=*/ 0, /*messageData=*/ 0); } private static void disposePlatformView( FlutterJNI jni, PlatformViewsController platformViewsController, int platformViewId) { final Map<String, Object> args = new HashMap<>(); args.put("hybrid", true); args.put("id", platformViewId); final MethodCall platformDisposeMethodCall = new MethodCall("dispose", args); jni.handlePlatformMessage( "flutter/platform_views", encodeMethodCall(platformDisposeMethodCall), /*replyId=*/ 0, /*messageData=*/ 0); } private static void synchronizeToNativeViewHierarchy( FlutterJNI jni, PlatformViewsController platformViewsController, boolean yes) { final MethodCall convertMethodCall = new MethodCall("synchronizeToNativeViewHierarchy", yes); jni.handlePlatformMessage( "flutter/platform_views", encodeMethodCall(convertMethodCall), /*replyId=*/ 0, /*messageData=*/ 0); } private static FlutterView attach( FlutterJNI jni, PlatformViewsController platformViewsController) { final Context context = ApplicationProvider.getApplicationContext(); final FlutterView flutterView = new FlutterView(context, new FlutterSurfaceView(context)) { @Override public FlutterImageView createImageView() { final FlutterImageView view = mock(FlutterImageView.class); when(view.acquireLatestImage()).thenReturn(true); return mock(FlutterImageView.class); } }; attachToFlutterView(jni, platformViewsController, flutterView); return flutterView; } private static void attachToFlutterView( FlutterJNI jni, PlatformViewsController platformViewsController, FlutterView flutterView) { final DartExecutor executor = new DartExecutor(jni, mock(AssetManager.class)); executor.onAttachedToJNI(); final Context context = ApplicationProvider.getApplicationContext(); final TextureRegistry registry = new TextureRegistry() { public void TextureRegistry() {} @Override public SurfaceTextureEntry createSurfaceTexture() { return registerSurfaceTexture(mock(SurfaceTexture.class)); } @Override public SurfaceTextureEntry registerSurfaceTexture(SurfaceTexture surfaceTexture) { return new SurfaceTextureEntry() { @NonNull @Override public SurfaceTexture surfaceTexture() { return mock(SurfaceTexture.class); } @Override public long id() { return 0; } @Override public void release() {} }; } @Override public ImageTextureEntry createImageTexture() { return new ImageTextureEntry() { @Override public long id() { return 0; } @Override public void release() {} @Override public void pushImage(Image image) {} }; } @Override public SurfaceProducer createSurfaceProducer() { return new SurfaceProducer() { @Override public long id() { return 0; } @Override public void release() {} @Override public int getWidth() { return 0; } @Override public int getHeight() { return 0; } @Override public void setSize(int width, int height) {} @Override public Surface getSurface() { return null; } public void scheduleFrame() {} }; } }; platformViewsController.attach(context, registry, executor); final FlutterEngine engine = mock(FlutterEngine.class); when(engine.getRenderer()).thenReturn(new FlutterRenderer(jni)); when(engine.getMouseCursorChannel()).thenReturn(mock(MouseCursorChannel.class)); when(engine.getTextInputChannel()).thenReturn(mock(TextInputChannel.class)); when(engine.getSettingsChannel()).thenReturn(new SettingsChannel(executor)); when(engine.getPlatformViewsController()).thenReturn(platformViewsController); when(engine.getLocalizationPlugin()).thenReturn(mock(LocalizationPlugin.class)); when(engine.getAccessibilityChannel()).thenReturn(mock(AccessibilityChannel.class)); when(engine.getDartExecutor()).thenReturn(executor); flutterView.attachToFlutterEngine(engine); platformViewsController.attachToView(flutterView); } /** * For convenience when writing tests, this allows us to make fake messages from Flutter via * Platform Channels. Typically those calls happen on the ui thread which dispatches to the * platform thread. Since tests run on the platform thread it makes it difficult to test without * this, but isn't technically required. */ @Implements(io.flutter.embedding.engine.dart.PlatformTaskQueue.class) public static class ShadowPlatformTaskQueue { @Implementation public void dispatch(Runnable runnable) { runnable.run(); } } /** * The shadow class of {@link Presentation} to simulate Presentation showing logic. * * <p>Robolectric doesn't support VirtualDisplay creating correctly now, so this shadow class is * used to simulate custom logic for Presentation. */ @Implements(Presentation.class) public static class ShadowPresentation extends ShadowDialog { private boolean isShowing = false; public ShadowPresentation() {} @Implementation protected void show() { isShowing = true; } @Implementation protected void dismiss() { isShowing = false; } @Implementation protected boolean isShowing() { return isShowing; } } @Implements(FlutterJNI.class) public static class ShadowFlutterJNI { private static SparseArray<ByteBuffer> replies = new SparseArray<>(); public ShadowFlutterJNI() {} @Implementation public boolean getIsSoftwareRenderingEnabled() { return false; } @Implementation public long performNativeAttach(FlutterJNI flutterJNI) { return 1; } @Implementation public void dispatchPlatformMessage( String channel, ByteBuffer message, int position, int responseId) {} @Implementation public void onSurfaceCreated(Surface surface) {} @Implementation public void onSurfaceDestroyed() {} @Implementation public void onSurfaceWindowChanged(Surface surface) {} @Implementation public void setViewportMetrics( float devicePixelRatio, int physicalWidth, int physicalHeight, int physicalPaddingTop, int physicalPaddingRight, int physicalPaddingBottom, int physicalPaddingLeft, int physicalViewInsetTop, int physicalViewInsetRight, int physicalViewInsetBottom, int physicalViewInsetLeft, int systemGestureInsetTop, int systemGestureInsetRight, int systemGestureInsetBottom, int systemGestureInsetLeft, int physicalTouchSlop, int[] displayFeaturesBounds, int[] displayFeaturesType, int[] displayFeaturesState) {} @Implementation public void invokePlatformMessageResponseCallback( int responseId, ByteBuffer message, int position) { replies.put(responseId, message); } public static SparseArray<ByteBuffer> getResponses() { return replies; } } @Implements(SurfaceView.class) public static class ShadowFlutterSurfaceView extends ShadowSurfaceView { private final FakeSurfaceHolder holder = new FakeSurfaceHolder(); public static class FakeSurfaceHolder extends ShadowSurfaceView.FakeSurfaceHolder { private final Surface surface = mock(Surface.class); public Surface getSurface() { return surface; } @Implementation public void addCallback(SurfaceHolder.Callback callback) { callback.surfaceCreated(this); } } public ShadowFlutterSurfaceView() {} @Implementation public SurfaceHolder getHolder() { return holder; } } }
engine/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsControllerTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsControllerTest.java", "repo_id": "engine", "token_count": 23034 }
306
android.useAndroidX=true
engine/shell/platform/android/test_runner/gradle.properties/0
{ "file_path": "engine/shell/platform/android/test_runner/gradle.properties", "repo_id": "engine", "token_count": 8 }
307
// Copyright 2013 The Flutter 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_BYTE_BUFFER_STREAMS_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BYTE_BUFFER_STREAMS_H_ #include <cassert> #include <cstdint> #include <cstring> #include <iostream> #include <vector> #include "include/flutter/byte_streams.h" namespace flutter { // Implementation of ByteStreamReader base on a byte array. class ByteBufferStreamReader : public ByteStreamReader { public: // Createa a reader reading from |bytes|, which must have a length of |size|. // |bytes| must remain valid for the lifetime of this object. explicit ByteBufferStreamReader(const uint8_t* bytes, size_t size) : bytes_(bytes), size_(size) {} virtual ~ByteBufferStreamReader() = default; // |ByteStreamReader| uint8_t ReadByte() override { if (location_ >= size_) { std::cerr << "Invalid read in StandardCodecByteStreamReader" << std::endl; return 0; } return bytes_[location_++]; } // |ByteStreamReader| void ReadBytes(uint8_t* buffer, size_t length) override { if (location_ + length > size_) { std::cerr << "Invalid read in StandardCodecByteStreamReader" << std::endl; return; } std::memcpy(buffer, &bytes_[location_], length); location_ += length; } // |ByteStreamReader| void ReadAlignment(uint8_t alignment) override { uint8_t mod = location_ % alignment; if (mod) { location_ += alignment - mod; } } private: // The buffer to read from. const uint8_t* bytes_; // The total size of the buffer. size_t size_; // The current read location. size_t location_ = 0; }; // Implementation of ByteStreamWriter based on a byte array. class ByteBufferStreamWriter : public ByteStreamWriter { public: // Creates a writer that writes into |buffer|. // |buffer| must remain valid for the lifetime of this object. explicit ByteBufferStreamWriter(std::vector<uint8_t>* buffer) : bytes_(buffer) { assert(buffer); } virtual ~ByteBufferStreamWriter() = default; // |ByteStreamWriter| void WriteByte(uint8_t byte) { bytes_->push_back(byte); } // |ByteStreamWriter| void WriteBytes(const uint8_t* bytes, size_t length) { assert(length > 0); bytes_->insert(bytes_->end(), bytes, bytes + length); } // |ByteStreamWriter| void WriteAlignment(uint8_t alignment) { uint8_t mod = bytes_->size() % alignment; if (mod) { for (int i = 0; i < alignment - mod; ++i) { WriteByte(0); } } } private: // The buffer to write to. std::vector<uint8_t>* bytes_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BYTE_BUFFER_STREAMS_H_
engine/shell/platform/common/client_wrapper/byte_buffer_streams.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/byte_buffer_streams.h", "repo_id": "engine", "token_count": 1011 }
308
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CALL_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CALL_H_ #include <memory> #include <string> namespace flutter { class EncodableValue; // An object encapsulating a method call from Flutter whose arguments are of // type T. template <typename T = EncodableValue> class MethodCall { public: // Creates a MethodCall with the given name and arguments. MethodCall(const std::string& method_name, std::unique_ptr<T> arguments) : method_name_(method_name), arguments_(std::move(arguments)) {} virtual ~MethodCall() = default; // Prevent copying. MethodCall(MethodCall<T> const&) = delete; MethodCall& operator=(MethodCall<T> const&) = delete; // The name of the method being called. const std::string& method_name() const { return method_name_; } // The arguments to the method call, or NULL if there are none. const T* arguments() const { return arguments_.get(); } private: std::string method_name_; std::unique_ptr<T> arguments_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CALL_H_
engine/shell/platform/common/client_wrapper/include/flutter/method_call.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/method_call.h", "repo_id": "engine", "token_count": 451 }
309
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("core_wrapper_files.gni") # Publishes client wrapper files to the output directory for distribution. # This can be used multiple times to combine various portions of a wrapper # library into one cohesive library for clients to consume. # # Files that should be built by clients go into 'sources', while headers meant # to be included by the consuming code go into 'public'. # # All public code is assumed to be in the 'flutter' namespace. template("publish_client_wrapper") { forward_variables_from(invoker, [ "directory_suffix" ]) if (defined(directory_suffix)) { publish_dir_root = "$root_out_dir/cpp_client_wrapper_$directory_suffix" } else { publish_dir_root = "$root_out_dir/cpp_client_wrapper" } template_target_name = target_name namespace = "flutter" group(template_target_name) { forward_variables_from(invoker, [ "public_deps", "visibility", ]) deps = [ ":${template_target_name}_publish_includes", ":${template_target_name}_publish_sources", ] if (defined(invoker.deps)) { deps += invoker.deps } } copy("${template_target_name}_publish_includes") { visibility = [ ":$template_target_name", ":${template_target_name}_publish_sources", ] sources = invoker.public outputs = [ "$publish_dir_root/include/$namespace/{{source_file_part}}" ] } copy("${template_target_name}_publish_sources") { visibility = [ ":$template_target_name" ] sources = invoker.sources outputs = [ "$publish_dir_root/{{source_file_part}}" ] # GN on Windows appears to do #include checks even for copy # targets, so add the dependency to the headers to satisfy # the check. deps = [ ":${template_target_name}_publish_includes" ] } } _wrapper_readme = get_path_info("README", "abspath") # Copies the client wrapper code to the output directory. template("publish_client_wrapper_core") { publish_client_wrapper(target_name) { forward_variables_from(invoker, [ "directory_suffix", "visibility", ]) public = core_cpp_client_wrapper_includes sources = core_cpp_client_wrapper_sources + core_cpp_client_wrapper_internal_headers + [ _wrapper_readme ] + temporary_shim_files } } # A wrapper for publish_client_wrapper that will also # publish_client_wrapper_core into the same directory. # # This is a convenience utility for the common case of wanting to publish # the core wrapper and a single set of extra wrapper files corresponding to # the platform. template("publish_client_wrapper_extension") { extension_target_name = target_name core_target_name = "${target_name}_core" publish_client_wrapper_core(core_target_name) { visibility = [ ":$extension_target_name" ] forward_variables_from(invoker, [ "directory_suffix" ]) } publish_client_wrapper(extension_target_name) { forward_variables_from(invoker, [ "public", "sources", "directory_suffix", ]) public_deps = [ ":$core_target_name" ] } }
engine/shell/platform/common/client_wrapper/publish.gni/0
{ "file_path": "engine/shell/platform/common/client_wrapper/publish.gni", "repo_id": "engine", "token_count": 1432 }
310
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_GEOMETRY_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_GEOMETRY_H_ #include <cmath> namespace flutter { // A point in Cartesian space relative to a separately-maintained origin. class Point { public: Point() = default; Point(double x, double y) : x_(x), y_(y) {} Point(const Point& point) = default; Point& operator=(const Point& other) = default; double x() const { return x_; } double y() const { return y_; } bool operator==(const Point& other) const { return x_ == other.x_ && y_ == other.y_; } private: double x_ = 0.0; double y_ = 0.0; }; // A 2D floating-point size with non-negative dimensions. class Size { public: Size() = default; Size(double width, double height) : width_(std::fmax(0.0, width)), height_(std::fmax(0.0, height)) {} Size(const Size& size) = default; Size& operator=(const Size& other) = default; double width() const { return width_; } double height() const { return height_; } bool operator==(const Size& other) const { return width_ == other.width_ && height_ == other.height_; } private: double width_ = 0.0; double height_ = 0.0; }; // A rectangle with position in Cartesian space specified relative to a // separately-maintained origin. class Rect { public: Rect() = default; Rect(const Point& origin, const Size& size) : origin_(origin), size_(size) {} Rect(const Rect& rect) = default; Rect& operator=(const Rect& other) = default; double left() const { return origin_.x(); } double top() const { return origin_.y(); } double right() const { return origin_.x() + size_.width(); } double bottom() const { return origin_.y() + size_.height(); } double width() const { return size_.width(); } double height() const { return size_.height(); } Point origin() const { return origin_; } Size size() const { return size_; } bool operator==(const Rect& other) const { return origin_ == other.origin_ && size_ == other.size_; } private: Point origin_; Size size_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_GEOMETRY_H_
engine/shell/platform/common/geometry.h/0
{ "file_path": "engine/shell/platform/common/geometry.h", "repo_id": "engine", "token_count": 747 }
311
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MACROS_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MACROS_H_ #ifdef FLUTTER_DESKTOP_LIBRARY // Do not add deprecation annotations when building the library. #define FLUTTER_DEPRECATED(message) #else // FLUTTER_DESKTOP_LIBRARY // Add deprecation warning for users of the library. #ifdef _WIN32 #define FLUTTER_DEPRECATED(message) __declspec(deprecated(message)) #else #define FLUTTER_DEPRECATED(message) __attribute__((deprecated(message))) #endif #endif // FLUTTER_DESKTOP_LIBRARY #endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MACROS_H_
engine/shell/platform/common/public/flutter_macros.h/0
{ "file_path": "engine/shell/platform/common/public/flutter_macros.h", "repo_id": "engine", "token_count": 286 }
312
# Doxyfile 1.8.17 ############################################################################## # This is a Doxyfile to help identify holes in iOS's Flutter.framework. ############################################################################## # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a double hash (##) is considered a comment and is placed in # front of the TAG it is preceding. # # All text after a single hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists, items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (\" \"). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the configuration # file that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # https://www.gnu.org/software/libiconv/ for the list of possible encodings. # The default value is: UTF-8. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded by # double-quotes, unless you are using Doxywizard) that should identify the # project for which the documentation is generated. This name is used in the # title of most generated pages and in a few other places. # The default value is: My Project. PROJECT_NAME = "Flutter.framework" # The PROJECT_NUMBER tag can be used to enter a project or revision number. This # could be handy for archiving the generated documentation or if some version # control system is used. PROJECT_NUMBER = # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = # With the PROJECT_LOGO tag one can specify a logo or an icon that is included # in the documentation. The maximum height of the logo should not exceed 55 # pixels and the maximum width should not exceed 200 pixels. Doxygen will copy # the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path # into which the generated documentation will be written. If a relative path is # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. OUTPUT_DIRECTORY = # If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and # will distribute the generated files over these directories. Enabling this # option can be useful when feeding doxygen a huge amount of source files, where # putting all generated files in the same directory would otherwise causes # performance problems for the file system. # The default value is: NO. CREATE_SUBDIRS = NO # If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII # characters to appear in the names of generated files. If set to NO, non-ASCII # characters will be escaped, for example _xE3_x81_x84 will be used for Unicode # U+3044. # The default value is: NO. ALLOW_UNICODE_NAMES = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, # Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), # Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, # Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), # Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, # Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, # Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, # Ukrainian and Vietnamese. # The default value is: English. OUTPUT_LANGUAGE = English # The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all generated output in the proper direction. # Possible values are: None, LTR, RTL and Context. # The default value is: None. OUTPUT_TEXT_DIRECTION = None # If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member # descriptions after the members that are listed in the file and class # documentation (similar to Javadoc). Set to NO to disable this. # The default value is: YES. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief # description of a member or function before the detailed description # # Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. # The default value is: YES. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator that is # used to form the text in various listings. Each string in this list, if found # as the leading text of the brief description, will be stripped from the text # and the result, after processing the whole list, is used as the annotated # text. Otherwise, the brief description is used as-is. If left blank, the # following values are used ($name is automatically replaced with the name of # the entity):The $name class, The $name widget, The $name file, is, provides, # specifies, contains, represents, a, an and the. ABBREVIATE_BRIEF = "The $name class" \ "The $name widget" \ "The $name file" \ is \ provides \ specifies \ contains \ represents \ a \ an \ the # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # doxygen will generate a detailed section even if there is only a brief # description. # The default value is: NO. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. # The default value is: NO. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path # before files name in the file list and in the header files. If set to NO the # shortest path that makes the file name unique will be used # The default value is: YES. FULL_PATH_NAMES = YES # The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. # Stripping is only done if one of the specified strings matches the left-hand # part of the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the path to # strip. # # Note that you can specify absolute paths here, but also relative paths, which # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which # header file to include in order to use a class. If left blank only the name of # the header file containing the class definition is used. Otherwise one should # specify the list of include paths that are normally passed to the compiler # using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't # support long names like on DOS, Mac, or CD-ROM. # The default value is: NO. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the # first line (until the first dot) of a Javadoc-style comment as the brief # description. If set to NO, the Javadoc-style will behave just like regular Qt- # style comments (thus requiring an explicit @brief command for a brief # description.) # The default value is: NO. JAVADOC_AUTOBRIEF = NO # If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line # such as # /*************** # as being the beginning of a Javadoc-style comment "banner". If set to NO, the # Javadoc-style will behave just like regular comments and it will not be # interpreted by doxygen. # The default value is: NO. JAVADOC_BANNER = NO # If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first # line (until the first dot) of a Qt-style comment as the brief description. If # set to NO, the Qt-style will behave just like regular Qt-style comments (thus # requiring an explicit \brief command for a brief description.) # The default value is: NO. QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a # multi-line C++ special comment block (i.e. a block of //! or /// comments) as # a brief description. This used to be the default behavior. The new default is # to treat a multi-line C++ comment block as a detailed description. Set this # tag to YES if you prefer the old behavior instead. # # Note that setting this tag to YES also means that rational rose comments are # not recognized any more. # The default value is: NO. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the # documentation from any documented member that it re-implements. # The default value is: YES. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new # page for each member. If set to NO, the documentation of a member will be part # of the file/class/namespace that contains it. # The default value is: NO. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen # uses this value to replace tabs by spaces in code fragments. # Minimum value: 1, maximum value: 16, default value: 4. TAB_SIZE = 4 # This tag can be used to specify a number of aliases that act as commands in # the documentation. An alias has the form: # name=value # For example adding # "sideeffect=@par Side Effects:\n" # will allow you to put the command \sideeffect (or @sideeffect) in the # documentation, which will result in a user-defined paragraph with heading # "Side Effects:". You can put \n's in the value part of an alias to insert # newlines (in the resulting output). You can put ^^ in the value part of an # alias to insert a newline as if a physical newline was in the original file. # When you need a literal { or } or , in the value part of an alias you have to # escape them by means of a backslash (\), this can lead to conflicts with the # commands \{ and \} for these it is advised to use the version @{ and @} or use # a double escape (\\{ and \\}) ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding "class=itcl::class" # will allow you to use the command class in the itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For # instance, some of the names that are used will be different. The list of all # members will be omitted, etc. # The default value is: NO. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or # Python sources only. Doxygen will then generate output that is more tailored # for that language. For instance, namespaces will be presented as packages, # qualified scopes will look different, etc. # The default value is: NO. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources. Doxygen will then generate output that is tailored for Fortran. # The default value is: NO. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for VHDL. # The default value is: NO. OPTIMIZE_OUTPUT_VHDL = NO # Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice # sources only. Doxygen will then generate output that is more tailored for that # language. For instance, namespaces will be presented as modules, types will be # separated into more groups, etc. # The default value is: NO. OPTIMIZE_OUTPUT_SLICE = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, and # language is one of the parsers supported by doxygen: IDL, Java, JavaScript, # Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice, # Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: # FortranFree, unknown formatted Fortran: Fortran. In the later case the parser # tries to guess whether the code is fixed or free formatted code, this is the # default for Fortran type files), VHDL, tcl. For instance to make doxygen treat # .inc files as Fortran files (default is PHP), and .f files as C (default is # Fortran), use: inc=Fortran f=C. # # Note: For files without extension you can use no_extension as a placeholder. # # Note that for custom extensions you also need to set FILE_PATTERNS otherwise # the files are not read by doxygen. EXTENSION_MAPPING = # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # according to the Markdown format, which allows for more readable # documentation. See https://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you can # mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in # case of backward compatibilities issues. # The default value is: YES. MARKDOWN_SUPPORT = YES # When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up # to that level are automatically included in the table of contents, even if # they do not have an id attribute. # Note: This feature currently applies only to Markdown headings. # Minimum value: 0, maximum value: 99, default value: 5. # This tag requires that the tag MARKDOWN_SUPPORT is set to YES. TOC_INCLUDE_HEADINGS = 5 # When enabled doxygen tries to link words that correspond to documented # classes, or namespaces to their corresponding documentation. Such a link can # be prevented in individual cases by putting a % sign in front of the word or # globally by setting AUTOLINK_SUPPORT to NO. # The default value is: YES. AUTOLINK_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should set this # tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); # versus func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. # The default value is: NO. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. # The default value is: NO. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip (see: # https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen # will parse them like normal C++ but will assume all classes use public instead # of private inheritance when no explicit protection keyword is present. # The default value is: NO. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate # getter and setter methods for a property. Setting this option to YES will make # doxygen to replace the get and set methods by a property in the documentation. # This will only work if the methods are indeed getting or setting a simple # type. If this is not the case, or you want to show the methods anyway, you # should set this option to NO. # The default value is: YES. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. # The default value is: NO. DISTRIBUTE_GROUP_DOC = NO # If one adds a struct or class to a group and this option is enabled, then also # any nested class or struct is added to the same group. By default this option # is disabled and one has to add nested compounds explicitly via \ingroup. # The default value is: NO. GROUP_NESTED_COMPOUNDS = NO # Set the SUBGROUPING tag to YES to allow class member groups of the same type # (for instance a group of public functions) to be put as a subgroup of that # type (e.g. under the Public Functions section). Set it to NO to prevent # subgrouping. Alternatively, this can be done per class using the # \nosubgrouping command. # The default value is: YES. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions # are shown inside the group in which they are included (e.g. using \ingroup) # instead of on a separate page (for HTML and Man pages) or section (for LaTeX # and RTF). # # Note that this feature does not work in combination with # SEPARATE_MEMBER_PAGES. # The default value is: NO. INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions # with only public data fields or simple typedef fields will be shown inline in # the documentation of the scope in which they are defined (i.e. file, # namespace, or group documentation), provided this scope is documented. If set # to NO, structs, classes, and unions are shown on a separate page (for HTML and # Man pages) or section (for LaTeX and RTF). # The default value is: NO. INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or # enum is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically be # useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. # The default value is: NO. TYPEDEF_HIDES_STRUCT = NO # The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This # cache is used to resolve symbols given their name and scope. Since this can be # an expensive process and often the same symbol appears multiple times in the # code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small # doxygen will become slower. If the cache is too large, memory is wasted. The # cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range # is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 # symbols. At the end of a run doxygen will report the cache usage and suggest # the optimal cache size from a speed point of view. # Minimum value: 0, maximum value: 9, default value: 0. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in # documentation are documented, even if no documentation was available. Private # class members and static file members will be hidden unless the # EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. # Note: This will also disable the warnings about undocumented members that are # normally produced when WARNINGS is set to YES. # The default value is: NO. EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will # be included in the documentation. # The default value is: NO. EXTRACT_PRIVATE = NO # If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual # methods of a class will be included in the documentation. # The default value is: NO. EXTRACT_PRIV_VIRTUAL = NO # If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal # scope will be included in the documentation. # The default value is: NO. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES, all static members of a file will be # included in the documentation. # The default value is: NO. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined # locally in source files will be included in the documentation. If set to NO, # only classes defined in header files are included. Does not have any effect # for Java sources. # The default value is: YES. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. If set to YES, local methods, # which are defined in the implementation section but not in the interface are # included in the documentation. If set to NO, only methods in the interface are # included. # The default value is: NO. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base name of # the file that contains the anonymous namespace. By default anonymous namespace # are hidden. # The default value is: NO. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all # undocumented members inside documented classes or files. If set to NO these # members will be included in the various overviews, but no documentation # section is generated. This option has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. If set # to NO, these classes will be included in the various overviews. This option # has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend # declarations. If set to NO, these declarations will be included in the # documentation. # The default value is: NO. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any # documentation blocks found inside the body of a function. If set to NO, these # blocks will be appended to the function's detailed documentation block. # The default value is: NO. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation that is typed after a # \internal command is included. If the tag is set to NO then the documentation # will be excluded. Set it to YES to include the internal documentation. # The default value is: NO. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file # names in lower-case letters. If set to YES, upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # (including Cygwin) ands Mac users are advised to set this option to NO. # The default value is: system dependent. CASE_SENSE_NAMES = NO # If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with # their full class and namespace scopes in the documentation. If set to YES, the # scope will be hidden. # The default value is: NO. HIDE_SCOPE_NAMES = NO # If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will # append additional text to a page's title, such as Class Reference. If set to # YES the compound reference will be hidden. # The default value is: NO. HIDE_COMPOUND_REFERENCE= NO # If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of # the files that are included by a file in the documentation of that file. # The default value is: YES. SHOW_INCLUDE_FILES = YES # If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each # grouped member an include statement to the documentation, telling the reader # which file to include in order to use the member. # The default value is: NO. SHOW_GROUPED_MEMB_INC = NO # If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include # files with double quotes in the documentation rather than with sharp brackets. # The default value is: NO. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the # documentation for inline members. # The default value is: YES. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the # (detailed) documentation of file and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. # The default value is: YES. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief # descriptions of file, namespace and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. Note that # this will also influence the order of the classes in the class list. # The default value is: NO. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the # (brief and detailed) documentation of class members so that constructors and # destructors are listed first. If set to NO the constructors will appear in the # respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. # Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief # member documentation. # Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting # detailed member documentation. # The default value is: NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy # of group names into alphabetical order. If set to NO the group names will # appear in their defined order. # The default value is: NO. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by # fully-qualified names, including namespaces. If set to NO, the class list will # be sorted only by class name, not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the alphabetical # list. # The default value is: NO. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper # type resolution of all parameters of a function it will reject a match between # the prototype and the implementation of a member function even if there is # only one candidate or it is obvious which candidate to choose by doing a # simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still # accept a match between prototype and implementation in such cases. # The default value is: NO. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo # list. This list is created by putting \todo commands in the documentation. # The default value is: YES. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test # list. This list is created by putting \test commands in the documentation. # The default value is: YES. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug # list. This list is created by putting \bug commands in the documentation. # The default value is: YES. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) # the deprecated list. This list is created by putting \deprecated commands in # the documentation. # The default value is: YES. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional documentation # sections, marked by \if <section_label> ... \endif and \cond <section_label> # ... \endcond blocks. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the # documentation. If the initializer consists of more lines than specified here # it will be hidden. Use a value of 0 to hide initializers completely. The # appearance of the value of individual variables and macros / defines can be # controlled using \showinitializer or \hideinitializer command in the # documentation regardless of this setting. # Minimum value: 0, maximum value: 10000, default value: 30. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated at # the bottom of the documentation of classes and structs. If set to YES, the # list will mention the files that were used to generate the documentation. # The default value is: YES. SHOW_USED_FILES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. This # will remove the Files entry from the Quick Index and from the Folder Tree View # (if specified). # The default value is: YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces # page. This will remove the Namespaces entry from the Quick Index and from the # Folder Tree View (if specified). # The default value is: YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command input-file, where command is the value of the # FILE_VERSION_FILTER tag, and input-file is the name of an input file provided # by doxygen. Whatever the program writes to standard output is used as the file # version. For an example see the documentation. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. You can # optionally specify a file name after the option, if omitted DoxygenLayout.xml # will be used as the name of the layout file. # # Note that if you run doxygen from a directory containing a file called # DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE # tag is left empty. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files containing # the reference definitions. This must be a list of .bib files. The .bib # extension is automatically appended if omitted. This requires the bibtex tool # to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. # For LaTeX the style of the bibliography can be controlled using # LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the # search path. See also \cite for info how to create references. CITE_BIB_FILES = #--------------------------------------------------------------------------- # Configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated to # standard output by doxygen. If QUIET is set to YES this implies that the # messages are off. # The default value is: NO. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated to standard error (stderr) by doxygen. If WARNINGS is set to YES # this implies that the warnings are on. # # Tip: Turn warnings on while writing the documentation. # The default value is: YES. WARNINGS = YES # If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate # warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag # will automatically be disabled. # The default value is: YES. WARN_IF_UNDOCUMENTED = YES # If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some parameters # in a documented function, or documenting parameters that don't exist or using # markup commands wrongly. # The default value is: YES. WARN_IF_DOC_ERROR = YES # This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that # are documented, but have no documentation for their parameters or return # value. If set to NO, doxygen will only warn about wrong or incomplete # parameter documentation, but not about the absence of documentation. If # EXTRACT_ALL is set to YES then this flag will automatically be disabled. # The default value is: NO. WARN_NO_PARAMDOC = NO # If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when # a warning is encountered. # The default value is: NO. WARN_AS_ERROR = NO # The WARN_FORMAT tag determines the format of the warning messages that doxygen # can produce. The string should contain the $file, $line, and $text tags, which # will be replaced by the file and line number from which the warning originated # and the warning text. Optionally the format may contain $version, which will # be replaced by the version of the file (if it could be obtained via # FILE_VERSION_FILTER) # The default value is: $file:$line: $text. WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning and error # messages should be written. If left blank the output is written to standard # error (stderr). WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag is used to specify the files and/or directories that contain # documented source files. You may enter file names like myfile.cpp or # directories like /usr/src/myproject. Separate the files or directories with # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # Note: If this tag is empty the current directory is searched. INPUT = common/framework/Headers \ ios/framework/Headers # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses # libiconv (or the iconv built into libc) for the transcoding. See the libiconv # documentation (see: https://www.gnu.org/software/libiconv/) for the list of # possible encodings. # The default value is: UTF-8. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and # *.h) to filter out the source-files in the directories. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # read by doxygen. # # If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, # *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, # *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, # *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C comment), # *.doc (to be provided as doxygen C comment), *.txt (to be provided as doxygen # C comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f, *.for, *.tcl, *.vhd, # *.vhdl, *.ucf, *.qsf and *.ice. FILE_PATTERNS = *.c \ *.cc \ *.cxx \ *.cpp \ *.c++ \ *.java \ *.ii \ *.ixx \ *.ipp \ *.i++ \ *.inl \ *.idl \ *.ddl \ *.odl \ *.h \ *.hh \ *.hxx \ *.hpp \ *.h++ \ *.cs \ *.d \ *.php \ *.php4 \ *.php5 \ *.phtml \ *.inc \ *.markdown \ *.md \ *.dox \ *.doc \ *.txt \ *.py \ *.pyw \ *.f90 \ *.f95 \ *.f03 \ *.f08 \ *.f \ *.for \ *.tcl \ *.vhd \ *.vhdl \ *.ucf \ *.qsf \ *.ice # The RECURSIVE tag can be used to specify whether or not subdirectories should # be searched for input files as well. # The default value is: NO. RECURSIVE = NO # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. # The default value is: NO. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and # *.h) to filter out the source-files in the directories. If left blank all # files are included. EXAMPLE_PATTERNS = * # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude commands # irrespective of the value of the RECURSIVE tag. # The default value is: NO. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or directories # that contain images that are to be included in the documentation (see the # \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command: # # <filter> <input-file> # # where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the # name of an input file. Doxygen will then use the output that the filter # program writes to standard output. If FILTER_PATTERNS is specified, this tag # will be ignored. # # Note that the filter must not add or remove lines; it is applied before the # code is scanned, but not when the output code is generated. If lines are added # or removed, the anchors will not be placed correctly. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: pattern=filter # (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how # filters are used. If the FILTER_PATTERNS tag is empty or if none of the # patterns match the file name, INPUT_FILTER is applied. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will also be used to filter the input files that are used for # producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). # The default value is: NO. FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) and # it is also possible to disable source filtering for a specific pattern using # *.ext= (so without naming a filter). # This tag requires that the tag FILTER_SOURCE_FILES is set to YES. FILTER_SOURCE_PATTERNS = # If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. USE_MDFILE_AS_MAINPAGE = #--------------------------------------------------------------------------- # Configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will be # generated. Documented entities will be cross-referenced with these sources. # # Note: To get rid of all source code in the generated output, make sure that # also VERBATIM_HEADERS is set to NO. # The default value is: NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body of functions, # classes and enums directly into the documentation. # The default value is: NO. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any # special comment blocks from generated source code fragments. Normal C, C++ and # Fortran comments will always remain visible. # The default value is: YES. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES then for each documented # entity all documented functions referencing it will be listed. # The default value is: NO. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES then for each documented function # all documented entities called/used by that function will be listed. # The default value is: NO. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set # to YES then the hyperlinks from functions in REFERENCES_RELATION and # REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will # link to the documentation. # The default value is: YES. REFERENCES_LINK_SOURCE = YES # If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the # source code will show a tooltip with additional information such as prototype, # brief description and links to the definition and documentation. Since this # will make the HTML file larger and loading of large files a bit slower, you # can opt to disable this feature. # The default value is: YES. # This tag requires that the tag SOURCE_BROWSER is set to YES. SOURCE_TOOLTIPS = YES # If the USE_HTAGS tag is set to YES then the references to source code will # point to the HTML generated by the htags(1) tool instead of doxygen built-in # source browser. The htags tool is part of GNU's global source tagging system # (see https://www.gnu.org/software/global/global.html). You will need version # 4.8.6 or higher. # # To use it do the following: # - Install the latest version of global # - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file # - Make sure the INPUT points to the root of the source tree # - Run doxygen as normal # # Doxygen will invoke htags (and that will in turn invoke gtags), so these # tools must be available from the command line (i.e. in the search path). # # The result: instead of the source browser generated by doxygen, the links to # source code will now point to the output of htags. # The default value is: NO. # This tag requires that the tag SOURCE_BROWSER is set to YES. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a # verbatim copy of the header file for each class for which an include is # specified. Set to NO to disable this. # See also: Section \class. # The default value is: YES. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all # compounds will be generated. Enable this if the project contains a lot of # classes, structs, unions or interfaces. # The default value is: YES. ALPHABETICAL_INDEX = YES # The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in # which the alphabetical index list will be split. # Minimum value: 1, maximum value: 20, default value: 5. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all classes will # be put under the same header in the alphabetical index. The IGNORE_PREFIX tag # can be used to specify a prefix (or a list of prefixes) that should be ignored # while generating the index headers. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. IGNORE_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output # The default value is: YES. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for each # generated HTML page (for example: .htm, .php, .asp). # The default value is: .html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a user-defined HTML header file for # each generated HTML page. If the tag is left blank doxygen will generate a # standard header. # # To get valid HTML the header file that includes any scripts and style sheets # that doxygen needs, which is dependent on the configuration options used (e.g. # the setting GENERATE_TREEVIEW). It is highly recommended to start with a # default header using # doxygen -w html new_header.html new_footer.html new_stylesheet.css # YourConfigFile # and then modify the file new_header.html. See also section "Doxygen usage" # for information on how to generate the default header that doxygen normally # uses. # Note: The header is subject to change so you typically have to regenerate the # default header when upgrading to a newer version of doxygen. For a description # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard # footer. See HTML_HEADER for more information on how to generate a default # footer and what special commands can be used inside the footer. See also # section "Doxygen usage" for information on how to generate the default footer # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of # the HTML output. If left blank doxygen will generate a default style sheet. # See also section "Doxygen usage" for information on how to generate the style # sheet that doxygen normally uses. # Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as # it is more robust and this tag (HTML_STYLESHEET) will in the future become # obsolete. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined # cascading style sheets that are included after the standard style sheets # created by doxygen. Using this option one can overrule certain style aspects. # This is preferred over using HTML_STYLESHEET since it does not replace the # standard style sheet and is therefore more robust against future updates. # Doxygen will copy the style sheet files to the output directory. # Note: The order of the extra style sheet files is of importance (e.g. the last # style sheet in the list overrules the setting of the previous ones in the # list). For an example see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that the # files will be copied as-is; there are no commands or markers available. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen # will adjust the colors in the style sheet and background images according to # this color. Hue is specified as an angle on a colorwheel, see # https://en.wikipedia.org/wiki/Hue for more information. For instance the value # 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 # purple, and 360 is red again. # Minimum value: 0, maximum value: 359, default value: 220. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors # in the HTML output. For a value of 0 the output will use grayscales only. A # value of 255 will produce the most vivid colors. # Minimum value: 0, maximum value: 255, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the # luminance component of the colors in the HTML output. Values below 100 # gradually make the output lighter, whereas values above 100 make the output # darker. The value divided by 100 is the actual gamma applied, so 80 represents # a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not # change the gamma. # Minimum value: 40, maximum value: 240, default value: 80. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting this # to YES can help to show when doxygen was last run and thus if the # documentation is up to date. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_TIMESTAMP = NO # If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML # documentation will contain a main index with vertical navigation menus that # are dynamically created via JavaScript. If disabled, the navigation index will # consists of multiple levels of tabs that are statically embedded in every HTML # page. Disable this option to support browsers that do not have JavaScript, # like the Qt help browser. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_MENUS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_SECTIONS = NO # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries # shown in the various tree structured indices initially; the user can expand # and collapse entries dynamically later on. Doxygen will expand the tree to # such a level that at most the specified number of entries are visible (unless # a fully collapsed tree already exceeds this amount). So setting the number of # entries 1 will produce a full collapsed tree by default. 0 is a special value # representing an infinite number of entries and will result in a full expanded # tree by default. # Minimum value: 0, maximum value: 9999, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files will be # generated that can be used as input for Apple's Xcode 3 integrated development # environment (see: https://developer.apple.com/xcode/), introduced with OSX # 10.5 (Leopard). To create a documentation set, doxygen will generate a # Makefile in the HTML output directory. Running make will produce the docset in # that directory and running make install will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at # startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy # genXcode/_index.html for more information. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_DOCSET = NO # This tag determines the name of the docset feed. A documentation feed provides # an umbrella under which multiple documentation sets from a single provider # (such as a company or product suite) can be grouped. # The default value is: Doxygen generated docs. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_FEEDNAME = "Doxygen generated docs" # This tag specifies a string that should uniquely identify the documentation # set bundle. This should be a reverse domain-name style string, e.g. # com.mycompany.MyDocSet. Doxygen will append .docset to the name. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_BUNDLE_ID = org.doxygen.Project # The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. # The default value is: org.doxygen.Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. # The default value is: Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three # additional HTML index files: index.hhp, index.hhc, and index.hhk. The # index.hhp is a project file that can be read by Microsoft's HTML Help Workshop # (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on # Windows. # # The HTML Help Workshop contains a compiler that can convert all HTML output # generated by doxygen into a single compiled HTML file (.chm). Compiled HTML # files are now used as the Windows 98 help format, and will replace the old # Windows help format (.hlp) on all Windows platforms in the future. Compressed # HTML files also contain an index, a table of contents, and you can search for # words in the documentation. The HTML workshop also contains a viewer for # compressed HTML files. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_HTMLHELP = NO # The CHM_FILE tag can be used to specify the file name of the resulting .chm # file. You can add a path in front of the file if the result should not be # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler (hhc.exe). If non-empty, # doxygen will try to run the HTML help compiler on the generated index.hhp. # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated # (YES) or that it should be included in the master .chm file (NO). # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. GENERATE_CHI = NO # The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) # and project file content. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated # (YES) or a normal table of contents (NO) in the .chm file. Furthermore it # enables the Previous and Next buttons. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members to # the table of contents of the HTML help documentation and to the tree view. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that # can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help # (.qch) of the generated HTML documentation. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify # the file name of the resulting .qch file. The path specified is relative to # the HTML output folder. # This tag requires that the tag GENERATE_QHP is set to YES. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # Project output. For more information please see Qt Help Project / Namespace # (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # Help Project output. For more information please see Qt Help Project / Virtual # Folders (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual- # folders). # The default value is: doc. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_VIRTUAL_FOLDER = doc # If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom # filter to add. For more information please see Qt Help Project / Custom # Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_NAME = # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see Qt Help Project / Custom # Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's filter section matches. Qt Help Project / Filter Attributes (see: # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_SECT_FILTER_ATTRS = # The QHG_LOCATION tag can be used to specify the location of Qt's # qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the # generated .qhp file. # This tag requires that the tag GENERATE_QHP is set to YES. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be # generated, together with the HTML files, they form an Eclipse help plugin. To # install this plugin and make it available under the help contents menu in # Eclipse, the contents of the directory containing the HTML and XML files needs # to be copied into the plugins directory of eclipse. The name of the directory # within the plugins directory should be the same as the ECLIPSE_DOC_ID value. # After copying Eclipse needs to be restarted before the help appears. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_ECLIPSEHELP = NO # A unique identifier for the Eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have this # name. Each documentation set should have its own identifier. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. ECLIPSE_DOC_ID = org.doxygen.Project # If you want full control over the layout of the generated HTML pages it might # be necessary to disable the index and replace it with your own. The # DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top # of each HTML page. A value of NO enables the index and the value YES disables # it. Since the tabs in the index contain the same information as the navigation # tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. DISABLE_INDEX = NO # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. If the tag # value is set to YES, a side panel will be generated containing a tree-like # index structure (just like the one that is generated for HTML Help). For this # to work a browser that supports JavaScript, DHTML, CSS and frames is required # (i.e. any modern browser). Windows users are probably better off using the # HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can # further fine-tune the look of the index. As an example, the default style # sheet generated by doxygen has an example that shows how to put an image at # the root of the tree instead of the PROJECT_NAME. Since the tree basically has # the same information as the tab index, you could consider setting # DISABLE_INDEX to YES when enabling this option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_TREEVIEW = NO # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that # doxygen will group on one line in the generated HTML documentation. # # Note that a value of 0 will completely suppress the enum values from appearing # in the overview section. # Minimum value: 0, maximum value: 20, default value: 4. # This tag requires that the tag GENERATE_HTML is set to YES. ENUM_VALUES_PER_LINE = 4 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used # to set the initial width (in pixels) of the frame in which the tree is shown. # Minimum value: 0, maximum value: 1500, default value: 250. # This tag requires that the tag GENERATE_HTML is set to YES. TREEVIEW_WIDTH = 250 # If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to # external symbols imported via tag files in a separate window. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of LaTeX formulas included as images in # the HTML documentation. When you change the font size after a successful # doxygen run you need to manually remove any form_*.png images from the HTML # output directory to force them to be regenerated. # Minimum value: 8, maximum value: 50, default value: 10. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANSPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are not # supported properly for IE 6.0, but are supported on all modern browsers. # # Note that when changing this option you need to delete any form_*.png files in # the HTML output directory before the changes have effect. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_TRANSPARENT = YES # The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands # to create new LaTeX commands to be used in formulas as building blocks. See # the section "Including formulas" for details. FORMULA_MACROFILE = # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see # https://www.mathjax.org) which uses client side JavaScript for the rendering # instead of using pre-rendered bitmaps. Use this if you do not have LaTeX # installed or if you want to formulas look prettier in the HTML output. When # enabled you may also need to install MathJax separately and configure the path # to it using the MATHJAX_RELPATH option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. USE_MATHJAX = NO # When MathJax is enabled you can set the default output format to be used for # the MathJax output. See the MathJax site (see: # http://docs.mathjax.org/en/latest/output.html) for more details. # Possible values are: HTML-CSS (which is slower, but has the best # compatibility), NativeMML (i.e. MathML) and SVG. # The default value is: HTML-CSS. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_FORMAT = HTML-CSS # When MathJax is enabled you need to specify the location relative to the HTML # output directory using the MATHJAX_RELPATH option. The destination directory # should contain the MathJax.js script. For instance, if the mathjax directory # is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax # Content Delivery Network so you can quickly see the result without installing # MathJax. However, it is strongly recommended to install a local copy of # MathJax from https://www.mathjax.org before deployment. # The default value is: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/ # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # extension names that should be enabled during MathJax rendering. For example # MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # of code that will be used on startup of the MathJax code. See the MathJax site # (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an # example see the documentation. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_CODEFILE = # When the SEARCHENGINE tag is enabled doxygen will generate a search box for # the HTML output. The underlying search engine uses javascript and DHTML and # should work on any modern browser. Note that when using HTML help # (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) # there is already a search function so this one should typically be disabled. # For large projects the javascript based search engine can be slow, then # enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to # search using the keyboard; to jump to the search box use <access key> + S # (what the <access key> is depends on the OS and browser, but it is typically # <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down # key> to jump into the search results window, the results can be navigated # using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel # the search. The filter options can be selected when the cursor is inside the # search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys> # to select a filter and <Enter> or <escape> to activate or cancel the filter # option. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a web server instead of a web client using JavaScript. There # are two flavors of web server based searching depending on the EXTERNAL_SEARCH # setting. When disabled, doxygen will generate a PHP script for searching and # an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing # and searching needs to be provided by external tools. See the section # "External Indexing and Searching" for details. # The default value is: NO. # This tag requires that the tag SEARCHENGINE is set to YES. SERVER_BASED_SEARCH = NO # When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP # script for searching. Instead the search results are written to an XML file # which needs to be processed by an external indexer. Doxygen will invoke an # external search engine pointed to by the SEARCHENGINE_URL option to obtain the # search results. # # Doxygen ships with an example indexer (doxyindexer) and search engine # (doxysearch.cgi) which are based on the open source search engine library # Xapian (see: https://xapian.org/). # # See the section "External Indexing and Searching" for details. # The default value is: NO. # This tag requires that the tag SEARCHENGINE is set to YES. EXTERNAL_SEARCH = NO # The SEARCHENGINE_URL should point to a search engine hosted by a web server # which will return the search results when EXTERNAL_SEARCH is enabled. # # Doxygen ships with an example indexer (doxyindexer) and search engine # (doxysearch.cgi) which are based on the open source search engine library # Xapian (see: https://xapian.org/). See the section "External Indexing and # Searching" for details. # This tag requires that the tag SEARCHENGINE is set to YES. SEARCHENGINE_URL = # When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed # search data is written to a file for indexing by an external tool. With the # SEARCHDATA_FILE tag the name of this file can be specified. # The default file is: searchdata.xml. # This tag requires that the tag SEARCHENGINE is set to YES. SEARCHDATA_FILE = searchdata.xml # When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the # EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is # useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple # projects and redirect the results back to the right project. # This tag requires that the tag SEARCHENGINE is set to YES. EXTERNAL_SEARCH_ID = # The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen # projects other than the one defined by this configuration file, but that are # all added to the same external search index. Each project needs to have a # unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of # to a relative location where the documentation can be found. The format is: # EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... # This tag requires that the tag SEARCHENGINE is set to YES. EXTRA_SEARCH_MAPPINGS = #--------------------------------------------------------------------------- # Configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output. # The default value is: YES. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: latex. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. # # Note that when not enabling USE_PDFLATEX the default is latex when enabling # USE_PDFLATEX the default is pdflatex and when in the later case latex is # chosen this is overwritten by pdflatex. For specific output languages the # default can have been set differently, this depends on the implementation of # the output language. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_CMD_NAME = # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate # index for LaTeX. # Note: This tag is used in the Makefile / make.bat. # See also: LATEX_MAKEINDEX_CMD for the part in the generated output file # (.tex). # The default file is: makeindex. # This tag requires that the tag GENERATE_LATEX is set to YES. MAKEINDEX_CMD_NAME = makeindex # The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to # generate index for LaTeX. In case there is no backslash (\) as first character # it will be automatically added in the LaTeX code. # Note: This tag is used in the generated output file (.tex). # See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat. # The default value is: makeindex. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_MAKEINDEX_CMD = makeindex # If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX # documents. This may be useful for small projects and may help to save some # trees in general. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used by the # printer. # Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x # 14 inches) and executive (7.25 x 10.5 inches). # The default value is: a4. # This tag requires that the tag GENERATE_LATEX is set to YES. PAPER_TYPE = a4 # The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names # that should be included in the LaTeX output. The package can be specified just # by its name or with the correct syntax as to be used with the LaTeX # \usepackage command. To get the times font for instance you can specify : # EXTRA_PACKAGES=times or EXTRA_PACKAGES={times} # To use the option intlimits with the amsmath package you can specify: # EXTRA_PACKAGES=[intlimits]{amsmath} # If left blank no extra packages will be included. # This tag requires that the tag GENERATE_LATEX is set to YES. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for the # generated LaTeX document. The header should contain everything until the first # chapter. If it is left blank doxygen will generate a standard header. See # section "Doxygen usage" for information on how to let doxygen write the # default header to a separate file. # # Note: Only use a user-defined header if you know what you are doing! The # following commands have a special meaning inside the header: $title, # $datetime, $date, $doxygenversion, $projectname, $projectnumber, # $projectbrief, $projectlogo. Doxygen will replace $title with the empty # string, for the replacement values of the other commands the user is referred # to HTML_HEADER. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the # generated LaTeX document. The footer should contain everything after the last # chapter. If it is left blank doxygen will generate a standard footer. See # LATEX_HEADER for more information on how to generate a default footer and what # special commands can be used inside the footer. # # Note: Only use a user-defined footer if you know what you are doing! # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_FOOTER = # The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined # LaTeX style sheets that are included after the standard style sheets created # by doxygen. Using this option one can overrule certain style aspects. Doxygen # will copy the style sheet files to the output directory. # Note: The order of the extra style sheet files is of importance (e.g. the last # style sheet in the list overrules the setting of the previous ones in the # list). # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_EXTRA_STYLESHEET = # The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the LATEX_OUTPUT output # directory. Note that the files will be copied as-is; there are no commands or # markers available. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_EXTRA_FILES = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is # prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will # contain links (just like the HTML output) instead of page references. This # makes the output suitable for online browsing using a PDF viewer. # The default value is: YES. # This tag requires that the tag GENERATE_LATEX is set to YES. PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate # the PDF file directly from the LaTeX files. Set this option to YES, to get a # higher quality PDF documentation. # The default value is: YES. # This tag requires that the tag GENERATE_LATEX is set to YES. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode # command to the generated LaTeX files. This will instruct LaTeX to keep running # if errors occur, instead of asking the user for help. This option is also used # when generating formulas in HTML. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_BATCHMODE = NO # If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the # index chapters (such as File Index, Compound Index, etc.) in the output. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_HIDE_INDICES = NO # If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source # code with syntax highlighting in the LaTeX output. # # Note that which sources are shown also depends on other settings such as # SOURCE_BROWSER. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_SOURCE_CODE = NO # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. See # https://en.wikipedia.org/wiki/BibTeX and \cite for more info. # The default value is: plain. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_BIB_STYLE = plain # If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated # page will contain the date and time when the page was generated. Setting this # to NO can help when comparing the output of multiple runs. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_TIMESTAMP = NO # The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute) # path from which the emoji images will be read. If a relative path is entered, # it will be relative to the LATEX_OUTPUT directory. If left blank the # LATEX_OUTPUT directory will be used. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_EMOJI_DIRECTORY = #--------------------------------------------------------------------------- # Configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The # RTF output is optimized for Word 97 and may not look too pretty with other RTF # readers/editors. # The default value is: NO. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: rtf. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF # documents. This may be useful for small projects and may help to save some # trees in general. # The default value is: NO. # This tag requires that the tag GENERATE_RTF is set to YES. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will # contain hyperlink fields. The RTF file will contain links (just like the HTML # output) instead of page references. This makes the output suitable for online # browsing using Word or some other Word compatible readers that support those # fields. # # Note: WordPad (write) and others do not support links. # The default value is: NO. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # configuration file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. # # See also section "Doxygen usage" for information on how to generate the # default style sheet that doxygen normally uses. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an RTF document. Syntax is # similar to doxygen's configuration file. A template extensions file can be # generated using doxygen -e rtf extensionFile. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_EXTENSIONS_FILE = # If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code # with syntax highlighting in the RTF output. # # Note that which sources are shown also depends on other settings such as # SOURCE_BROWSER. # The default value is: NO. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_SOURCE_CODE = NO #--------------------------------------------------------------------------- # Configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for # classes and files. # The default value is: NO. GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. A directory man3 will be created inside the directory specified by # MAN_OUTPUT. # The default directory is: man. # This tag requires that the tag GENERATE_MAN is set to YES. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to the generated # man pages. In case the manual section does not start with a number, the number # 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is # optional. # The default value is: .3. # This tag requires that the tag GENERATE_MAN is set to YES. MAN_EXTENSION = .3 # The MAN_SUBDIR tag determines the name of the directory created within # MAN_OUTPUT in which the man pages are placed. If defaults to man followed by # MAN_EXTENSION with the initial . removed. # This tag requires that the tag GENERATE_MAN is set to YES. MAN_SUBDIR = # If the MAN_LINKS tag is set to YES and doxygen generates man output, then it # will generate one additional man file for each entity documented in the real # man page(s). These additional files only source the real man page, but without # them the man command would be unable to find the correct page. # The default value is: NO. # This tag requires that the tag GENERATE_MAN is set to YES. MAN_LINKS = NO #--------------------------------------------------------------------------- # Configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that # captures the structure of the code including all documentation. # The default value is: NO. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: xml. # This tag requires that the tag GENERATE_XML is set to YES. XML_OUTPUT = xml # If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program # listings (including syntax highlighting and cross-referencing information) to # the XML output. Note that enabling this will significantly increase the size # of the XML output. # The default value is: YES. # This tag requires that the tag GENERATE_XML is set to YES. XML_PROGRAMLISTING = YES # If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include # namespace members in file scope as well, matching the HTML output. # The default value is: NO. # This tag requires that the tag GENERATE_XML is set to YES. XML_NS_MEMB_FILE_SCOPE = NO #--------------------------------------------------------------------------- # Configuration options related to the DOCBOOK output #--------------------------------------------------------------------------- # If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files # that can be used to generate PDF. # The default value is: NO. GENERATE_DOCBOOK = NO # The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be put in # front of it. # The default directory is: docbook. # This tag requires that the tag GENERATE_DOCBOOK is set to YES. DOCBOOK_OUTPUT = docbook # If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the # program listings (including syntax highlighting and cross-referencing # information) to the DOCBOOK output. Note that enabling this will significantly # increase the size of the DOCBOOK output. # The default value is: NO. # This tag requires that the tag GENERATE_DOCBOOK is set to YES. DOCBOOK_PROGRAMLISTING = NO #--------------------------------------------------------------------------- # Configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an # AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures # the structure of the code including all documentation. Note that this feature # is still experimental and incomplete at the moment. # The default value is: NO. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # Configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module # file that captures the structure of the code including all documentation. # # Note that this feature is still experimental and incomplete at the moment. # The default value is: NO. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary # Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI # output from the Perl module output. # The default value is: NO. # This tag requires that the tag GENERATE_PERLMOD is set to YES. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely # formatted so it can be parsed by a human reader. This is useful if you want to # understand what is going on. On the other hand, if this tag is set to NO, the # size of the Perl module output will be much smaller and Perl will parse it # just the same. # The default value is: YES. # This tag requires that the tag GENERATE_PERLMOD is set to YES. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file are # prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful # so different doxyrules.make files included by the same Makefile don't # overwrite each other's variables. # This tag requires that the tag GENERATE_PERLMOD is set to YES. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all # C-preprocessor directives found in the sources and include files. # The default value is: YES. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names # in the source code. If set to NO, only conditional compilation will be # performed. Macro expansion can be done in a controlled way by setting # EXPAND_ONLY_PREDEF to YES. # The default value is: NO. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then # the macro expansion is limited to the macros specified with the PREDEFINED and # EXPAND_AS_DEFINED tags. # The default value is: NO. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. EXPAND_ONLY_PREDEF = YES # If the SEARCH_INCLUDES tag is set to YES, the include files in the # INCLUDE_PATH will be searched if a #include is found. # The default value is: YES. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by the # preprocessor. # This tag requires that the tag SEARCH_INCLUDES is set to YES. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will be # used. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that are # defined before the preprocessor is started (similar to the -D option of e.g. # gcc). The argument of the tag is a list of macros of the form: name or # name=definition (no spaces). If the definition and the "=" are omitted, "=1" # is assumed. To prevent a macro definition from being undefined via #undef or # recursively expanded use the := operator instead of the = operator. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. PREDEFINED = NS_UNAVAILABLE \ "NS_ENUM(type, name)=enum name" \ NS_ASSUME_NONNULL_BEGIN \ NS_ASSUME_NONNULL_END \ NS_DESIGNATED_INITIALIZER \ __attribute__(x)= # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # tag can be used to specify a list of macro names that should be expanded. The # macro definition that is found in the sources will be used. Use the PREDEFINED # tag if you want to use a different macro definition that overrules the # definition found in the source code. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will # remove all references to function-like macros that are alone on a line, have # an all uppercase name, and do not end with a semicolon. Such function macros # are typically used for boiler-plate code, and will confuse the parser if not # removed. # The default value is: YES. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration options related to external references #--------------------------------------------------------------------------- # The TAGFILES tag can be used to specify one or more tag files. For each tag # file the location of the external documentation should be added. The format of # a tag file without this location is as follows: # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # TAGFILES = file1=loc1 "file2 = loc2" ... # where loc1 and loc2 can be relative or absolute paths or URLs. See the # section "Linking to external documentation" for more information about the use # of tag files. # Note: Each tag file must have a unique name (where the name does NOT include # the path). If a tag file is not located in the directory in which doxygen is # run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create a # tag file that is based on the input files it reads. See section "Linking to # external documentation" for more information about the usage of tag files. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES, all external class will be listed in # the class index. If set to NO, only the inherited external classes will be # listed. # The default value is: NO. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed # in the modules index. If set to NO, only the current project's groups will be # listed. # The default value is: YES. EXTERNAL_GROUPS = YES # If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in # the related pages index. If set to NO, only the current project's pages will # be listed. # The default value is: YES. EXTERNAL_PAGES = YES #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram # (in HTML and LaTeX) for classes with base or super classes. Setting the tag to # NO turns the diagrams off. Note that this option also works with HAVE_DOT # disabled, but it is recommended to install and use dot, since it yields more # powerful graphs. # The default value is: YES. CLASS_DIAGRAMS = YES # You can include diagrams made with dia in doxygen documentation. Doxygen will # then run dia to produce the diagram and insert it in the documentation. The # DIA_PATH tag allows you to specify the directory where the dia binary resides. # If left empty dia is assumed to be found in the default search path. DIA_PATH = # If set to YES the inheritance and collaboration graphs will hide inheritance # and usage relations if the target is undocumented or is not a class. # The default value is: YES. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz (see: # http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent # Bell Labs. The other options in this section have no effect if this option is # set to NO # The default value is: NO. HAVE_DOT = NO # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed # to run in parallel. When set to 0 doxygen will base this on the number of # processors available in the system. You can set it explicitly to a value # larger than 0 to get control over the balance between CPU load and processing # speed. # Minimum value: 0, maximum value: 32, default value: 0. # This tag requires that the tag HAVE_DOT is set to YES. DOT_NUM_THREADS = 0 # When you want a differently looking font in the dot files that doxygen # generates you can specify the font name using DOT_FONTNAME. You need to make # sure dot is able to find the font, which can be done by putting it in a # standard location or by setting the DOTFONTPATH environment variable or by # setting DOT_FONTPATH to the directory containing the font. # The default value is: Helvetica. # This tag requires that the tag HAVE_DOT is set to YES. DOT_FONTNAME = Helvetica # The DOT_FONTSIZE tag can be used to set the size (in points) of the font of # dot graphs. # Minimum value: 4, maximum value: 24, default value: 10. # This tag requires that the tag HAVE_DOT is set to YES. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the default font as specified with # DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set # the path where dot can find it using this tag. # This tag requires that the tag HAVE_DOT is set to YES. DOT_FONTPATH = # If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for # each documented class showing the direct and indirect inheritance relations. # Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a # graph for each documented class showing the direct and indirect implementation # dependencies (inheritance, containment, and class references variables) of the # class with other documented classes. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for # groups, showing the direct groups dependencies. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES, doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. UML_LOOK = NO # If the UML_LOOK tag is enabled, the fields and methods are shown inside the # class node. If there are many fields or methods and many nodes the graph may # become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the # number of items for each type to make the size more manageable. Set this to 0 # for no limit. Note that the threshold may be exceeded by 50% before the limit # is enforced. So when you set the threshold to 10, up to 15 fields may appear, # but if the number exceeds 15, the total amount of fields shown is limited to # 10. # Minimum value: 0, maximum value: 100, default value: 10. # This tag requires that the tag HAVE_DOT is set to YES. UML_LIMIT_NUM_FIELDS = 10 # If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and # collaboration graphs will show the relations between templates and their # instances. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. TEMPLATE_RELATIONS = NO # If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to # YES then doxygen will generate a graph for each documented file showing the # direct and indirect include dependencies of the file with other documented # files. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. INCLUDE_GRAPH = YES # If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are # set to YES then doxygen will generate a graph for each documented file showing # the direct and indirect include dependencies of the file with other documented # files. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH tag is set to YES then doxygen will generate a call # dependency graph for every global function or class method. # # Note that enabling this option will significantly increase the time of a run. # So in most cases it will be better to enable call graphs for selected # functions only using the \callgraph command. Disabling a call graph can be # accomplished by means of the command \hidecallgraph. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. CALL_GRAPH = NO # If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller # dependency graph for every global function or class method. # # Note that enabling this option will significantly increase the time of a run. # So in most cases it will be better to enable caller graphs for selected # functions only using the \callergraph command. Disabling a caller graph can be # accomplished by means of the command \hidecallergraph. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical # hierarchy of all classes instead of a textual one. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the # dependencies a directory has on other directories in a graphical way. The # dependency relations are determined by the #include relations between the # files in the directories. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. For an explanation of the image formats see the section # output formats in the documentation of the dot tool (Graphviz (see: # http://www.graphviz.org/)). # Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order # to make the SVG files visible in IE 9+ (other browsers do not have this # requirement). # Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo, # png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and # png:gdiplus:gdiplus. # The default value is: png. # This tag requires that the tag HAVE_DOT is set to YES. DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # # Note that this requires a modern browser other than Internet Explorer. Tested # and working are Firefox, Chrome, Safari, and Opera. # Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make # the SVG files visible. Older versions of IE do not have SVG support. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. INTERACTIVE_SVG = NO # The DOT_PATH tag can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. # This tag requires that the tag HAVE_DOT is set to YES. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the \dotfile # command). # This tag requires that the tag HAVE_DOT is set to YES. DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the \mscfile # command). MSCFILE_DIRS = # The DIAFILE_DIRS tag can be used to specify one or more directories that # contain dia files that are included in the documentation (see the \diafile # command). DIAFILE_DIRS = # When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the # path where java can find the plantuml.jar file. If left blank, it is assumed # PlantUML is not used or called during a preprocessing step. Doxygen will # generate a warning when it encounters a \startuml command in this case and # will not generate output for the diagram. PLANTUML_JAR_PATH = # When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a # configuration file for plantuml. PLANTUML_CFG_FILE = # When using plantuml, the specified paths are searched for files specified by # the !include statement in a plantuml block. PLANTUML_INCLUDE_PATH = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes # that will be shown in the graph. If the number of nodes in a graph becomes # larger than this value, doxygen will truncate the graph, which is visualized # by representing a node as a red box. Note that doxygen if the number of direct # children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that # the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. # Minimum value: 0, maximum value: 10000, default value: 50. # This tag requires that the tag HAVE_DOT is set to YES. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs # generated by dot. A depth value of 3 means that only nodes reachable from the # root by following a path via at most 3 edges will be shown. Nodes that lay # further from the root node will be omitted. Note that setting this option to 1 # or 2 may greatly reduce the computation time needed for large code bases. Also # note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. # Minimum value: 0, maximum value: 1000, default value: 0. # This tag requires that the tag HAVE_DOT is set to YES. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not seem # to support this out of the box. # # Warning: Depending on the platform used, enabling this option may lead to # badly anti-aliased labels on the edges of a graph (i.e. they become hard to # read). # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) support # this, this feature is disabled by default. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page # explaining the meaning of the various boxes and arrows in the dot generated # graphs. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot # files that are used to generate the various graphs. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. DOT_CLEANUP = YES
engine/shell/platform/darwin/Doxyfile/0
{ "file_path": "engine/shell/platform/darwin/Doxyfile", "repo_id": "engine", "token_count": 33553 }
313
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" #include "flutter/fml/logging.h" FLUTTER_ASSERT_ARC @implementation FlutterBinaryMessengerRelay #pragma mark - FlutterBinaryMessenger - (instancetype)initWithParent:(NSObject<FlutterBinaryMessenger>*)parent { self = [super init]; if (self != nil) { _parent = parent; } return self; } - (void)sendOnChannel:(NSString*)channel message:(NSData*)message { if (self.parent) { [self.parent sendOnChannel:channel message:message binaryReply:nil]; } else { FML_LOG(WARNING) << "Communicating on a dead channel."; } } - (void)sendOnChannel:(NSString*)channel message:(NSData*)message binaryReply:(FlutterBinaryReply)callback { if (self.parent) { [self.parent sendOnChannel:channel message:message binaryReply:callback]; } else { FML_LOG(WARNING) << "Communicating on a dead channel."; } } - (NSObject<FlutterTaskQueue>*)makeBackgroundTaskQueue { if (self.parent) { return [self.parent makeBackgroundTaskQueue]; } else { return nil; }; } - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel binaryMessageHandler: (FlutterBinaryMessageHandler)handler { if (self.parent) { return [self.parent setMessageHandlerOnChannel:channel binaryMessageHandler:handler]; } else { FML_LOG(WARNING) << "Communicating on a dead channel."; return -1; } } - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel binaryMessageHandler:(FlutterBinaryMessageHandler)handler taskQueue: (NSObject<FlutterTaskQueue>*)taskQueue { if (self.parent) { return [self.parent setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:taskQueue]; } else { FML_LOG(WARNING) << "Communicating on a dead channel."; return -1; } } - (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { if (self.parent) { return [self.parent cleanUpConnection:connection]; } else { FML_LOG(WARNING) << "Communicating on a dead channel."; } } @end
engine/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.mm/0
{ "file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.mm", "repo_id": "engine", "token_count": 1058 }
314
doxygen Doxyfile 2>&1 | grep "not documented"
engine/shell/platform/darwin/find-undocumented-ios.sh/0
{ "file_path": "engine/shell/platform/darwin/find-undocumented-ios.sh", "repo_id": "engine", "token_count": 17 }
315
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ #import <UIKit/UIKit.h> #import "FlutterCodecs.h" #import "FlutterMacros.h" NS_ASSUME_NONNULL_BEGIN /** * Wraps a `UIView` for embedding in the Flutter hierarchy */ @protocol FlutterPlatformView <NSObject> /** * Returns a reference to the `UIView` that is wrapped by this `FlutterPlatformView`. */ - (UIView*)view; @end FLUTTER_DARWIN_EXPORT @protocol FlutterPlatformViewFactory <NSObject> /** * Create a `FlutterPlatformView`. * * Implemented by iOS code that expose a `UIView` for embedding in a Flutter app. * * The implementation of this method should create a new `UIView` and return it. * * @param frame The rectangle for the newly created `UIView` measured in points. * @param viewId A unique identifier for this `UIView`. * @param args Parameters for creating the `UIView` sent from the Dart side of the Flutter app. * If `createArgsCodec` is not implemented, or if no creation arguments were sent from the Dart * code, this will be null. Otherwise this will be the value sent from the Dart code as decoded by * `createArgsCodec`. */ - (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args; /** * Returns the `FlutterMessageCodec` for decoding the args parameter of `createWithFrame`. * * Only needs to be implemented if `createWithFrame` needs an arguments parameter. */ @optional - (NSObject<FlutterMessageCodec>*)createArgsCodec; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_
engine/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h", "repo_id": "engine", "token_count": 705 }
316
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ #include "flutter/common/settings.h" #include "flutter/runtime/platform_data.h" #include "flutter/shell/common/engine.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterDartProject.h" #import "flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h" NS_ASSUME_NONNULL_BEGIN flutter::Settings FLTDefaultSettingsForBundle(NSBundle* _Nullable bundle = nil, NSProcessInfo* _Nullable processInfoOrNil = nil); @interface FlutterDartProject () @property(nonatomic, readonly) BOOL isWideGamutEnabled; @property(nonatomic, readonly) BOOL isImpellerEnabled; /** * This is currently used for *only for tests* to override settings. */ - (instancetype)initWithSettings:(const flutter::Settings&)settings; - (const flutter::Settings&)settings; - (const flutter::PlatformData)defaultPlatformData; - (flutter::RunConfiguration)runConfiguration; - (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil; - (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil libraryOrNil:(nullable NSString*)dartLibraryOrNil; - (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil libraryOrNil:(nullable NSString*)dartLibraryOrNil entrypointArgs: (nullable NSArray<NSString*>*)entrypointArgs; + (NSString*)flutterAssetsName:(NSBundle*)bundle; + (NSString*)domainNetworkPolicy:(NSDictionary*)appTransportSecurity; + (bool)allowsArbitraryLoads:(NSDictionary*)appTransportSecurity; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h", "repo_id": "engine", "token_count": 891 }
317
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERINDIRECTSCRIBBLEDELEGATE_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERINDIRECTSCRIBBLEDELEGATE_H_ #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class FlutterTextInputPlugin; @protocol FlutterIndirectScribbleDelegate <NSObject> - (void)flutterTextInputPlugin:(FlutterTextInputPlugin*)textInputPlugin focusElement:(UIScribbleElementIdentifier)elementIdentifier atPoint:(CGPoint)referencePoint result:(FlutterResult)callback; - (void)flutterTextInputPlugin:(FlutterTextInputPlugin*)textInputPlugin requestElementsInRect:(CGRect)rect result:(FlutterResult)callback; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERINDIRECTSCRIBBLEDELEGATE_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h", "repo_id": "engine", "token_count": 440 }
318
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWS_INTERNAL_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWS_INTERNAL_H_ #include <Metal/Metal.h> #include "flutter/flow/embedded_views.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" #include "flutter/shell/common/shell.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" #import "flutter/shell/platform/darwin/ios/ios_context.h" @class FlutterTouchInterceptingView; // A UIView that acts as a clipping mask for the |ChildClippingView|. // // On the [UIView drawRect:] method, this view performs a series of clipping operations and sets the // alpha channel to the final resulting area to be 1; it also sets the "clipped out" area's alpha // channel to be 0. // // When a UIView sets a |FlutterClippingMaskView| as its `maskView`, the alpha channel of the UIView // is replaced with the alpha channel of the |FlutterClippingMaskView|. @interface FlutterClippingMaskView : UIView - (instancetype)initWithFrame:(CGRect)frame screenScale:(CGFloat)screenScale; - (void)reset; // Adds a clip rect operation to the queue. // // The `clipSkRect` is transformed with the `matrix` before adding to the queue. - (void)clipRect:(const SkRect&)clipSkRect matrix:(const SkMatrix&)matrix; // Adds a clip rrect operation to the queue. // // The `clipSkRRect` is transformed with the `matrix` before adding to the queue. - (void)clipRRect:(const SkRRect&)clipSkRRect matrix:(const SkMatrix&)matrix; // Adds a clip path operation to the queue. // // The `path` is transformed with the `matrix` before adding to the queue. - (void)clipPath:(const SkPath&)path matrix:(const SkMatrix&)matrix; @end // A pool that provides |FlutterClippingMaskView|s. // // The pool has a capacity that can be set in the initializer. // When requesting a FlutterClippingMaskView, the pool will first try to reuse an available maskView // in the pool. If there are none available, a new FlutterClippingMaskView is constructed. If the // capacity is reached, the newly constructed FlutterClippingMaskView is not added to the pool. // // Call |insertViewToPoolIfNeeded:| to return a maskView to the pool. @interface FlutterClippingMaskViewPool : NSObject // Initialize the pool with `capacity`. When the `capacity` is reached, a FlutterClippingMaskView is // constructed when requested, and it is not added to the pool. - (instancetype)initWithCapacity:(NSInteger)capacity; // Reuse a maskView from the pool, or allocate a new one. - (FlutterClippingMaskView*)getMaskViewWithFrame:(CGRect)frame; // Insert the `maskView` into the pool. - (void)insertViewToPoolIfNeeded:(FlutterClippingMaskView*)maskView; @end // An object represents a blur filter. // // This object produces a `backdropFilterView`. // To blur a View, add `backdropFilterView` as a subView of the View. @interface PlatformViewFilter : NSObject // Determines the rect of the blur effect in the coordinate system of `backdropFilterView`'s // parentView. @property(assign, nonatomic, readonly) CGRect frame; // Determines the blur intensity. // // It is set as the value of `inputRadius` of the `gaussianFilter` that is internally used. @property(assign, nonatomic, readonly) CGFloat blurRadius; // This is the view to use to blur the PlatformView. // // It is a modified version of UIKit's `UIVisualEffectView`. // The inputRadius can be customized and it doesn't add any color saturation to the blurred view. @property(nonatomic, retain, readonly) UIVisualEffectView* backdropFilterView; // For testing only. + (void)resetPreparation; - (instancetype)init NS_UNAVAILABLE; // Initialize the filter object. // // The `frame` determines the rect of the blur effect in the coordinate system of // `backdropFilterView`'s parentView. The `blurRadius` determines the blur intensity. It is set as // the value of `inputRadius` of the `gaussianFilter` that is internally used. The // `UIVisualEffectView` is the view that is used to add the blur effects. It is modified to become // `backdropFilterView`, which better supports the need of Flutter. // // Note: if the implementation of UIVisualEffectView changes in a way that affects the // implementation in `PlatformViewFilter`, this method will return nil. - (instancetype)initWithFrame:(CGRect)frame blurRadius:(CGFloat)blurRadius visualEffectView:(UIVisualEffectView*)visualEffectView NS_DESIGNATED_INITIALIZER; @end // The parent view handles clipping to its subViews. @interface ChildClippingView : UIView // Applies blur backdrop filters to the ChildClippingView with blur values from // filters. - (void)applyBlurBackdropFilters:(NSArray<PlatformViewFilter*>*)filters; // For testing only. - (NSMutableArray*)backdropFilterSubviews; @end namespace flutter { // Converts a SkMatrix to CATransform3D. // Certain fields are ignored in CATransform3D since SkMatrix is 3x3 and CATransform3D is 4x4. CATransform3D GetCATransform3DFromSkMatrix(const SkMatrix& matrix); // Reset the anchor of `layer` to match the transform operation from flow. // The position of the `layer` should be unchanged after resetting the anchor. void ResetAnchor(CALayer* layer); CGRect GetCGRectFromSkRect(const SkRect& clipSkRect); BOOL BlurRadiusEqualToBlurRadius(CGFloat radius1, CGFloat radius2); class IOSContextGL; class IOSSurface; struct FlutterPlatformViewLayer { FlutterPlatformViewLayer(const fml::scoped_nsobject<UIView>& overlay_view, const fml::scoped_nsobject<UIView>& overlay_view_wrapper, std::unique_ptr<IOSSurface> ios_surface, std::unique_ptr<Surface> surface); ~FlutterPlatformViewLayer(); fml::scoped_nsobject<UIView> overlay_view; fml::scoped_nsobject<UIView> overlay_view_wrapper; std::unique_ptr<IOSSurface> ios_surface; std::unique_ptr<Surface> surface; // Whether a frame for this layer was submitted. bool did_submit_last_frame; // 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. GrDirectContext* gr_context; }; // This class isn't thread safe. class FlutterPlatformViewLayerPool { public: FlutterPlatformViewLayerPool() = default; ~FlutterPlatformViewLayerPool() = default; // 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<FlutterPlatformViewLayer> GetLayer(GrDirectContext* gr_context, const std::shared_ptr<IOSContext>& ios_context, MTLPixelFormat pixel_format); // 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<FlutterPlatformViewLayer>> GetUnusedLayers(); // Marks the layers in the pool as available for reuse. void RecycleLayers(); 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; std::vector<std::shared_ptr<FlutterPlatformViewLayer>> layers_; FML_DISALLOW_COPY_AND_ASSIGN(FlutterPlatformViewLayerPool); }; class FlutterPlatformViewsController { public: FlutterPlatformViewsController(); ~FlutterPlatformViewsController(); fml::WeakPtr<flutter::FlutterPlatformViewsController> GetWeakPtr(); void SetFlutterView(UIView* flutter_view); void SetFlutterViewController(UIViewController* flutter_view_controller); UIViewController* getFlutterViewController(); void RegisterViewFactory( NSObject<FlutterPlatformViewFactory>* factory, NSString* factoryId, FlutterPlatformViewGestureRecognizersBlockingPolicy gestureRecognizerBlockingPolicy); // Called at the beginning of each frame. void BeginFrame(SkISize frame_size); // Indicates that we don't compisite any platform views or overlays during this frame. // Also reverts the composition_order_ to its original state at the beginning of the frame. void CancelFrame(); void PrerollCompositeEmbeddedView(int64_t view_id, std::unique_ptr<flutter::EmbeddedViewParams> params); size_t EmbeddedViewCount(); // Returns the `FlutterPlatformView`'s `view` object associated with the view_id. // // If the `FlutterPlatformViewsController` does not contain any `FlutterPlatformView` object or // a `FlutterPlatformView` object associated with the view_id cannot be found, the method // returns nil. UIView* GetPlatformViewByID(int64_t view_id); // Returns the `FlutterTouchInterceptingView` with the view_id. // // If the `FlutterPlatformViewsController` does not contain any `FlutterPlatformView` object or // a `FlutterPlatformView` object associated with the view_id cannot be found, the method // returns nil. FlutterTouchInterceptingView* GetFlutterTouchInterceptingViewByID(int64_t view_id); PostPrerollResult PostPrerollAction( const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger); void EndFrame(bool should_resubmit_frame, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger); DlCanvas* CompositeEmbeddedView(int64_t view_id); // The rect of the platform view at index view_id. This rect has been translated into the // host view coordinate system. Units are device screen pixels. SkRect GetPlatformViewRect(int64_t view_id); // Discards all platform views instances and auxiliary resources. void Reset(); bool SubmitFrame(GrDirectContext* gr_context, const std::shared_ptr<IOSContext>& ios_context, std::unique_ptr<SurfaceFrame> frame); void OnMethodCall(FlutterMethodCall* call, FlutterResult result); // Returns the platform view id if the platform view (or any of its descendant view) is the first // responder. Returns -1 if no such platform view is found. long FindFirstResponderPlatformViewId(); // Pushes backdrop filter mutation to the mutator stack of each visited platform view. void PushFilterToVisitedPlatformViews(const std::shared_ptr<const DlImageFilter>& filter, const SkRect& filter_rect); // Pushes the view id of a visted platform view to the list of visied platform views. void PushVisitedPlatformView(int64_t view_id) { visited_platform_views_.push_back(view_id); } private: static const size_t kMaxLayerAllocations = 2; using LayersMap = std::map<int64_t, std::vector<std::shared_ptr<FlutterPlatformViewLayer>>>; void OnCreate(FlutterMethodCall* call, FlutterResult result); void OnDispose(FlutterMethodCall* call, FlutterResult result); void OnAcceptGesture(FlutterMethodCall* call, FlutterResult result); void OnRejectGesture(FlutterMethodCall* call, FlutterResult result); // Dispose the views in `views_to_dispose_`. void DisposeViews(); // Returns true if there are embedded views in the scene at current frame // Or there will be embedded views in the next frame. // TODO(cyanglaz): https://github.com/flutter/flutter/issues/56474 // Make this method check if there are pending view operations instead. // Also rename it to `HasPendingViewOperations`. bool HasPlatformViewThisOrNextFrame(); // Traverse the `mutators_stack` and return the number of clip operations. int CountClips(const MutatorsStack& mutators_stack); void ClipViewSetMaskView(UIView* clipView); // Applies the mutators in the mutators_stack to the UIView chain that was constructed by // `ReconstructClipViewsChain` // // Clips are applied to the `embedded_view`'s super view(|ChildClippingView|) using a // |FlutterClippingMaskView|. Transforms are applied to `embedded_view` // // The `bounding_rect` is the final bounding rect of the PlatformView // (EmbeddedViewParams::finalBoundingRect). If a clip mutator's rect contains the final bounding // rect of the PlatformView, the clip mutator is not applied for performance optimization. void ApplyMutators(const MutatorsStack& mutators_stack, UIView* embedded_view, const SkRect& bounding_rect); void CompositeWithParams(int64_t view_id, const EmbeddedViewParams& params); // Allocates a new FlutterPlatformViewLayer if needed, draws the pixels within the rect from // the picture on the layer's canvas. std::shared_ptr<FlutterPlatformViewLayer> GetLayer(GrDirectContext* gr_context, const std::shared_ptr<IOSContext>& ios_context, EmbedderViewSlice* slice, SkIRect rect, int64_t view_id, int64_t overlay_id, MTLPixelFormat pixel_format); // Removes overlay views and platform views that aren't needed in the current frame. // Must run on the platform thread. void RemoveUnusedLayers(); // Appends the overlay views and platform view and sets their z index based on the composition // order. void BringLayersIntoView(LayersMap layer_map); // Begin a CATransaction. // This transaction needs to be balanced with |CommitCATransactionIfNeeded|. void BeginCATransaction(); // Commit a CATransaction if |BeginCATransaction| has been called during the frame. void CommitCATransactionIfNeeded(); // Resets the state of the frame. void ResetFrameState(); // The pool of reusable view layers. The pool allows to recycle layer in each frame. std::unique_ptr<FlutterPlatformViewLayerPool> layer_pool_; // The platform view's |EmbedderViewSlice| keyed off the view id, which contains any subsequent // operation until the next platform view or the end of the last leaf node in the layer tree. // // The Slices are deleted by the FlutterPlatformViewsController.reset(). std::map<int64_t, std::unique_ptr<EmbedderViewSlice>> slices_; fml::scoped_nsobject<FlutterMethodChannel> channel_; fml::scoped_nsobject<UIView> flutter_view_; fml::scoped_nsobject<UIViewController> flutter_view_controller_; fml::scoped_nsobject<FlutterClippingMaskViewPool> mask_view_pool_; std::map<std::string, fml::scoped_nsobject<NSObject<FlutterPlatformViewFactory>>> factories_; std::map<int64_t, fml::scoped_nsobject<NSObject<FlutterPlatformView>>> views_; std::map<int64_t, fml::scoped_nsobject<FlutterTouchInterceptingView>> touch_interceptors_; // Mapping a platform view ID to the top most parent view (root_view) of a platform view. In // |SubmitFrame|, root_views_ are added to flutter_view_ as child views. // // The platform view with the view ID is a child of the root view; If the platform view is not // clipped, and no clipping view is added, the root view will be the intercepting view. std::map<int64_t, fml::scoped_nsobject<UIView>> root_views_; // Mapping a platform view ID to its latest composition params. std::map<int64_t, EmbeddedViewParams> current_composition_params_; // Mapping a platform view ID to the count of the clipping operations that were applied to the // platform view last time it was composited. std::map<int64_t, int64_t> clip_count_; SkISize frame_size_; // The number of frames the rasterizer task runner will continue // to run on the platform thread after no platform view is rendered. // // Note: this is an arbitrary number that attempts to account for cases // where the platform view might be momentarily off the screen. static const int kDefaultMergedLeaseDuration = 10; // Method channel `OnDispose` calls adds the views to be disposed to this set to be disposed on // the next frame. std::unordered_set<int64_t> views_to_dispose_; // A vector of embedded view IDs according to their composition order. // The last ID in this vector belond to the that is composited on top of all others. std::vector<int64_t> composition_order_; // A vector of visited platform view IDs. std::vector<int64_t> visited_platform_views_; // The latest composition order that was presented in Present(). std::vector<int64_t> active_composition_order_; // Only compoiste platform views in this set. std::unordered_set<int64_t> views_to_recomposite_; // The FlutterPlatformViewGestureRecognizersBlockingPolicy for each type of platform view. std::map<std::string, FlutterPlatformViewGestureRecognizersBlockingPolicy> gesture_recognizers_blocking_policies_; bool catransaction_added_ = false; // WeakPtrFactory must be the last member. std::unique_ptr<fml::WeakPtrFactory<FlutterPlatformViewsController>> weak_factory_; #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG // A set to keep track of embedded views that does not have (0, 0) origin. // An insertion triggers a warning message about non-zero origin logged on the debug console. // See https://github.com/flutter/flutter/issues/109700 for details. std::unordered_set<int64_t> non_zero_origin_views_; #endif FML_DISALLOW_COPY_AND_ASSIGN(FlutterPlatformViewsController); }; } // namespace flutter // A UIView that is used as the parent for embedded UIViews. // // This view has 2 roles: // 1. Delay or prevent touch events from arriving the embedded view. // 2. Dispatching all events that are hittested to the embedded view to the FlutterView. @interface FlutterTouchInterceptingView : UIView - (instancetype)initWithEmbeddedView:(UIView*)embeddedView platformViewsController: (fml::WeakPtr<flutter::FlutterPlatformViewsController>)platformViewsController gestureRecognizersBlockingPolicy: (FlutterPlatformViewGestureRecognizersBlockingPolicy)blockingPolicy; // Stop delaying any active touch sequence (and let it arrive the embedded view). - (void)releaseGesture; // Prevent the touch sequence from ever arriving to the embedded view. - (void)blockGesture; // Get embedded view - (UIView*)embeddedView; // Sets flutterAccessibilityContainer as this view's accessibilityContainer. - (void)setFlutterAccessibilityContainer:(NSObject*)flutterAccessibilityContainer; @end @interface UIView (FirstResponder) // Returns YES if a view or any of its descendant view is the first responder. Returns NO otherwise. @property(nonatomic, readonly) BOOL flt_hasFirstResponderInViewHierarchySubtree; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWS_INTERNAL_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h", "repo_id": "engine", "token_count": 6416 }
319
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" #import <OCMock/OCMock.h> #import <XCTest/XCTest.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" FLUTTER_ASSERT_ARC @interface FlutterEngine () - (nonnull FlutterTextInputPlugin*)textInputPlugin; @end @interface FlutterTextInputView () @property(nonatomic, copy) NSString* autofillId; - (void)setEditableTransform:(NSArray*)matrix; - (void)setTextInputClient:(int)client; - (void)setTextInputState:(NSDictionary*)state; - (void)setMarkedRect:(CGRect)markedRect; - (void)updateEditingState; - (BOOL)isVisibleToAutofill; - (id<FlutterTextInputDelegate>)textInputDelegate; - (void)configureWithDictionary:(NSDictionary*)configuration; @end @interface FlutterTextInputViewSpy : FlutterTextInputView @property(nonatomic, assign) UIAccessibilityNotifications receivedNotification; @property(nonatomic, assign) id receivedNotificationTarget; @property(nonatomic, assign) BOOL isAccessibilityFocused; - (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(id)target; @end @implementation FlutterTextInputViewSpy { } - (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(id)target { self.receivedNotification = notification; self.receivedNotificationTarget = target; } - (BOOL)accessibilityElementIsFocused { return _isAccessibilityFocused; } @end @interface FlutterSecureTextInputView : FlutterTextInputView @property(nonatomic, strong) UITextField* textField; @end @interface FlutterTextInputPlugin () @property(nonatomic, assign) FlutterTextInputView* activeView; @property(nonatomic, readonly) UIView* inputHider; @property(nonatomic, readonly) UIView* keyboardViewContainer; @property(nonatomic, readonly) UIView* keyboardView; @property(nonatomic, assign) UIView* cachedFirstResponder; @property(nonatomic, readonly) CGRect keyboardRect; @property(nonatomic, readonly) NSMutableDictionary<NSString*, FlutterTextInputView*>* autofillContext; - (void)cleanUpViewHierarchy:(BOOL)includeActiveView clearText:(BOOL)clearText delayRemoval:(BOOL)delayRemoval; - (NSArray<UIView*>*)textInputViews; - (UIView*)hostView; - (void)addToInputParentViewIfNeeded:(FlutterTextInputView*)inputView; - (void)startLiveTextInput; - (void)showKeyboardAndRemoveScreenshot; @end @interface FlutterTextInputPluginTest : XCTestCase @end @implementation FlutterTextInputPluginTest { NSDictionary* _template; NSDictionary* _passwordTemplate; id engine; FlutterTextInputPlugin* textInputPlugin; FlutterViewController* viewController; } - (void)setUp { [super setUp]; engine = OCMClassMock([FlutterEngine class]); textInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine]; viewController = [[FlutterViewController alloc] init]; textInputPlugin.viewController = viewController; // Clear pasteboard between tests. UIPasteboard.generalPasteboard.items = @[]; } - (void)tearDown { textInputPlugin = nil; engine = nil; [textInputPlugin.autofillContext removeAllObjects]; [textInputPlugin cleanUpViewHierarchy:YES clearText:YES delayRemoval:NO]; [[[[textInputPlugin textInputView] superview] subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)]; viewController = nil; [super tearDown]; } - (void)setClientId:(int)clientId configuration:(NSDictionary*)config { FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" arguments:@[ [NSNumber numberWithInt:clientId], config ]]; [textInputPlugin handleMethodCall:setClientCall result:^(id _Nullable result){ }]; } - (void)setTextInputShow { FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.show" arguments:@[]]; [textInputPlugin handleMethodCall:setClientCall result:^(id _Nullable result){ }]; } - (void)setTextInputHide { FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.hide" arguments:@[]]; [textInputPlugin handleMethodCall:setClientCall result:^(id _Nullable result){ }]; } - (void)flushScheduledAsyncBlocks { __block bool done = false; XCTestExpectation* expectation = [[XCTestExpectation alloc] initWithDescription:@"Testing on main queue"]; dispatch_async(dispatch_get_main_queue(), ^{ done = true; }); dispatch_async(dispatch_get_main_queue(), ^{ XCTAssertTrue(done); [expectation fulfill]; }); [self waitForExpectations:@[ expectation ] timeout:10]; } - (NSMutableDictionary*)mutableTemplateCopy { if (!_template) { _template = @{ @"inputType" : @{@"name" : @"TextInuptType.text"}, @"keyboardAppearance" : @"Brightness.light", @"obscureText" : @NO, @"inputAction" : @"TextInputAction.unspecified", @"smartDashesType" : @"0", @"smartQuotesType" : @"0", @"autocorrect" : @YES, @"enableInteractiveSelection" : @YES, }; } return [_template mutableCopy]; } - (NSArray<FlutterTextInputView*>*)installedInputViews { return (NSArray<FlutterTextInputView*>*)[textInputPlugin.textInputViews filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self isKindOfClass: %@", [FlutterTextInputView class]]]; } - (FlutterTextRange*)getLineRangeFromTokenizer:(id<UITextInputTokenizer>)tokenizer atIndex:(NSInteger)index { UITextRange* range = [tokenizer rangeEnclosingPosition:[FlutterTextPosition positionWithIndex:index] withGranularity:UITextGranularityLine inDirection:UITextLayoutDirectionRight]; XCTAssertTrue([range isKindOfClass:[FlutterTextRange class]]); return (FlutterTextRange*)range; } - (void)updateConfig:(NSDictionary*)config { FlutterMethodCall* updateConfigCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.updateConfig" arguments:config]; [textInputPlugin handleMethodCall:updateConfigCall result:^(id _Nullable result){ }]; } #pragma mark - Tests - (void)testWillNotCrashWhenViewControllerIsNil { FlutterEngine* flutterEngine = [[FlutterEngine alloc] init]; FlutterTextInputPlugin* inputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:(id<FlutterTextInputDelegate>)flutterEngine]; XCTAssertNil(inputPlugin.viewController); FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.show" arguments:nil]; XCTestExpectation* expectation = [[XCTestExpectation alloc] initWithDescription:@"result called"]; [inputPlugin handleMethodCall:methodCall result:^(id _Nullable result) { XCTAssertNil(result); [expectation fulfill]; }]; XCTAssertNil(inputPlugin.activeView); [self waitForExpectations:@[ expectation ] timeout:1.0]; } - (void)testInvokeStartLiveTextInput { FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.startLiveTextInput" arguments:nil]; FlutterTextInputPlugin* mockPlugin = OCMPartialMock(textInputPlugin); [mockPlugin handleMethodCall:methodCall result:^(id _Nullable result){ }]; OCMVerify([mockPlugin startLiveTextInput]); } - (void)testNoDanglingEnginePointer { __weak FlutterTextInputPlugin* weakFlutterTextInputPlugin; FlutterViewController* flutterViewController = [[FlutterViewController alloc] init]; __weak FlutterEngine* weakFlutterEngine; FlutterTextInputView* currentView; // The engine instance will be deallocated after the autorelease pool is drained. @autoreleasepool { FlutterEngine* flutterEngine = OCMClassMock([FlutterEngine class]); weakFlutterEngine = flutterEngine; NSAssert(weakFlutterEngine, @"flutter engine must not be nil"); FlutterTextInputPlugin* flutterTextInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:(id<FlutterTextInputDelegate>)flutterEngine]; weakFlutterTextInputPlugin = flutterTextInputPlugin; flutterTextInputPlugin.viewController = flutterViewController; // Set client so the text input plugin has an active view. NSDictionary* config = self.mutableTemplateCopy; FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" arguments:@[ [NSNumber numberWithInt:123], config ]]; [flutterTextInputPlugin handleMethodCall:setClientCall result:^(id _Nullable result){ }]; currentView = flutterTextInputPlugin.activeView; } NSAssert(!weakFlutterEngine, @"flutter engine must be nil"); NSAssert(currentView, @"current view must not be nil"); XCTAssertNil(weakFlutterTextInputPlugin); // Verify that the view can no longer access the deallocated engine/text input plugin // instance. XCTAssertNil(currentView.textInputDelegate); } - (void)testSecureInput { NSDictionary* config = self.mutableTemplateCopy; [config setValue:@"YES" forKey:@"obscureText"]; [self setClientId:123 configuration:config]; // Find all the FlutterTextInputViews we created. NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; // There are no autofill and the mock framework requested a secure entry. The first and only // inserted FlutterTextInputView should be a secure text entry one. FlutterTextInputView* inputView = inputFields[0]; // Verify secureTextEntry is set to the correct value. XCTAssertTrue(inputView.secureTextEntry); // Verify keyboardType is set to the default value. XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeDefault); // We should have only ever created one FlutterTextInputView. XCTAssertEqual(inputFields.count, 1ul); // The one FlutterTextInputView we inserted into the view hierarchy should be the text input // plugin's active text input view. XCTAssertEqual(inputView, textInputPlugin.textInputView); // Despite not given an id in configuration, inputView has // an autofill id. XCTAssert(inputView.autofillId.length > 0); } - (void)testKeyboardType { NSDictionary* config = self.mutableTemplateCopy; [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"]; [self setClientId:123 configuration:config]; // Find all the FlutterTextInputViews we created. NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; // Verify keyboardType is set to the value specified in config. XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeURL); } - (void)testVisiblePasswordUseAlphanumeric { NSDictionary* config = self.mutableTemplateCopy; [config setValue:@{@"name" : @"TextInputType.visiblePassword"} forKey:@"inputType"]; [self setClientId:123 configuration:config]; // Find all the FlutterTextInputViews we created. NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; // Verify keyboardType is set to the value specified in config. XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeASCIICapable); } - (void)testSettingKeyboardTypeNoneDisablesSystemKeyboard { NSDictionary* config = self.mutableTemplateCopy; [config setValue:@{@"name" : @"TextInputType.none"} forKey:@"inputType"]; [self setClientId:123 configuration:config]; // Verify the view's inputViewController is not nil; XCTAssertNotNil(textInputPlugin.activeView.inputViewController); [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"]; [self setClientId:124 configuration:config]; XCTAssertNotNil(textInputPlugin.activeView); XCTAssertNil(textInputPlugin.activeView.inputViewController); } - (void)testAutocorrectionPromptRectAppearsBeforeIOS17AndDoesNotAppearAfterIOS17 { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; if (@available(iOS 17.0, *)) { // Auto-correction prompt is disabled in iOS 17+. OCMVerify(never(), [engine flutterTextInputView:inputView showAutocorrectionPromptRectForStart:0 end:1 withClient:0]); } else { OCMVerify([engine flutterTextInputView:inputView showAutocorrectionPromptRectForStart:0 end:1 withClient:0]); } } - (void)testIgnoresSelectionChangeIfSelectionIsDisabled { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView.text setString:@"Some initial text"]; XCTAssertEqual(updateCount, 0); FlutterTextRange* textRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; [inputView setSelectedTextRange:textRange]; XCTAssertEqual(updateCount, 1); // Disable the interactive selection. NSDictionary* config = self.mutableTemplateCopy; [config setValue:@(NO) forKey:@"enableInteractiveSelection"]; [config setValue:@(NO) forKey:@"obscureText"]; [config setValue:@(NO) forKey:@"enableDeltaModel"]; [inputView configureWithDictionary:config]; textRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(2, 3)]; [inputView setSelectedTextRange:textRange]; // The update count does not change. XCTAssertEqual(updateCount, 1); } - (void)testAutocorrectionPromptRectDoesNotAppearDuringScribble { // Auto-correction prompt is disabled in iOS 17+. if (@available(iOS 17.0, *)) { return; } if (@available(iOS 14.0, *)) { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; __block int callCount = 0; OCMStub([engine flutterTextInputView:inputView showAutocorrectionPromptRectForStart:0 end:1 withClient:0]) .andDo(^(NSInvocation* invocation) { callCount++; }); [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; // showAutocorrectionPromptRectForStart fires in response to firstRectForRange XCTAssertEqual(callCount, 1); UIScribbleInteraction* scribbleInteraction = [[UIScribbleInteraction alloc] initWithDelegate:inputView]; [inputView scribbleInteractionWillBeginWriting:scribbleInteraction]; [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; // showAutocorrectionPromptRectForStart does not fire in response to setMarkedText during a // scribble interaction.firstRectForRange XCTAssertEqual(callCount, 1); [inputView scribbleInteractionDidFinishWriting:scribbleInteraction]; [inputView resetScribbleInteractionStatusIfEnding]; [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; // showAutocorrectionPromptRectForStart fires in response to firstRectForRange. XCTAssertEqual(callCount, 2); inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocusing; [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; // showAutocorrectionPromptRectForStart does not fire in response to firstRectForRange during a // scribble-initiated focus. XCTAssertEqual(callCount, 2); inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocused; [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; // showAutocorrectionPromptRectForStart does not fire in response to firstRectForRange after a // scribble-initiated focus. XCTAssertEqual(callCount, 2); inputView.scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; // showAutocorrectionPromptRectForStart fires in response to firstRectForRange. XCTAssertEqual(callCount, 3); } } - (void)testInputHiderOverlapWithTextWhenScribbleIsDisabledAfterIOS17AndDoesNotOverlapBeforeIOS17 { FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])]; FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" arguments:@[ @(123), self.mutableTemplateCopy ]]; [myInputPlugin handleMethodCall:setClientCall result:^(id _Nullable result){ }]; FlutterTextInputView* mockInputView = OCMPartialMock(myInputPlugin.activeView); OCMStub([mockInputView isScribbleAvailable]).andReturn(NO); // yOffset = 200. NSArray* yOffsetMatrix = @[ @1, @0, @0, @0, @0, @1, @0, @0, @0, @0, @1, @0, @0, @200, @0, @1 ]; FlutterMethodCall* setPlatformViewClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditableSizeAndTransform" arguments:@{@"transform" : yOffsetMatrix}]; [myInputPlugin handleMethodCall:setPlatformViewClientCall result:^(id _Nullable result){ }]; if (@available(iOS 17, *)) { XCTAssert(CGRectEqualToRect(myInputPlugin.inputHider.frame, CGRectMake(0, 200, 0, 0)), @"The input hider should overlap with the text on and after iOS 17"); } else { XCTAssert(CGRectEqualToRect(myInputPlugin.inputHider.frame, CGRectZero), @"The input hider should be on the origin of screen on and before iOS 16."); } } - (void)testTextRangeFromPositionMatchesUITextViewBehavior { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; FlutterTextPosition* fromPosition = [FlutterTextPosition positionWithIndex:2]; FlutterTextPosition* toPosition = [FlutterTextPosition positionWithIndex:0]; FlutterTextRange* flutterRange = (FlutterTextRange*)[inputView textRangeFromPosition:fromPosition toPosition:toPosition]; NSRange range = flutterRange.range; XCTAssertEqual(range.location, 0ul); XCTAssertEqual(range.length, 2ul); } - (void)testTextInRange { NSDictionary* config = self.mutableTemplateCopy; [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"]; [self setClientId:123 configuration:config]; NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; [inputView insertText:@"test"]; UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 20)]; NSString* substring = [inputView textInRange:range]; XCTAssertEqual(substring.length, 4ul); range = [FlutterTextRange rangeWithNSRange:NSMakeRange(10, 20)]; substring = [inputView textInRange:range]; XCTAssertEqual(substring.length, 0ul); } - (void)testStandardEditActions { NSDictionary* config = self.mutableTemplateCopy; [self setClientId:123 configuration:config]; NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; [inputView insertText:@"aaaa"]; [inputView selectAll:nil]; [inputView cut:nil]; [inputView insertText:@"bbbb"]; XCTAssertTrue([inputView canPerformAction:@selector(paste:) withSender:nil]); [inputView paste:nil]; [inputView selectAll:nil]; [inputView copy:nil]; [inputView paste:nil]; [inputView selectAll:nil]; [inputView delete:nil]; [inputView paste:nil]; [inputView paste:nil]; UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 30)]; NSString* substring = [inputView textInRange:range]; XCTAssertEqualObjects(substring, @"bbbbaaaabbbbaaaa"); } - (void)testDeletingBackward { NSDictionary* config = self.mutableTemplateCopy; [self setClientId:123 configuration:config]; NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; [inputView insertText:@"ឹ😀 text 🥰👨‍👩‍👧‍👦🇺🇳ดี "]; [inputView deleteBackward]; [inputView deleteBackward]; // Thai vowel is removed. XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰👨‍👩‍👧‍👦🇺🇳ด"); [inputView deleteBackward]; XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰👨‍👩‍👧‍👦🇺🇳"); [inputView deleteBackward]; XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰👨‍👩‍👧‍👦"); [inputView deleteBackward]; XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰"); [inputView deleteBackward]; XCTAssertEqualObjects(inputView.text, @"ឹ😀 text "); [inputView deleteBackward]; [inputView deleteBackward]; [inputView deleteBackward]; [inputView deleteBackward]; [inputView deleteBackward]; [inputView deleteBackward]; XCTAssertEqualObjects(inputView.text, @"ឹ😀"); [inputView deleteBackward]; XCTAssertEqualObjects(inputView.text, @"ឹ"); [inputView deleteBackward]; XCTAssertEqualObjects(inputView.text, @""); } // This tests the workaround to fix an iOS 16 bug // See: https://github.com/flutter/flutter/issues/111494 - (void)testSystemOnlyAddingPartialComposedCharacter { NSDictionary* config = self.mutableTemplateCopy; [self setClientId:123 configuration:config]; NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; [inputView insertText:@"👨‍👩‍👧‍👦"]; [inputView deleteBackward]; // Insert the first unichar in the emoji. [inputView insertText:[@"👨‍👩‍👧‍👦" substringWithRange:NSMakeRange(0, 1)]]; [inputView insertText:@"아"]; XCTAssertEqualObjects(inputView.text, @"👨‍👩‍👧‍👦아"); // Deleting 아. [inputView deleteBackward]; // 👨‍👩‍👧‍👦 should be the current string. [inputView insertText:@"😀"]; [inputView deleteBackward]; // Insert the first unichar in the emoji. [inputView insertText:[@"😀" substringWithRange:NSMakeRange(0, 1)]]; [inputView insertText:@"아"]; XCTAssertEqualObjects(inputView.text, @"👨‍👩‍👧‍👦😀아"); // Deleting 아. [inputView deleteBackward]; // 👨‍👩‍👧‍👦😀 should be the current string. [inputView deleteBackward]; // Insert the first unichar in the emoji. [inputView insertText:[@"😀" substringWithRange:NSMakeRange(0, 1)]]; [inputView insertText:@"아"]; XCTAssertEqualObjects(inputView.text, @"👨‍👩‍👧‍👦😀아"); } - (void)testCachedComposedCharacterClearedAtKeyboardInteraction { NSDictionary* config = self.mutableTemplateCopy; [self setClientId:123 configuration:config]; NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; [inputView insertText:@"👨‍👩‍👧‍👦"]; [inputView deleteBackward]; [inputView shouldChangeTextInRange:OCMClassMock([UITextRange class]) replacementText:@""]; // Insert the first unichar in the emoji. NSString* brokenEmoji = [@"👨‍👩‍👧‍👦" substringWithRange:NSMakeRange(0, 1)]; [inputView insertText:brokenEmoji]; [inputView insertText:@"아"]; NSString* finalText = [NSString stringWithFormat:@"%@아", brokenEmoji]; XCTAssertEqualObjects(inputView.text, finalText); } - (void)testPastingNonTextDisallowed { NSDictionary* config = self.mutableTemplateCopy; [self setClientId:123 configuration:config]; NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; UIPasteboard.generalPasteboard.color = UIColor.redColor; XCTAssertNil(UIPasteboard.generalPasteboard.string); XCTAssertFalse([inputView canPerformAction:@selector(paste:) withSender:nil]); [inputView paste:nil]; XCTAssertEqualObjects(inputView.text, @""); } - (void)testNoZombies { // Regression test for https://github.com/flutter/flutter/issues/62501. FlutterSecureTextInputView* passwordView = [[FlutterSecureTextInputView alloc] initWithOwner:textInputPlugin]; @autoreleasepool { // Initialize the lazy textField. [passwordView.textField description]; } XCTAssert([[passwordView.textField description] containsString:@"TextField"]); } - (void)testInputViewCrash { FlutterTextInputView* activeView = nil; @autoreleasepool { FlutterEngine* flutterEngine = [[FlutterEngine alloc] init]; FlutterTextInputPlugin* inputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:(id<FlutterTextInputDelegate>)flutterEngine]; activeView = inputPlugin.activeView; } [activeView updateEditingState]; } - (void)testDoNotReuseInputViews { NSDictionary* config = self.mutableTemplateCopy; [self setClientId:123 configuration:config]; FlutterTextInputView* currentView = textInputPlugin.activeView; [self setClientId:456 configuration:config]; XCTAssertNotNil(currentView); XCTAssertNotNil(textInputPlugin.activeView); XCTAssertNotEqual(currentView, textInputPlugin.activeView); } - (void)ensureOnlyActiveViewCanBecomeFirstResponder { for (FlutterTextInputView* inputView in self.installedInputViews) { XCTAssertEqual(inputView.canBecomeFirstResponder, inputView == textInputPlugin.activeView); } } - (void)testPropagatePressEventsToViewController { FlutterViewController* mockViewController = OCMPartialMock(viewController); OCMStub([mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); OCMStub([mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); textInputPlugin.viewController = mockViewController; NSDictionary* config = self.mutableTemplateCopy; [self setClientId:123 configuration:config]; FlutterTextInputView* currentView = textInputPlugin.activeView; [self setTextInputShow]; [currentView pressesBegan:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil] withEvent:OCMClassMock([UIPressesEvent class])]; OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); OCMVerify(times(0), [mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); [currentView pressesEnded:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil] withEvent:OCMClassMock([UIPressesEvent class])]; OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); OCMVerify(times(1), [mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); } - (void)testPropagatePressEventsToViewController2 { FlutterViewController* mockViewController = OCMPartialMock(viewController); OCMStub([mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); OCMStub([mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); textInputPlugin.viewController = mockViewController; NSDictionary* config = self.mutableTemplateCopy; [self setClientId:123 configuration:config]; [self setTextInputShow]; FlutterTextInputView* currentView = textInputPlugin.activeView; [currentView pressesBegan:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil] withEvent:OCMClassMock([UIPressesEvent class])]; OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); OCMVerify(times(0), [mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); // Switch focus to a different view. [self setClientId:321 configuration:config]; [self setTextInputShow]; NSAssert(textInputPlugin.activeView, @"active view must not be nil"); NSAssert(textInputPlugin.activeView != currentView, @"active view must change"); currentView = textInputPlugin.activeView; [currentView pressesEnded:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil] withEvent:OCMClassMock([UIPressesEvent class])]; OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); OCMVerify(times(1), [mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); } - (void)testUpdateSecureTextEntry { NSDictionary* config = self.mutableTemplateCopy; [config setValue:@"YES" forKey:@"obscureText"]; [self setClientId:123 configuration:config]; NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = OCMPartialMock(inputFields[0]); __block int callCount = 0; OCMStub([inputView reloadInputViews]).andDo(^(NSInvocation* invocation) { callCount++; }); XCTAssertTrue(inputView.isSecureTextEntry); config = self.mutableTemplateCopy; [config setValue:@"NO" forKey:@"obscureText"]; [self updateConfig:config]; XCTAssertEqual(callCount, 1); XCTAssertFalse(inputView.isSecureTextEntry); } - (void)testInputActionContinueAction { id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]); FlutterEngine* testEngine = [[FlutterEngine alloc] init]; [testEngine setBinaryMessenger:mockBinaryMessenger]; [testEngine runWithEntrypoint:FlutterDefaultDartEntrypoint initialRoute:@"test"]; FlutterTextInputPlugin* inputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:(id<FlutterTextInputDelegate>)testEngine]; FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:inputPlugin]; [testEngine flutterTextInputView:inputView performAction:FlutterTextInputActionContinue withClient:123]; FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"TextInputClient.performAction" arguments:@[ @(123), @"TextInputAction.continueAction" ]]; NSData* encodedMethodCall = [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:methodCall]; OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/textinput" message:encodedMethodCall]); } - (void)testDisablingAutocorrectDisablesSpellChecking { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; // Disable the interactive selection. NSDictionary* config = self.mutableTemplateCopy; [inputView configureWithDictionary:config]; XCTAssertEqual(inputView.autocorrectionType, UITextAutocorrectionTypeDefault); XCTAssertEqual(inputView.spellCheckingType, UITextSpellCheckingTypeDefault); [config setValue:@(NO) forKey:@"autocorrect"]; [inputView configureWithDictionary:config]; XCTAssertEqual(inputView.autocorrectionType, UITextAutocorrectionTypeNo); XCTAssertEqual(inputView.spellCheckingType, UITextSpellCheckingTypeNo); } - (void)testReplaceTestLocalAdjustSelectionAndMarkedTextRange { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setMarkedText:@"test text" selectedRange:NSMakeRange(0, 5)]; NSRange selectedTextRange = ((FlutterTextRange*)inputView.selectedTextRange).range; const NSRange markedTextRange = ((FlutterTextRange*)inputView.markedTextRange).range; XCTAssertEqual(selectedTextRange.location, 0ul); XCTAssertEqual(selectedTextRange.length, 5ul); XCTAssertEqual(markedTextRange.location, 0ul); XCTAssertEqual(markedTextRange.length, 9ul); // Replaces space with space. [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(4, 1)] withText:@" "]; selectedTextRange = ((FlutterTextRange*)inputView.selectedTextRange).range; XCTAssertEqual(selectedTextRange.location, 5ul); XCTAssertEqual(selectedTextRange.length, 0ul); XCTAssertEqual(inputView.markedTextRange, nil); } - (void)testFlutterTextInputViewOnlyRespondsToInsertionPointColorBelowIOS17 { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; BOOL respondsToInsertionPointColor = [inputView respondsToSelector:@selector(insertionPointColor)]; if (@available(iOS 17, *)) { XCTAssertFalse(respondsToInsertionPointColor); } else { XCTAssertTrue(respondsToInsertionPointColor); } } #pragma mark - TextEditingDelta tests - (void)testTextEditingDeltasAreGeneratedOnTextInput { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; inputView.enableDeltaModel = YES; __block int updateCount = 0; [inputView insertText:@"text to insert"]; OCMExpect( [engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] isEqualToString:@""]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] isEqualToString:@"text to insert"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 0) && ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 0); }]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); XCTAssertEqual(updateCount, 0); [self flushScheduledAsyncBlocks]; // Update the framework exactly once. XCTAssertEqual(updateCount, 1); [inputView deleteBackward]; OCMExpect([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] isEqualToString:@"text to insert"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] isEqualToString:@""]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) && ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 14); }]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 2); inputView.selectedTextRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; OCMExpect([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] isEqualToString:@"text to inser"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] isEqualToString:@""]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == -1) && ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == -1); }]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 3); [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)] withText:@"replace text"]; OCMExpect( [engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] isEqualToString:@"text to inser"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] isEqualToString:@"replace text"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 0) && ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 1); }]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 4); [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; OCMExpect([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] isEqualToString:@"replace textext to inser"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] isEqualToString:@"marked text"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 12) && ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 12); }]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 5); [inputView unmarkText]; OCMExpect([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] isEqualToString:@"replace textmarked textext to inser"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] isEqualToString:@""]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == -1) && ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == -1); }]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 6); OCMVerifyAll(engine); } - (void)testTextEditingDeltasAreBatchedAndForwardedToFramework { // Setup FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; inputView.enableDeltaModel = YES; // Expected call. OCMExpect([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { NSArray* deltas = state[@"deltas"]; NSDictionary* firstDelta = deltas[0]; NSDictionary* secondDelta = deltas[1]; NSDictionary* thirdDelta = deltas[2]; return [firstDelta[@"oldText"] isEqualToString:@""] && [firstDelta[@"deltaText"] isEqualToString:@"-"] && [firstDelta[@"deltaStart"] intValue] == 0 && [firstDelta[@"deltaEnd"] intValue] == 0 && [secondDelta[@"oldText"] isEqualToString:@"-"] && [secondDelta[@"deltaText"] isEqualToString:@""] && [secondDelta[@"deltaStart"] intValue] == 0 && [secondDelta[@"deltaEnd"] intValue] == 1 && [thirdDelta[@"oldText"] isEqualToString:@""] && [thirdDelta[@"deltaText"] isEqualToString:@"—"] && [thirdDelta[@"deltaStart"] intValue] == 0 && [thirdDelta[@"deltaEnd"] intValue] == 0; }]]); // Simulate user input. [inputView insertText:@"-"]; [inputView deleteBackward]; [inputView insertText:@"—"]; [self flushScheduledAsyncBlocks]; OCMVerifyAll(engine); } - (void)testTextEditingDeltasAreGeneratedOnSetMarkedTextReplacement { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; inputView.enableDeltaModel = YES; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView.text setString:@"Some initial text"]; XCTAssertEqual(updateCount, 0); UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(13, 4)]; inputView.markedTextRange = range; inputView.selectedTextRange = nil; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); [inputView setMarkedText:@"new marked text." selectedRange:NSMakeRange(0, 1)]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] isEqualToString:@"Some initial text"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] isEqualToString:@"new marked text."]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) && ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 17); }]]); [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 2); } - (void)testTextEditingDeltasAreGeneratedOnSetMarkedTextInsertion { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; inputView.enableDeltaModel = YES; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView.text setString:@"Some initial text"]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 0); UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(13, 4)]; inputView.markedTextRange = range; inputView.selectedTextRange = nil; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); [inputView setMarkedText:@"text." selectedRange:NSMakeRange(0, 1)]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] isEqualToString:@"Some initial text"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] isEqualToString:@"text."]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) && ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 17); }]]); [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 2); } - (void)testTextEditingDeltasAreGeneratedOnSetMarkedTextDeletion { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; inputView.enableDeltaModel = YES; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView.text setString:@"Some initial text"]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 0); UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(13, 4)]; inputView.markedTextRange = range; inputView.selectedTextRange = nil; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); [inputView setMarkedText:@"tex" selectedRange:NSMakeRange(0, 1)]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] isEqualToString:@"Some initial text"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] isEqualToString:@"tex"]) && ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) && ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 17); }]]); [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 2); } #pragma mark - EditingState tests - (void)testUITextInputCallsUpdateEditingStateOnce { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView insertText:@"text to insert"]; // Update the framework exactly once. XCTAssertEqual(updateCount, 1); [inputView deleteBackward]; XCTAssertEqual(updateCount, 2); inputView.selectedTextRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; XCTAssertEqual(updateCount, 3); [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)] withText:@"replace text"]; XCTAssertEqual(updateCount, 4); [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; XCTAssertEqual(updateCount, 5); [inputView unmarkText]; XCTAssertEqual(updateCount, 6); } - (void)testUITextInputCallsUpdateEditingStateWithDeltaOnce { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; inputView.enableDeltaModel = YES; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView insertText:@"text to insert"]; [self flushScheduledAsyncBlocks]; // Update the framework exactly once. XCTAssertEqual(updateCount, 1); [inputView deleteBackward]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 2); inputView.selectedTextRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 3); [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)] withText:@"replace text"]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 4); [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 5); [inputView unmarkText]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 6); } - (void)testTextChangesDoNotTriggerUpdateEditingClient { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView.text setString:@"BEFORE"]; XCTAssertEqual(updateCount, 0); inputView.markedTextRange = nil; inputView.selectedTextRange = nil; XCTAssertEqual(updateCount, 1); // Text changes don't trigger an update. XCTAssertEqual(updateCount, 1); [inputView setTextInputState:@{@"text" : @"AFTER"}]; XCTAssertEqual(updateCount, 1); [inputView setTextInputState:@{@"text" : @"AFTER"}]; XCTAssertEqual(updateCount, 1); // Selection changes don't trigger an update. [inputView setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @3}]; XCTAssertEqual(updateCount, 1); [inputView setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @3}]; XCTAssertEqual(updateCount, 1); // Composing region changes don't trigger an update. [inputView setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @2}]; XCTAssertEqual(updateCount, 1); [inputView setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}]; XCTAssertEqual(updateCount, 1); } - (void)testTextChangesDoNotTriggerUpdateEditingClientWithDelta { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; inputView.enableDeltaModel = YES; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView.text setString:@"BEFORE"]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 0); inputView.markedTextRange = nil; inputView.selectedTextRange = nil; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); // Text changes don't trigger an update. XCTAssertEqual(updateCount, 1); [inputView setTextInputState:@{@"text" : @"AFTER"}]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); [inputView setTextInputState:@{@"text" : @"AFTER"}]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); // Selection changes don't trigger an update. [inputView setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @3}]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); [inputView setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @3}]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); // Composing region changes don't trigger an update. [inputView setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @2}]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); [inputView setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}]; [self flushScheduledAsyncBlocks]; XCTAssertEqual(updateCount, 1); } - (void)testUITextInputAvoidUnnecessaryUndateEditingClientCalls { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView unmarkText]; // updateEditingClient shouldn't fire as the text is already unmarked. XCTAssertEqual(updateCount, 0); [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; // updateEditingClient fires in response to setMarkedText. XCTAssertEqual(updateCount, 1); [inputView unmarkText]; // updateEditingClient fires in response to unmarkText. XCTAssertEqual(updateCount, 2); } - (void)testCanCopyPasteWithScribbleEnabled { if (@available(iOS 14.0, *)) { NSDictionary* config = self.mutableTemplateCopy; [self setClientId:123 configuration:config]; NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; FlutterTextInputView* mockInputView = OCMPartialMock(inputView); OCMStub([mockInputView isScribbleAvailable]).andReturn(YES); [mockInputView insertText:@"aaaa"]; [mockInputView selectAll:nil]; XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:NULL]); XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:@"sender"]); XCTAssertFalse([mockInputView canPerformAction:@selector(paste:) withSender:NULL]); XCTAssertFalse([mockInputView canPerformAction:@selector(paste:) withSender:@"sender"]); [mockInputView copy:NULL]; XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:NULL]); XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:@"sender"]); XCTAssertTrue([mockInputView canPerformAction:@selector(paste:) withSender:NULL]); XCTAssertTrue([mockInputView canPerformAction:@selector(paste:) withSender:@"sender"]); } } - (void)testSetMarkedTextDuringScribbleDoesNotTriggerUpdateEditingClient { if (@available(iOS 14.0, *)) { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; __block int updateCount = 0; OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { updateCount++; }); [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; // updateEditingClient fires in response to setMarkedText. XCTAssertEqual(updateCount, 1); UIScribbleInteraction* scribbleInteraction = [[UIScribbleInteraction alloc] initWithDelegate:inputView]; [inputView scribbleInteractionWillBeginWriting:scribbleInteraction]; [inputView setMarkedText:@"during writing" selectedRange:NSMakeRange(1, 2)]; // updateEditingClient does not fire in response to setMarkedText during a scribble interaction. XCTAssertEqual(updateCount, 1); [inputView scribbleInteractionDidFinishWriting:scribbleInteraction]; [inputView resetScribbleInteractionStatusIfEnding]; [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; // updateEditingClient fires in response to setMarkedText. XCTAssertEqual(updateCount, 2); inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocusing; [inputView setMarkedText:@"during focus" selectedRange:NSMakeRange(1, 2)]; // updateEditingClient does not fire in response to setMarkedText during a scribble-initiated // focus. XCTAssertEqual(updateCount, 2); inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocused; [inputView setMarkedText:@"after focus" selectedRange:NSMakeRange(2, 3)]; // updateEditingClient does not fire in response to setMarkedText after a scribble-initiated // focus. XCTAssertEqual(updateCount, 2); inputView.scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; // updateEditingClient fires in response to setMarkedText. XCTAssertEqual(updateCount, 3); } } - (void)testUpdateEditingClientNegativeSelection { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView.text setString:@"SELECTION"]; inputView.markedTextRange = nil; inputView.selectedTextRange = nil; [inputView setTextInputState:@{ @"text" : @"SELECTION", @"selectionBase" : @-1, @"selectionExtent" : @-1 }]; [inputView updateEditingState]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"selectionBase"] intValue]) == 0 && ([state[@"selectionExtent"] intValue] == 0); }]]); // Returns (0, 0) when either end goes below 0. [inputView setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @-1, @"selectionExtent" : @1}]; [inputView updateEditingState]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"selectionBase"] intValue]) == 0 && ([state[@"selectionExtent"] intValue] == 0); }]]); [inputView setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @-1}]; [inputView updateEditingState]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"selectionBase"] intValue]) == 0 && ([state[@"selectionExtent"] intValue] == 0); }]]); } - (void)testUpdateEditingClientSelectionClamping { // Regression test for https://github.com/flutter/flutter/issues/62992. FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView.text setString:@"SELECTION"]; inputView.markedTextRange = nil; inputView.selectedTextRange = nil; [inputView setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @0}]; [inputView updateEditingState]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"selectionBase"] intValue]) == 0 && ([state[@"selectionExtent"] intValue] == 0); }]]); // Needs clamping. [inputView setTextInputState:@{ @"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @9999 }]; [inputView updateEditingState]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"selectionBase"] intValue]) == 0 && ([state[@"selectionExtent"] intValue] == 9); }]]); // No clamping needed, but in reverse direction. [inputView setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @0}]; [inputView updateEditingState]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"selectionBase"] intValue]) == 0 && ([state[@"selectionExtent"] intValue] == 1); }]]); // Both ends need clamping. [inputView setTextInputState:@{ @"text" : @"SELECTION", @"selectionBase" : @9999, @"selectionExtent" : @9999 }]; [inputView updateEditingState]; OCMVerify([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"selectionBase"] intValue]) == 9 && ([state[@"selectionExtent"] intValue] == 9); }]]); } - (void)testInputViewsHasNonNilInputDelegate { if (@available(iOS 13.0, *)) { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [UIApplication.sharedApplication.keyWindow addSubview:inputView]; [inputView setTextInputClient:123]; [inputView reloadInputViews]; [inputView becomeFirstResponder]; NSAssert(inputView.isFirstResponder, @"inputView is not first responder"); inputView.inputDelegate = nil; FlutterTextInputView* mockInputView = OCMPartialMock(inputView); [mockInputView setTextInputState:@{ @"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3 }]; OCMVerify([mockInputView setInputDelegate:[OCMArg isNotNil]]); [inputView removeFromSuperview]; } } - (void)testInputViewsDoNotHaveUITextInteractions { if (@available(iOS 13.0, *)) { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; BOOL hasTextInteraction = NO; for (id interaction in inputView.interactions) { hasTextInteraction = [interaction isKindOfClass:[UITextInteraction class]]; if (hasTextInteraction) { break; } } XCTAssertFalse(hasTextInteraction); } } #pragma mark - UITextInput methods - Tests - (void)testUpdateFirstRectForRange { [self setClientId:123 configuration:self.mutableTemplateCopy]; FlutterTextInputView* inputView = textInputPlugin.activeView; textInputPlugin.viewController.view.frame = CGRectMake(0, 0, 0, 0); [inputView setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}]; CGRect kInvalidFirstRect = CGRectMake(-1, -1, 9999, 9999); FlutterTextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; // yOffset = 200. NSArray* yOffsetMatrix = @[ @1, @0, @0, @0, @0, @1, @0, @0, @0, @0, @1, @0, @0, @200, @0, @1 ]; NSArray* zeroMatrix = @[ @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0 ]; // This matrix can be generated by running this dart code snippet: // Matrix4.identity()..scale(3.0)..rotateZ(math.pi/2)..translate(1.0, 2.0, // 3.0); NSArray* affineMatrix = @[ @(0.0), @(3.0), @(0.0), @(0.0), @(-3.0), @(0.0), @(0.0), @(0.0), @(0.0), @(0.0), @(3.0), @(0.0), @(-6.0), @(3.0), @(9.0), @(1.0) ]; // Invalid since we don't have the transform or the rect. XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); [inputView setEditableTransform:yOffsetMatrix]; // Invalid since we don't have the rect. XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); // Valid rect and transform. CGRect testRect = CGRectMake(0, 0, 100, 100); [inputView setMarkedRect:testRect]; CGRect finalRect = CGRectOffset(testRect, 0, 200); XCTAssertTrue(CGRectEqualToRect(finalRect, [inputView firstRectForRange:range])); // Idempotent. XCTAssertTrue(CGRectEqualToRect(finalRect, [inputView firstRectForRange:range])); // Use an invalid matrix: [inputView setEditableTransform:zeroMatrix]; // Invalid matrix is invalid. XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); // Revert the invalid matrix change. [inputView setEditableTransform:yOffsetMatrix]; [inputView setMarkedRect:testRect]; XCTAssertTrue(CGRectEqualToRect(finalRect, [inputView firstRectForRange:range])); // Use an invalid rect: [inputView setMarkedRect:kInvalidFirstRect]; // Invalid marked rect is invalid. XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); // Use a 3d affine transform that does 3d-scaling, z-index rotating and 3d translation. [inputView setEditableTransform:affineMatrix]; [inputView setMarkedRect:testRect]; XCTAssertTrue( CGRectEqualToRect(CGRectMake(-306, 3, 300, 300), [inputView firstRectForRange:range])); NSAssert(inputView.superview, @"inputView is not in the view hierarchy!"); const CGPoint offset = CGPointMake(113, 119); CGRect currentFrame = inputView.frame; currentFrame.origin = offset; inputView.frame = currentFrame; // Moving the input view within the FlutterView shouldn't affect the coordinates, // since the framework sends us global coordinates. XCTAssertTrue(CGRectEqualToRect(CGRectMake(-306 - 113, 3 - 119, 300, 300), [inputView firstRectForRange:range])); } - (void)testFirstRectForRangeReturnsNoneZeroRectWhenScribbleIsEnabled { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; FlutterTextInputView* mockInputView = OCMPartialMock(inputView); OCMStub([mockInputView isScribbleAvailable]).andReturn(YES); [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], ]]; FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 100, 100), [inputView firstRectForRange:multiRectRange])); } } - (void)testFirstRectForRangeReturnsCorrectRectOnASingleLineLeftToRight { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], ]]; FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 100, 100), [inputView firstRectForRange:singleRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange])); } FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } [inputView setTextInputState:@{@"text" : @"COM"}]; FlutterTextRange* rangeOutsideBounds = [FlutterTextRange rangeWithNSRange:NSMakeRange(3, 1)]; XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:rangeOutsideBounds])); } - (void)testFirstRectForRangeReturnsCorrectRectOnASingleLineRightToLeft { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U], ]]; FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(200, 0, 100, 100), [inputView firstRectForRange:singleRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange])); } FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 300, 100), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } [inputView setTextInputState:@{@"text" : @"COM"}]; FlutterTextRange* rangeOutsideBounds = [FlutterTextRange rangeWithNSRange:NSMakeRange(3, 1)]; XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:rangeOutsideBounds])); } - (void)testFirstRectForRangeReturnsCorrectRectOnMultipleLinesLeftToRight { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:4U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:5U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:6U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 100, 100, 100) position:7U], ]]; FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 100, 100), [inputView firstRectForRange:singleRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange])); } FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } } - (void)testFirstRectForRangeReturnsCorrectRectOnMultipleLinesRightToLeft { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 100, 100, 100) position:4U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:5U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:6U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:7U], ]]; FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(200, 0, 100, 100), [inputView firstRectForRange:singleRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange])); } FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 300, 100), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } } - (void)testFirstRectForRangeReturnsCorrectRectOnSingleLineWithVaryingMinYAndMaxYLeftToRight { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 10, 100, 80) position:1U], // shorter [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, -10, 100, 120) position:2U], // taller [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], ]]; FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, -10, 300, 120), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } } - (void)testFirstRectForRangeReturnsCorrectRectOnSingleLineWithVaryingMinYAndMaxYRightToLeft { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, -10, 100, 120) position:1U], // taller [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 10, 100, 80) position:2U], // shorter [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U], ]]; FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, -10, 300, 120), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } } - (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsExceedingThresholdLeftToRight { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], // y=60 exceeds threshold, so treat it as a new line. [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 60, 100, 100) position:4U], ]]; FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } } - (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsExceedingThresholdRightToLeft { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U], // y=60 exceeds threshold, so treat it as a new line. [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 60, 100, 100) position:4U], ]]; FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 300, 100), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } } - (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsWithinThresholdLeftToRight { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], // y=40 is within line threshold, so treat it as the same line [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(400, 40, 100, 100) position:4U], ]]; FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 400, 140), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } } - (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsWithinThresholdRightToLeft { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(400, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:3U], // y=40 is within line threshold, so treat it as the same line [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 40, 100, 100) position:4U], ]]; FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; if (@available(iOS 17, *)) { XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 400, 140), [inputView firstRectForRange:multiRectRange])); } else { XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); } } - (void)testClosestPositionToPoint { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; // Minimize the vertical distance from the center of the rects first [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:2U], ]]; CGPoint point = CGPointMake(150, 150); XCTAssertEqual(2U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); XCTAssertEqual(UITextStorageDirectionBackward, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); // Then, if the point is above the bottom of the closest rects vertically, get the closest x // origin [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:4U], ]]; point = CGPointMake(125, 150); XCTAssertEqual(2U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); XCTAssertEqual(UITextStorageDirectionForward, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); // However, if the point is below the bottom of the closest rects vertically, get the position // farthest to the right [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 300, 100, 100) position:4U], ]]; point = CGPointMake(125, 201); XCTAssertEqual(4U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); XCTAssertEqual(UITextStorageDirectionBackward, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); // Also check a point at the right edge of the last selection rect [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], ]]; point = CGPointMake(125, 250); XCTAssertEqual(4U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); XCTAssertEqual(UITextStorageDirectionBackward, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); // Minimize vertical distance if the difference is more than 1 point. [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 2, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 2, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], ]]; point = CGPointMake(110, 50); XCTAssertEqual(2U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); XCTAssertEqual(UITextStorageDirectionForward, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); // In floating cursor mode, the vertical difference is allowed to be 10 points. // The closest horizontal position will now win. [inputView beginFloatingCursorAtPoint:CGPointZero]; XCTAssertEqual(1U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); XCTAssertEqual(UITextStorageDirectionForward, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); [inputView endFloatingCursor]; } - (void)testClosestPositionToPointRTL { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:0U writingDirection:NSWritingDirectionRightToLeft], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U writingDirection:NSWritingDirectionRightToLeft], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:2U writingDirection:NSWritingDirectionRightToLeft], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:3U writingDirection:NSWritingDirectionRightToLeft], ]]; FlutterTextPosition* position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(275, 50)]; XCTAssertEqual(0U, position.index); XCTAssertEqual(UITextStorageDirectionForward, position.affinity); position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(225, 50)]; XCTAssertEqual(1U, position.index); XCTAssertEqual(UITextStorageDirectionBackward, position.affinity); position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(175, 50)]; XCTAssertEqual(1U, position.index); XCTAssertEqual(UITextStorageDirectionForward, position.affinity); position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(125, 50)]; XCTAssertEqual(2U, position.index); XCTAssertEqual(UITextStorageDirectionBackward, position.affinity); position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(75, 50)]; XCTAssertEqual(2U, position.index); XCTAssertEqual(UITextStorageDirectionForward, position.affinity); position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(25, 50)]; XCTAssertEqual(3U, position.index); XCTAssertEqual(UITextStorageDirectionBackward, position.affinity); position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(-25, 50)]; XCTAssertEqual(3U, position.index); XCTAssertEqual(UITextStorageDirectionBackward, position.affinity); } - (void)testSelectionRectsForRange { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; CGRect testRect0 = CGRectMake(100, 100, 100, 100); CGRect testRect1 = CGRectMake(200, 200, 100, 100); [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:testRect0 position:1U], [FlutterTextSelectionRect selectionRectWithRect:testRect1 position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 300, 100, 100) position:3U], ]]; // Returns the matching rects within a range FlutterTextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 2)]; XCTAssertTrue(CGRectEqualToRect(testRect0, [inputView selectionRectsForRange:range][0].rect)); XCTAssertTrue(CGRectEqualToRect(testRect1, [inputView selectionRectsForRange:range][1].rect)); XCTAssertEqual(2U, [[inputView selectionRectsForRange:range] count]); // Returns a 0 width rect for a 0-length range range = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 0)]; XCTAssertEqual(1U, [[inputView selectionRectsForRange:range] count]); XCTAssertTrue(CGRectEqualToRect( CGRectMake(testRect0.origin.x, testRect0.origin.y, 0, testRect0.size.height), [inputView selectionRectsForRange:range][0].rect)); } - (void)testClosestPositionToPointWithinRange { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; // Do not return a position before the start of the range [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:4U], ]]; CGPoint point = CGPointMake(125, 150); FlutterTextRange* range = [[FlutterTextRange rangeWithNSRange:NSMakeRange(3, 2)] copy]; XCTAssertEqual( 3U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).index); XCTAssertEqual( UITextStorageDirectionForward, ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).affinity); // Do not return a position after the end of the range [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:4U], ]]; point = CGPointMake(125, 150); range = [[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)] copy]; XCTAssertEqual( 1U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).index); XCTAssertEqual( UITextStorageDirectionForward, ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).affinity); } - (void)testClosestPositionToPointWithPartialSelectionRects { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; [inputView setSelectionRects:@[ [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U] ]]; // Asking with a position at the end of selection rects should give you the trailing edge of // the last rect. XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:1 affinity:UITextStorageDirectionForward]], CGRectMake(100, 0, 0, 100))); // Asking with a position beyond the end of selection rects should return CGRectZero without // crashing. XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:2 affinity:UITextStorageDirectionForward]], CGRectZero)); } #pragma mark - Floating Cursor - Tests - (void)testFloatingCursorDoesNotThrow { // The keyboard implementation may send unbalanced calls to the input view. FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)]; [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)]; [inputView endFloatingCursor]; [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)]; [inputView endFloatingCursor]; } - (void)testFloatingCursor { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{ @"text" : @"test", @"selectionBase" : @1, @"selectionExtent" : @1, }]; FlutterTextSelectionRect* first = [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U]; FlutterTextSelectionRect* second = [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:1U]; FlutterTextSelectionRect* third = [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 200, 100, 100) position:2U]; FlutterTextSelectionRect* fourth = [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 300, 100, 100) position:3U]; [inputView setSelectionRects:@[ first, second, third, fourth ]]; // Verify zeroth caret rect is based on left edge of first character. XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:0 affinity:UITextStorageDirectionForward]], CGRectMake(0, 0, 0, 100))); // Since the textAffinity is downstream, the caret rect will be based on the // left edge of the succeeding character. XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:1 affinity:UITextStorageDirectionForward]], CGRectMake(100, 100, 0, 100))); XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:2 affinity:UITextStorageDirectionForward]], CGRectMake(200, 200, 0, 100))); XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:3 affinity:UITextStorageDirectionForward]], CGRectMake(300, 300, 0, 100))); // There is no subsequent character for the last position, so the caret rect // will be based on the right edge of the preceding character. XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:4 affinity:UITextStorageDirectionForward]], CGRectMake(400, 300, 0, 100))); // Verify no caret rect for out-of-range character. XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:5 affinity:UITextStorageDirectionForward]], CGRectZero)); // Check caret rects again again when text affinity is upstream. [inputView setTextInputState:@{ @"text" : @"test", @"selectionBase" : @2, @"selectionExtent" : @2, }]; // Verify zeroth caret rect is based on left edge of first character. XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:0 affinity:UITextStorageDirectionBackward]], CGRectMake(0, 0, 0, 100))); // Since the textAffinity is upstream, all below caret rects will be based on // the right edge of the preceding character. XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:1 affinity:UITextStorageDirectionBackward]], CGRectMake(100, 0, 0, 100))); XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:2 affinity:UITextStorageDirectionBackward]], CGRectMake(200, 100, 0, 100))); XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:3 affinity:UITextStorageDirectionBackward]], CGRectMake(300, 200, 0, 100))); XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:4 affinity:UITextStorageDirectionBackward]], CGRectMake(400, 300, 0, 100))); // Verify no caret rect for out-of-range character. XCTAssertTrue(CGRectEqualToRect( [inputView caretRectForPosition:[FlutterTextPosition positionWithIndex:5 affinity:UITextStorageDirectionBackward]], CGRectZero)); // Verify floating cursor updates are relative to original position, and that there is no bounds // change. CGRect initialBounds = inputView.bounds; [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)]; XCTAssertTrue(CGRectEqualToRect(initialBounds, inputView.bounds)); OCMVerify([engine flutterTextInputView:inputView updateFloatingCursor:FlutterFloatingCursorDragStateStart withClient:0 withPosition:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"X"] isEqualToNumber:@(0)]) && ([state[@"Y"] isEqualToNumber:@(0)]); }]]); [inputView updateFloatingCursorAtPoint:CGPointMake(456, 654)]; XCTAssertTrue(CGRectEqualToRect(initialBounds, inputView.bounds)); OCMVerify([engine flutterTextInputView:inputView updateFloatingCursor:FlutterFloatingCursorDragStateUpdate withClient:0 withPosition:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"X"] isEqualToNumber:@(333)]) && ([state[@"Y"] isEqualToNumber:@(333)]); }]]); [inputView endFloatingCursor]; XCTAssertTrue(CGRectEqualToRect(initialBounds, inputView.bounds)); OCMVerify([engine flutterTextInputView:inputView updateFloatingCursor:FlutterFloatingCursorDragStateEnd withClient:0 withPosition:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { return ([state[@"X"] isEqualToNumber:@(0)]) && ([state[@"Y"] isEqualToNumber:@(0)]); }]]); } #pragma mark - UIKeyInput Overrides - Tests - (void)testInsertTextAddsPlaceholderSelectionRects { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView setTextInputState:@{@"text" : @"test", @"selectionBase" : @1, @"selectionExtent" : @1}]; FlutterTextSelectionRect* first = [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U]; FlutterTextSelectionRect* second = [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:1U]; FlutterTextSelectionRect* third = [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 200, 100, 100) position:2U]; FlutterTextSelectionRect* fourth = [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 300, 100, 100) position:3U]; [inputView setSelectionRects:@[ first, second, third, fourth ]]; // Inserts additional selection rects at the selection start [inputView insertText:@"in"]; NSArray* selectionRects = [inputView selectionRectsForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 6)]]; XCTAssertEqual(6U, [selectionRects count]); XCTAssertEqual(first.position, ((FlutterTextSelectionRect*)selectionRects[0]).position); XCTAssertTrue(CGRectEqualToRect(first.rect, ((FlutterTextSelectionRect*)selectionRects[0]).rect)); XCTAssertEqual(second.position, ((FlutterTextSelectionRect*)selectionRects[1]).position); XCTAssertTrue( CGRectEqualToRect(second.rect, ((FlutterTextSelectionRect*)selectionRects[1]).rect)); XCTAssertEqual(second.position + 1, ((FlutterTextSelectionRect*)selectionRects[2]).position); XCTAssertTrue( CGRectEqualToRect(second.rect, ((FlutterTextSelectionRect*)selectionRects[2]).rect)); XCTAssertEqual(second.position + 2, ((FlutterTextSelectionRect*)selectionRects[3]).position); XCTAssertTrue( CGRectEqualToRect(second.rect, ((FlutterTextSelectionRect*)selectionRects[3]).rect)); XCTAssertEqual(third.position + 2, ((FlutterTextSelectionRect*)selectionRects[4]).position); XCTAssertTrue(CGRectEqualToRect(third.rect, ((FlutterTextSelectionRect*)selectionRects[4]).rect)); XCTAssertEqual(fourth.position + 2, ((FlutterTextSelectionRect*)selectionRects[5]).position); XCTAssertTrue( CGRectEqualToRect(fourth.rect, ((FlutterTextSelectionRect*)selectionRects[5]).rect)); } #pragma mark - Autofill - Utilities - (NSMutableDictionary*)mutablePasswordTemplateCopy { if (!_passwordTemplate) { _passwordTemplate = @{ @"inputType" : @{@"name" : @"TextInuptType.text"}, @"keyboardAppearance" : @"Brightness.light", @"obscureText" : @YES, @"inputAction" : @"TextInputAction.unspecified", @"smartDashesType" : @"0", @"smartQuotesType" : @"0", @"autocorrect" : @YES }; } return [_passwordTemplate mutableCopy]; } - (NSArray<FlutterTextInputView*>*)viewsVisibleToAutofill { return [self.installedInputViews filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isVisibleToAutofill == YES"]]; } - (void)commitAutofillContextAndVerify { FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.finishAutofillContext" arguments:@YES]; [textInputPlugin handleMethodCall:methodCall result:^(id _Nullable result){ }]; XCTAssertEqual(self.viewsVisibleToAutofill.count, [textInputPlugin.activeView isVisibleToAutofill] ? 1ul : 0ul); XCTAssertNotEqual(textInputPlugin.textInputView, nil); // The active view should still be installed so it doesn't get // deallocated. XCTAssertEqual(self.installedInputViews.count, 1ul); XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul); } #pragma mark - Autofill - Tests - (void)testDisablingAutofillOnInputClient { NSDictionary* config = self.mutableTemplateCopy; [config setValue:@"YES" forKey:@"obscureText"]; [self setClientId:123 configuration:config]; FlutterTextInputView* inputView = self.installedInputViews[0]; XCTAssertEqualObjects(inputView.textContentType, @""); } - (void)testAutofillEnabledByDefault { NSDictionary* config = self.mutableTemplateCopy; [config setValue:@"NO" forKey:@"obscureText"]; [config setValue:@{@"uniqueIdentifier" : @"field1", @"editingValue" : @{@"text" : @""}} forKey:@"autofill"]; [self setClientId:123 configuration:config]; FlutterTextInputView* inputView = self.installedInputViews[0]; XCTAssertNil(inputView.textContentType); } - (void)testAutofillContext { NSMutableDictionary* field1 = self.mutableTemplateCopy; [field1 setValue:@{ @"uniqueIdentifier" : @"field1", @"hints" : @[ @"hint1" ], @"editingValue" : @{@"text" : @""} } forKey:@"autofill"]; NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy; [field2 setValue:@{ @"uniqueIdentifier" : @"field2", @"hints" : @[ @"hint2" ], @"editingValue" : @{@"text" : @""} } forKey:@"autofill"]; NSMutableDictionary* config = [field1 mutableCopy]; [config setValue:@[ field1, field2 ] forKey:@"fields"]; [self setClientId:123 configuration:config]; XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; XCTAssertEqual(self.installedInputViews.count, 2ul); XCTAssertEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); [self ensureOnlyActiveViewCanBecomeFirstResponder]; // The configuration changes. NSMutableDictionary* field3 = self.mutablePasswordTemplateCopy; [field3 setValue:@{ @"uniqueIdentifier" : @"field3", @"hints" : @[ @"hint3" ], @"editingValue" : @{@"text" : @""} } forKey:@"autofill"]; NSMutableDictionary* oldContext = textInputPlugin.autofillContext; // Replace field2 with field3. [config setValue:@[ field1, field3 ] forKey:@"fields"]; [self setClientId:123 configuration:config]; XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; XCTAssertEqual(self.installedInputViews.count, 3ul); XCTAssertEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); [self ensureOnlyActiveViewCanBecomeFirstResponder]; // Old autofill input fields are still installed and reused. for (NSString* key in oldContext.allKeys) { XCTAssertEqual(oldContext[key], textInputPlugin.autofillContext[key]); } // Switch to a password field that has no contentType and is not in an AutofillGroup. config = self.mutablePasswordTemplateCopy; oldContext = textInputPlugin.autofillContext; [self setClientId:124 configuration:config]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul); XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; XCTAssertEqual(self.installedInputViews.count, 4ul); // Old autofill input fields are still installed and reused. for (NSString* key in oldContext.allKeys) { XCTAssertEqual(oldContext[key], textInputPlugin.autofillContext[key]); } // The active view should change. XCTAssertNotEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); [self ensureOnlyActiveViewCanBecomeFirstResponder]; // Switch to a similar password field, the previous field should be reused. oldContext = textInputPlugin.autofillContext; [self setClientId:200 configuration:config]; // Reuse the input view instance from the last time. XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul); XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; XCTAssertEqual(self.installedInputViews.count, 4ul); // Old autofill input fields are still installed and reused. for (NSString* key in oldContext.allKeys) { XCTAssertEqual(oldContext[key], textInputPlugin.autofillContext[key]); } XCTAssertNotEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); [self ensureOnlyActiveViewCanBecomeFirstResponder]; } - (void)testCommitAutofillContext { NSMutableDictionary* field1 = self.mutableTemplateCopy; [field1 setValue:@{ @"uniqueIdentifier" : @"field1", @"hints" : @[ @"hint1" ], @"editingValue" : @{@"text" : @""} } forKey:@"autofill"]; NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy; [field2 setValue:@{ @"uniqueIdentifier" : @"field2", @"hints" : @[ @"hint2" ], @"editingValue" : @{@"text" : @""} } forKey:@"autofill"]; NSMutableDictionary* field3 = self.mutableTemplateCopy; [field3 setValue:@{ @"uniqueIdentifier" : @"field3", @"hints" : @[ @"hint3" ], @"editingValue" : @{@"text" : @""} } forKey:@"autofill"]; NSMutableDictionary* config = [field1 mutableCopy]; [config setValue:@[ field1, field2 ] forKey:@"fields"]; [self setClientId:123 configuration:config]; XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul); [self ensureOnlyActiveViewCanBecomeFirstResponder]; [self commitAutofillContextAndVerify]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; // Install the password field again. [self setClientId:123 configuration:config]; // Switch to a regular autofill group. [self setClientId:124 configuration:field3]; XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; XCTAssertEqual(self.installedInputViews.count, 3ul); XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul); XCTAssertNotEqual(textInputPlugin.textInputView, nil); [self ensureOnlyActiveViewCanBecomeFirstResponder]; [self commitAutofillContextAndVerify]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; // Now switch to an input field that does not autofill. [self setClientId:125 configuration:self.mutableTemplateCopy]; XCTAssertEqual(self.viewsVisibleToAutofill.count, 0ul); // The active view should still be installed so it doesn't get // deallocated. [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; XCTAssertEqual(self.installedInputViews.count, 1ul); XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul); [self ensureOnlyActiveViewCanBecomeFirstResponder]; [self commitAutofillContextAndVerify]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; } - (void)testAutofillInputViews { NSMutableDictionary* field1 = self.mutableTemplateCopy; [field1 setValue:@{ @"uniqueIdentifier" : @"field1", @"hints" : @[ @"hint1" ], @"editingValue" : @{@"text" : @""} } forKey:@"autofill"]; NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy; [field2 setValue:@{ @"uniqueIdentifier" : @"field2", @"hints" : @[ @"hint2" ], @"editingValue" : @{@"text" : @""} } forKey:@"autofill"]; NSMutableDictionary* config = [field1 mutableCopy]; [config setValue:@[ field1, field2 ] forKey:@"fields"]; [self setClientId:123 configuration:config]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; // Find all the FlutterTextInputViews we created. NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; // Both fields are installed and visible because it's a password group. XCTAssertEqual(inputFields.count, 2ul); XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); // Find the inactive autofillable input field. FlutterTextInputView* inactiveView = inputFields[1]; [inactiveView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 0)] withText:@"Autofilled!"]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; // Verify behavior. OCMVerify([engine flutterTextInputView:inactiveView updateEditingClient:0 withState:[OCMArg isNotNil] withTag:@"field2"]); } - (void)testPasswordAutofillHack { NSDictionary* config = self.mutableTemplateCopy; [config setValue:@"YES" forKey:@"obscureText"]; [self setClientId:123 configuration:config]; // Find all the FlutterTextInputViews we created. NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; FlutterTextInputView* inputView = inputFields[0]; XCTAssert([inputView isKindOfClass:[UITextField class]]); // FlutterSecureTextInputView does not respond to font, // but it should return the default UITextField.font. XCTAssertNotEqual([inputView performSelector:@selector(font)], nil); } - (void)testClearAutofillContextClearsSelection { NSMutableDictionary* regularField = self.mutableTemplateCopy; NSDictionary* editingValue = @{ @"text" : @"REGULAR_TEXT_FIELD", @"composingBase" : @0, @"composingExtent" : @3, @"selectionBase" : @1, @"selectionExtent" : @4 }; [regularField setValue:@{ @"uniqueIdentifier" : @"field2", @"hints" : @[ @"hint2" ], @"editingValue" : editingValue, } forKey:@"autofill"]; [regularField addEntriesFromDictionary:editingValue]; [self setClientId:123 configuration:regularField]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; XCTAssertEqual(self.installedInputViews.count, 1ul); FlutterTextInputView* oldInputView = self.installedInputViews[0]; XCTAssert([oldInputView.text isEqualToString:@"REGULAR_TEXT_FIELD"]); FlutterTextRange* selectionRange = (FlutterTextRange*)oldInputView.selectedTextRange; XCTAssert(NSEqualRanges(selectionRange.range, NSMakeRange(1, 3))); // Replace the original password field with new one. This should remove // the old password field, but not immediately. [self setClientId:124 configuration:self.mutablePasswordTemplateCopy]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; XCTAssertEqual(self.installedInputViews.count, 2ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; XCTAssertEqual(self.installedInputViews.count, 1ul); // Verify the old input view is properly cleaned up. XCTAssert([oldInputView.text isEqualToString:@""]); selectionRange = (FlutterTextRange*)oldInputView.selectedTextRange; XCTAssert(NSEqualRanges(selectionRange.range, NSMakeRange(0, 0))); } - (void)testGarbageInputViewsAreNotRemovedImmediately { // Add a password field that should autofill. [self setClientId:123 configuration:self.mutablePasswordTemplateCopy]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; XCTAssertEqual(self.installedInputViews.count, 1ul); // Add an input field that doesn't autofill. This should remove the password // field, but not immediately. [self setClientId:124 configuration:self.mutableTemplateCopy]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; XCTAssertEqual(self.installedInputViews.count, 2ul); [self commitAutofillContextAndVerify]; } - (void)testScribbleSetSelectionRects { NSMutableDictionary* regularField = self.mutableTemplateCopy; NSDictionary* editingValue = @{ @"text" : @"REGULAR_TEXT_FIELD", @"composingBase" : @0, @"composingExtent" : @3, @"selectionBase" : @1, @"selectionExtent" : @4 }; [regularField setValue:@{ @"uniqueIdentifier" : @"field1", @"hints" : @[ @"hint2" ], @"editingValue" : editingValue, } forKey:@"autofill"]; [regularField addEntriesFromDictionary:editingValue]; [self setClientId:123 configuration:regularField]; XCTAssertEqual(self.installedInputViews.count, 1ul); XCTAssertEqual([textInputPlugin.activeView.selectionRects count], 0u); NSArray<NSNumber*>* selectionRect = [NSArray arrayWithObjects:@0, @0, @100, @100, @0, @1, nil]; NSArray* selectionRects = [NSArray arrayWithObjects:selectionRect, nil]; FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"Scribble.setSelectionRects" arguments:selectionRects]; [textInputPlugin handleMethodCall:methodCall result:^(id _Nullable result){ }]; XCTAssertEqual([textInputPlugin.activeView.selectionRects count], 1u); } - (void)testDecommissionedViewAreNotReusedByAutofill { // Regression test for https://github.com/flutter/flutter/issues/84407. NSMutableDictionary* configuration = self.mutableTemplateCopy; [configuration setValue:@{ @"uniqueIdentifier" : @"field1", @"hints" : @[ UITextContentTypePassword ], @"editingValue" : @{@"text" : @""} } forKey:@"autofill"]; [configuration setValue:@[ [configuration copy] ] forKey:@"fields"]; [self setClientId:123 configuration:configuration]; [self setTextInputHide]; UIView* previousActiveView = textInputPlugin.activeView; [self setClientId:124 configuration:configuration]; // Make sure the autofillable view is reused. XCTAssertEqual(previousActiveView, textInputPlugin.activeView); XCTAssertNotNil(previousActiveView); // Does not crash. } - (void)testInitialActiveViewCantAccessTextInputDelegate { // Before the framework sends the first text input configuration, // the dummy "activeView" we use should never have access to // its textInputDelegate. XCTAssertNil(textInputPlugin.activeView.textInputDelegate); } #pragma mark - Accessibility - Tests - (void)testUITextInputAccessibilityNotHiddenWhenShowed { [self setClientId:123 configuration:self.mutableTemplateCopy]; // Send show text input method call. [self setTextInputShow]; // Find all the FlutterTextInputViews we created. NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews; // The input view should not be hidden. XCTAssertEqual([inputFields count], 1u); // Send hide text input method call. [self setTextInputHide]; inputFields = self.installedInputViews; // The input view should be hidden. XCTAssertEqual([inputFields count], 0u); } - (void)testFlutterTextInputViewDirectFocusToBackingTextInput { FlutterTextInputViewSpy* inputView = [[FlutterTextInputViewSpy alloc] initWithOwner:textInputPlugin]; UIView* container = [[UIView alloc] init]; UIAccessibilityElement* backing = [[UIAccessibilityElement alloc] initWithAccessibilityContainer:container]; inputView.backingTextInputAccessibilityObject = backing; // Simulate accessibility focus. inputView.isAccessibilityFocused = YES; [inputView accessibilityElementDidBecomeFocused]; XCTAssertEqual(inputView.receivedNotification, UIAccessibilityScreenChangedNotification); XCTAssertEqual(inputView.receivedNotificationTarget, backing); } - (void)testFlutterTokenizerCanParseLines { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; id<UITextInputTokenizer> tokenizer = [inputView tokenizer]; // The tokenizer returns zero range When text is empty. FlutterTextRange* range = [self getLineRangeFromTokenizer:tokenizer atIndex:0]; XCTAssertEqual(range.range.location, 0u); XCTAssertEqual(range.range.length, 0u); [inputView insertText:@"how are you\nI am fine, Thank you"]; range = [self getLineRangeFromTokenizer:tokenizer atIndex:0]; XCTAssertEqual(range.range.location, 0u); XCTAssertEqual(range.range.length, 11u); range = [self getLineRangeFromTokenizer:tokenizer atIndex:2]; XCTAssertEqual(range.range.location, 0u); XCTAssertEqual(range.range.length, 11u); range = [self getLineRangeFromTokenizer:tokenizer atIndex:11]; XCTAssertEqual(range.range.location, 0u); XCTAssertEqual(range.range.length, 11u); range = [self getLineRangeFromTokenizer:tokenizer atIndex:12]; XCTAssertEqual(range.range.location, 12u); XCTAssertEqual(range.range.length, 20u); range = [self getLineRangeFromTokenizer:tokenizer atIndex:15]; XCTAssertEqual(range.range.location, 12u); XCTAssertEqual(range.range.length, 20u); range = [self getLineRangeFromTokenizer:tokenizer atIndex:32]; XCTAssertEqual(range.range.location, 12u); XCTAssertEqual(range.range.length, 20u); } - (void)testFlutterTokenizerLineEnclosingEndOfDocumentInBackwardDirectionShouldNotReturnNil { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView insertText:@"0123456789\n012345"]; id<UITextInputTokenizer> tokenizer = [inputView tokenizer]; FlutterTextRange* range = (FlutterTextRange*)[tokenizer rangeEnclosingPosition:[inputView endOfDocument] withGranularity:UITextGranularityLine inDirection:UITextStorageDirectionBackward]; XCTAssertEqual(range.range.location, 11u); XCTAssertEqual(range.range.length, 6u); } - (void)testFlutterTokenizerLineEnclosingEndOfDocumentInForwardDirectionShouldReturnNilOnIOS17 { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView insertText:@"0123456789\n012345"]; id<UITextInputTokenizer> tokenizer = [inputView tokenizer]; FlutterTextRange* range = (FlutterTextRange*)[tokenizer rangeEnclosingPosition:[inputView endOfDocument] withGranularity:UITextGranularityLine inDirection:UITextStorageDirectionForward]; if (@available(iOS 17.0, *)) { XCTAssertNil(range); } else { XCTAssertEqual(range.range.location, 11u); XCTAssertEqual(range.range.length, 6u); } } - (void)testFlutterTokenizerLineEnclosingOutOfRangePositionShouldReturnNilOnIOS17 { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [inputView insertText:@"0123456789\n012345"]; id<UITextInputTokenizer> tokenizer = [inputView tokenizer]; FlutterTextPosition* position = [FlutterTextPosition positionWithIndex:100]; FlutterTextRange* range = (FlutterTextRange*)[tokenizer rangeEnclosingPosition:position withGranularity:UITextGranularityLine inDirection:UITextStorageDirectionForward]; if (@available(iOS 17.0, *)) { XCTAssertNil(range); } else { XCTAssertEqual(range.range.location, 0u); XCTAssertEqual(range.range.length, 0u); } } - (void)testFlutterTextInputPluginRetainsFlutterTextInputView { FlutterViewController* flutterViewController = [[FlutterViewController alloc] init]; FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine]; myInputPlugin.viewController = flutterViewController; __weak UIView* activeView; @autoreleasepool { FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" arguments:@[ [NSNumber numberWithInt:123], self.mutablePasswordTemplateCopy ]]; [myInputPlugin handleMethodCall:setClientCall result:^(id _Nullable result){ }]; activeView = myInputPlugin.textInputView; FlutterMethodCall* hideCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.hide" arguments:@[]]; [myInputPlugin handleMethodCall:hideCall result:^(id _Nullable result){ }]; XCTAssertNotNil(activeView); } // This assert proves the myInputPlugin.textInputView is not deallocated. XCTAssertNotNil(activeView); } - (void)testFlutterTextInputPluginHostViewNilCrash { FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine]; myInputPlugin.viewController = nil; XCTAssertThrows([myInputPlugin hostView], @"Throws exception if host view is nil"); } - (void)testFlutterTextInputPluginHostViewNotNil { FlutterViewController* flutterViewController = [[FlutterViewController alloc] init]; FlutterEngine* flutterEngine = [[FlutterEngine alloc] init]; [flutterEngine runWithEntrypoint:nil]; flutterEngine.viewController = flutterViewController; XCTAssertNotNil(flutterEngine.textInputPlugin.viewController); XCTAssertNotNil([flutterEngine.textInputPlugin hostView]); } - (void)testSetPlatformViewClient { FlutterViewController* flutterViewController = [[FlutterViewController alloc] init]; FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine]; myInputPlugin.viewController = flutterViewController; FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" arguments:@[ [NSNumber numberWithInt:123], self.mutablePasswordTemplateCopy ]]; [myInputPlugin handleMethodCall:setClientCall result:^(id _Nullable result){ }]; UIView* activeView = myInputPlugin.textInputView; XCTAssertNotNil(activeView.superview, @"activeView must be added to the view hierarchy."); FlutterMethodCall* setPlatformViewClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setPlatformViewClient" arguments:@{@"platformViewId" : [NSNumber numberWithLong:456]}]; [myInputPlugin handleMethodCall:setPlatformViewClientCall result:^(id _Nullable result){ }]; XCTAssertNil(activeView.superview, @"activeView must be removed from view hierarchy."); } - (void)testInteractiveKeyboardAfterUserScrollWillResignFirstResponder { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [UIApplication.sharedApplication.keyWindow addSubview:inputView]; [inputView setTextInputClient:123]; [inputView reloadInputViews]; [inputView becomeFirstResponder]; XCTAssert(inputView.isFirstResponder); CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); [NSNotificationCenter.defaultCenter postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; FlutterMethodCall* onPointerMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(500)}]; [textInputPlugin handleMethodCall:onPointerMoveCall result:^(id _Nullable result){ }]; XCTAssertFalse(inputView.isFirstResponder); textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardAfterUserScrollToTopOfKeyboardWillTakeScreenshot { NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes; XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); UIScene* scene = scenes.anyObject; XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); UIWindowScene* windowScene = (UIWindowScene*)scene; XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); UIWindow* window = windowScene.windows[0]; [window addSubview:viewController.view]; [viewController loadView]; FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [UIApplication.sharedApplication.keyWindow addSubview:inputView]; [inputView setTextInputClient:123]; [inputView reloadInputViews]; [inputView becomeFirstResponder]; if (textInputPlugin.keyboardView.superview != nil) { for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) { [subView removeFromSuperview]; } } XCTAssert(textInputPlugin.keyboardView.superview == nil); CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); [NSNotificationCenter.defaultCenter postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; FlutterMethodCall* onPointerMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(510)}]; [textInputPlugin handleMethodCall:onPointerMoveCall result:^(id _Nullable result){ }]; XCTAssertFalse(textInputPlugin.keyboardView.superview == nil); for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) { [subView removeFromSuperview]; } textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardScreenshotWillBeMovedDownAfterUserScroll { NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes; XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); UIScene* scene = scenes.anyObject; XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); UIWindowScene* windowScene = (UIWindowScene*)scene; XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); UIWindow* window = windowScene.windows[0]; [window addSubview:viewController.view]; [viewController loadView]; FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [UIApplication.sharedApplication.keyWindow addSubview:inputView]; [inputView setTextInputClient:123]; [inputView reloadInputViews]; [inputView becomeFirstResponder]; CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); [NSNotificationCenter.defaultCenter postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; FlutterMethodCall* onPointerMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(510)}]; [textInputPlugin handleMethodCall:onPointerMoveCall result:^(id _Nullable result){ }]; XCTAssert(textInputPlugin.keyboardView.superview != nil); XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, keyboardFrame.origin.y); FlutterMethodCall* onPointerMoveCallMove = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(600)}]; [textInputPlugin handleMethodCall:onPointerMoveCallMove result:^(id _Nullable result){ }]; XCTAssert(textInputPlugin.keyboardView.superview != nil); XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, 600.0); for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) { [subView removeFromSuperview]; } textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardScreenshotWillBeMovedToOrginalPositionAfterUserScroll { NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes; XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); UIScene* scene = scenes.anyObject; XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); UIWindowScene* windowScene = (UIWindowScene*)scene; XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); UIWindow* window = windowScene.windows[0]; [window addSubview:viewController.view]; [viewController loadView]; FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [UIApplication.sharedApplication.keyWindow addSubview:inputView]; [inputView setTextInputClient:123]; [inputView reloadInputViews]; [inputView becomeFirstResponder]; CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); [NSNotificationCenter.defaultCenter postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; FlutterMethodCall* onPointerMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(500)}]; [textInputPlugin handleMethodCall:onPointerMoveCall result:^(id _Nullable result){ }]; XCTAssert(textInputPlugin.keyboardView.superview != nil); XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, keyboardFrame.origin.y); FlutterMethodCall* onPointerMoveCallMove = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(600)}]; [textInputPlugin handleMethodCall:onPointerMoveCallMove result:^(id _Nullable result){ }]; XCTAssert(textInputPlugin.keyboardView.superview != nil); XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, 600.0); FlutterMethodCall* onPointerMoveCallBackUp = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(10)}]; [textInputPlugin handleMethodCall:onPointerMoveCallBackUp result:^(id _Nullable result){ }]; XCTAssert(textInputPlugin.keyboardView.superview != nil); XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, keyboardFrame.origin.y); for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) { [subView removeFromSuperview]; } textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardFindFirstResponderRecursive { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [UIApplication.sharedApplication.keyWindow addSubview:inputView]; [inputView setTextInputClient:123]; [inputView reloadInputViews]; [inputView becomeFirstResponder]; UIView* firstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder; XCTAssertEqualObjects(inputView, firstResponder); textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardFindFirstResponderRecursiveInMultipleSubviews { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; FlutterTextInputView* subInputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; FlutterTextInputView* otherSubInputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; FlutterTextInputView* subFirstResponderInputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [subInputView addSubview:subFirstResponderInputView]; [inputView addSubview:subInputView]; [inputView addSubview:otherSubInputView]; [UIApplication.sharedApplication.keyWindow addSubview:inputView]; [inputView setTextInputClient:123]; [inputView reloadInputViews]; [subInputView setTextInputClient:123]; [subInputView reloadInputViews]; [otherSubInputView setTextInputClient:123]; [otherSubInputView reloadInputViews]; [subFirstResponderInputView setTextInputClient:123]; [subFirstResponderInputView reloadInputViews]; [subFirstResponderInputView becomeFirstResponder]; UIView* firstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder; XCTAssertEqualObjects(subFirstResponderInputView, firstResponder); textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardFindFirstResponderIsNilRecursive { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [UIApplication.sharedApplication.keyWindow addSubview:inputView]; [inputView setTextInputClient:123]; [inputView reloadInputViews]; UIView* firstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder; XCTAssertNil(firstResponder); textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardDidResignFirstResponderDelegateisCalledAfterDismissedKeyboard { NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes; XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); UIScene* scene = scenes.anyObject; XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); UIWindowScene* windowScene = (UIWindowScene*)scene; XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); UIWindow* window = windowScene.windows[0]; [window addSubview:viewController.view]; [viewController loadView]; XCTestExpectation* expectation = [[XCTestExpectation alloc] initWithDescription: @"didResignFirstResponder is called after screenshot keyboard dismissed."]; OCMStub([engine flutterTextInputView:[OCMArg any] didResignFirstResponderWithTextInputClient:0]) .andDo(^(NSInvocation* invocation) { [expectation fulfill]; }); CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); [NSNotificationCenter.defaultCenter postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; FlutterMethodCall* initialMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(500)}]; [textInputPlugin handleMethodCall:initialMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* subsequentMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(1000)}]; [textInputPlugin handleMethodCall:subsequentMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* pointerUpCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" arguments:@{@"pointerY" : @(1000)}]; [textInputPlugin handleMethodCall:pointerUpCall result:^(id _Nullable result){ }]; [self waitForExpectations:@[ expectation ] timeout:2.0]; textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardScreenshotDismissedAfterPointerLiftedAboveMiddleYOfKeyboard { NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes; XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); UIScene* scene = scenes.anyObject; XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); UIWindowScene* windowScene = (UIWindowScene*)scene; XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); UIWindow* window = windowScene.windows[0]; [window addSubview:viewController.view]; [viewController loadView]; CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); [NSNotificationCenter.defaultCenter postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; FlutterMethodCall* initialMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(500)}]; [textInputPlugin handleMethodCall:initialMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* subsequentMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(1000)}]; [textInputPlugin handleMethodCall:subsequentMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* subsequentMoveBackUpCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(0)}]; [textInputPlugin handleMethodCall:subsequentMoveBackUpCall result:^(id _Nullable result){ }]; FlutterMethodCall* pointerUpCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" arguments:@{@"pointerY" : @(0)}]; [textInputPlugin handleMethodCall:pointerUpCall result:^(id _Nullable result){ }]; NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary* bindings) { return textInputPlugin.keyboardViewContainer.subviews.count == 0; }]; XCTNSPredicateExpectation* expectation = [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:nil]; [self waitForExpectations:@[ expectation ] timeout:10.0]; textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardKeyboardReappearsAfterPointerLiftedAboveMiddleYOfKeyboard { NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes; XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); UIScene* scene = scenes.anyObject; XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); UIWindowScene* windowScene = (UIWindowScene*)scene; XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); UIWindow* window = windowScene.windows[0]; [window addSubview:viewController.view]; [viewController loadView]; FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; [UIApplication.sharedApplication.keyWindow addSubview:inputView]; [inputView setTextInputClient:123]; [inputView reloadInputViews]; [inputView becomeFirstResponder]; CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); [NSNotificationCenter.defaultCenter postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; FlutterMethodCall* initialMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(500)}]; [textInputPlugin handleMethodCall:initialMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* subsequentMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(1000)}]; [textInputPlugin handleMethodCall:subsequentMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* subsequentMoveBackUpCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(0)}]; [textInputPlugin handleMethodCall:subsequentMoveBackUpCall result:^(id _Nullable result){ }]; FlutterMethodCall* pointerUpCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" arguments:@{@"pointerY" : @(0)}]; [textInputPlugin handleMethodCall:pointerUpCall result:^(id _Nullable result){ }]; NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary* bindings) { return textInputPlugin.cachedFirstResponder.isFirstResponder; }]; XCTNSPredicateExpectation* expectation = [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:nil]; [self waitForExpectations:@[ expectation ] timeout:10.0]; textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardKeyboardAnimatesToOriginalPositionalOnPointerUp { NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes; XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); UIScene* scene = scenes.anyObject; XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); UIWindowScene* windowScene = (UIWindowScene*)scene; XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); UIWindow* window = windowScene.windows[0]; [window addSubview:viewController.view]; [viewController loadView]; XCTestExpectation* expectation = [[XCTestExpectation alloc] initWithDescription:@"Keyboard animates to proper position."]; CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); [NSNotificationCenter.defaultCenter postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; FlutterMethodCall* initialMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(500)}]; [textInputPlugin handleMethodCall:initialMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* subsequentMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(1000)}]; [textInputPlugin handleMethodCall:subsequentMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* upwardVelocityMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(500)}]; [textInputPlugin handleMethodCall:upwardVelocityMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* pointerUpCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" arguments:@{@"pointerY" : @(0)}]; [textInputPlugin handleMethodCall:pointerUpCall result:^(id _Nullable result) { XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, viewController.flutterScreenIfViewLoaded.bounds.size.height - keyboardFrame.origin.y); [expectation fulfill]; }]; textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardKeyboardAnimatesToDismissalPositionalOnPointerUp { NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes; XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); UIScene* scene = scenes.anyObject; XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); UIWindowScene* windowScene = (UIWindowScene*)scene; XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); UIWindow* window = windowScene.windows[0]; [window addSubview:viewController.view]; [viewController loadView]; XCTestExpectation* expectation = [[XCTestExpectation alloc] initWithDescription:@"Keyboard animates to proper position."]; CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); [NSNotificationCenter.defaultCenter postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; FlutterMethodCall* initialMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(500)}]; [textInputPlugin handleMethodCall:initialMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* subsequentMoveCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" arguments:@{@"pointerY" : @(1000)}]; [textInputPlugin handleMethodCall:subsequentMoveCall result:^(id _Nullable result){ }]; FlutterMethodCall* pointerUpCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" arguments:@{@"pointerY" : @(1000)}]; [textInputPlugin handleMethodCall:pointerUpCall result:^(id _Nullable result) { XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, viewController.flutterScreenIfViewLoaded.bounds.size.height); [expectation fulfill]; }]; textInputPlugin.cachedFirstResponder = nil; } - (void)testInteractiveKeyboardShowKeyboardAndRemoveScreenshotAnimationIsNotImmediatelyEnable { [UIView setAnimationsEnabled:YES]; [textInputPlugin showKeyboardAndRemoveScreenshot]; XCTAssertFalse( UIView.areAnimationsEnabled, @"The animation should still be disabled following showKeyboardAndRemoveScreenshot"); } - (void)testInteractiveKeyboardShowKeyboardAndRemoveScreenshotAnimationIsReenabledAfterDelay { [UIView setAnimationsEnabled:YES]; [textInputPlugin showKeyboardAndRemoveScreenshot]; NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary* bindings) { // This will be enabled after a delay return UIView.areAnimationsEnabled; }]; XCTNSPredicateExpectation* expectation = [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:nil]; [self waitForExpectations:@[ expectation ] timeout:10.0]; } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm", "repo_id": "engine", "token_count": 60984 }
320
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_ #include "flutter/fml/platform/darwin/weak_nsobject.h" #include "flutter/fml/time/time_point.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h" namespace flutter { class FlutterPlatformViewsController; } FLUTTER_DARWIN_EXPORT // NOLINTNEXTLINE(readability-identifier-naming) extern NSNotificationName const FlutterViewControllerWillDealloc; FLUTTER_DARWIN_EXPORT // NOLINTNEXTLINE(readability-identifier-naming) extern NSNotificationName const FlutterViewControllerHideHomeIndicator; FLUTTER_DARWIN_EXPORT // NOLINTNEXTLINE(readability-identifier-naming) extern NSNotificationName const FlutterViewControllerShowHomeIndicator; typedef NS_ENUM(NSInteger, FlutterKeyboardMode) { // NOLINTBEGIN(readability-identifier-naming) FlutterKeyboardModeHidden = 0, FlutterKeyboardModeDocked = 1, FlutterKeyboardModeFloating = 2, // NOLINTEND(readability-identifier-naming) }; typedef void (^FlutterKeyboardAnimationCallback)(fml::TimePoint); @interface FlutterViewController () <FlutterViewResponder> @property(class, nonatomic, readonly) BOOL accessibilityIsOnOffSwitchLabelsEnabled; @property(nonatomic, readonly) BOOL isPresentingViewController; @property(nonatomic, readonly) BOOL isVoiceOverRunning; @property(nonatomic, retain) FlutterKeyboardManager* keyboardManager; /** * @brief Whether the status bar is preferred hidden. * * This overrides the |UIViewController:prefersStatusBarHidden|. * This is ignored when `UIViewControllerBasedStatusBarAppearance` in info.plist * of the app project is `false`. */ @property(nonatomic, assign, readwrite) BOOL prefersStatusBarHidden; - (fml::WeakNSObject<FlutterViewController>)getWeakNSObject; - (std::shared_ptr<flutter::FlutterPlatformViewsController>&)platformViewsController; - (FlutterRestorationPlugin*)restorationPlugin; // Send touches to the Flutter Engine while forcing the change type to be cancelled. // The `phase`s in `touches` are ignored. - (void)forceTouchesCancelled:(NSSet*)touches; // Accepts keypress events, and then calls |nextAction| if the event was not // handled. - (void)handlePressEvent:(FlutterUIPressProxy*)press nextAction:(void (^)())nextAction API_AVAILABLE(ios(13.4)); - (void)addInternalPlugins; - (void)deregisterNotifications; - (int32_t)accessibilityFlags; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h", "repo_id": "engine", "token_count": 1097 }
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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_IOS_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_IOS_H_ #include <memory> #include <vector> #import "flutter/fml/mapping.h" #include "flutter/lib/ui/semantics/semantics_node.h" @class UIView; namespace flutter { class FlutterPlatformViewsController; /// Interface that represents an accessibility bridge for iOS. class AccessibilityBridgeIos { public: virtual ~AccessibilityBridgeIos() = default; virtual UIView* view() const = 0; virtual bool isVoiceOverRunning() const = 0; virtual UIView<UITextInput>* textInputView() = 0; virtual void DispatchSemanticsAction(int32_t id, flutter::SemanticsAction action) = 0; virtual void DispatchSemanticsAction(int32_t id, flutter::SemanticsAction action, fml::MallocMapping args) = 0; /** * A callback that is called when a SemanticObject receives focus. * * The input id is the uid of the newly focused SemanticObject. */ virtual void AccessibilityObjectDidBecomeFocused(int32_t id) = 0; /** * A callback that is called when a SemanticObject loses focus * * The input id is the uid of the newly focused SemanticObject. */ virtual void AccessibilityObjectDidLoseFocus(int32_t id) = 0; virtual std::shared_ptr<FlutterPlatformViewsController> GetPlatformViewsController() const = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_IOS_H_
engine/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h", "repo_id": "engine", "token_count": 639 }
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. #include "flutter/shell/platform/darwin/ios/ios_context.h" #include "flutter/shell/platform/darwin/ios/rendering_api_selection.h" #include "flutter/fml/logging.h" #include "flutter/shell/platform/darwin/ios/ios_context_software.h" #if SHELL_ENABLE_METAL #include "flutter/shell/platform/darwin/ios/ios_context_metal_impeller.h" #include "flutter/shell/platform/darwin/ios/ios_context_metal_skia.h" #endif // SHELL_ENABLE_METAL namespace flutter { IOSContext::IOSContext(MsaaSampleCount msaa_samples) : msaa_samples_(msaa_samples) {} IOSContext::~IOSContext() = default; std::unique_ptr<IOSContext> IOSContext::Create( IOSRenderingAPI api, IOSRenderingBackend backend, MsaaSampleCount msaa_samples, const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch) { switch (api) { case IOSRenderingAPI::kSoftware: FML_CHECK(backend != IOSRenderingBackend::kImpeller) << "Software rendering is incompatible with Impeller.\n" "Software rendering may have been automatically selected when running on a simulator " "in an environment that does not support Metal. Enabling GPU pass through in your " "environment may fix this. If that is not possible, then disable Impeller."; return std::make_unique<IOSContextSoftware>(); #if SHELL_ENABLE_METAL case IOSRenderingAPI::kMetal: switch (backend) { case IOSRenderingBackend::kSkia: return std::make_unique<IOSContextMetalSkia>(msaa_samples); case IOSRenderingBackend::kImpeller: return std::make_unique<IOSContextMetalImpeller>(is_gpu_disabled_sync_switch); } #endif // SHELL_ENABLE_METAL default: break; } FML_CHECK(false); return nullptr; } IOSRenderingBackend IOSContext::GetBackend() const { return IOSRenderingBackend::kSkia; } std::shared_ptr<impeller::Context> IOSContext::GetImpellerContext() const { return nullptr; } } // namespace flutter
engine/shell/platform/darwin/ios/ios_context.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_context.mm", "repo_id": "engine", "token_count": 808 }
323
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/ios_surface_metal_skia.h" #include "flutter/shell/gpu/gpu_surface_metal_delegate.h" #include "flutter/shell/gpu/gpu_surface_metal_skia.h" #include "flutter/shell/platform/darwin/ios/ios_context_metal_skia.h" @protocol FlutterMetalDrawable <MTLDrawable> - (void)flutterPrepareForPresent:(nonnull id<MTLCommandBuffer>)commandBuffer; @end namespace flutter { static IOSContextMetalSkia* CastToMetalContext(const std::shared_ptr<IOSContext>& context) { return reinterpret_cast<IOSContextMetalSkia*>(context.get()); } IOSSurfaceMetalSkia::IOSSurfaceMetalSkia(const fml::scoped_nsobject<CAMetalLayer>& layer, std::shared_ptr<IOSContext> context) : IOSSurface(std::move(context)), GPUSurfaceMetalDelegate(MTLRenderTargetType::kCAMetalLayer), layer_(layer) { is_valid_ = layer_; auto metal_context = CastToMetalContext(GetContext()); auto darwin_context = metal_context->GetDarwinContext().get(); command_queue_ = darwin_context.commandQueue; device_ = darwin_context.device; } // |IOSSurface| IOSSurfaceMetalSkia::~IOSSurfaceMetalSkia() = default; // |IOSSurface| bool IOSSurfaceMetalSkia::IsValid() const { return is_valid_; } // |IOSSurface| void IOSSurfaceMetalSkia::UpdateStorageSizeIfNecessary() { // Nothing to do. } // |IOSSurface| std::unique_ptr<Surface> IOSSurfaceMetalSkia::CreateGPUSurface(GrDirectContext* context) { FML_DCHECK(context); return std::make_unique<GPUSurfaceMetalSkia>(this, // delegate sk_ref_sp(context), // context GetContext()->GetMsaaSampleCount() // sample count ); } // |GPUSurfaceMetalDelegate| GPUCAMetalLayerHandle IOSSurfaceMetalSkia::GetCAMetalLayer(const SkISize& frame_info) const { CAMetalLayer* layer = layer_.get(); layer.device = device_; layer.pixelFormat = MTLPixelFormatBGRA8Unorm; // Flutter needs to read from the color attachment in cases where there are effects such as // backdrop filters. Flutter plugins that create platform views may also read from the layer. layer.framebufferOnly = NO; const auto drawable_size = CGSizeMake(frame_info.width(), frame_info.height()); if (!CGSizeEqualToSize(drawable_size, layer.drawableSize)) { layer.drawableSize = drawable_size; } // When there are platform views in the scene, the drawable needs to be presented in the same // transaction as the one created for platform views. When the drawable are being presented from // the raster thread, there is no such transaction. layer.presentsWithTransaction = [[NSThread currentThread] isMainThread]; return layer; } // |GPUSurfaceMetalDelegate| bool IOSSurfaceMetalSkia::PresentDrawable(GrMTLHandle drawable) const { if (drawable == nullptr) { FML_DLOG(ERROR) << "Could not acquire next Metal drawable from the SkSurface."; return false; } auto command_buffer = fml::scoped_nsprotocol<id<MTLCommandBuffer>>([[command_queue_ commandBuffer] retain]); id<CAMetalDrawable> metal_drawable = reinterpret_cast<id<CAMetalDrawable>>(drawable); if ([metal_drawable conformsToProtocol:@protocol(FlutterMetalDrawable)]) { [(id<FlutterMetalDrawable>)metal_drawable flutterPrepareForPresent:command_buffer.get()]; } [command_buffer.get() commit]; [command_buffer.get() waitUntilScheduled]; [metal_drawable present]; return true; } // |GPUSurfaceMetalDelegate| GPUMTLTextureInfo IOSSurfaceMetalSkia::GetMTLTexture(const SkISize& frame_info) const { FML_CHECK(false) << "render to texture not supported on ios"; return {.texture_id = -1, .texture = nullptr}; } // |GPUSurfaceMetalDelegate| bool IOSSurfaceMetalSkia::PresentTexture(GPUMTLTextureInfo texture) const { FML_CHECK(false) << "render to texture not supported on ios"; return false; } // |GPUSurfaceMetalDelegate| bool IOSSurfaceMetalSkia::AllowsDrawingWhenGpuDisabled() const { return false; } } // namespace flutter
engine/shell/platform/darwin/ios/ios_surface_metal_skia.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_surface_metal_skia.mm", "repo_id": "engine", "token_count": 1540 }
324
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ #import <AppKit/AppKit.h> #import "FlutterCodecs.h" #import "FlutterMacros.h" @protocol FlutterPlatformViewFactory <NSObject> /** * Create a Platform View which is an `NSView`. * * A MacOS plugin should implement this method and return an `NSView`, which can be embedded in a * Flutter App. * * The implementation of this method should create a new `NSView`. * * @param viewId A unique identifier for this view. * @param args Parameters for creating the view sent from the Dart side of the * Flutter app. If `createArgsCodec` is not implemented, or if no creation arguments were sent from * the Dart code, this will be null. Otherwise this will be the value sent from the Dart code as * decoded by `createArgsCodec`. */ - (nonnull NSView*)createWithViewIdentifier:(int64_t)viewId arguments:(nullable id)args; /** * Returns the `FlutterMessageCodec` for decoding the args parameter of `createWithFrame`. * * Only implement this if `createWithFrame` needs an arguments parameter. */ @optional - (nullable NSObject<FlutterMessageCodec>*)createArgsCodec; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_
engine/shell/platform/darwin/macos/framework/Headers/FlutterPlatformViews.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Headers/FlutterPlatformViews.h", "repo_id": "engine", "token_count": 475 }
325
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCHANNELKEYRESPONDER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCHANNELKEYRESPONDER_H_ #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h" #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" /** * A primary responder of |FlutterKeyboardManager| that handles events by * sending the raw information through the method channel. * * This class communicates with the RawKeyboard API in the framework. */ @interface FlutterChannelKeyResponder : NSObject <FlutterKeyPrimaryResponder> /** * Create an instance by specifying the method channel to use. */ - (nonnull instancetype)initWithChannel:(nonnull FlutterBasicMessageChannel*)channel; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCHANNELKEYRESPONDER_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h", "repo_id": "engine", "token_count": 365 }
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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINETESTUTILS_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINETESTUTILS_H_ #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" #import <OCMock/OCMock.h> #include "flutter/testing/autoreleasepool_test.h" #include "flutter/testing/test_dart_native_resolver.h" #include "gtest/gtest.h" namespace flutter::testing { class FlutterEngineTest : public AutoreleasePoolTest { public: FlutterEngineTest(); FlutterEngine* GetFlutterEngine() { return engine_; }; void SetUp() override; void TearDown() override; void AddNativeCallback(const char* name, Dart_NativeFunction function); static void IsolateCreateCallback(void* user_data); void ShutDownEngine(); private: inline static std::shared_ptr<TestDartNativeResolver> native_resolver_; FlutterDartProject* project_; FlutterEngine* engine_; FML_DISALLOW_COPY_AND_ASSIGN(FlutterEngineTest); }; // Returns a mock FlutterEngine that is able to work in environments // without a real pasteboard. // // Callers MUST call [mockEngine shutDownEngine] when finished with the returned engine. id CreateMockFlutterEngine(NSString* pasteboardString); class MockFlutterEngineTest : public AutoreleasePoolTest { public: MockFlutterEngineTest(); void SetUp() override; void TearDown() override; id GetMockEngine() { return engine_mock_; } void ShutDownEngine(); ~MockFlutterEngineTest() { [engine_mock_ shutDownEngine]; [engine_mock_ stopMocking]; } private: id engine_mock_; FML_DISALLOW_COPY_AND_ASSIGN(MockFlutterEngineTest); }; } // namespace flutter::testing #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINETESTUTILS_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h", "repo_id": "engine", "token_count": 666 }
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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMUTATORVIEW_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMUTATORVIEW_H_ #import <Cocoa/Cocoa.h> #include <vector> #include "flutter/shell/platform/embedder/embedder.h" namespace flutter { /// Represents a platform view layer, including all mutations. class PlatformViewLayer { public: /// Creates platform view from provided FlutterLayer, which must be /// of type kFlutterLayerContentTypePlatformView. explicit PlatformViewLayer(const FlutterLayer* _Nonnull layer); PlatformViewLayer(FlutterPlatformViewIdentifier identifier, const std::vector<FlutterPlatformViewMutation>& mutations, FlutterPoint offset, FlutterSize size); FlutterPlatformViewIdentifier identifier() const { return identifier_; } const std::vector<FlutterPlatformViewMutation>& mutations() const { return mutations_; } FlutterPoint offset() const { return offset_; } FlutterSize size() const { return size_; } private: FlutterPlatformViewIdentifier identifier_; std::vector<FlutterPlatformViewMutation> mutations_; FlutterPoint offset_; FlutterSize size_; }; } // namespace flutter /// FlutterMutatorView contains platform view and is responsible for applying /// FlutterLayer mutations to it. @interface FlutterMutatorView : NSView /// Designated initializer. - (nonnull instancetype)initWithPlatformView:(nonnull NSView*)platformView; /// Returns wrapped platform view. @property(readonly, nonnull) NSView* platformView; /// Applies mutations from FlutterLayer to the platform view. This may involve /// creating or removing intermediate subviews depending on current state and /// requested mutations. - (void)applyFlutterLayer:(nonnull const flutter::PlatformViewLayer*)layer; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMUTATORVIEW_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h", "repo_id": "engine", "token_count": 655 }
328
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_ #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" @class FlutterTextField; /** * A plugin to handle text input. * * Responsible for bridging the native macOS text input system with the Flutter framework text * editing classes, via system channels. * * This is not an FlutterPlugin since it needs access to FlutterViewController internals, so needs * to be managed differently. * * When accessibility is on, accessibility bridge creates a NSTextField, i.e. FlutterTextField, * for every text field in the Flutter. This plugin acts as a field editor for those NSTextField[s]. */ @interface FlutterTextInputPlugin : NSTextView /** * The NSTextField that currently has this plugin as its field editor. * * Must be nil if accessibility is off. */ @property(nonatomic, weak) FlutterTextField* client; /** * Initializes a text input plugin that coordinates key event handling with |viewController|. */ - (instancetype)initWithViewController:(FlutterViewController*)viewController; /** * Whether this plugin is the first responder of this NSWindow. * * When accessibility is on, this plugin is set as the first responder to act as the field * editor for FlutterTextFields. * * Returns false if accessibility is off. */ - (BOOL)isFirstResponder; /** * Handles key down events received from the view controller, responding YES if * the event was handled. * * Note, the Apple docs suggest that clients should override essentially all the * mouse and keyboard event-handling methods of NSResponder. However, experimentation * indicates that only key events are processed by the native layer; Flutter processes * mouse events. Additionally, processing both keyUp and keyDown results in duplicate * processing of the same keys. */ - (BOOL)handleKeyEvent:(NSEvent*)event; @end // Private methods made visible for testing @interface FlutterTextInputPlugin (TestMethods) - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; - (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange; - (NSDictionary*)editingState; @property(nonatomic) NSTextInputContext* textInputContext; @property(readwrite, nonatomic) NSString* customRunLoopMode; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h", "repo_id": "engine", "token_count": 809 }
329
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h" #import "flutter/testing/testing.h" @interface TestDisplayLink : FlutterDisplayLink { } @property(nonatomic) CFTimeInterval nominalOutputRefreshPeriod; @end @implementation TestDisplayLink @synthesize nominalOutputRefreshPeriod = _nominalOutputRefreshPeriod; @synthesize delegate = _delegate; @synthesize paused = _paused; - (instancetype)init { if (self = [super init]) { _paused = YES; } return self; } - (void)tickWithTimestamp:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp { [_delegate onDisplayLink:timestamp targetTimestamp:targetTimestamp]; } - (void)invalidate { } @end TEST(FlutterVSyncWaiterTest, RequestsInitialVSync) { TestDisplayLink* displayLink = [[TestDisplayLink alloc] init]; EXPECT_TRUE(displayLink.paused); // When created waiter requests a reference vsync to determine vsync phase. FlutterVSyncWaiter* waiter = [[FlutterVSyncWaiter alloc] initWithDisplayLink:displayLink block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp, uintptr_t baton){ }]; (void)waiter; EXPECT_FALSE(displayLink.paused); [displayLink tickWithTimestamp:CACurrentMediaTime() targetTimestamp:CACurrentMediaTime() + 1.0 / 60.0]; EXPECT_TRUE(displayLink.paused); } static void BusyWait(CFTimeInterval duration) { CFTimeInterval start = CACurrentMediaTime(); while (CACurrentMediaTime() < start + duration) { } } // See FlutterVSyncWaiter.mm for the original definition. static const CFTimeInterval kTimerLatencyCompensation = 0.001; TEST(FlutterVSyncWaiterTest, FirstVSyncIsSynthesized) { TestDisplayLink* displayLink = [[TestDisplayLink alloc] init]; displayLink.nominalOutputRefreshPeriod = 1.0 / 60.0; auto test = [&](CFTimeInterval waitDuration, CFTimeInterval expectedDelay) { __block CFTimeInterval timestamp = 0; __block CFTimeInterval targetTimestamp = 0; __block size_t baton = 0; const uintptr_t kWarmUpBaton = 0xFFFFFFFF; FlutterVSyncWaiter* waiter = [[FlutterVSyncWaiter alloc] initWithDisplayLink:displayLink block:^(CFTimeInterval _timestamp, CFTimeInterval _targetTimestamp, uintptr_t _baton) { if (_baton == kWarmUpBaton) { return; } timestamp = _timestamp; targetTimestamp = _targetTimestamp; baton = _baton; EXPECT_TRUE(CACurrentMediaTime() >= _timestamp - kTimerLatencyCompensation); CFRunLoopStop(CFRunLoopGetCurrent()); }]; [waiter waitForVSync:kWarmUpBaton]; // Reference vsync to setup phase. CFTimeInterval now = CACurrentMediaTime(); // CVDisplayLink callback is called one and a half frame before the target. [displayLink tickWithTimestamp:now + 0.5 * displayLink.nominalOutputRefreshPeriod targetTimestamp:now + 2 * displayLink.nominalOutputRefreshPeriod]; EXPECT_EQ(displayLink.paused, YES); // Vsync was not requested yet, block should not have been called. EXPECT_EQ(timestamp, 0); BusyWait(waitDuration); // Synthesized vsync should come in 1/60th of a second after the first. CFTimeInterval expectedTimestamp = now + expectedDelay; [waiter waitForVSync:1]; CFRunLoopRun(); EXPECT_DOUBLE_EQ(timestamp, expectedTimestamp); EXPECT_DOUBLE_EQ(targetTimestamp, expectedTimestamp + displayLink.nominalOutputRefreshPeriod); EXPECT_EQ(baton, size_t(1)); }; // First argument if the wait duration after reference vsync. // Second argument is the expected delay between reference vsync and synthesized vsync. test(0.005, displayLink.nominalOutputRefreshPeriod); test(0.025, 2 * displayLink.nominalOutputRefreshPeriod); test(0.040, 3 * displayLink.nominalOutputRefreshPeriod); } TEST(FlutterVSyncWaiterTest, VSyncWorks) { TestDisplayLink* displayLink = [[TestDisplayLink alloc] init]; displayLink.nominalOutputRefreshPeriod = 1.0 / 60.0; const uintptr_t kWarmUpBaton = 0xFFFFFFFF; struct Entry { CFTimeInterval timestamp; CFTimeInterval targetTimestamp; size_t baton; }; __block std::vector<Entry> entries; FlutterVSyncWaiter* waiter = [[FlutterVSyncWaiter alloc] initWithDisplayLink:displayLink block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp, uintptr_t baton) { entries.push_back({timestamp, targetTimestamp, baton}); if (baton == kWarmUpBaton) { return; } EXPECT_TRUE(CACurrentMediaTime() >= timestamp - kTimerLatencyCompensation); CFRunLoopStop(CFRunLoopGetCurrent()); }]; __block CFTimeInterval expectedStartUntil; // Warm up tick is scheduled immediately in a scheduled block. Schedule another // block here to determine the maximum time when the warm up tick should be // scheduled. [waiter waitForVSync:kWarmUpBaton]; [[NSRunLoop currentRunLoop] performBlock:^{ expectedStartUntil = CACurrentMediaTime(); }]; // Reference vsync to setup phase. CFTimeInterval now = CACurrentMediaTime(); // CVDisplayLink callback is called one and a half frame before the target. [displayLink tickWithTimestamp:now + 0.5 * displayLink.nominalOutputRefreshPeriod targetTimestamp:now + 2 * displayLink.nominalOutputRefreshPeriod]; EXPECT_EQ(displayLink.paused, YES); [waiter waitForVSync:1]; CFRunLoopRun(); [waiter waitForVSync:2]; [displayLink tickWithTimestamp:now + 1.5 * displayLink.nominalOutputRefreshPeriod targetTimestamp:now + 3 * displayLink.nominalOutputRefreshPeriod]; CFRunLoopRun(); [waiter waitForVSync:3]; [displayLink tickWithTimestamp:now + 2.5 * displayLink.nominalOutputRefreshPeriod targetTimestamp:now + 4 * displayLink.nominalOutputRefreshPeriod]; CFRunLoopRun(); EXPECT_FALSE(displayLink.paused); // Vsync without baton should pause the display link. [displayLink tickWithTimestamp:now + 3.5 * displayLink.nominalOutputRefreshPeriod targetTimestamp:now + 5 * displayLink.nominalOutputRefreshPeriod]; CFTimeInterval start = CACurrentMediaTime(); while (!displayLink.paused) { // Make sure to run the timer scheduled in display link callback. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.02, NO); if (CACurrentMediaTime() - start > 1.0) { break; } } ASSERT_TRUE(displayLink.paused); EXPECT_EQ(entries.size(), size_t(4)); // Warm up frame should be presented as soon as possible. EXPECT_TRUE(entries[0].timestamp <= expectedStartUntil); EXPECT_TRUE(entries[0].targetTimestamp <= expectedStartUntil); EXPECT_EQ(entries[0].baton, kWarmUpBaton); EXPECT_DOUBLE_EQ(entries[1].timestamp, now + displayLink.nominalOutputRefreshPeriod); EXPECT_DOUBLE_EQ(entries[1].targetTimestamp, now + 2 * displayLink.nominalOutputRefreshPeriod); EXPECT_EQ(entries[1].baton, size_t(1)); EXPECT_DOUBLE_EQ(entries[2].timestamp, now + 2 * displayLink.nominalOutputRefreshPeriod); EXPECT_DOUBLE_EQ(entries[2].targetTimestamp, now + 3 * displayLink.nominalOutputRefreshPeriod); EXPECT_EQ(entries[2].baton, size_t(2)); EXPECT_DOUBLE_EQ(entries[3].timestamp, now + 3 * displayLink.nominalOutputRefreshPeriod); EXPECT_DOUBLE_EQ(entries[3].targetTimestamp, now + 4 * displayLink.nominalOutputRefreshPeriod); EXPECT_EQ(entries[3].baton, size_t(3)); }
engine/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiterTest.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiterTest.mm", "repo_id": "engine", "token_count": 3126 }
330
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_TEXTURE_METAL_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_TEXTURE_METAL_H_ #include "flutter/common/graphics/texture.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/embedder/embedder.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkSize.h" namespace flutter { class EmbedderExternalTextureMetal : public flutter::Texture { public: using ExternalTextureCallback = std::function< std::unique_ptr<FlutterMetalExternalTexture>(int64_t, size_t, size_t)>; EmbedderExternalTextureMetal(int64_t texture_identifier, const ExternalTextureCallback& callback); ~EmbedderExternalTextureMetal(); private: const ExternalTextureCallback& external_texture_callback_; sk_sp<DlImage> last_image_; sk_sp<DlImage> ResolveTexture(int64_t texture_id, GrDirectContext* context, const SkISize& size); // |flutter::Texture| void Paint(PaintContext& context, const SkRect& bounds, bool freeze, const DlImageSampling sampling) override; // |flutter::Texture| void OnGrContextCreated() override; // |flutter::Texture| void OnGrContextDestroyed() override; // |flutter::Texture| void MarkNewFrameAvailable() override; // |flutter::Texture| void OnTextureUnregistered() override; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderExternalTextureMetal); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_TEXTURE_METAL_H_
engine/shell/platform/embedder/embedder_external_texture_metal.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_external_texture_metal.h", "repo_id": "engine", "token_count": 698 }
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 "flutter/shell/platform/embedder/embedder_render_target_cache.h" namespace flutter { EmbedderRenderTargetCache::EmbedderRenderTargetCache() = default; EmbedderRenderTargetCache::~EmbedderRenderTargetCache() = default; std::unique_ptr<EmbedderRenderTarget> EmbedderRenderTargetCache::GetRenderTarget( const EmbedderExternalView::RenderTargetDescriptor& descriptor) { auto compatible_target = cached_render_targets_.find(descriptor); if (compatible_target == cached_render_targets_.end()) { return nullptr; } auto target = std::move(compatible_target->second); cached_render_targets_.erase(compatible_target); return target; } std::set<std::unique_ptr<EmbedderRenderTarget>> EmbedderRenderTargetCache::ClearAllRenderTargetsInCache() { std::set<std::unique_ptr<EmbedderRenderTarget>> cleared_targets; for (auto& targets : cached_render_targets_) { cleared_targets.insert(std::move(targets.second)); } cached_render_targets_.clear(); return cleared_targets; } void EmbedderRenderTargetCache::CacheRenderTarget( std::unique_ptr<EmbedderRenderTarget> target) { if (target == nullptr) { return; } auto desc = EmbedderExternalView::RenderTargetDescriptor{ target->GetRenderTargetSize()}; cached_render_targets_.insert(std::make_pair(desc, std::move(target))); } size_t EmbedderRenderTargetCache::GetCachedTargetsCount() const { return cached_render_targets_.size(); } } // namespace flutter
engine/shell/platform/embedder/embedder_render_target_cache.cc/0
{ "file_path": "engine/shell/platform/embedder/embedder_render_target_cache.cc", "repo_id": "engine", "token_count": 532 }
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 <utility> #include "flutter/shell/platform/embedder/embedder_surface_metal.h" #include "flutter/fml/logging.h" #include "flutter/shell/gpu/gpu_surface_metal_delegate.h" #import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h" #include "third_party/skia/include/gpu/GrDirectContext.h" FLUTTER_ASSERT_NOT_ARC namespace flutter { EmbedderSurfaceMetal::EmbedderSurfaceMetal( GPUMTLDeviceHandle device, GPUMTLCommandQueueHandle command_queue, MetalDispatchTable metal_dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder) : GPUSurfaceMetalDelegate(MTLRenderTargetType::kMTLTexture), metal_dispatch_table_(std::move(metal_dispatch_table)), external_view_embedder_(std::move(external_view_embedder)) { main_context_ = [FlutterDarwinContextMetalSkia createGrContext:(id<MTLDevice>)device commandQueue:(id<MTLCommandQueue>)command_queue]; resource_context_ = [FlutterDarwinContextMetalSkia createGrContext:(id<MTLDevice>)device commandQueue:(id<MTLCommandQueue>)command_queue]; valid_ = main_context_ && resource_context_; } EmbedderSurfaceMetal::~EmbedderSurfaceMetal() = default; bool EmbedderSurfaceMetal::IsValid() const { return valid_; } std::unique_ptr<Surface> EmbedderSurfaceMetal::CreateGPUSurface() API_AVAILABLE(ios(13.0)) { if (@available(iOS 13.0, *)) { } else { return nullptr; } if (!IsValid()) { return nullptr; } const bool render_to_surface = !external_view_embedder_; auto surface = std::make_unique<GPUSurfaceMetalSkia>(this, main_context_, MsaaSampleCount::kNone, render_to_surface); if (!surface->IsValid()) { return nullptr; } return surface; } sk_sp<GrDirectContext> EmbedderSurfaceMetal::CreateResourceContext() const { return resource_context_; } GPUCAMetalLayerHandle EmbedderSurfaceMetal::GetCAMetalLayer(const SkISize& frame_info) const { FML_CHECK(false) << "Only rendering to MTLTexture is supported."; return nullptr; } bool EmbedderSurfaceMetal::PresentDrawable(GrMTLHandle drawable) const { FML_CHECK(false) << "Only rendering to MTLTexture is supported."; return false; } GPUMTLTextureInfo EmbedderSurfaceMetal::GetMTLTexture(const SkISize& frame_info) const { return metal_dispatch_table_.get_texture(frame_info); } bool EmbedderSurfaceMetal::PresentTexture(GPUMTLTextureInfo texture) const { return metal_dispatch_table_.present(texture); } } // namespace flutter
engine/shell/platform/embedder/embedder_surface_metal.mm/0
{ "file_path": "engine/shell/platform/embedder/embedder_surface_metal.mm", "repo_id": "engine", "token_count": 1041 }
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. #define FML_USED_ON_EMBEDDER #include <string> #include <vector> #import <Metal/Metal.h> #include "embedder.h" #include "flutter/display_list/skia/dl_sk_canvas.h" #include "flutter/fml/synchronization/count_down_latch.h" #include "flutter/shell/platform/embedder/tests/embedder_assertions.h" #include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" #include "flutter/shell/platform/embedder/tests/embedder_test.h" #include "flutter/shell/platform/embedder/tests/embedder_test_context_metal.h" #include "flutter/shell/platform/embedder/tests/embedder_unittests_util.h" #include "flutter/testing/assertions_skia.h" #include "flutter/testing/testing.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" // CREATE_NATIVE_ENTRY is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) namespace flutter { namespace testing { using EmbedderTest = testing::EmbedderTest; TEST_F(EmbedderTest, CanRenderGradientWithMetal) { auto& context = GetEmbedderContext(EmbedderTestContextType::kMetalContext); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient"); builder.SetMetalRendererConfig(SkISize::Make(800, 600)); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); // TODO (https://github.com/flutter/flutter/issues/73590): re-enable once // we are able to figure out why this fails on the bots. // ASSERT_TRUE(ImageMatchesFixture("gradient_metal.png", rendered_scene)); } static sk_sp<SkSurface> GetSurfaceFromTexture(const sk_sp<GrDirectContext>& skia_context, SkISize texture_size, void* texture) { GrMtlTextureInfo info; info.fTexture.reset([(id<MTLTexture>)texture retain]); GrBackendTexture backend_texture(texture_size.width(), texture_size.height(), skgpu::Mipmapped::kNo, info); return SkSurfaces::WrapBackendTexture(skia_context.get(), backend_texture, kTopLeft_GrSurfaceOrigin, 1, kBGRA_8888_SkColorType, nullptr, nullptr); } TEST_F(EmbedderTest, ExternalTextureMetal) { EmbedderTestContextMetal& context = reinterpret_cast<EmbedderTestContextMetal&>( GetEmbedderContext(EmbedderTestContextType::kMetalContext)); const auto texture_size = SkISize::Make(800, 600); const int64_t texture_id = 1; TestMetalContext* metal_context = context.GetTestMetalContext(); TestMetalContext::TextureInfo texture_info = metal_context->CreateMetalTexture(texture_size); sk_sp<SkSurface> surface = GetSurfaceFromTexture(metal_context->GetSkiaContext(), texture_size, texture_info.texture); auto canvas = surface->getCanvas(); canvas->clear(SK_ColorRED); metal_context->GetSkiaContext()->flushAndSubmit(); std::vector<FlutterMetalTextureHandle> textures{texture_info.texture}; context.SetExternalTextureCallback( [&](int64_t id, size_t w, size_t h, FlutterMetalExternalTexture* output) { EXPECT_TRUE(w == texture_size.width()); EXPECT_TRUE(h == texture_size.height()); EXPECT_TRUE(texture_id == id); output->num_textures = 1; output->height = h; output->width = w; output->pixel_format = FlutterMetalExternalTexturePixelFormat::kRGBA; output->textures = textures.data(); return true; }); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_texture"); builder.SetMetalRendererConfig(texture_size); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ASSERT_EQ(FlutterEngineRegisterExternalTexture(engine.get(), texture_id), kSuccess); auto rendered_scene = context.GetNextSceneImage(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = texture_size.width(); event.height = texture_size.height(); event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture("external_texture_metal.png", rendered_scene)); } TEST_F(EmbedderTest, MetalCompositorMustBeAbleToRenderPlatformViews) { auto& context = GetEmbedderContext(EmbedderTestContextType::kMetalContext); EmbedderConfigBuilder builder(context); builder.SetMetalRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views"); builder.SetRenderTargetType(EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture); fml::CountDownLatch latch(3); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeMetal; backing_store.did_update = true; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeMetal; backing_store.did_update = true; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(2, 3, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } TEST_F(EmbedderTest, CanRenderSceneWithoutCustomCompositorMetal) { auto& context = GetEmbedderContext(EmbedderTestContextType::kMetalContext); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); builder.SetMetalRendererConfig(SkISize::Make(800, 600)); auto rendered_scene = context.GetNextSceneImage(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(ImageMatchesFixture("scene_without_custom_compositor.png", rendered_scene)); } TEST_F(EmbedderTest, TextureDestructionCallbackCalledWithoutCustomCompositorMetal) { EmbedderTestContextMetal& context = reinterpret_cast<EmbedderTestContextMetal&>( GetEmbedderContext(EmbedderTestContextType::kMetalContext)); EmbedderConfigBuilder builder(context); builder.SetMetalRendererConfig(SkISize::Make(800, 600)); builder.SetDartEntrypoint("texture_destruction_callback_called_without_custom_compositor"); struct CollectContext { int present_count = 0; int collect_count = 0; fml::AutoResetWaitableEvent latch; }; auto collect_context = std::make_unique<CollectContext>(); context.SetNextDrawableCallback([&context, &collect_context](const FlutterFrameInfo* frame_info) { auto texture_info = context.GetTestMetalSurface()->GetTextureInfo(); FlutterMetalTexture texture; texture.struct_size = sizeof(FlutterMetalTexture); texture.texture_id = texture_info.texture_id; texture.texture = reinterpret_cast<FlutterMetalTextureHandle>(texture_info.texture); texture.user_data = collect_context.get(); texture.destruction_callback = [](void* user_data) { CollectContext* callback_collect_context = reinterpret_cast<CollectContext*>(user_data); ASSERT_TRUE(callback_collect_context->present_count > 0); callback_collect_context->collect_count++; callback_collect_context->latch.Signal(); }; return texture; }); context.SetPresentCallback([&context, &collect_context](int64_t texture_id) { collect_context->present_count++; return context.GetTestMetalContext()->Present(texture_id); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); collect_context->latch.Wait(); EXPECT_EQ(collect_context->collect_count, 1); } TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownSceneMetal) { auto& context = GetEmbedderContext(EmbedderTestContextType::kMetalContext); EmbedderConfigBuilder builder(context); builder.SetMetalRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); builder.SetRenderTargetType(EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture); fml::CountDownLatch latch(5); auto scene_image = context.GetNextSceneImage(); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 5u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeMetal; backing_store.did_update = true; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(20.0, 20.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeMetal; backing_store.did_update = true; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(30, 30, 80, 180), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } // Layer 3 { FlutterPlatformView platform_view = *layers[3]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 2; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(40.0, 40.0); ASSERT_EQ(*layers[3], layer); } // Layer 4 { FlutterBackingStore backing_store = *layers[4]->backing_store; backing_store.type = kFlutterBackingStoreTypeMetal; backing_store.did_update = true; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(50, 50, 100, 200), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[4], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrDirectContext* context) -> sk_sp<SkImage> { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; case 2: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorMAGENTA); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. Only the root surface is rotated. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("compositor.png", scene_image)); } TEST_F(EmbedderTest, CreateInvalidBackingstoreMetalTexture) { auto& context = GetEmbedderContext(EmbedderTestContextType::kMetalContext); EmbedderConfigBuilder builder(context); builder.SetMetalRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetRenderTargetType(EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture); builder.SetDartEntrypoint("invalid_backingstore"); class TestCollectOnce { public: // Collect() should only be called once void Collect() { ASSERT_FALSE(collected_); collected_ = true; } private: bool collected_ = false; }; fml::AutoResetWaitableEvent latch; builder.GetCompositor().create_backing_store_callback = [](const FlutterBackingStoreConfig* config, // FlutterBackingStore* backing_store_out, // void* user_data // ) { backing_store_out->type = kFlutterBackingStoreTypeMetal; // Deliberately set this to be invalid backing_store_out->user_data = nullptr; backing_store_out->metal.texture.texture = 0; backing_store_out->metal.struct_size = sizeof(FlutterMetalBackingStore); backing_store_out->metal.texture.user_data = new TestCollectOnce(); backing_store_out->metal.texture.destruction_callback = [](void* user_data) { reinterpret_cast<TestCollectOnce*>(user_data)->Collect(); }; return true; }; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&latch](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } TEST_F(EmbedderTest, ExternalTextureMetalRefreshedTooOften) { EmbedderTestContextMetal& context = reinterpret_cast<EmbedderTestContextMetal&>( GetEmbedderContext(EmbedderTestContextType::kMetalContext)); TestMetalContext* metal_context = context.GetTestMetalContext(); auto metal_texture = metal_context->CreateMetalTexture(SkISize::Make(100, 100)); std::vector<FlutterMetalTextureHandle> textures{metal_texture.texture}; bool resolve_called = false; EmbedderExternalTextureMetal::ExternalTextureCallback callback([&](int64_t id, size_t, size_t) { resolve_called = true; auto res = std::make_unique<FlutterMetalExternalTexture>(); res->struct_size = sizeof(FlutterMetalExternalTexture); res->width = res->height = 100; res->pixel_format = FlutterMetalExternalTexturePixelFormat::kRGBA; res->textures = textures.data(); res->num_textures = 1; return res; }); EmbedderExternalTextureMetal texture(1, callback); auto surface = TestMetalSurface::Create(*metal_context, SkISize::Make(100, 100)); auto skia_surface = surface->GetSurface(); DlSkCanvasAdapter canvas(skia_surface->getCanvas()); Texture* texture_ = &texture; DlImageSampling sampling = DlImageSampling::kLinear; Texture::PaintContext ctx{ .canvas = &canvas, .gr_context = surface->GetGrContext().get(), }; texture_->Paint(ctx, SkRect::MakeXYWH(0, 0, 100, 100), false, sampling); EXPECT_TRUE(resolve_called); resolve_called = false; texture_->Paint(ctx, SkRect::MakeXYWH(0, 0, 100, 100), false, sampling); EXPECT_FALSE(resolve_called); texture_->MarkNewFrameAvailable(); texture_->Paint(ctx, SkRect::MakeXYWH(0, 0, 100, 100), false, sampling); EXPECT_TRUE(resolve_called); } } // namespace testing } // namespace flutter // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/shell/platform/embedder/tests/embedder_metal_unittests.mm/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_metal_unittests.mm", "repo_id": "engine", "token_count": 9068 }
334
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_H_ #include <future> #include <map> #include <memory> #include <mutex> #include <string> #include <vector> #include "flutter/fml/closure.h" #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h" #include "flutter/testing/elf_loader.h" #include "flutter/testing/test_dart_native_resolver.h" #include "third_party/skia/include/core/SkImage.h" namespace flutter { namespace testing { using SemanticsUpdateCallback2 = std::function<void(const FlutterSemanticsUpdate2*)>; using SemanticsUpdateCallback = std::function<void(const FlutterSemanticsUpdate*)>; using SemanticsNodeCallback = std::function<void(const FlutterSemanticsNode*)>; using SemanticsActionCallback = std::function<void(const FlutterSemanticsCustomAction*)>; using LogMessageCallback = std::function<void(const char* tag, const char* message)>; using ChannelUpdateCallback = std::function<void(const FlutterChannelUpdate*)>; struct AOTDataDeleter { void operator()(FlutterEngineAOTData aot_data) { if (aot_data) { FlutterEngineCollectAOTData(aot_data); } } }; using UniqueAOTData = std::unique_ptr<_FlutterEngineAOTData, AOTDataDeleter>; enum class EmbedderTestContextType { kSoftwareContext, kOpenGLContext, kMetalContext, kVulkanContext, }; class EmbedderTestContext { public: explicit EmbedderTestContext(std::string assets_path = ""); virtual ~EmbedderTestContext(); const std::string& GetAssetsPath() const; const fml::Mapping* GetVMSnapshotData() const; const fml::Mapping* GetVMSnapshotInstructions() const; const fml::Mapping* GetIsolateSnapshotData() const; const fml::Mapping* GetIsolateSnapshotInstructions() const; FlutterEngineAOTData GetAOTData() const; void SetRootSurfaceTransformation(SkMatrix matrix); void AddIsolateCreateCallback(const fml::closure& closure); void SetSemanticsUpdateCallback2(SemanticsUpdateCallback2 update_semantics); void SetSemanticsUpdateCallback(SemanticsUpdateCallback update_semantics); void AddNativeCallback(const char* name, Dart_NativeFunction function); void SetSemanticsNodeCallback(SemanticsNodeCallback update_semantics_node); void SetSemanticsCustomActionCallback( SemanticsActionCallback semantics_custom_action); void SetPlatformMessageCallback( const std::function<void(const FlutterPlatformMessage*)>& callback); void SetLogMessageCallback(const LogMessageCallback& log_message_callback); void SetChannelUpdateCallback(const ChannelUpdateCallback& callback); std::future<sk_sp<SkImage>> GetNextSceneImage(); EmbedderTestCompositor& GetCompositor(); virtual size_t GetSurfacePresentCount() const = 0; virtual EmbedderTestContextType GetContextType() const = 0; // Sets up the callback for vsync. This callback will be invoked // for every vsync. This should be used in conjunction with SetupVsyncCallback // on the EmbedderConfigBuilder. Any callback setup here must call // `FlutterEngineOnVsync` from the platform task runner. void SetVsyncCallback(std::function<void(intptr_t)> callback); // Runs the vsync callback. void RunVsyncCallback(intptr_t baton); // TODO(gw280): encapsulate these properly for subclasses to use protected: // This allows the builder to access the hooks. friend class EmbedderConfigBuilder; using NextSceneCallback = std::function<void(sk_sp<SkImage> image)>; #ifdef SHELL_ENABLE_VULKAN // The TestVulkanContext destructor must be called _after_ the compositor is // freed. fml::RefPtr<TestVulkanContext> vulkan_context_ = nullptr; #endif std::string assets_path_; ELFAOTSymbols aot_symbols_; std::unique_ptr<fml::Mapping> vm_snapshot_data_; std::unique_ptr<fml::Mapping> vm_snapshot_instructions_; std::unique_ptr<fml::Mapping> isolate_snapshot_data_; std::unique_ptr<fml::Mapping> isolate_snapshot_instructions_; UniqueAOTData aot_data_; std::vector<fml::closure> isolate_create_callbacks_; std::shared_ptr<TestDartNativeResolver> native_resolver_; SemanticsUpdateCallback2 update_semantics_callback2_; SemanticsUpdateCallback update_semantics_callback_; SemanticsNodeCallback update_semantics_node_callback_; SemanticsActionCallback update_semantics_custom_action_callback_; ChannelUpdateCallback channel_update_callback_; std::function<void(const FlutterPlatformMessage*)> platform_message_callback_; LogMessageCallback log_message_callback_; std::unique_ptr<EmbedderTestCompositor> compositor_; NextSceneCallback next_scene_callback_; SkMatrix root_surface_transformation_; std::function<void(intptr_t)> vsync_callback_ = nullptr; static VoidCallback GetIsolateCreateCallbackHook(); FlutterUpdateSemanticsCallback2 GetUpdateSemanticsCallback2Hook(); FlutterUpdateSemanticsCallback GetUpdateSemanticsCallbackHook(); FlutterUpdateSemanticsNodeCallback GetUpdateSemanticsNodeCallbackHook(); FlutterUpdateSemanticsCustomActionCallback GetUpdateSemanticsCustomActionCallbackHook(); static FlutterLogMessageCallback GetLogMessageCallbackHook(); static FlutterComputePlatformResolvedLocaleCallback GetComputePlatformResolvedLocaleCallbackHook(); FlutterChannelUpdateCallback GetChannelUpdateCallbackHook(); void SetupAOTMappingsIfNecessary(); void SetupAOTDataIfNecessary(); virtual void SetupCompositor() = 0; void FireIsolateCreateCallbacks(); void SetNativeResolver(); FlutterTransformation GetRootSurfaceTransformation(); void PlatformMessageCallback(const FlutterPlatformMessage* message); void FireRootSurfacePresentCallbackIfPresent( const std::function<sk_sp<SkImage>(void)>& image_callback); void SetNextSceneCallback(const NextSceneCallback& next_scene_callback); virtual void SetupSurface(SkISize surface_size) = 0; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContext); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_H_
engine/shell/platform/embedder/tests/embedder_test_context.h/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_context.h", "repo_id": "engine", "token_count": 1980 }
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. assert(is_fuchsia) import("//flutter/common/config.gni") import("//flutter/testing/testing.gni") import("//flutter/tools/fuchsia/dart.gni") import("//flutter/tools/fuchsia/fuchsia_host_bundle.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") product_suffix = "" if (flutter_runtime_mode == "release") { product_suffix = "product_" } fuchsia_host_bundle("flutter_binaries") { name = "flutter_binaries" _flutter_tester_label = "//flutter/shell/testing:testing($host_toolchain)" deps = [ _flutter_tester_label ] _flutter_tester_bin_path = rebase_path(get_label_info(_flutter_tester_label, "root_out_dir") + "/flutter_tester") sources = [ _flutter_tester_bin_path ] } fuchsia_host_bundle("dart_binaries") { name = "dart_binaries" _gen_snapshot_to_use = gen_snapshot + "($host_toolchain)" if (flutter_runtime_mode == "release") { _gen_snapshot_to_use = gen_snapshot_product + "($host_toolchain)" } _kernel_compiler_label = "dart:kernel_compiler($host_toolchain)" _frontend_server_label = "//flutter/flutter_frontend_server:frontend_server($host_toolchain)" _list_libraries_label = "dart:list_libraries($host_toolchain)" deps = [ _frontend_server_label, _gen_snapshot_to_use, _kernel_compiler_label, _list_libraries_label, ] _gen_snapshot_bin_path = rebase_path(get_label_info(_gen_snapshot_to_use, "root_out_dir") + "/" + get_label_info(_gen_snapshot_to_use, "name")) _kernel_compiler_path = rebase_path(get_label_info(_kernel_compiler_label, "root_gen_dir") + "/kernel_compiler.dart.snapshot") _frontend_server_path = rebase_path(get_label_info(_frontend_server_label, "root_gen_dir") + "/frontend_server.dart.snapshot") _list_libraries_path = rebase_path(get_label_info(_list_libraries_label, "root_gen_dir") + "/list_libraries.dart.snapshot") sources = [ _frontend_server_path, _gen_snapshot_bin_path, _kernel_compiler_path, _list_libraries_path, ] } group("fuchsia") { deps = [ ":dart_binaries", ":flutter_binaries", "dart_runner:dart_aot_${product_suffix}runner", "dart_runner:dart_jit_${product_suffix}runner", "flutter:flutter_aot_${product_suffix}runner", "flutter:flutter_jit_${product_suffix}runner", ] } if (enable_unittests) { group("tests") { testonly = true deps = [ "dart-pkg/zircon:tests", "dart_runner:tests", "flutter:tests", ] } }
engine/shell/platform/fuchsia/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/BUILD.gn", "repo_id": "engine", "token_count": 1176 }
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. part of zircon; @pragma('vm:entry-point') class ZDChannel { static ZDChannel? create([int options = 0]) { final Pointer<zircon_dart_handle_pair_t>? channelPtr = zirconFFIBindings?.zircon_dart_channel_create(options); if (channelPtr == null || channelPtr.address == 0) { throw Exception('Unable to create a channel'); } return ZDChannel._(ZDHandlePair._(channelPtr)); } static int _write(ZDHandle channel, ByteData data, List<ZDHandle> handles) { final Pointer<zircon_dart_handle_list_t> handleList = zirconFFIBindings!.zircon_dart_handle_list_create(); handles.forEach((ZDHandle handle) { zirconFFIBindings! .zircon_dart_handle_list_append(handleList, handle._ptr); }); final Uint8List dataAsBytes = data.buffer.asUint8List(); final Pointer<zircon_dart_byte_array_t> byteArray = zirconFFIBindings!.zircon_dart_byte_array_create(dataAsBytes.length); for (int i = 0; i < dataAsBytes.length; i++) { zirconFFIBindings!.zircon_dart_byte_array_set_value( byteArray, i, dataAsBytes.elementAt(i)); } int ret = zirconFFIBindings! .zircon_dart_channel_write(channel._ptr, byteArray, handleList); zirconFFIBindings!.zircon_dart_byte_array_free(byteArray); zirconFFIBindings!.zircon_dart_handle_list_free(handleList); return ret; } int writeLeft(ByteData data, List<ZDHandle> handles) { return _write(handlePair.left, data, handles); } int writeRight(ByteData data, List<ZDHandle> handles) { return _write(handlePair.right, data, handles); } @pragma('vm:entry-point') ZDChannel._(this.handlePair); final ZDHandlePair handlePair; @override String toString() => 'Channel(handlePair=$handlePair)'; }
engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_channel.dart/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_channel.dart", "repo_id": "engine", "token_count": 761 }
337
# Dart Runner Tests Contains tests for the Dart Runner and their corresponding utility code
engine/shell/platform/fuchsia/dart_runner/tests/README.md/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/tests/README.md", "repo_id": "engine", "token_count": 19 }
338
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//build/compiled_action.gni") import("//flutter/common/config.gni") import("//flutter/tools/fuchsia/dart.gni") import("//flutter/tools/fuchsia/dart_kernel.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("$dart_src/utils/compile_platform.gni") dart_kernel("vmservice_product_aot_kernel") { kernel_platform_files = "../kernel:kernel_platform_files" main_dart = "empty.dart" product = true aot = true } dart_kernel("vmservice_aot_kernel") { kernel_platform_files = "../kernel:kernel_platform_files" main_dart = "empty.dart" product = false aot = true } template("aot_snapshot") { compiled_action(target_name) { kernel_name = target_name if (defined(invoker.kernel_name)) { kernel_name = invoker.kernel_name } product = defined(invoker.product) && invoker.product product_suffix = "" if (product) { product_suffix = "_product" } shim_target = ":vmservice${product_suffix}_aot_kernel($host_toolchain)" shim_kernel = get_label_info(shim_target, "target_gen_dir") + "/vmservice${product_suffix}_aot_kernel.dill" deps = [ shim_target ] snapshot_path = "$target_gen_dir/${kernel_name}_snapshot.so" inputs = [ shim_kernel ] outputs = [ snapshot_path ] if (product) { tool = gen_snapshot_product } else { tool = gen_snapshot } args = [ "--deterministic", "--snapshot_kind=app-aot-elf", "--elf=" + rebase_path(snapshot_path), ] # No asserts in debug or release product. # No asserts in release with flutter_profile=true (non-product) # Yes asserts in non-product debug. if (!product && (flutter_runtime_mode == "debug" || is_debug)) { args += [ "--enable_asserts" ] } args += [ rebase_path(shim_kernel) ] } } aot_snapshot("vmservice_snapshot") { kernel_name = "vmservice" product = false }
engine/shell/platform/fuchsia/dart_runner/vmservice/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/vmservice/BUILD.gn", "repo_id": "engine", "token_count": 834 }
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. #include "component_v2.h" #include <gtest/gtest.h> #include <optional> namespace flutter_runner { namespace { TEST(ComponentV2, ParseProgramMetadataDefaultAssets) { // The assets_path defaults to the "data" value if unspecified. std::vector<fuchsia::data::DictionaryEntry> entries; fuchsia::data::DictionaryEntry data_entry; data_entry.key = "data"; data_entry.value = std::make_unique<fuchsia::data::DictionaryValue>( fuchsia::data::DictionaryValue::WithStr("foobar")); entries.push_back(std::move(data_entry)); fuchsia::data::Dictionary program_metadata; program_metadata.set_entries(std::move(entries)); ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); EXPECT_EQ(result.data_path, "pkg/foobar"); EXPECT_EQ(result.assets_path, "pkg/foobar"); EXPECT_EQ(result.old_gen_heap_size, std::nullopt); } TEST(ComponentV2, ParseProgramMetadataIgnoreInvalidKeys) { // Invalid keys are ignored. std::vector<fuchsia::data::DictionaryEntry> entries; fuchsia::data::DictionaryEntry not_data_entry; not_data_entry.key = "not_data"; not_data_entry.value = std::make_unique<fuchsia::data::DictionaryValue>( fuchsia::data::DictionaryValue::WithStr("foo")); entries.push_back(std::move(not_data_entry)); fuchsia::data::DictionaryEntry data_entry; data_entry.key = "data"; data_entry.value = std::make_unique<fuchsia::data::DictionaryValue>( fuchsia::data::DictionaryValue::WithStr("bar")); entries.push_back(std::move(data_entry)); fuchsia::data::DictionaryEntry assets_entry; assets_entry.key = "assets"; assets_entry.value = std::make_unique<fuchsia::data::DictionaryValue>( fuchsia::data::DictionaryValue::WithStr("baz")); entries.push_back(std::move(assets_entry)); fuchsia::data::Dictionary program_metadata; program_metadata.set_entries(std::move(entries)); ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); EXPECT_EQ(result.data_path, "pkg/bar"); EXPECT_EQ(result.assets_path, "pkg/baz"); EXPECT_EQ(result.old_gen_heap_size, std::nullopt); } TEST(ComponentV2, ParseProgramMetadataOldGenHeapSize) { // The old_gen_heap_size can be specified. std::vector<fuchsia::data::DictionaryEntry> entries; fuchsia::data::DictionaryEntry args_entry; args_entry.key = "args"; args_entry.value = std::make_unique<fuchsia::data::DictionaryValue>( fuchsia::data::DictionaryValue::WithStrVec({"--old_gen_heap_size=100"})); entries.push_back(std::move(args_entry)); fuchsia::data::Dictionary program_metadata; program_metadata.set_entries(std::move(entries)); ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); EXPECT_EQ(result.data_path, ""); EXPECT_EQ(result.assets_path, ""); EXPECT_EQ(result.old_gen_heap_size, 100); } TEST(ComponentV2, ParseProgramMetadataOldGenHeapSizeInvalid) { // Invalid old_gen_heap_sizes should be ignored. std::vector<fuchsia::data::DictionaryEntry> entries; fuchsia::data::DictionaryEntry args_entry; args_entry.key = "args"; args_entry.value = std::make_unique<fuchsia::data::DictionaryValue>( fuchsia::data::DictionaryValue::WithStrVec( {"--old_gen_heap_size=asdf100"})); entries.push_back(std::move(args_entry)); fuchsia::data::Dictionary program_metadata; program_metadata.set_entries(std::move(entries)); ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); EXPECT_EQ(result.data_path, ""); EXPECT_EQ(result.assets_path, ""); EXPECT_EQ(result.old_gen_heap_size, std::nullopt); } TEST(ComponentV2, ParseProgramMetadataNoExposeDirs) { // Should always have a valid expose_dirs entry std::vector<fuchsia::data::DictionaryEntry> entries; fuchsia::data::Dictionary program_metadata; program_metadata.set_entries(std::move(entries)); ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); EXPECT_EQ(result.expose_dirs.empty(), true); } TEST(ComponentV2, ParseProgramMetadataWithSingleExposeDirs) { // Can parse a single exposed dir std::vector<fuchsia::data::DictionaryEntry> entries; fuchsia::data::DictionaryEntry args_entry; args_entry.key = "args"; args_entry.value = std::make_unique<fuchsia::data::DictionaryValue>( fuchsia::data::DictionaryValue::WithStrVec({"--expose_dirs=foo"})); entries.push_back(std::move(args_entry)); fuchsia::data::Dictionary program_metadata; program_metadata.set_entries(std::move(entries)); ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); ASSERT_EQ(result.expose_dirs.size(), 1u); EXPECT_EQ(result.expose_dirs[0], "foo"); } TEST(ComponentV2, ParseProgramMetadataWithMultipleExposeDirs) { // Can parse a multiple exposed dirs std::vector<fuchsia::data::DictionaryEntry> entries; fuchsia::data::DictionaryEntry args_entry; args_entry.key = "args"; args_entry.value = std::make_unique<fuchsia::data::DictionaryValue>( fuchsia::data::DictionaryValue::WithStrVec( {"--expose_dirs=foo,bar,baz"})); entries.push_back(std::move(args_entry)); fuchsia::data::Dictionary program_metadata; program_metadata.set_entries(std::move(entries)); ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); ASSERT_EQ(result.expose_dirs.size(), 3u); EXPECT_EQ(result.expose_dirs[0], "foo"); EXPECT_EQ(result.expose_dirs[1], "bar"); EXPECT_EQ(result.expose_dirs[2], "baz"); } TEST(ComponentV2, ParseProgramMetadataWithSingleExposeDirsAndOtherArgs) { // Can parse a single exposed dir when other args are present std::vector<fuchsia::data::DictionaryEntry> entries; fuchsia::data::DictionaryEntry args_entry; args_entry.key = "args"; args_entry.value = std::make_unique<fuchsia::data::DictionaryValue>( fuchsia::data::DictionaryValue::WithStrVec( {"--expose_dirs=foo", "--foo=bar"})); entries.push_back(std::move(args_entry)); fuchsia::data::Dictionary program_metadata; program_metadata.set_entries(std::move(entries)); ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); ASSERT_EQ(result.expose_dirs.size(), 1u); EXPECT_EQ(result.expose_dirs[0], "foo"); } } // anonymous namespace } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/component_v2_unittest.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/component_v2_unittest.cc", "repo_id": "engine", "token_count": 2289 }
340
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FUCHSIA_INTL_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FUCHSIA_INTL_H_ #include <fuchsia/intl/cpp/fidl.h> #include "flutter/fml/mapping.h" namespace flutter_runner { // Make a byte vector containing the JSON string used for a localization // PlatformMessage, using the locale list in the given Profile. // // This method does not return a `std::unique_ptr<flutter::PlatformMessage>` for // testing convenience; that would require an unreasonably large set of // dependencies for the unit tests. fml::MallocMapping MakeLocalizationPlatformMessageData( const fuchsia::intl::Profile& intl_profile); } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FUCHSIA_INTL_H_
engine/shell/platform/fuchsia/flutter/fuchsia_intl.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/fuchsia_intl.h", "repo_id": "engine", "token_count": 309 }
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. #include "flutter/shell/platform/fuchsia/flutter/rtree.h" #include "flutter/testing/testing.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPicture.h" #include "third_party/skia/include/core/SkPictureRecorder.h" namespace flutter { namespace testing { TEST(RTree, searchNonOverlappingDrawnRectsNoIntersection) { auto rtree_factory = RTreeFactory(); auto recorder = std::make_unique<SkPictureRecorder>(); auto recording_canvas = recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); auto rect_paint = SkPaint(); rect_paint.setColor(SkColors::kCyan); rect_paint.setStyle(SkPaint::Style::kFill_Style); // If no rect is intersected with the query rect, then the result list is // empty. recording_canvas->drawRect(SkRect::MakeLTRB(20, 20, 40, 40), rect_paint); recorder->finishRecordingAsPicture(); auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( SkRect::MakeLTRB(40, 40, 80, 80)); ASSERT_TRUE(hits.empty()); } TEST(RTree, searchNonOverlappingDrawnRectsSingleRectIntersection) { auto rtree_factory = RTreeFactory(); auto recorder = std::make_unique<SkPictureRecorder>(); auto recording_canvas = recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); auto rect_paint = SkPaint(); rect_paint.setColor(SkColors::kCyan); rect_paint.setStyle(SkPaint::Style::kFill_Style); // Given a single rect A that intersects with the query rect, // the result list contains this rect. recording_canvas->drawRect(SkRect::MakeLTRB(120, 120, 160, 160), rect_paint); recorder->finishRecordingAsPicture(); auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( SkRect::MakeLTRB(140, 140, 150, 150)); ASSERT_EQ(1UL, hits.size()); ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(120, 120, 160, 160)); } TEST(RTree, searchNonOverlappingDrawnRectsIgnoresNonDrawingRecords) { auto rtree_factory = RTreeFactory(); auto recorder = std::make_unique<SkPictureRecorder>(); auto recording_canvas = recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); auto rect_paint = SkPaint(); rect_paint.setColor(SkColors::kCyan); rect_paint.setStyle(SkPaint::Style::kFill_Style); // Creates two non drawing records. recording_canvas->translate(100, 100); // The result list should only contain the clipping rect. recording_canvas->clipRect(SkRect::MakeLTRB(40, 40, 50, 50), SkClipOp::kIntersect); recording_canvas->drawRect(SkRect::MakeLTRB(20, 20, 80, 80), rect_paint); recorder->finishRecordingAsPicture(); // The rtree has a translate, a clip and a rect record. ASSERT_EQ(3, rtree_factory.getInstance()->getCount()); auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( SkRect::MakeLTRB(0, 0, 1000, 1000)); ASSERT_EQ(1UL, hits.size()); ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(120, 120, 180, 180)); } TEST(RTree, searchNonOverlappingDrawnRectsMultipleRectIntersection) { auto rtree_factory = RTreeFactory(); auto recorder = std::make_unique<SkPictureRecorder>(); auto recording_canvas = recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); auto rect_paint = SkPaint(); rect_paint.setColor(SkColors::kCyan); rect_paint.setStyle(SkPaint::Style::kFill_Style); // Given the A, B that intersect with the query rect, // there should be A and B in the result list since // they don't intersect with each other. // // +-----+ +-----+ // | A | | B | // +-----+ +-----+ // A recording_canvas->drawRect(SkRect::MakeLTRB(100, 100, 200, 200), rect_paint); // B recording_canvas->drawRect(SkRect::MakeLTRB(300, 100, 400, 200), rect_paint); recorder->finishRecordingAsPicture(); auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( SkRect::MakeLTRB(0, 0, 1000, 1050)); ASSERT_EQ(2UL, hits.size()); ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(100, 100, 200, 200)); ASSERT_EQ(*std::next(hits.begin(), 1), SkRect::MakeLTRB(300, 100, 400, 200)); } TEST(RTree, searchNonOverlappingDrawnRectsJoinRectsWhenIntersectedCase1) { auto rtree_factory = RTreeFactory(); auto recorder = std::make_unique<SkPictureRecorder>(); auto recording_canvas = recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); auto rect_paint = SkPaint(); rect_paint.setColor(SkColors::kCyan); rect_paint.setStyle(SkPaint::Style::kFill_Style); // Given the A, and B rects, which intersect with the query rect, // the result list contains the three rectangles covering same area. // // +-----+ +-----+ // | A | | A | // | +-----+ +---------+ // | | | | B | // +---| B | +---+-----+ // | | | C | // +-----+ +-----+ // A recording_canvas->drawRect(SkRect::MakeLTRB(100, 100, 150, 150), rect_paint); // B recording_canvas->drawRect(SkRect::MakeLTRB(125, 125, 175, 175), rect_paint); recorder->finishRecordingAsPicture(); auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( SkRect::MakeXYWH(120, 120, 126, 126)); ASSERT_EQ(3UL, hits.size()); ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(100, 100, 150, 125)); ASSERT_EQ(*std::next(hits.begin(), 1), SkRect::MakeLTRB(100, 125, 175, 150)); ASSERT_EQ(*std::next(hits.begin(), 2), SkRect::MakeLTRB(125, 150, 175, 175)); } TEST(RTree, searchNonOverlappingDrawnRectsJoinRectsWhenIntersectedCase2) { auto rtree_factory = RTreeFactory(); auto recorder = std::make_unique<SkPictureRecorder>(); auto recording_canvas = recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); auto rect_paint = SkPaint(); rect_paint.setColor(SkColors::kCyan); rect_paint.setStyle(SkPaint::Style::kFill_Style); // Given the A, B, and C rects that intersect with the query rect, // there should be only C in the result list, // since A and B are contained in C. // // +---------------------+ // | C | // | +-----+ +-----+ | // | | A | | B | | // | +-----+ +-----+ | // +---------------------+ // +-----+ // | D | // +-----+ // A recording_canvas->drawRect(SkRect::MakeLTRB(100, 100, 200, 200), rect_paint); // B recording_canvas->drawRect(SkRect::MakeLTRB(300, 100, 400, 200), rect_paint); // C recording_canvas->drawRect(SkRect::MakeLTRB(50, 50, 500, 250), rect_paint); // D recording_canvas->drawRect(SkRect::MakeLTRB(280, 100, 280, 320), rect_paint); recorder->finishRecordingAsPicture(); auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( SkRect::MakeLTRB(30, 30, 550, 270)); ASSERT_EQ(1UL, hits.size()); ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(50, 50, 500, 250)); } TEST(RTree, searchNonOverlappingDrawnRectsJoinRectsWhenIntersectedCase3) { auto rtree_factory = RTreeFactory(); auto recorder = std::make_unique<SkPictureRecorder>(); auto recording_canvas = recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); auto rect_paint = SkPaint(); rect_paint.setColor(SkColors::kCyan); rect_paint.setStyle(SkPaint::Style::kFill_Style); // Given the A, B, C and D rects that intersect with the query rect, // the result list contains two rects - D and remainder of C // these four rects. // // +------------------------------+ // | D | // | +-----+ +-----+ +-----+ | // | | A | | B | | C | | // | +-----+ +-----+ | | | // +----------------------| |-+ // +-----+ // +-----+ // | E | // +-----+ // A recording_canvas->drawRect(SkRect::MakeLTRB(100, 100, 200, 200), rect_paint); // B recording_canvas->drawRect(SkRect::MakeLTRB(300, 100, 400, 200), rect_paint); // C recording_canvas->drawRect(SkRect::MakeLTRB(500, 100, 600, 300), rect_paint); // D recording_canvas->drawRect(SkRect::MakeLTRB(50, 50, 620, 250), rect_paint); // E recording_canvas->drawRect(SkRect::MakeLTRB(280, 100, 280, 320), rect_paint); recorder->finishRecordingAsPicture(); auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( SkRect::MakeLTRB(30, 30, 550, 270)); ASSERT_EQ(2UL, hits.size()); ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(50, 50, 620, 250)); ASSERT_EQ(*std::next(hits.begin(), 1), SkRect::MakeLTRB(500, 250, 600, 300)); } } // namespace testing } // namespace flutter
engine/shell/platform/fuchsia/flutter/rtree_unittests.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/rtree_unittests.cc", "repo_id": "engine", "token_count": 3457 }
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. #include "fakes/scenic/fake_flatland.h" #include <lib/async-testing/test_loop.h> #include <lib/async/dispatcher.h> #include <string> #include "flutter/fml/logging.h" #include "fuchsia/ui/composition/cpp/fidl.h" #include "gtest/gtest.h" namespace flutter_runner::testing { namespace { std::string GetCurrentTestName() { return ::testing::UnitTest::GetInstance()->current_test_info()->name(); } } // namespace class FakeFlatlandTest : public ::testing::Test { protected: FakeFlatlandTest() : flatland_subloop_(loop_.StartNewLoop()) {} ~FakeFlatlandTest() override = default; async::TestLoop& loop() { return loop_; } FakeFlatland& fake_flatland() { return fake_flatland_; } fuchsia::ui::composition::FlatlandPtr ConnectFlatland() { FML_CHECK(!fake_flatland_.is_flatland_connected()); auto flatland_handle = fake_flatland_.ConnectFlatland(flatland_subloop_->dispatcher()); return flatland_handle.Bind(); } private: // Primary loop and subloop for the FakeFlatland instance to process its // messages. The subloop allocates it's own zx_port_t, allowing us to use a // separate port for each end of the message channel, rather than sharing a // single one. Dual ports allow messages and responses to be intermingled, // which is how production code behaves; this improves test realism. async::TestLoop loop_; std::unique_ptr<async::LoopInterface> flatland_subloop_; FakeFlatland fake_flatland_; }; TEST_F(FakeFlatlandTest, Initialization) { EXPECT_EQ(fake_flatland().debug_name(), ""); // Pump the loop one time; the flatland should retain its initial state. loop().RunUntilIdle(); EXPECT_EQ(fake_flatland().debug_name(), ""); } TEST_F(FakeFlatlandTest, DebugLabel) { const std::string debug_label = GetCurrentTestName(); fuchsia::ui::composition::FlatlandPtr flatland = ConnectFlatland(); // Set the flatland's debug name. The `SetDebugName` hasn't been processed // yet, so the flatland's view of the debug name is still empty. flatland->SetDebugName(debug_label); EXPECT_EQ(fake_flatland().debug_name(), ""); // Pump the loop; the contents of the initial `SetDebugName` should be // processed. loop().RunUntilIdle(); EXPECT_EQ(fake_flatland().debug_name(), debug_label); } TEST_F(FakeFlatlandTest, Present) { fuchsia::ui::composition::FlatlandPtr flatland = ConnectFlatland(); // Fire an OnNextFrameBegin event and verify the test receives it. constexpr uint64_t kOnNextFrameAdditionalPresentCredits = 10u; uint64_t on_next_frame_additional_present_credits = 0u; fuchsia::ui::composition::OnNextFrameBeginValues on_next_frame_begin_values; on_next_frame_begin_values.set_additional_present_credits( kOnNextFrameAdditionalPresentCredits); flatland.events().OnNextFrameBegin = [&on_next_frame_additional_present_credits]( auto on_next_frame_begin_values) { static bool called_once = false; EXPECT_FALSE(called_once); on_next_frame_additional_present_credits = on_next_frame_begin_values.additional_present_credits(); called_once = true; }; fake_flatland().FireOnNextFrameBeginEvent( std::move(on_next_frame_begin_values)); EXPECT_EQ(on_next_frame_additional_present_credits, 0u); loop().RunUntilIdle(); EXPECT_EQ(on_next_frame_additional_present_credits, kOnNextFrameAdditionalPresentCredits); // Fire an OnFramePresented event and verify the test receives it. constexpr uint64_t kOnFramePresentedNumPresentsAllowed = 20u; uint64_t frame_presented_num_presents_allowed = 0u; flatland.events().OnFramePresented = [&frame_presented_num_presents_allowed](auto frame_presented_info) { static bool called_once = false; EXPECT_FALSE(called_once); frame_presented_num_presents_allowed = frame_presented_info.num_presents_allowed; called_once = true; }; fake_flatland().FireOnFramePresentedEvent( fuchsia::scenic::scheduling::FramePresentedInfo{ .actual_presentation_time = 0, .num_presents_allowed = kOnFramePresentedNumPresentsAllowed, }); EXPECT_EQ(frame_presented_num_presents_allowed, 0u); loop().RunUntilIdle(); EXPECT_EQ(frame_presented_num_presents_allowed, kOnFramePresentedNumPresentsAllowed); // Call Present and verify the fake handled it. constexpr int64_t kPresentRequestedTime = 42; int64_t present_requested_time = 0; fuchsia::ui::composition::PresentArgs present_args; present_args.set_requested_presentation_time(kPresentRequestedTime); fake_flatland().SetPresentHandler( [&present_requested_time](auto present_args) { static bool called_once = false; EXPECT_FALSE(called_once); present_requested_time = present_args.requested_presentation_time(); called_once = true; }); flatland->Present(std::move(present_args)); EXPECT_EQ(present_requested_time, 0); loop().RunUntilIdle(); EXPECT_EQ(present_requested_time, kPresentRequestedTime); } } // namespace flutter_runner::testing
engine/shell/platform/fuchsia/flutter/tests/fake_flatland_unittests.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/fake_flatland_unittests.cc", "repo_id": "engine", "token_count": 1869 }
343
# Flutter runner integration tests To run the Flutter runner integration tests locally, first start a Fuchsia package server: ```shell cd "$FUCHSIA_DIR" fx serve ``` Then run the integration test: ```shell $ENGINE_DIR/flutter/tools/fuchsia/devshell/run_integration_test.sh <integration_test_folder_name> --no-lto ``` For example, to run the `embedder` integration test: ```shell $ENGINE_DIR/flutter/tools/fuchsia/devshell/run_integration_test.sh embedder --no-lto ``` Command-line options: * Pass `--unoptimized` to disable C++ compiler optimizations. * Add `--fuchsia-cpu x64` or `--fuchsia-cpu arm64` to target a particular architecture. The default is x64. * Add `--runtime-mode debug` or `--runtime-mode profile` to switch between JIT and AOT builds. These correspond to a vanilla Fuchsia build and a `--release` Fuchsia build respectively. The default is debug/JIT builds. * For Googlers, add the `--goma` argument when using goma, and add the `--xcode-symlinks` argument when using goma on macOS. * Remove `--no-lto` if you care about performance or binary size; unfortunately it results in a *much* slower build. ## Iterating on tests By default, `run_integration_test.sh` will build Fuchsia and start up a Fuchsia emulator to ensure that the test runs on the correct environment. However, this is slow for iterating on tests. Once you've run `run_integration_tests.sh` once, you don't need to build Fuchsia or start the emulator anymore, and can pass `--skip-fuchsia-build` and `--skip-fuchsia-emu` to skip those steps. ```shell $ENGINE_DIR/flutter/tools/fuchsia/devshell/run_integration_test.sh embedder --no-lto --skip-fuchsia-build --skip-fuchsia-emu ```
engine/shell/platform/fuchsia/flutter/tests/integration/README.md/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/README.md", "repo_id": "engine", "token_count": 546 }
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. import("//flutter/tools/fuchsia/dart/dart_library.gni") import("//flutter/tools/fuchsia/flutter/flutter_component.gni") import("//flutter/tools/fuchsia/gn-sdk/src/component.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") dart_library("lib") { package_name = "mouse-input-view" sources = [ "mouse-input-view.dart" ] deps = [ "//flutter/shell/platform/fuchsia/dart:args" ] } flutter_component("component") { testonly = true component_name = "mouse-input-view" manifest = rebase_path("meta/mouse-input-view.cml") main_package = "mouse-input-view" main_dart = "mouse-input-view.dart" deps = [ ":lib" ] } fuchsia_package("package") { testonly = true package_name = "mouse-input-view" deps = [ ":component" ] }
engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/BUILD.gn", "repo_id": "engine", "token_count": 369 }
345
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_POINTER_EVENT_UTILITY_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_POINTER_EVENT_UTILITY_H_ #include <fuchsia/ui/pointer/cpp/fidl.h> #include <zircon/types.h> #include <array> #include <optional> #include <vector> namespace flutter_runner::testing { // A helper class for crafting a fuchsia.ui.pointer.TouchEvent table. class TouchEventBuilder { public: static TouchEventBuilder New(); TouchEventBuilder& AddTime(zx_time_t time); TouchEventBuilder& AddSample(fuchsia::ui::pointer::TouchInteractionId id, fuchsia::ui::pointer::EventPhase phase, std::array<float, 2> position); TouchEventBuilder& AddViewParameters( std::array<std::array<float, 2>, 2> view, std::array<std::array<float, 2>, 2> viewport, std::array<float, 9> transform); TouchEventBuilder& AddResult( fuchsia::ui::pointer::TouchInteractionResult result); fuchsia::ui::pointer::TouchEvent Build(); std::vector<fuchsia::ui::pointer::TouchEvent> BuildAsVector(); private: std::optional<zx_time_t> time_; std::optional<fuchsia::ui::pointer::ViewParameters> params_; std::optional<fuchsia::ui::pointer::TouchPointerSample> sample_; std::optional<fuchsia::ui::pointer::TouchInteractionResult> result_; }; // A helper class for crafting a fuchsia.ui.pointer.MouseEventBuilder table. class MouseEventBuilder { public: static MouseEventBuilder New(); MouseEventBuilder& AddTime(zx_time_t time); MouseEventBuilder& AddSample(uint32_t id, std::array<float, 2> position, std::vector<uint8_t> pressed_buttons, std::array<int64_t, 2> scroll, std::array<int64_t, 2> scroll_in_physical_pixel, bool is_precision_scroll); MouseEventBuilder& AddViewParameters( std::array<std::array<float, 2>, 2> view, std::array<std::array<float, 2>, 2> viewport, std::array<float, 9> transform); MouseEventBuilder& AddMouseDeviceInfo(uint32_t id, std::vector<uint8_t> buttons); fuchsia::ui::pointer::MouseEvent Build(); std::vector<fuchsia::ui::pointer::MouseEvent> BuildAsVector(); private: std::optional<zx_time_t> time_; std::optional<fuchsia::ui::pointer::MousePointerSample> sample_; std::optional<fuchsia::ui::pointer::ViewParameters> params_; std::optional<fuchsia::ui::pointer::MouseDeviceInfo> device_info_; }; } // namespace flutter_runner::testing #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_POINTER_EVENT_UTILITY_H_
engine/shell/platform/fuchsia/flutter/tests/pointer_event_utility.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/pointer_event_utility.h", "repo_id": "engine", "token_count": 1167 }
346
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_POOL_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_POOL_H_ #include <fuchsia/ui/composition/cpp/fidl.h> #include <unordered_map> #include <vector> #include "flutter/fml/macros.h" #include "vulkan_surface.h" namespace flutter_runner { class VulkanSurfacePool final { public: // Only keep 12 surfaces at a time. This value was based on how many // surfaces got cached in the old, exact-match-only caching logic. 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; VulkanSurfacePool(vulkan::VulkanProvider& vulkan_provider, sk_sp<GrDirectContext> context); ~VulkanSurfacePool(); std::unique_ptr<VulkanSurface> CreateSurface(const SkISize& size); std::unique_ptr<VulkanSurface> AcquireSurface(const SkISize& size); void SubmitSurface(std::unique_ptr<SurfaceProducerSurface> surface); void AgeAndCollectOldBuffers(); // Shrink all oversized |VulkanSurfaces| in |available_surfaces_| to as // small as they can be. void ShrinkToFit(); private: vulkan::VulkanProvider& vulkan_provider_; sk_sp<GrDirectContext> context_; fuchsia::sysmem::AllocatorSyncPtr sysmem_allocator_; fuchsia::ui::composition::AllocatorPtr flatland_allocator_; std::vector<std::unique_ptr<VulkanSurface>> available_surfaces_; std::unordered_map<uintptr_t, std::unique_ptr<VulkanSurface>> pending_surfaces_; size_t trace_surfaces_created_ = 0; size_t trace_surfaces_reused_ = 0; std::unique_ptr<VulkanSurface> GetCachedOrCreateSurface(const SkISize& size); void RecycleSurface(std::unique_ptr<VulkanSurface> surface); void RecyclePendingSurface(uintptr_t surface_key); void TraceStats(); FML_DISALLOW_COPY_AND_ASSIGN(VulkanSurfacePool); }; } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_POOL_H_
engine/shell/platform/fuchsia/flutter/vulkan_surface_pool.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/vulkan_surface_pool.h", "repo_id": "engine", "token_count": 784 }
347
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_LOGGING_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_LOGGING_H_ namespace dart_utils { // Use to mark logs published via the syslog API. #define LOG_TAG "dart-utils" } // namespace dart_utils #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_LOGGING_H_
engine/shell/platform/fuchsia/runtime/dart/utils/logging.h/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/logging.h", "repo_id": "engine", "token_count": 195 }
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 <memory> #include <string> #include "flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_engine.h" #include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h" #include "gtest/gtest.h" namespace flutter { namespace { // Stub implementation to validate calls to the API. class TestGlfwApi : public testing::StubFlutterGlfwApi { public: // |flutter::testing::StubFlutterGlfwApi| FlutterDesktopEngineRef RunEngine( const FlutterDesktopEngineProperties& properties) override { run_called_ = true; return reinterpret_cast<FlutterDesktopEngineRef>(1); } // |flutter::testing::StubFlutterGlfwApi| void RunEngineEventLoopWithTimeout(uint32_t millisecond_timeout) override { last_run_loop_timeout_ = millisecond_timeout; } // |flutter::testing::StubFlutterGlfwApi| bool ShutDownEngine() override { shut_down_called_ = true; return true; } bool run_called() { return run_called_; } bool shut_down_called() { return shut_down_called_; } uint32_t last_run_loop_timeout() { return last_run_loop_timeout_; } private: bool run_called_ = false; bool shut_down_called_ = false; uint32_t last_run_loop_timeout_ = 0; }; } // namespace TEST(FlutterEngineTest, CreateDestroy) { const std::string icu_data_path = "fake/path/to/icu"; const std::string assets_path = "fake/path/to/assets"; testing::ScopedStubFlutterGlfwApi scoped_api_stub( std::make_unique<TestGlfwApi>()); auto test_api = static_cast<TestGlfwApi*>(scoped_api_stub.stub()); { FlutterEngine engine; engine.Start(icu_data_path, assets_path, {}); EXPECT_EQ(test_api->run_called(), true); EXPECT_EQ(test_api->shut_down_called(), false); } // Destroying should implicitly shut down if it hasn't been done manually. EXPECT_EQ(test_api->shut_down_called(), true); } TEST(FlutterEngineTest, ExplicitShutDown) { const std::string icu_data_path = "fake/path/to/icu"; const std::string assets_path = "fake/path/to/assets"; testing::ScopedStubFlutterGlfwApi scoped_api_stub( std::make_unique<TestGlfwApi>()); auto test_api = static_cast<TestGlfwApi*>(scoped_api_stub.stub()); FlutterEngine engine; engine.Start(icu_data_path, assets_path, {}); EXPECT_EQ(test_api->run_called(), true); EXPECT_EQ(test_api->shut_down_called(), false); engine.ShutDown(); EXPECT_EQ(test_api->shut_down_called(), true); } TEST(FlutterEngineTest, RunloopTimeoutTranslation) { const std::string icu_data_path = "fake/path/to/icu"; const std::string assets_path = "fake/path/to/assets"; testing::ScopedStubFlutterGlfwApi scoped_api_stub( std::make_unique<TestGlfwApi>()); auto test_api = static_cast<TestGlfwApi*>(scoped_api_stub.stub()); FlutterEngine engine; engine.Start(icu_data_path, assets_path, {}); engine.RunEventLoopWithTimeout(std::chrono::milliseconds(100)); EXPECT_EQ(test_api->last_run_loop_timeout(), 100U); engine.RunEventLoopWithTimeout(std::chrono::milliseconds::max() - std::chrono::milliseconds(1)); EXPECT_EQ(test_api->last_run_loop_timeout(), UINT32_MAX); engine.RunEventLoopWithTimeout(std::chrono::milliseconds::max()); EXPECT_EQ(test_api->last_run_loop_timeout(), 0U); } } // namespace flutter
engine/shell/platform/glfw/client_wrapper/flutter_engine_unittests.cc/0
{ "file_path": "engine/shell/platform/glfw/client_wrapper/flutter_engine_unittests.cc", "repo_id": "engine", "token_count": 1299 }
349
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_GLFW_GLFW_EVENT_LOOP_H_ #define FLUTTER_SHELL_PLATFORM_GLFW_GLFW_EVENT_LOOP_H_ #include "flutter/shell/platform/glfw/event_loop.h" namespace flutter { // An event loop implementation that supports Flutter Engine tasks scheduling in // the GLFW event loop. class GLFWEventLoop : public EventLoop { public: GLFWEventLoop(std::thread::id main_thread_id, const TaskExpiredCallback& on_task_expired); virtual ~GLFWEventLoop(); // Prevent copying. GLFWEventLoop(const GLFWEventLoop&) = delete; GLFWEventLoop& operator=(const GLFWEventLoop&) = delete; private: // |EventLoop| void WaitUntil(const TaskTimePoint& time) override; // |EventLoop| void Wake() override; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_GLFW_GLFW_EVENT_LOOP_H_
engine/shell/platform/glfw/glfw_event_loop.h/0
{ "file_path": "engine/shell/platform/glfw/glfw_event_loop.h", "repo_id": "engine", "token_count": 351 }
350
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_accessible_node.h" #include "flutter/shell/platform/linux/fl_engine_private.h" // Maps Flutter semantics flags to ATK flags. static struct { AtkStateType state; FlutterSemanticsFlag flag; gboolean invert; } flag_mapping[] = { {ATK_STATE_SHOWING, kFlutterSemanticsFlagIsObscured, TRUE}, {ATK_STATE_VISIBLE, kFlutterSemanticsFlagIsHidden, TRUE}, {ATK_STATE_CHECKABLE, kFlutterSemanticsFlagHasCheckedState, FALSE}, {ATK_STATE_FOCUSABLE, kFlutterSemanticsFlagIsFocusable, FALSE}, {ATK_STATE_FOCUSED, kFlutterSemanticsFlagIsFocused, FALSE}, {ATK_STATE_CHECKED, static_cast<FlutterSemanticsFlag>(kFlutterSemanticsFlagIsChecked | kFlutterSemanticsFlagIsToggled), FALSE}, {ATK_STATE_SELECTED, kFlutterSemanticsFlagIsSelected, FALSE}, {ATK_STATE_ENABLED, kFlutterSemanticsFlagIsEnabled, FALSE}, {ATK_STATE_SENSITIVE, kFlutterSemanticsFlagIsEnabled, FALSE}, {ATK_STATE_READ_ONLY, kFlutterSemanticsFlagIsReadOnly, FALSE}, {ATK_STATE_EDITABLE, kFlutterSemanticsFlagIsTextField, FALSE}, {ATK_STATE_INVALID, static_cast<FlutterSemanticsFlag>(0), FALSE}, }; // Maps Flutter semantics actions to ATK actions. typedef struct { FlutterSemanticsAction action; const gchar* name; } ActionData; static ActionData action_mapping[] = { {kFlutterSemanticsActionTap, "Tap"}, {kFlutterSemanticsActionLongPress, "LongPress"}, {kFlutterSemanticsActionScrollLeft, "ScrollLeft"}, {kFlutterSemanticsActionScrollRight, "ScrollRight"}, {kFlutterSemanticsActionScrollUp, "ScrollUp"}, {kFlutterSemanticsActionScrollDown, "ScrollDown"}, {kFlutterSemanticsActionIncrease, "Increase"}, {kFlutterSemanticsActionDecrease, "Decrease"}, {kFlutterSemanticsActionShowOnScreen, "ShowOnScreen"}, {kFlutterSemanticsActionMoveCursorForwardByCharacter, "MoveCursorForwardByCharacter"}, {kFlutterSemanticsActionMoveCursorBackwardByCharacter, "MoveCursorBackwardByCharacter"}, {kFlutterSemanticsActionCopy, "Copy"}, {kFlutterSemanticsActionCut, "Cut"}, {kFlutterSemanticsActionPaste, "Paste"}, {kFlutterSemanticsActionDidGainAccessibilityFocus, "DidGainAccessibilityFocus"}, {kFlutterSemanticsActionDidLoseAccessibilityFocus, "DidLoseAccessibilityFocus"}, {kFlutterSemanticsActionCustomAction, "CustomAction"}, {kFlutterSemanticsActionDismiss, "Dismiss"}, {kFlutterSemanticsActionMoveCursorForwardByWord, "MoveCursorForwardByWord"}, {kFlutterSemanticsActionMoveCursorBackwardByWord, "MoveCursorBackwardByWord"}, {static_cast<FlutterSemanticsAction>(0), nullptr}}; struct FlAccessibleNodePrivate { AtkObject parent_instance; // Weak reference to the engine this node is created for. FlEngine* engine; // Weak reference to the parent node of this one or %NULL. AtkObject* parent; int32_t id; gchar* name; gint index; gint x, y, width, height; GPtrArray* actions; gsize actions_length; GPtrArray* children; FlutterSemanticsFlag flags; }; enum { kProp0, kPropEngine, kPropId, kPropLast }; #define FL_ACCESSIBLE_NODE_GET_PRIVATE(node) \ ((FlAccessibleNodePrivate*)fl_accessible_node_get_instance_private( \ FL_ACCESSIBLE_NODE(node))) static void fl_accessible_node_component_interface_init( AtkComponentIface* iface); static void fl_accessible_node_action_interface_init(AtkActionIface* iface); G_DEFINE_TYPE_WITH_CODE( FlAccessibleNode, fl_accessible_node, ATK_TYPE_OBJECT, G_ADD_PRIVATE(FlAccessibleNode) G_IMPLEMENT_INTERFACE(ATK_TYPE_COMPONENT, fl_accessible_node_component_interface_init) G_IMPLEMENT_INTERFACE(ATK_TYPE_ACTION, fl_accessible_node_action_interface_init)) // Returns TRUE if [flag] has changed between [old_flags] and [flags]. static gboolean flag_is_changed(FlutterSemanticsFlag old_flags, FlutterSemanticsFlag flags, FlutterSemanticsFlag flag) { return (old_flags & flag) != (flags & flag); } // Returns TRUE if [flag] is set in [flags]. static gboolean has_flag(FlutterSemanticsFlag flags, FlutterSemanticsFlag flag) { return (flags & flag) != 0; } // Returns TRUE if [action] is set in [actions]. static gboolean has_action(FlutterSemanticsAction actions, FlutterSemanticsAction action) { return (actions & action) != 0; } // Gets the nth action. static ActionData* get_action(FlAccessibleNodePrivate* priv, gint index) { if (index < 0 || static_cast<guint>(index) >= priv->actions->len) { return nullptr; } return static_cast<ActionData*>(g_ptr_array_index(priv->actions, index)); } // Checks if [object] is in [children]. static gboolean has_child(GPtrArray* children, AtkObject* object) { for (guint i = 0; i < children->len; i++) { if (g_ptr_array_index(children, i) == object) { return TRUE; } } return FALSE; } static void fl_accessible_node_set_property(GObject* object, guint prop_id, const GValue* value, GParamSpec* pspec) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(object); switch (prop_id) { case kPropEngine: g_assert(priv->engine == nullptr); priv->engine = FL_ENGINE(g_value_get_object(value)); g_object_add_weak_pointer(object, reinterpret_cast<gpointer*>(&priv->engine)); break; case kPropId: priv->id = g_value_get_int(value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void fl_accessible_node_dispose(GObject* object) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(object); if (priv->engine != nullptr) { g_object_remove_weak_pointer(object, reinterpret_cast<gpointer*>(&(priv->engine))); priv->engine = nullptr; } if (priv->parent != nullptr) { g_object_remove_weak_pointer(object, reinterpret_cast<gpointer*>(&(priv->parent))); priv->parent = nullptr; } g_clear_pointer(&priv->name, g_free); g_clear_pointer(&priv->actions, g_ptr_array_unref); g_clear_pointer(&priv->children, g_ptr_array_unref); G_OBJECT_CLASS(fl_accessible_node_parent_class)->dispose(object); } // Implements AtkObject::get_name. static const gchar* fl_accessible_node_get_name(AtkObject* accessible) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(accessible); return priv->name; } // Implements AtkObject::get_parent. static AtkObject* fl_accessible_node_get_parent(AtkObject* accessible) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(accessible); return priv->parent; } // Implements AtkObject::get_index_in_parent. static gint fl_accessible_node_get_index_in_parent(AtkObject* accessible) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(accessible); return priv->index; } // Implements AtkObject::get_n_children. static gint fl_accessible_node_get_n_children(AtkObject* accessible) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(accessible); return priv->children->len; } // Implements AtkObject::ref_child. static AtkObject* fl_accessible_node_ref_child(AtkObject* accessible, gint i) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(accessible); if (i < 0 || static_cast<guint>(i) >= priv->children->len) { return nullptr; } return ATK_OBJECT(g_object_ref(g_ptr_array_index(priv->children, i))); } // Implements AtkObject::get_role. static AtkRole fl_accessible_node_get_role(AtkObject* accessible) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(accessible); if ((priv->flags & kFlutterSemanticsFlagIsButton) != 0) { return ATK_ROLE_PUSH_BUTTON; } if ((priv->flags & kFlutterSemanticsFlagIsInMutuallyExclusiveGroup) != 0 && (priv->flags & kFlutterSemanticsFlagHasCheckedState) != 0) { return ATK_ROLE_RADIO_BUTTON; } if ((priv->flags & kFlutterSemanticsFlagHasCheckedState) != 0) { return ATK_ROLE_CHECK_BOX; } if ((priv->flags & kFlutterSemanticsFlagHasToggledState) != 0) { return ATK_ROLE_TOGGLE_BUTTON; } if ((priv->flags & kFlutterSemanticsFlagIsSlider) != 0) { return ATK_ROLE_SLIDER; } if ((priv->flags & kFlutterSemanticsFlagIsTextField) != 0 && (priv->flags & kFlutterSemanticsFlagIsObscured) != 0) { return ATK_ROLE_PASSWORD_TEXT; } if ((priv->flags & kFlutterSemanticsFlagIsTextField) != 0) { return ATK_ROLE_TEXT; } if ((priv->flags & kFlutterSemanticsFlagIsHeader) != 0) { return ATK_ROLE_HEADER; } if ((priv->flags & kFlutterSemanticsFlagIsLink) != 0) { return ATK_ROLE_LINK; } if ((priv->flags & kFlutterSemanticsFlagIsImage) != 0) { return ATK_ROLE_IMAGE; } return ATK_ROLE_PANEL; } // Implements AtkObject::ref_state_set. static AtkStateSet* fl_accessible_node_ref_state_set(AtkObject* accessible) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(accessible); AtkStateSet* state_set = atk_state_set_new(); for (int i = 0; flag_mapping[i].state != ATK_STATE_INVALID; i++) { gboolean enabled = has_flag(priv->flags, flag_mapping[i].flag); if (flag_mapping[i].invert) { enabled = !enabled; } if (enabled) { atk_state_set_add_state(state_set, flag_mapping[i].state); } } return state_set; } // Implements AtkComponent::get_extents. static void fl_accessible_node_get_extents(AtkComponent* component, gint* x, gint* y, gint* width, gint* height, AtkCoordType coord_type) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(component); *x = 0; *y = 0; if (priv->parent != nullptr) { atk_component_get_extents(ATK_COMPONENT(priv->parent), x, y, nullptr, nullptr, coord_type); } *x += priv->x; *y += priv->y; *width = priv->width; *height = priv->height; } // Implements AtkComponent::get_layer. static AtkLayer fl_accessible_node_get_layer(AtkComponent* component) { return ATK_LAYER_WIDGET; } // Implements AtkAction::do_action. static gboolean fl_accessible_node_do_action(AtkAction* action, gint i) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(action); if (priv->engine == nullptr) { return FALSE; } ActionData* data = get_action(priv, i); if (data == nullptr) { return FALSE; } fl_accessible_node_perform_action(FL_ACCESSIBLE_NODE(action), data->action, nullptr); return TRUE; } // Implements AtkAction::get_n_actions. static gint fl_accessible_node_get_n_actions(AtkAction* action) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(action); return priv->actions->len; } // Implements AtkAction::get_name. static const gchar* fl_accessible_node_get_name(AtkAction* action, gint i) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(action); ActionData* data = get_action(priv, i); if (data == nullptr) { return nullptr; } return data->name; } // Implements FlAccessibleNode::set_name. static void fl_accessible_node_set_name_impl(FlAccessibleNode* self, const gchar* name) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(self); g_free(priv->name); priv->name = g_strdup(name); } // Implements FlAccessibleNode::set_extents. static void fl_accessible_node_set_extents_impl(FlAccessibleNode* self, gint x, gint y, gint width, gint height) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(self); priv->x = x; priv->y = y; priv->width = width; priv->height = height; } // Implements FlAccessibleNode::set_flags. static void fl_accessible_node_set_flags_impl(FlAccessibleNode* self, FlutterSemanticsFlag flags) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(self); FlutterSemanticsFlag old_flags = priv->flags; priv->flags = flags; for (int i = 0; flag_mapping[i].state != ATK_STATE_INVALID; i++) { if (flag_is_changed(old_flags, flags, flag_mapping[i].flag)) { gboolean enabled = has_flag(flags, flag_mapping[i].flag); if (flag_mapping[i].invert) { enabled = !enabled; } atk_object_notify_state_change(ATK_OBJECT(self), flag_mapping[i].state, enabled); } } } // Implements FlAccessibleNode::set_actions. static void fl_accessible_node_set_actions_impl( FlAccessibleNode* self, FlutterSemanticsAction actions) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(self); // NOTE(robert-ancell): It appears that AtkAction doesn't have a method of // notifying that actions have changed, and even if it did an ATK client // might access the old IDs before checking for new ones. Keep an eye // out for a case where Flutter changes the actions on an item and see // if we can resolve this in another way. g_ptr_array_remove_range(priv->actions, 0, priv->actions->len); for (int i = 0; action_mapping[i].name != nullptr; i++) { if (has_action(actions, action_mapping[i].action)) { g_ptr_array_add(priv->actions, &action_mapping[i]); } } } // Implements FlAccessibleNode::set_value. static void fl_accessible_node_set_value_impl(FlAccessibleNode* self, const gchar* value) {} // Implements FlAccessibleNode::set_text_selection. static void fl_accessible_node_set_text_selection_impl(FlAccessibleNode* self, gint base, gint extent) {} // Implements FlAccessibleNode::set_text_direction. static void fl_accessible_node_set_text_direction_impl( FlAccessibleNode* self, FlutterTextDirection direction) {} // Implements FlAccessibleNode::perform_action. static void fl_accessible_node_perform_action_impl( FlAccessibleNode* self, FlutterSemanticsAction action, GBytes* data) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(self); fl_engine_dispatch_semantics_action(priv->engine, priv->id, action, data); } static void fl_accessible_node_class_init(FlAccessibleNodeClass* klass) { G_OBJECT_CLASS(klass)->set_property = fl_accessible_node_set_property; G_OBJECT_CLASS(klass)->dispose = fl_accessible_node_dispose; ATK_OBJECT_CLASS(klass)->get_name = fl_accessible_node_get_name; ATK_OBJECT_CLASS(klass)->get_parent = fl_accessible_node_get_parent; ATK_OBJECT_CLASS(klass)->get_index_in_parent = fl_accessible_node_get_index_in_parent; ATK_OBJECT_CLASS(klass)->get_n_children = fl_accessible_node_get_n_children; ATK_OBJECT_CLASS(klass)->ref_child = fl_accessible_node_ref_child; ATK_OBJECT_CLASS(klass)->get_role = fl_accessible_node_get_role; ATK_OBJECT_CLASS(klass)->ref_state_set = fl_accessible_node_ref_state_set; FL_ACCESSIBLE_NODE_CLASS(klass)->set_name = fl_accessible_node_set_name_impl; FL_ACCESSIBLE_NODE_CLASS(klass)->set_extents = fl_accessible_node_set_extents_impl; FL_ACCESSIBLE_NODE_CLASS(klass)->set_flags = fl_accessible_node_set_flags_impl; FL_ACCESSIBLE_NODE_CLASS(klass)->set_actions = fl_accessible_node_set_actions_impl; FL_ACCESSIBLE_NODE_CLASS(klass)->set_value = fl_accessible_node_set_value_impl; FL_ACCESSIBLE_NODE_CLASS(klass)->set_text_selection = fl_accessible_node_set_text_selection_impl; FL_ACCESSIBLE_NODE_CLASS(klass)->set_text_direction = fl_accessible_node_set_text_direction_impl; FL_ACCESSIBLE_NODE_CLASS(klass)->perform_action = fl_accessible_node_perform_action_impl; g_object_class_install_property( G_OBJECT_CLASS(klass), kPropEngine, g_param_spec_object( "engine", "engine", "Flutter engine", fl_engine_get_type(), static_cast<GParamFlags>(G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS))); g_object_class_install_property( G_OBJECT_CLASS(klass), kPropId, g_param_spec_int( "id", "id", "Accessibility node ID", 0, G_MAXINT, 0, static_cast<GParamFlags>(G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS))); } static void fl_accessible_node_component_interface_init( AtkComponentIface* iface) { iface->get_extents = fl_accessible_node_get_extents; iface->get_layer = fl_accessible_node_get_layer; } static void fl_accessible_node_action_interface_init(AtkActionIface* iface) { iface->do_action = fl_accessible_node_do_action; iface->get_n_actions = fl_accessible_node_get_n_actions; iface->get_name = fl_accessible_node_get_name; } static void fl_accessible_node_init(FlAccessibleNode* self) { FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(self); priv->actions = g_ptr_array_new(); priv->children = g_ptr_array_new_with_free_func(g_object_unref); } FlAccessibleNode* fl_accessible_node_new(FlEngine* engine, int32_t id) { FlAccessibleNode* self = FL_ACCESSIBLE_NODE(g_object_new( fl_accessible_node_get_type(), "engine", engine, "id", id, nullptr)); return self; } void fl_accessible_node_set_parent(FlAccessibleNode* self, AtkObject* parent, gint index) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(self); priv->parent = parent; priv->index = index; g_object_add_weak_pointer(G_OBJECT(self), reinterpret_cast<gpointer*>(&(priv->parent))); } void fl_accessible_node_set_children(FlAccessibleNode* self, GPtrArray* children) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); FlAccessibleNodePrivate* priv = FL_ACCESSIBLE_NODE_GET_PRIVATE(self); // Remove nodes that are no longer required. for (guint i = 0; i < priv->children->len;) { AtkObject* object = ATK_OBJECT(g_ptr_array_index(priv->children, i)); if (has_child(children, object)) { i++; } else { g_signal_emit_by_name(self, "children-changed::remove", i, object, nullptr); g_ptr_array_remove_index(priv->children, i); } } // Add new nodes. for (guint i = 0; i < children->len; i++) { AtkObject* object = ATK_OBJECT(g_ptr_array_index(children, i)); if (!has_child(priv->children, object)) { g_ptr_array_add(priv->children, g_object_ref(object)); g_signal_emit_by_name(self, "children-changed::add", i, object, nullptr); } } } void fl_accessible_node_set_name(FlAccessibleNode* self, const gchar* name) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); return FL_ACCESSIBLE_NODE_GET_CLASS(self)->set_name(self, name); } void fl_accessible_node_set_extents(FlAccessibleNode* self, gint x, gint y, gint width, gint height) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); return FL_ACCESSIBLE_NODE_GET_CLASS(self)->set_extents(self, x, y, width, height); } void fl_accessible_node_set_flags(FlAccessibleNode* self, FlutterSemanticsFlag flags) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); return FL_ACCESSIBLE_NODE_GET_CLASS(self)->set_flags(self, flags); } void fl_accessible_node_set_actions(FlAccessibleNode* self, FlutterSemanticsAction actions) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); return FL_ACCESSIBLE_NODE_GET_CLASS(self)->set_actions(self, actions); } void fl_accessible_node_set_value(FlAccessibleNode* self, const gchar* value) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); return FL_ACCESSIBLE_NODE_GET_CLASS(self)->set_value(self, value); } void fl_accessible_node_set_text_selection(FlAccessibleNode* self, gint base, gint extent) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); return FL_ACCESSIBLE_NODE_GET_CLASS(self)->set_text_selection(self, base, extent); } void fl_accessible_node_set_text_direction(FlAccessibleNode* self, FlutterTextDirection direction) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); return FL_ACCESSIBLE_NODE_GET_CLASS(self)->set_text_direction(self, direction); } void fl_accessible_node_perform_action(FlAccessibleNode* self, FlutterSemanticsAction action, GBytes* data) { g_return_if_fail(FL_IS_ACCESSIBLE_NODE(self)); return FL_ACCESSIBLE_NODE_GET_CLASS(self)->perform_action(self, action, data); }
engine/shell/platform/linux/fl_accessible_node.cc/0
{ "file_path": "engine/shell/platform/linux/fl_accessible_node.cc", "repo_id": "engine", "token_count": 9500 }
351
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_key_channel_responder.h" #include "gtest/gtest.h" #include "flutter/shell/platform/linux/fl_binary_messenger_private.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/testing/fl_test.h" static const char* expected_value = nullptr; static gboolean expected_handled = FALSE; static FlValue* echo_response_cb(FlValue* echoed_value) { gchar* text = fl_value_to_string(echoed_value); EXPECT_STREQ(text, expected_value); g_free(text); FlValue* value = fl_value_new_map(); fl_value_set_string_take(value, "handled", fl_value_new_bool(expected_handled)); return value; } static void responder_callback(bool handled, gpointer user_data) { EXPECT_EQ(handled, expected_handled); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } namespace { // A global variable to store new event. It is a global variable so that it can // be returned by #fl_key_event_new_by_mock for easy use. FlKeyEvent _g_key_event; } // namespace // Create a new #FlKeyEvent with the given information. // // This event is passed to #fl_key_responder_handle_event, // which assumes that the event is managed by callee. // Therefore #fl_key_event_new_by_mock doesn't need to // dynamically allocate, but reuses the same global object. static FlKeyEvent* fl_key_event_new_by_mock(guint32 time_in_milliseconds, bool is_press, guint keyval, guint16 keycode, GdkModifierType state, gboolean is_modifier) { _g_key_event.is_press = is_press; _g_key_event.time = time_in_milliseconds; _g_key_event.state = state; _g_key_event.keyval = keyval; _g_key_event.keycode = keycode; _g_key_event.origin = nullptr; return &_g_key_event; } // Test sending a letter "A"; TEST(FlKeyChannelResponderTest, SendKeyEvent) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); g_autoptr(FlBinaryMessenger) messenger = fl_binary_messenger_new(engine); FlKeyChannelResponderMock mock{ .value_converter = echo_response_cb, .channel_name = "test/echo", }; g_autoptr(FlKeyResponder) responder = FL_KEY_RESPONDER(fl_key_channel_responder_new(messenger, &mock)); fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12345, true, GDK_KEY_A, 0x04, static_cast<GdkModifierType>(0), false), responder_callback, loop); expected_value = "{type: keydown, keymap: linux, scanCode: 4, toolkit: gtk, keyCode: 65, " "modifiers: 0, unicodeScalarValues: 65}"; expected_handled = FALSE; // Blocks here until echo_response_cb is called. g_main_loop_run(loop); fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(23456, false, GDK_KEY_A, 0x04, static_cast<GdkModifierType>(0), false), responder_callback, loop); expected_value = "{type: keyup, keymap: linux, scanCode: 4, toolkit: gtk, keyCode: 65, " "modifiers: 0, unicodeScalarValues: 65}"; expected_handled = FALSE; // Blocks here until echo_response_cb is called. g_main_loop_run(loop); } void test_lock_event(guint key_code, const char* down_expected, const char* up_expected) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); g_autoptr(FlBinaryMessenger) messenger = fl_binary_messenger_new(engine); FlKeyChannelResponderMock mock{ .value_converter = echo_response_cb, .channel_name = "test/echo", }; g_autoptr(FlKeyResponder) responder = FL_KEY_RESPONDER(fl_key_channel_responder_new(messenger, &mock)); fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12345, true, key_code, 0x04, static_cast<GdkModifierType>(0), false), responder_callback, loop); expected_value = down_expected; expected_handled = FALSE; // Blocks here until echo_response_cb is called. g_main_loop_run(loop); expected_value = up_expected; expected_handled = FALSE; fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12346, false, key_code, 0x04, static_cast<GdkModifierType>(0), false), responder_callback, loop); // Blocks here until echo_response_cb is called. g_main_loop_run(loop); } // Test sending a "NumLock" keypress. TEST(FlKeyChannelResponderTest, SendNumLockKeyEvent) { test_lock_event(GDK_KEY_Num_Lock, "{type: keydown, keymap: linux, scanCode: 4, toolkit: gtk, " "keyCode: 65407, modifiers: 16}", "{type: keyup, keymap: linux, scanCode: 4, toolkit: gtk, " "keyCode: 65407, modifiers: 0}"); } // Test sending a "CapsLock" keypress. TEST(FlKeyChannelResponderTest, SendCapsLockKeyEvent) { test_lock_event(GDK_KEY_Caps_Lock, "{type: keydown, keymap: linux, scanCode: 4, toolkit: gtk, " "keyCode: 65509, modifiers: 2}", "{type: keyup, keymap: linux, scanCode: 4, toolkit: gtk, " "keyCode: 65509, modifiers: 0}"); } // Test sending a "ShiftLock" keypress. TEST(FlKeyChannelResponderTest, SendShiftLockKeyEvent) { test_lock_event(GDK_KEY_Shift_Lock, "{type: keydown, keymap: linux, scanCode: 4, toolkit: gtk, " "keyCode: 65510, modifiers: 2}", "{type: keyup, keymap: linux, scanCode: 4, toolkit: gtk, " "keyCode: 65510, modifiers: 0}"); } TEST(FlKeyChannelResponderTest, TestKeyEventHandledByFramework) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); g_autoptr(FlBinaryMessenger) messenger = fl_binary_messenger_new(engine); FlKeyChannelResponderMock mock{ .value_converter = echo_response_cb, .channel_name = "test/echo", }; g_autoptr(FlKeyResponder) responder = FL_KEY_RESPONDER(fl_key_channel_responder_new(messenger, &mock)); fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12345, true, GDK_KEY_A, 0x04, static_cast<GdkModifierType>(0), false), responder_callback, loop); expected_handled = TRUE; expected_value = "{type: keydown, keymap: linux, scanCode: 4, toolkit: gtk, " "keyCode: 65, modifiers: 0, unicodeScalarValues: 65}"; // Blocks here until echo_response_cb is called. g_main_loop_run(loop); } TEST(FlKeyChannelResponderTest, UseSpecifiedLogicalKey) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); g_autoptr(FlBinaryMessenger) messenger = fl_binary_messenger_new(engine); FlKeyChannelResponderMock mock{ .value_converter = echo_response_cb, .channel_name = "test/echo", }; g_autoptr(FlKeyResponder) responder = FL_KEY_RESPONDER(fl_key_channel_responder_new(messenger, &mock)); fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12345, true, GDK_KEY_A, 0x04, static_cast<GdkModifierType>(0), false), responder_callback, loop, 888); expected_handled = TRUE; expected_value = "{type: keydown, keymap: linux, scanCode: 4, toolkit: gtk, " "keyCode: 65, modifiers: 0, unicodeScalarValues: 65, " "specifiedLogicalKey: 888}"; // Blocks here until echo_response_cb is called. g_main_loop_run(loop); }
engine/shell/platform/linux/fl_key_channel_responder_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_key_channel_responder_test.cc", "repo_id": "engine", "token_count": 3489 }
352
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_call.h" #include "flutter/shell/platform/linux/fl_method_call_private.h" #include "flutter/shell/platform/linux/fl_method_channel_private.h" #include <gmodule.h> struct _FlMethodCall { GObject parent_instance; // Name of method being called. gchar* name; // Arguments provided to method call. FlValue* args; // Channel to respond on. FlMethodChannel* channel; FlBinaryMessengerResponseHandle* response_handle; }; G_DEFINE_TYPE(FlMethodCall, fl_method_call, G_TYPE_OBJECT) static void fl_method_call_dispose(GObject* object) { FlMethodCall* self = FL_METHOD_CALL(object); g_clear_pointer(&self->name, g_free); g_clear_pointer(&self->args, fl_value_unref); g_clear_object(&self->channel); g_clear_object(&self->response_handle); G_OBJECT_CLASS(fl_method_call_parent_class)->dispose(object); } static void fl_method_call_class_init(FlMethodCallClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_method_call_dispose; } static void fl_method_call_init(FlMethodCall* self) {} FlMethodCall* fl_method_call_new( const gchar* name, FlValue* args, FlMethodChannel* channel, FlBinaryMessengerResponseHandle* response_handle) { g_return_val_if_fail(name != nullptr, nullptr); g_return_val_if_fail(args != nullptr, nullptr); g_return_val_if_fail(FL_IS_METHOD_CHANNEL(channel), nullptr); g_return_val_if_fail(FL_IS_BINARY_MESSENGER_RESPONSE_HANDLE(response_handle), nullptr); FlMethodCall* self = FL_METHOD_CALL(g_object_new(fl_method_call_get_type(), nullptr)); self->name = g_strdup(name); self->args = fl_value_ref(args); self->channel = FL_METHOD_CHANNEL(g_object_ref(channel)); self->response_handle = FL_BINARY_MESSENGER_RESPONSE_HANDLE(g_object_ref(response_handle)); return self; } G_MODULE_EXPORT const gchar* fl_method_call_get_name(FlMethodCall* self) { g_return_val_if_fail(FL_IS_METHOD_CALL(self), nullptr); return self->name; } G_MODULE_EXPORT FlValue* fl_method_call_get_args(FlMethodCall* self) { g_return_val_if_fail(FL_IS_METHOD_CALL(self), nullptr); return self->args; } G_MODULE_EXPORT gboolean fl_method_call_respond(FlMethodCall* self, FlMethodResponse* response, GError** error) { g_return_val_if_fail(FL_IS_METHOD_CALL(self), FALSE); g_return_val_if_fail(FL_IS_METHOD_RESPONSE(response), FALSE); g_autoptr(GError) local_error = nullptr; if (!fl_method_channel_respond(self->channel, self->response_handle, response, &local_error)) { // If the developer chose not to handle the error then log it so it's not // missed. if (error == nullptr) { g_warning("Failed to send method call response: %s", local_error->message); } g_propagate_error(error, local_error); return FALSE; } return TRUE; } G_MODULE_EXPORT gboolean fl_method_call_respond_success(FlMethodCall* self, FlValue* result, GError** error) { g_return_val_if_fail(FL_IS_METHOD_CALL(self), FALSE); g_autoptr(FlMethodResponse) response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); return fl_method_channel_respond(self->channel, self->response_handle, response, error); } G_MODULE_EXPORT gboolean fl_method_call_respond_error(FlMethodCall* self, const gchar* code, const gchar* message, FlValue* details, GError** error) { g_return_val_if_fail(FL_IS_METHOD_CALL(self), FALSE); g_return_val_if_fail(code != nullptr, FALSE); g_autoptr(FlMethodResponse) response = FL_METHOD_RESPONSE(fl_method_error_response_new(code, message, details)); return fl_method_channel_respond(self->channel, self->response_handle, response, error); } G_MODULE_EXPORT gboolean fl_method_call_respond_not_implemented( FlMethodCall* self, GError** error) { g_return_val_if_fail(FL_IS_METHOD_CALL(self), FALSE); g_autoptr(FlMethodResponse) response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); return fl_method_channel_respond(self->channel, self->response_handle, response, error); }
engine/shell/platform/linux/fl_method_call.cc/0
{ "file_path": "engine/shell/platform/linux/fl_method_call.cc", "repo_id": "engine", "token_count": 2150 }
353
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_PLATFORM_PLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_PLATFORM_PLUGIN_H_ #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlPlatformPlugin, fl_platform_plugin, FL, PLATFORM_PLUGIN, GObject); /** * FlPlatformPlugin: * * #FlPlatformPlugin is a plugin that implements the shell side * of SystemChannels.platform from the Flutter services library. */ /** * fl_platform_plugin_new: * @messenger: an #FlBinaryMessenger * * Creates a new plugin that implements SystemChannels.platform from the * Flutter services library. * * Returns: a new #FlPlatformPlugin */ FlPlatformPlugin* fl_platform_plugin_new(FlBinaryMessenger* messenger); /** * fl_platform_plugin_request_app_exit: * @plugin: an #FlPlatformPlugin * * Request the application exits (i.e. due to the window being requested to be * closed). * * Calling this will only send an exit request to the framework if the framework * has already indicated that it is ready to receive requests by sending a * "System.initializationComplete" method call on the platform channel. Calls * before initialization is complete will result in an immediate exit. */ void fl_platform_plugin_request_app_exit(FlPlatformPlugin* plugin); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_PLATFORM_PLUGIN_H_
engine/shell/platform/linux/fl_platform_plugin.h/0
{ "file_path": "engine/shell/platform/linux/fl_platform_plugin.h", "repo_id": "engine", "token_count": 566 }
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. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_SCROLLING_VIEW_DELEGATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_SCROLLING_VIEW_DELEGATE_H_ #include <gdk/gdk.h> #include <cinttypes> #include <memory> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/linux/fl_key_event.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" G_BEGIN_DECLS G_DECLARE_INTERFACE(FlScrollingViewDelegate, fl_scrolling_view_delegate, FL, SCROLLING_VIEW_DELEGATE, GObject); /** * FlScrollingViewDelegate: * * An interface for a class that provides `FlScrollingManager` with * platform-related features. * * This interface is typically implemented by `FlView`. */ struct _FlScrollingViewDelegateInterface { GTypeInterface g_iface; void (*send_mouse_pointer_event)(FlScrollingViewDelegate* delegate, FlutterPointerPhase phase, size_t timestamp, double x, double y, double scroll_delta_x, double scroll_delta_y, int64_t buttons); void (*send_pointer_pan_zoom_event)(FlScrollingViewDelegate* delegate, size_t timestamp, double x, double y, FlutterPointerPhase phase, double pan_x, double pan_y, double scale, double rotation); }; void fl_scrolling_view_delegate_send_mouse_pointer_event( FlScrollingViewDelegate* delegate, FlutterPointerPhase phase, size_t timestamp, double x, double y, double scroll_delta_x, double scroll_delta_y, int64_t buttons); void fl_scrolling_view_delegate_send_pointer_pan_zoom_event( FlScrollingViewDelegate* delegate, size_t timestamp, double x, double y, FlutterPointerPhase phase, double pan_x, double pan_y, double scale, double rotation); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_SCROLLING_VIEW_DELEGATE_H_
engine/shell/platform/linux/fl_scrolling_view_delegate.h/0
{ "file_path": "engine/shell/platform/linux/fl_scrolling_view_delegate.h", "repo_id": "engine", "token_count": 1334 }
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_LINUX_FL_TASK_RUNNER_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_TASK_RUNNER_H_ #include <glib-object.h> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlTaskRunner, fl_task_runner, FL, TASK_RUNNER, GObject); /** * fl_task_runner_new: * @engine: the #FlEngine owning the task runner. * * Creates new task runner instance. * * Returns: an #FlTaskRunner. */ FlTaskRunner* fl_task_runner_new(FlEngine* engine); /** * fl_task_runner_post_task: * @task_runner: an #FlTaskRunner. * @task: Flutter task being scheduled * @target_time_nanos: absolute time in nanoseconds * * Posts a Flutter task to be executed on main thread. This function is thread * safe and may be called from any thread. */ void fl_task_runner_post_task(FlTaskRunner* task_runner, FlutterTask task, uint64_t target_time_nanos); /** * fl_task_runner_block_main_thread: * @task_runner: an #FlTaskRunner. * * Blocks main thread until fl_task_runner_release_main_thread is called. * While main thread is blocked tasks posted to #FlTaskRunner are executed as * usual. * Must be invoked on main thread. */ void fl_task_runner_block_main_thread(FlTaskRunner* task_runner); /** * fl_task_runner_release_main_thread: * @task_runner: an #FlTaskRunner. * * Unblocks main thread. This will resume normal processing of main loop. * Can be invoked from any thread. */ void fl_task_runner_release_main_thread(FlTaskRunner* self); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_TASK_RUNNER_H_
engine/shell/platform/linux/fl_task_runner.h/0
{ "file_path": "engine/shell/platform/linux/fl_task_runner.h", "repo_id": "engine", "token_count": 684 }
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. #include "flutter/shell/platform/linux/public/flutter_linux/fl_view.h" #include "flutter/shell/platform/linux/fl_view_private.h" #include <cstring> #include "flutter/shell/platform/linux/fl_backing_store_provider.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/fl_key_event.h" #include "flutter/shell/platform/linux/fl_keyboard_manager.h" #include "flutter/shell/platform/linux/fl_keyboard_view_delegate.h" #include "flutter/shell/platform/linux/fl_mouse_cursor_plugin.h" #include "flutter/shell/platform/linux/fl_platform_plugin.h" #include "flutter/shell/platform/linux/fl_plugin_registrar_private.h" #include "flutter/shell/platform/linux/fl_renderer_gdk.h" #include "flutter/shell/platform/linux/fl_scrolling_manager.h" #include "flutter/shell/platform/linux/fl_scrolling_view_delegate.h" #include "flutter/shell/platform/linux/fl_text_input_plugin.h" #include "flutter/shell/platform/linux/fl_text_input_view_delegate.h" #include "flutter/shell/platform/linux/fl_view_accessible.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registry.h" static constexpr int kMicrosecondsPerMillisecond = 1000; struct _FlView { GtkBox parent_instance; // Project being run. FlDartProject* project; // Rendering output. FlRendererGdk* renderer; // Engine running @project. FlEngine* engine; // Pointer button state recorded for sending status updates. int64_t button_state; // Current state information for the window associated with this view. GdkWindowState window_state; // Flutter system channel handlers. FlKeyboardManager* keyboard_manager; FlScrollingManager* scrolling_manager; FlTextInputPlugin* text_input_plugin; FlMouseCursorPlugin* mouse_cursor_plugin; FlPlatformPlugin* platform_plugin; GtkWidget* event_box; GtkGLArea* gl_area; // Tracks whether mouse pointer is inside the view. gboolean pointer_inside; /* FlKeyboardViewDelegate related properties */ KeyboardLayoutNotifier keyboard_layout_notifier; GdkKeymap* keymap; gulong keymap_keys_changed_cb_id; // Signal connection ID for // keymap-keys-changed gulong window_state_cb_id; // Signal connection ID for window-state-changed }; enum { kPropFlutterProject = 1, kPropLast }; static void fl_view_plugin_registry_iface_init( FlPluginRegistryInterface* iface); static void fl_view_keyboard_delegate_iface_init( FlKeyboardViewDelegateInterface* iface); static void fl_view_scrolling_delegate_iface_init( FlScrollingViewDelegateInterface* iface); static void fl_view_text_input_delegate_iface_init( FlTextInputViewDelegateInterface* iface); G_DEFINE_TYPE_WITH_CODE( FlView, fl_view, GTK_TYPE_BOX, G_IMPLEMENT_INTERFACE(fl_plugin_registry_get_type(), fl_view_plugin_registry_iface_init) G_IMPLEMENT_INTERFACE(fl_keyboard_view_delegate_get_type(), fl_view_keyboard_delegate_iface_init) G_IMPLEMENT_INTERFACE(fl_scrolling_view_delegate_get_type(), fl_view_scrolling_delegate_iface_init) G_IMPLEMENT_INTERFACE(fl_text_input_view_delegate_get_type(), fl_view_text_input_delegate_iface_init)) // Signal handler for GtkWidget::delete-event static gboolean window_delete_event_cb(FlView* self) { fl_platform_plugin_request_app_exit(self->platform_plugin); // Stop the event from propagating. return TRUE; } // Initialize keyboard manager. static void init_keyboard(FlView* self) { FlBinaryMessenger* messenger = fl_engine_get_binary_messenger(self->engine); GdkWindow* window = gtk_widget_get_window(gtk_widget_get_toplevel(GTK_WIDGET(self))); g_return_if_fail(GDK_IS_WINDOW(window)); g_autoptr(GtkIMContext) im_context = gtk_im_multicontext_new(); gtk_im_context_set_client_window(im_context, window); g_clear_object(&self->text_input_plugin); self->text_input_plugin = fl_text_input_plugin_new( messenger, im_context, FL_TEXT_INPUT_VIEW_DELEGATE(self)); g_clear_object(&self->keyboard_manager); self->keyboard_manager = fl_keyboard_manager_new(messenger, FL_KEYBOARD_VIEW_DELEGATE(self)); } static void init_scrolling(FlView* self) { g_clear_object(&self->scrolling_manager); self->scrolling_manager = fl_scrolling_manager_new(FL_SCROLLING_VIEW_DELEGATE(self)); } // Converts a GDK button event into a Flutter event and sends it to the engine. static gboolean send_pointer_button_event(FlView* self, GdkEvent* event) { guint event_time = gdk_event_get_time(event); GdkEventType event_type = gdk_event_get_event_type(event); GdkModifierType event_state = static_cast<GdkModifierType>(0); gdk_event_get_state(event, &event_state); guint event_button = 0; gdk_event_get_button(event, &event_button); gdouble event_x = 0.0, event_y = 0.0; gdk_event_get_coords(event, &event_x, &event_y); int64_t button; switch (event_button) { case 1: button = kFlutterPointerButtonMousePrimary; break; case 2: button = kFlutterPointerButtonMouseMiddle; break; case 3: button = kFlutterPointerButtonMouseSecondary; break; default: return FALSE; } int old_button_state = self->button_state; FlutterPointerPhase phase = kMove; if (event_type == GDK_BUTTON_PRESS) { // Drop the event if Flutter already thinks the button is down. if ((self->button_state & button) != 0) { return FALSE; } self->button_state ^= button; phase = old_button_state == 0 ? kDown : kMove; } else if (event_type == GDK_BUTTON_RELEASE) { // Drop the event if Flutter already thinks the button is up. if ((self->button_state & button) == 0) { return FALSE; } self->button_state ^= button; phase = self->button_state == 0 ? kUp : kMove; } if (self->engine == nullptr) { return FALSE; } gint scale_factor = gtk_widget_get_scale_factor(GTK_WIDGET(self)); fl_scrolling_manager_set_last_mouse_position( self->scrolling_manager, event_x * scale_factor, event_y * scale_factor); fl_keyboard_manager_sync_modifier_if_needed(self->keyboard_manager, event_state, event_time); fl_engine_send_mouse_pointer_event( self->engine, phase, event_time * kMicrosecondsPerMillisecond, event_x * scale_factor, event_y * scale_factor, 0, 0, self->button_state); return TRUE; } // Generates a mouse pointer event if the pointer appears inside the window. static void check_pointer_inside(FlView* self, GdkEvent* event) { if (!self->pointer_inside) { self->pointer_inside = TRUE; gdouble x, y; if (gdk_event_get_coords(event, &x, &y)) { gint scale_factor = gtk_widget_get_scale_factor(GTK_WIDGET(self)); fl_engine_send_mouse_pointer_event( self->engine, kAdd, gdk_event_get_time(event) * kMicrosecondsPerMillisecond, x * scale_factor, y * scale_factor, 0, 0, self->button_state); } } } // Updates the engine with the current window metrics. static void handle_geometry_changed(FlView* self) { GtkAllocation allocation; gtk_widget_get_allocation(GTK_WIDGET(self), &allocation); gint scale_factor = gtk_widget_get_scale_factor(GTK_WIDGET(self)); fl_engine_send_window_metrics_event( self->engine, allocation.width * scale_factor, allocation.height * scale_factor, scale_factor); // Make sure the view has been realized and its size has been allocated before // waiting for a frame. `fl_view_realize()` and `fl_view_size_allocate()` may // be called in either order depending on the order in which the window is // shown and the view is added to a container in the app runner. // // Note: `gtk_widget_init()` initializes the size allocation to 1x1. if (allocation.width > 1 && allocation.height > 1 && gtk_widget_get_realized(GTK_WIDGET(self))) { fl_renderer_wait_for_frame(FL_RENDERER(self->renderer), allocation.width * scale_factor, allocation.height * scale_factor); } } // Called when the engine updates accessibility. static void update_semantics_cb(FlEngine* engine, const FlutterSemanticsUpdate2* update, gpointer user_data) { FlView* self = FL_VIEW(user_data); AtkObject* accessible = gtk_widget_get_accessible(GTK_WIDGET(self)); fl_view_accessible_handle_update_semantics(FL_VIEW_ACCESSIBLE(accessible), update); } // Invoked by the engine right before the engine is restarted. // // This method should reset states to be as if the engine had just been started, // which usually indicates the user has requested a hot restart (Shift-R in the // Flutter CLI.) static void on_pre_engine_restart_cb(FlEngine* engine, gpointer user_data) { FlView* self = FL_VIEW(user_data); init_keyboard(self); init_scrolling(self); } // Implements FlPluginRegistry::get_registrar_for_plugin. static FlPluginRegistrar* fl_view_get_registrar_for_plugin( FlPluginRegistry* registry, const gchar* name) { FlView* self = FL_VIEW(registry); return fl_plugin_registrar_new(self, fl_engine_get_binary_messenger(self->engine), fl_engine_get_texture_registrar(self->engine)); } static void fl_view_plugin_registry_iface_init( FlPluginRegistryInterface* iface) { iface->get_registrar_for_plugin = fl_view_get_registrar_for_plugin; } static void fl_view_keyboard_delegate_iface_init( FlKeyboardViewDelegateInterface* iface) { iface->send_key_event = [](FlKeyboardViewDelegate* view_delegate, const FlutterKeyEvent* event, FlutterKeyEventCallback callback, void* user_data) { FlView* self = FL_VIEW(view_delegate); if (self->engine != nullptr) { fl_engine_send_key_event(self->engine, event, callback, user_data); }; }; iface->text_filter_key_press = [](FlKeyboardViewDelegate* view_delegate, FlKeyEvent* event) { FlView* self = FL_VIEW(view_delegate); return fl_text_input_plugin_filter_keypress(self->text_input_plugin, event); }; iface->get_messenger = [](FlKeyboardViewDelegate* view_delegate) { FlView* self = FL_VIEW(view_delegate); return fl_engine_get_binary_messenger(self->engine); }; iface->redispatch_event = [](FlKeyboardViewDelegate* view_delegate, std::unique_ptr<FlKeyEvent> in_event) { FlKeyEvent* event = in_event.release(); GdkEventType event_type = gdk_event_get_event_type(event->origin); g_return_if_fail(event_type == GDK_KEY_PRESS || event_type == GDK_KEY_RELEASE); gdk_event_put(event->origin); fl_key_event_dispose(event); }; iface->subscribe_to_layout_change = [](FlKeyboardViewDelegate* view_delegate, KeyboardLayoutNotifier notifier) { FlView* self = FL_VIEW(view_delegate); self->keyboard_layout_notifier = std::move(notifier); }; iface->lookup_key = [](FlKeyboardViewDelegate* view_delegate, const GdkKeymapKey* key) -> guint { FlView* self = FL_VIEW(view_delegate); g_return_val_if_fail(self->keymap != nullptr, 0); return gdk_keymap_lookup_key(self->keymap, key); }; iface->get_keyboard_state = [](FlKeyboardViewDelegate* view_delegate) -> GHashTable* { FlView* self = FL_VIEW(view_delegate); return fl_view_get_keyboard_state(self); }; } static void fl_view_scrolling_delegate_iface_init( FlScrollingViewDelegateInterface* iface) { iface->send_mouse_pointer_event = [](FlScrollingViewDelegate* view_delegate, FlutterPointerPhase phase, size_t timestamp, double x, double y, double scroll_delta_x, double scroll_delta_y, int64_t buttons) { FlView* self = FL_VIEW(view_delegate); if (self->engine != nullptr) { fl_engine_send_mouse_pointer_event(self->engine, phase, timestamp, x, y, scroll_delta_x, scroll_delta_y, buttons); } }; iface->send_pointer_pan_zoom_event = [](FlScrollingViewDelegate* view_delegate, size_t timestamp, double x, double y, FlutterPointerPhase phase, double pan_x, double pan_y, double scale, double rotation) { FlView* self = FL_VIEW(view_delegate); if (self->engine != nullptr) { fl_engine_send_pointer_pan_zoom_event(self->engine, timestamp, x, y, phase, pan_x, pan_y, scale, rotation); }; }; } static void fl_view_text_input_delegate_iface_init( FlTextInputViewDelegateInterface* iface) { iface->translate_coordinates = [](FlTextInputViewDelegate* delegate, gint view_x, gint view_y, gint* window_x, gint* window_y) { FlView* self = FL_VIEW(delegate); gtk_widget_translate_coordinates(GTK_WIDGET(self), gtk_widget_get_toplevel(GTK_WIDGET(self)), view_x, view_y, window_x, window_y); }; } // Signal handler for GtkWidget::button-press-event static gboolean button_press_event_cb(FlView* self, GdkEventButton* button_event) { GdkEvent* event = reinterpret_cast<GdkEvent*>(button_event); // Flutter doesn't handle double and triple click events. GdkEventType event_type = gdk_event_get_event_type(event); if (event_type == GDK_DOUBLE_BUTTON_PRESS || event_type == GDK_TRIPLE_BUTTON_PRESS) { return FALSE; } check_pointer_inside(self, event); return send_pointer_button_event(self, event); } // Signal handler for GtkWidget::button-release-event static gboolean button_release_event_cb(FlView* self, GdkEventButton* button_event) { GdkEvent* event = reinterpret_cast<GdkEvent*>(button_event); return send_pointer_button_event(self, event); } // Signal handler for GtkWidget::scroll-event static gboolean scroll_event_cb(FlView* self, GdkEventScroll* event) { // TODO(robert-ancell): Update to use GtkEventControllerScroll when we can // depend on GTK 3.24. fl_scrolling_manager_handle_scroll_event( self->scrolling_manager, event, gtk_widget_get_scale_factor(GTK_WIDGET(self))); return TRUE; } // Signal handler for GtkWidget::motion-notify-event static gboolean motion_notify_event_cb(FlView* self, GdkEventMotion* motion_event) { GdkEvent* event = reinterpret_cast<GdkEvent*>(motion_event); if (self->engine == nullptr) { return FALSE; } guint event_time = gdk_event_get_time(event); GdkModifierType event_state = static_cast<GdkModifierType>(0); gdk_event_get_state(event, &event_state); gdouble event_x = 0.0, event_y = 0.0; gdk_event_get_coords(event, &event_x, &event_y); check_pointer_inside(self, event); gint scale_factor = gtk_widget_get_scale_factor(GTK_WIDGET(self)); fl_keyboard_manager_sync_modifier_if_needed(self->keyboard_manager, event_state, event_time); fl_engine_send_mouse_pointer_event( self->engine, self->button_state != 0 ? kMove : kHover, event_time * kMicrosecondsPerMillisecond, event_x * scale_factor, event_y * scale_factor, 0, 0, self->button_state); return TRUE; } // Signal handler for GtkWidget::enter-notify-event static gboolean enter_notify_event_cb(FlView* self, GdkEventCrossing* crossing_event) { GdkEvent* event = reinterpret_cast<GdkEvent*>(crossing_event); if (self->engine == nullptr) { return FALSE; } check_pointer_inside(self, event); return TRUE; } // Signal handler for GtkWidget::leave-notify-event static gboolean leave_notify_event_cb(FlView* self, GdkEventCrossing* crossing_event) { GdkEvent* event = reinterpret_cast<GdkEvent*>(crossing_event); guint event_time = gdk_event_get_time(event); gdouble event_x = 0.0, event_y = 0.0; gdk_event_get_coords(event, &event_x, &event_y); if (crossing_event->mode != GDK_CROSSING_NORMAL) { return FALSE; } if (self->engine == nullptr) { return FALSE; } // Don't remove pointer while button is down; In case of dragging outside of // window with mouse grab active Gtk will send another leave notify on // release. if (self->pointer_inside && self->button_state == 0) { gint scale_factor = gtk_widget_get_scale_factor(GTK_WIDGET(self)); fl_engine_send_mouse_pointer_event( self->engine, kRemove, event_time * kMicrosecondsPerMillisecond, event_x * scale_factor, event_y * scale_factor, 0, 0, self->button_state); self->pointer_inside = FALSE; } return TRUE; } static void keymap_keys_changed_cb(FlView* self) { if (self->keyboard_layout_notifier == nullptr) { return; } self->keyboard_layout_notifier(); } static void gesture_rotation_begin_cb(FlView* self) { fl_scrolling_manager_handle_rotation_begin(self->scrolling_manager); } static void gesture_rotation_update_cb(FlView* self, gdouble rotation, gdouble delta) { fl_scrolling_manager_handle_rotation_update(self->scrolling_manager, rotation); } static void gesture_rotation_end_cb(FlView* self) { fl_scrolling_manager_handle_rotation_end(self->scrolling_manager); } static void gesture_zoom_begin_cb(FlView* self) { fl_scrolling_manager_handle_zoom_begin(self->scrolling_manager); } static void gesture_zoom_update_cb(FlView* self, gdouble scale) { fl_scrolling_manager_handle_zoom_update(self->scrolling_manager, scale); } static void gesture_zoom_end_cb(FlView* self) { fl_scrolling_manager_handle_zoom_end(self->scrolling_manager); } static gboolean window_state_event_cb(FlView* self, GdkEvent* event) { g_return_val_if_fail(FL_IS_ENGINE(self->engine), FALSE); GdkWindowState state = event->window_state.new_window_state; GdkWindowState previous_state = self->window_state; self->window_state = state; bool was_visible = !((previous_state & GDK_WINDOW_STATE_WITHDRAWN) || (previous_state & GDK_WINDOW_STATE_ICONIFIED)); bool is_visible = !((state & GDK_WINDOW_STATE_WITHDRAWN) || (state & GDK_WINDOW_STATE_ICONIFIED)); bool was_focused = (previous_state & GDK_WINDOW_STATE_FOCUSED); bool is_focused = (state & GDK_WINDOW_STATE_FOCUSED); if (was_visible != is_visible || was_focused != is_focused) { if (self->engine != nullptr) { fl_engine_send_window_state_event(FL_ENGINE(self->engine), is_visible, is_focused); } } return FALSE; } static GdkGLContext* create_context_cb(FlView* self) { self->renderer = fl_renderer_gdk_new(gtk_widget_get_parent_window(GTK_WIDGET(self))); self->engine = fl_engine_new(self->project, FL_RENDERER(self->renderer)); fl_engine_set_update_semantics_handler(self->engine, update_semantics_cb, self, nullptr); fl_engine_set_on_pre_engine_restart_handler( self->engine, on_pre_engine_restart_cb, self, nullptr); // Must initialize the keymap before the keyboard. self->keymap = gdk_keymap_get_for_display(gdk_display_get_default()); self->keymap_keys_changed_cb_id = g_signal_connect_swapped( self->keymap, "keys-changed", G_CALLBACK(keymap_keys_changed_cb), self); // Create system channel handlers. FlBinaryMessenger* messenger = fl_engine_get_binary_messenger(self->engine); init_scrolling(self); self->mouse_cursor_plugin = fl_mouse_cursor_plugin_new(messenger, self); self->platform_plugin = fl_platform_plugin_new(messenger); g_autoptr(GError) error = nullptr; if (!fl_renderer_gdk_create_contexts(self->renderer, &error)) { gtk_gl_area_set_error(self->gl_area, error); return nullptr; } return GDK_GL_CONTEXT( g_object_ref(fl_renderer_gdk_get_context(self->renderer))); } static void realize_cb(FlView* self) { g_autoptr(GError) error = nullptr; fl_renderer_make_current(FL_RENDERER(self->renderer)); GError* gl_error = gtk_gl_area_get_error(self->gl_area); if (gl_error != NULL) { g_warning("Failed to initialize GLArea: %s", gl_error->message); return; } fl_renderer_setup(FL_RENDERER(self->renderer)); // Handle requests by the user to close the application. GtkWidget* toplevel_window = gtk_widget_get_toplevel(GTK_WIDGET(self)); // Listen to window state changes. self->window_state_cb_id = g_signal_connect_swapped(toplevel_window, "window-state-event", G_CALLBACK(window_state_event_cb), self); self->window_state = gdk_window_get_state(gtk_widget_get_window(toplevel_window)); g_signal_connect_swapped(toplevel_window, "delete-event", G_CALLBACK(window_delete_event_cb), self); init_keyboard(self); fl_renderer_start(FL_RENDERER(FL_RENDERER(self->renderer)), self); if (!fl_engine_start(self->engine, &error)) { g_warning("Failed to start Flutter engine: %s", error->message); return; } handle_geometry_changed(self); } static gboolean render_cb(FlView* self, GdkGLContext* context) { if (gtk_gl_area_get_error(self->gl_area) != NULL) { return FALSE; } int width = gtk_widget_get_allocated_width(GTK_WIDGET(self->gl_area)); int height = gtk_widget_get_allocated_height(GTK_WIDGET(self->gl_area)); gint scale_factor = gtk_widget_get_scale_factor(GTK_WIDGET(self->gl_area)); fl_renderer_render(FL_RENDERER(self->renderer), width * scale_factor, height * scale_factor); return TRUE; } static void unrealize_cb(FlView* self) { g_autoptr(GError) error = nullptr; fl_renderer_make_current(FL_RENDERER(self->renderer)); GError* gl_error = gtk_gl_area_get_error(self->gl_area); if (gl_error != NULL) { g_warning("Failed to uninitialize GLArea: %s", gl_error->message); return; } fl_renderer_cleanup(FL_RENDERER(self->renderer)); } static void size_allocate_cb(FlView* self) { handle_geometry_changed(self); } static void fl_view_set_property(GObject* object, guint prop_id, const GValue* value, GParamSpec* pspec) { FlView* self = FL_VIEW(object); switch (prop_id) { case kPropFlutterProject: g_set_object(&self->project, static_cast<FlDartProject*>(g_value_get_object(value))); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void fl_view_get_property(GObject* object, guint prop_id, GValue* value, GParamSpec* pspec) { FlView* self = FL_VIEW(object); switch (prop_id) { case kPropFlutterProject: g_value_set_object(value, self->project); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void fl_view_notify(GObject* object, GParamSpec* pspec) { FlView* self = FL_VIEW(object); if (strcmp(pspec->name, "scale-factor") == 0) { handle_geometry_changed(self); } if (G_OBJECT_CLASS(fl_view_parent_class)->notify != nullptr) { G_OBJECT_CLASS(fl_view_parent_class)->notify(object, pspec); } } static void fl_view_dispose(GObject* object) { FlView* self = FL_VIEW(object); if (self->engine != nullptr) { fl_engine_set_update_semantics_handler(self->engine, nullptr, nullptr, nullptr); fl_engine_set_on_pre_engine_restart_handler(self->engine, nullptr, nullptr, nullptr); } if (self->window_state_cb_id != 0) { GtkWidget* toplevel_window = gtk_widget_get_toplevel(GTK_WIDGET(self)); g_signal_handler_disconnect(toplevel_window, self->window_state_cb_id); self->window_state_cb_id = 0; } g_clear_object(&self->project); g_clear_object(&self->renderer); g_clear_object(&self->engine); g_clear_object(&self->keyboard_manager); if (self->keymap_keys_changed_cb_id != 0) { g_signal_handler_disconnect(self->keymap, self->keymap_keys_changed_cb_id); self->keymap_keys_changed_cb_id = 0; } g_clear_object(&self->mouse_cursor_plugin); g_clear_object(&self->platform_plugin); G_OBJECT_CLASS(fl_view_parent_class)->dispose(object); } // Implements GtkWidget::key_press_event. static gboolean fl_view_key_press_event(GtkWidget* widget, GdkEventKey* event) { FlView* self = FL_VIEW(widget); return fl_keyboard_manager_handle_event( self->keyboard_manager, fl_key_event_new_from_gdk_event(gdk_event_copy( reinterpret_cast<GdkEvent*>(event)))); } // Implements GtkWidget::key_release_event. static gboolean fl_view_key_release_event(GtkWidget* widget, GdkEventKey* event) { FlView* self = FL_VIEW(widget); return fl_keyboard_manager_handle_event( self->keyboard_manager, fl_key_event_new_from_gdk_event(gdk_event_copy( reinterpret_cast<GdkEvent*>(event)))); } static void fl_view_class_init(FlViewClass* klass) { GObjectClass* object_class = G_OBJECT_CLASS(klass); object_class->set_property = fl_view_set_property; object_class->get_property = fl_view_get_property; object_class->notify = fl_view_notify; object_class->dispose = fl_view_dispose; GtkWidgetClass* widget_class = GTK_WIDGET_CLASS(klass); widget_class->key_press_event = fl_view_key_press_event; widget_class->key_release_event = fl_view_key_release_event; g_object_class_install_property( G_OBJECT_CLASS(klass), kPropFlutterProject, g_param_spec_object( "flutter-project", "flutter-project", "Flutter project in use", fl_dart_project_get_type(), static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS))); gtk_widget_class_set_accessible_type(GTK_WIDGET_CLASS(klass), fl_view_accessible_get_type()); } static void fl_view_init(FlView* self) { gtk_widget_set_can_focus(GTK_WIDGET(self), TRUE); self->event_box = gtk_event_box_new(); gtk_widget_set_hexpand(self->event_box, TRUE); gtk_widget_set_vexpand(self->event_box, TRUE); gtk_container_add(GTK_CONTAINER(self), self->event_box); gtk_widget_show(self->event_box); gtk_widget_add_events(self->event_box, GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_SCROLL_MASK | GDK_SMOOTH_SCROLL_MASK); g_signal_connect_swapped(self->event_box, "button-press-event", G_CALLBACK(button_press_event_cb), self); g_signal_connect_swapped(self->event_box, "button-release-event", G_CALLBACK(button_release_event_cb), self); g_signal_connect_swapped(self->event_box, "scroll-event", G_CALLBACK(scroll_event_cb), self); g_signal_connect_swapped(self->event_box, "motion-notify-event", G_CALLBACK(motion_notify_event_cb), self); g_signal_connect_swapped(self->event_box, "enter-notify-event", G_CALLBACK(enter_notify_event_cb), self); g_signal_connect_swapped(self->event_box, "leave-notify-event", G_CALLBACK(leave_notify_event_cb), self); GtkGesture* zoom = gtk_gesture_zoom_new(self->event_box); g_signal_connect_swapped(zoom, "begin", G_CALLBACK(gesture_zoom_begin_cb), self); g_signal_connect_swapped(zoom, "scale-changed", G_CALLBACK(gesture_zoom_update_cb), self); g_signal_connect_swapped(zoom, "end", G_CALLBACK(gesture_zoom_end_cb), self); GtkGesture* rotate = gtk_gesture_rotate_new(self->event_box); g_signal_connect_swapped(rotate, "begin", G_CALLBACK(gesture_rotation_begin_cb), self); g_signal_connect_swapped(rotate, "angle-changed", G_CALLBACK(gesture_rotation_update_cb), self); g_signal_connect_swapped(rotate, "end", G_CALLBACK(gesture_rotation_end_cb), self); self->gl_area = GTK_GL_AREA(gtk_gl_area_new()); gtk_widget_show(GTK_WIDGET(self->gl_area)); gtk_container_add(GTK_CONTAINER(self->event_box), GTK_WIDGET(self->gl_area)); g_signal_connect_swapped(self->gl_area, "create-context", G_CALLBACK(create_context_cb), self); g_signal_connect_swapped(self->gl_area, "realize", G_CALLBACK(realize_cb), self); g_signal_connect_swapped(self->gl_area, "render", G_CALLBACK(render_cb), self); g_signal_connect_swapped(self->gl_area, "unrealize", G_CALLBACK(unrealize_cb), self); g_signal_connect_swapped(self, "size-allocate", G_CALLBACK(size_allocate_cb), self); } G_MODULE_EXPORT FlView* fl_view_new(FlDartProject* project) { return static_cast<FlView*>( g_object_new(fl_view_get_type(), "flutter-project", project, nullptr)); } G_MODULE_EXPORT FlEngine* fl_view_get_engine(FlView* self) { g_return_val_if_fail(FL_IS_VIEW(self), nullptr); return self->engine; } void fl_view_redraw(FlView* self) { g_return_if_fail(FL_IS_VIEW(self)); gtk_widget_queue_draw(GTK_WIDGET(self->gl_area)); } GHashTable* fl_view_get_keyboard_state(FlView* self) { g_return_val_if_fail(FL_IS_VIEW(self), nullptr); return fl_keyboard_manager_get_pressed_state(self->keyboard_manager); }
engine/shell/platform/linux/fl_view.cc/0
{ "file_path": "engine/shell/platform/linux/fl_view.cc", "repo_id": "engine", "token_count": 13123 }
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_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_METHOD_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_METHOD_CODEC_H_ #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif #include <gmodule.h> #include "fl_method_codec.h" G_BEGIN_DECLS G_MODULE_EXPORT G_DECLARE_FINAL_TYPE(FlJsonMethodCodec, fl_json_method_codec, FL, JSON_METHOD_CODEC, FlMethodCodec) /** * FlJsonMethodCodec: * * #FlJsonMessageCodec is an #FlMethodCodec that implements method calls using * the Flutter JSON message encoding. It should be used with an * #FlMethodChannel. * * #FlJsonMethodCodec matches the JSONMethodCodec class in the Flutter services * library. */ /** * fl_json_method_codec_new: * * Creates an #FlJsonMethodCodec. * * Returns: a new #FlJsonMethodCodec. */ FlJsonMethodCodec* fl_json_method_codec_new(); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_METHOD_CODEC_H_
engine/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h", "repo_id": "engine", "token_count": 556 }
358
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VIEW_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VIEW_H_ #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif #include <gmodule.h> #include <gtk/gtk.h> #include "fl_dart_project.h" #include "fl_engine.h" G_BEGIN_DECLS G_MODULE_EXPORT G_DECLARE_FINAL_TYPE(FlView, fl_view, FL, VIEW, GtkBox) /** * FlView: * * #FlView is a GTK widget that is capable of displaying a Flutter application. * * The following example shows how to set up a view in a GTK application: * |[<!-- language="C" --> * FlDartProject *project = fl_dart_project_new (); * FlView *view = fl_view_new (project); * gtk_widget_show (GTK_WIDGET (view)); * gtk_container_add (GTK_CONTAINER (parent), view); * * FlBinaryMessenger *messenger = * fl_engine_get_binary_messenger (fl_view_get_engine (view)); * setup_channels_or_plugins (messenger); * ]| */ /** * fl_view_new: * @project: The project to show. * * Creates a widget to show Flutter application. * * Returns: a new #FlView. */ FlView* fl_view_new(FlDartProject* project); /** * fl_view_get_engine: * @view: an #FlView. * * Gets the engine being rendered in the view. * * Returns: an #FlEngine. */ FlEngine* fl_view_get_engine(FlView* view); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VIEW_H_
engine/shell/platform/linux/public/flutter_linux/fl_view.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_view.h", "repo_id": "engine", "token_count": 642 }
359
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/testing/mock_plugin_registrar.h" struct _FlMockPluginRegistrar { GObject parent_instance; FlBinaryMessenger* messenger; FlTextureRegistrar* texture_registrar; }; static void fl_mock_plugin_registrar_iface_init( FlPluginRegistrarInterface* iface); G_DEFINE_TYPE_WITH_CODE( FlMockPluginRegistrar, fl_mock_plugin_registrar, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE(fl_plugin_registrar_get_type(), fl_mock_plugin_registrar_iface_init)) static void fl_mock_plugin_registrar_dispose(GObject* object) { FlMockPluginRegistrar* self = FL_MOCK_PLUGIN_REGISTRAR(object); g_clear_object(&self->messenger); g_clear_object(&self->texture_registrar); G_OBJECT_CLASS(fl_mock_plugin_registrar_parent_class)->dispose(object); } static void fl_mock_plugin_registrar_class_init( FlMockPluginRegistrarClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_mock_plugin_registrar_dispose; } static FlBinaryMessenger* get_messenger(FlPluginRegistrar* registrar) { FlMockPluginRegistrar* self = FL_MOCK_PLUGIN_REGISTRAR(registrar); return self->messenger; } static FlTextureRegistrar* get_texture_registrar(FlPluginRegistrar* registrar) { FlMockPluginRegistrar* self = FL_MOCK_PLUGIN_REGISTRAR(registrar); return self->texture_registrar; } static FlView* get_view(FlPluginRegistrar* registrar) { return NULL; } static void fl_mock_plugin_registrar_iface_init( FlPluginRegistrarInterface* iface) { iface->get_messenger = get_messenger; iface->get_texture_registrar = get_texture_registrar; iface->get_view = get_view; } static void fl_mock_plugin_registrar_init(FlMockPluginRegistrar* self) {} FlPluginRegistrar* fl_mock_plugin_registrar_new( FlBinaryMessenger* messenger, FlTextureRegistrar* texture_registrar) { FlMockPluginRegistrar* registrar = FL_MOCK_PLUGIN_REGISTRAR( g_object_new(fl_mock_plugin_registrar_get_type(), NULL)); registrar->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger)); registrar->texture_registrar = FL_TEXTURE_REGISTRAR(g_object_ref(texture_registrar)); return FL_PLUGIN_REGISTRAR(registrar); }
engine/shell/platform/linux/testing/mock_plugin_registrar.cc/0
{ "file_path": "engine/shell/platform/linux/testing/mock_plugin_registrar.cc", "repo_id": "engine", "token_count": 916 }
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. #include "flutter/shell/platform/windows/accessibility_bridge_windows.h" #include "flutter/fml/logging.h" #include "flutter/shell/platform/windows/flutter_platform_node_delegate_windows.h" #include "flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate_base.h" namespace flutter { AccessibilityBridgeWindows::AccessibilityBridgeWindows(FlutterWindowsView* view) : view_(view) { FML_DCHECK(view_); } void AccessibilityBridgeWindows::OnAccessibilityEvent( ui::AXEventGenerator::TargetedEvent targeted_event) { ui::AXNode* ax_node = targeted_event.node; ui::AXEventGenerator::Event event_type = targeted_event.event_params.event; auto node_delegate = GetFlutterPlatformNodeDelegateFromID(ax_node->id()).lock(); FML_DCHECK(node_delegate) << "No FlutterPlatformNodeDelegate found for node ID " << ax_node->id(); std::shared_ptr<FlutterPlatformNodeDelegateWindows> win_delegate = std::static_pointer_cast<FlutterPlatformNodeDelegateWindows>( node_delegate); switch (event_type) { case ui::AXEventGenerator::Event::ALERT: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kAlert); break; case ui::AXEventGenerator::Event::CHECKED_STATE_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kValueChanged); break; case ui::AXEventGenerator::Event::CHILDREN_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kChildrenChanged); break; case ui::AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED: { // An event indicating a change in document selection should be fired // only for the focused node whose selection has changed. If a valid // caret and selection exist in the app tree, they must both be within // the focus node. auto focus_delegate = GetFocusedNode().lock(); if (focus_delegate) { win_delegate = std::static_pointer_cast<FlutterPlatformNodeDelegateWindows>( focus_delegate); } DispatchWinAccessibilityEvent( win_delegate, ax::mojom::Event::kDocumentSelectionChanged); break; } case ui::AXEventGenerator::Event::FOCUS_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kFocus); SetFocus(win_delegate); break; case ui::AXEventGenerator::Event::IGNORED_CHANGED: if (ax_node->IsIgnored()) { DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kHide); } break; case ui::AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kTextChanged); break; case ui::AXEventGenerator::Event::LIVE_REGION_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kLiveRegionChanged); break; case ui::AXEventGenerator::Event::NAME_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kTextChanged); break; case ui::AXEventGenerator::Event::SCROLL_HORIZONTAL_POSITION_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kScrollPositionChanged); break; case ui::AXEventGenerator::Event::SCROLL_VERTICAL_POSITION_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kScrollPositionChanged); break; case ui::AXEventGenerator::Event::SELECTED_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kValueChanged); break; case ui::AXEventGenerator::Event::SELECTED_CHILDREN_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kSelectedChildrenChanged); break; case ui::AXEventGenerator::Event::SUBTREE_CREATED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kShow); break; case ui::AXEventGenerator::Event::VALUE_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kValueChanged); break; case ui::AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED: DispatchWinAccessibilityEvent(win_delegate, ax::mojom::Event::kStateChanged); break; case ui::AXEventGenerator::Event::ACCESS_KEY_CHANGED: case ui::AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED: case ui::AXEventGenerator::Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::ATOMIC_CHANGED: case ui::AXEventGenerator::Event::AUTO_COMPLETE_CHANGED: case ui::AXEventGenerator::Event::BUSY_CHANGED: case ui::AXEventGenerator::Event::CLASS_NAME_CHANGED: case ui::AXEventGenerator::Event::COLLAPSED: case ui::AXEventGenerator::Event::CONTROLS_CHANGED: case ui::AXEventGenerator::Event::DESCRIBED_BY_CHANGED: case ui::AXEventGenerator::Event::DESCRIPTION_CHANGED: case ui::AXEventGenerator::Event::DOCUMENT_TITLE_CHANGED: case ui::AXEventGenerator::Event::DROPEFFECT_CHANGED: case ui::AXEventGenerator::Event::ENABLED_CHANGED: case ui::AXEventGenerator::Event::EXPANDED: case ui::AXEventGenerator::Event::FLOW_FROM_CHANGED: case ui::AXEventGenerator::Event::FLOW_TO_CHANGED: case ui::AXEventGenerator::Event::GRABBED_CHANGED: case ui::AXEventGenerator::Event::HASPOPUP_CHANGED: case ui::AXEventGenerator::Event::HIERARCHICAL_LEVEL_CHANGED: case ui::AXEventGenerator::Event::INVALID_STATUS_CHANGED: case ui::AXEventGenerator::Event::KEY_SHORTCUTS_CHANGED: case ui::AXEventGenerator::Event::LABELED_BY_CHANGED: case ui::AXEventGenerator::Event::LANGUAGE_CHANGED: case ui::AXEventGenerator::Event::LAYOUT_INVALIDATED: case ui::AXEventGenerator::Event::LIVE_REGION_CREATED: case ui::AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED: case ui::AXEventGenerator::Event::LIVE_RELEVANT_CHANGED: case ui::AXEventGenerator::Event::LIVE_STATUS_CHANGED: case ui::AXEventGenerator::Event::LOAD_COMPLETE: case ui::AXEventGenerator::Event::LOAD_START: case ui::AXEventGenerator::Event::MENU_ITEM_SELECTED: case ui::AXEventGenerator::Event::MULTILINE_STATE_CHANGED: case ui::AXEventGenerator::Event::MULTISELECTABLE_STATE_CHANGED: case ui::AXEventGenerator::Event::OBJECT_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::PLACEHOLDER_CHANGED: case ui::AXEventGenerator::Event::PORTAL_ACTIVATED: case ui::AXEventGenerator::Event::POSITION_IN_SET_CHANGED: case ui::AXEventGenerator::Event::READONLY_CHANGED: case ui::AXEventGenerator::Event::RELATED_NODE_CHANGED: case ui::AXEventGenerator::Event::REQUIRED_STATE_CHANGED: case ui::AXEventGenerator::Event::ROLE_CHANGED: case ui::AXEventGenerator::Event::ROW_COUNT_CHANGED: case ui::AXEventGenerator::Event::SET_SIZE_CHANGED: case ui::AXEventGenerator::Event::SORT_CHANGED: case ui::AXEventGenerator::Event::STATE_CHANGED: case ui::AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::VALUE_MAX_CHANGED: case ui::AXEventGenerator::Event::VALUE_MIN_CHANGED: case ui::AXEventGenerator::Event::VALUE_STEP_CHANGED: // Unhandled event type. break; } } void AccessibilityBridgeWindows::DispatchAccessibilityAction( AccessibilityNodeId target, FlutterSemanticsAction action, fml::MallocMapping data) { view_->GetEngine()->DispatchSemanticsAction(target, action, std::move(data)); } std::shared_ptr<FlutterPlatformNodeDelegate> AccessibilityBridgeWindows::CreateFlutterPlatformNodeDelegate() { return std::make_shared<FlutterPlatformNodeDelegateWindows>( shared_from_this(), view_); } void AccessibilityBridgeWindows::DispatchWinAccessibilityEvent( std::shared_ptr<FlutterPlatformNodeDelegateWindows> node_delegate, ax::mojom::Event event_type) { node_delegate->DispatchWinAccessibilityEvent(event_type); } void AccessibilityBridgeWindows::SetFocus( std::shared_ptr<FlutterPlatformNodeDelegateWindows> node_delegate) { node_delegate->SetFocus(); } gfx::NativeViewAccessible AccessibilityBridgeWindows::GetChildOfAXFragmentRoot() { ui::AXPlatformNodeDelegate* root_delegate = RootDelegate(); if (!root_delegate) { return nullptr; } return root_delegate->GetNativeViewAccessible(); } gfx::NativeViewAccessible AccessibilityBridgeWindows::GetParentOfAXFragmentRoot() { return nullptr; } bool AccessibilityBridgeWindows::IsAXFragmentRootAControlElement() { return true; } std::weak_ptr<FlutterPlatformNodeDelegate> AccessibilityBridgeWindows::GetFocusedNode() { ui::AXNode::AXID focus_id = GetAXTreeData().sel_focus_object_id; return GetFlutterPlatformNodeDelegateFromID(focus_id); } } // namespace flutter
engine/shell/platform/windows/accessibility_bridge_windows.cc/0
{ "file_path": "engine/shell/platform/windows/accessibility_bridge_windows.cc", "repo_id": "engine", "token_count": 3753 }
361
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_WINDOWS_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_WINDOWS_H_ #include <flutter_windows.h> #include <windows.h> #include <memory> #include <optional> #include "flutter_view.h" #include "plugin_registrar.h" namespace flutter { // A delegate callback for WindowProc delegation. // // Implementations should return a value only if they have handled the message // and want to stop all further handling. using WindowProcDelegate = std::function<std::optional< LRESULT>(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)>; // An extension to PluginRegistrar providing access to Windows-specific // functionality. class PluginRegistrarWindows : public PluginRegistrar { public: // Creates a new PluginRegistrar. |core_registrar| and the messenger it // provides must remain valid as long as this object exists. explicit PluginRegistrarWindows( FlutterDesktopPluginRegistrarRef core_registrar) : PluginRegistrar(core_registrar) { FlutterDesktopViewRef implicit_view = FlutterDesktopPluginRegistrarGetView(core_registrar); if (implicit_view) { implicit_view_ = std::make_unique<FlutterView>(implicit_view); } } virtual ~PluginRegistrarWindows() { // Must be the first call. ClearPlugins(); // Explicitly cleared to facilitate destruction order testing. implicit_view_.reset(); } // Prevent copying. PluginRegistrarWindows(PluginRegistrarWindows const&) = delete; PluginRegistrarWindows& operator=(PluginRegistrarWindows const&) = delete; // Returns the implicit view, or nullptr if there is no implicit view. // // See: // https://api.flutter.dev/flutter/dart-ui/PlatformDispatcher/implicitView.html // // DEPRECATED: Use |GetViewById| instead. FlutterView* GetView() { return implicit_view_.get(); } // Returns the view with the given ID, or nullptr if the view does not exist. // // Destroying the shared pointer destroys the reference to the view; it does // not destroy the underlying view. std::shared_ptr<FlutterView> GetViewById(FlutterViewId view_id) const { FlutterDesktopViewRef view = FlutterDesktopPluginRegistrarGetViewById(registrar(), view_id); if (!view) { return nullptr; } return std::make_shared<FlutterView>(view); } // Registers |delegate| to receive WindowProc callbacks for the top-level // window containing this Flutter instance. Returns an ID that can be used to // unregister the handler. // // Delegates are not guaranteed to be called: // - The application may choose not to delegate WindowProc calls. // - If multiple plugins are registered, the first one that returns a value // from the delegate message will "win", and others will not be called. // The order of delegate calls is not defined. // // Delegates should be implemented as narrowly as possible, only returning // a value in cases where it's important that other delegates not run, to // minimize the chances of conflicts between plugins. int RegisterTopLevelWindowProcDelegate(WindowProcDelegate delegate) { if (window_proc_delegates_.empty()) { FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate( registrar(), PluginRegistrarWindows::OnTopLevelWindowProc, this); } int delegate_id = next_window_proc_delegate_id_++; window_proc_delegates_.emplace(delegate_id, std::move(delegate)); return delegate_id; } // Unregisters a previously registered delegate. void UnregisterTopLevelWindowProcDelegate(int proc_id) { window_proc_delegates_.erase(proc_id); if (window_proc_delegates_.empty()) { FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate( registrar(), PluginRegistrarWindows::OnTopLevelWindowProc); } } private: // A FlutterDesktopWindowProcCallback implementation that forwards back to // a PluginRegistarWindows instance provided as |user_data|. static bool OnTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, void* user_data, LRESULT* result) { const auto* registrar = static_cast<PluginRegistrarWindows*>(user_data); std::optional optional_result = registrar->CallTopLevelWindowProcDelegates( hwnd, message, wparam, lparam); if (optional_result) { *result = *optional_result; } return optional_result.has_value(); } std::optional<LRESULT> CallTopLevelWindowProcDelegates(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) const { std::optional<LRESULT> result; for (const auto& pair : window_proc_delegates_) { result = pair.second(hwnd, message, wparam, lparam); // Stop as soon as any delegate indicates that it has handled the message. if (result) { break; } } return result; } // The associated FlutterView, if any. std::unique_ptr<FlutterView> implicit_view_; // The next ID to return from RegisterWindowProcDelegate. int next_window_proc_delegate_id_ = 1; std::map<int, WindowProcDelegate> window_proc_delegates_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_WINDOWS_H_
engine/shell/platform/windows/client_wrapper/include/flutter/plugin_registrar_windows.h/0
{ "file_path": "engine/shell/platform/windows/client_wrapper/include/flutter/plugin_registrar_windows.h", "repo_id": "engine", "token_count": 2142 }
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. #include "flutter/shell/platform/windows/direct_manipulation.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/testing/mock_window_binding_handler_delegate.h" #include "gtest/gtest.h" using testing::_; namespace flutter { namespace testing { class MockIDirectManipulationViewport : public IDirectManipulationViewport { public: MockIDirectManipulationViewport() {} MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, AddRef, ULONG()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, Release, ULONG()); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, QueryInterface, HRESULT(REFIID, void**)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, Abandon, HRESULT()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ActivateConfiguration, HRESULT(DIRECTMANIPULATION_CONFIGURATION)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, AddConfiguration, HRESULT(DIRECTMANIPULATION_CONFIGURATION)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, AddContent, HRESULT(IDirectManipulationContent*)); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, AddEventHandler, HRESULT(HWND, IDirectManipulationViewportEventHandler*, DWORD*)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, Disable, HRESULT()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, Enable, HRESULT()); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, GetPrimaryContent, HRESULT(REFIID, void**)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, GetStatus, HRESULT(DIRECTMANIPULATION_STATUS*)); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTag, HRESULT(REFIID, void**, UINT32*)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, GetViewportRect, HRESULT(RECT*)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, ReleaseAllContacts, HRESULT()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, ReleaseContact, HRESULT(UINT32)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, RemoveConfiguration, HRESULT(DIRECTMANIPULATION_CONFIGURATION)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, RemoveContent, HRESULT(IDirectManipulationContent*)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, RemoveEventHandler, HRESULT(DWORD)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, SetChaining, HRESULT(DIRECTMANIPULATION_MOTION_TYPES)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, SetContact, HRESULT(UINT32)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, SetInputMode, HRESULT(DIRECTMANIPULATION_INPUT_MODE)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, SetManualGesture, HRESULT(DIRECTMANIPULATION_GESTURE_CONFIGURATION)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, SetTag, HRESULT(IUnknown*, UINT32)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, SetUpdateMode, HRESULT(DIRECTMANIPULATION_INPUT_MODE)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, SetViewportOptions, HRESULT(DIRECTMANIPULATION_VIEWPORT_OPTIONS)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, SetViewportRect, HRESULT(const RECT*)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, SetViewportTransform, HRESULT(const float*, DWORD)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, Stop, HRESULT()); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, SyncDisplayTransform, HRESULT(const float*, DWORD)); MOCK_METHOD5_WITH_CALLTYPE( STDMETHODCALLTYPE, ZoomToRect, HRESULT(const float, const float, const float, const float, BOOL)); private: FML_DISALLOW_COPY_AND_ASSIGN(MockIDirectManipulationViewport); }; class MockIDirectManipulationContent : public IDirectManipulationContent { public: MockIDirectManipulationContent() {} MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, AddRef, ULONG()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, Release, ULONG()); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, QueryInterface, HRESULT(REFIID, void**)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, GetContentRect, HRESULT(RECT*)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, GetContentTransform, HRESULT(float*, DWORD)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, GetOutputTransform, HRESULT(float*, DWORD)); MOCK_METHOD3_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTag, HRESULT(REFIID, void**, UINT32*)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, GetViewport, HRESULT(REFIID, void**)); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, SetContentRect, HRESULT(const RECT*)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, SetTag, HRESULT(IUnknown*, UINT32)); MOCK_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, SyncContentTransform, HRESULT(const float*, DWORD)); private: FML_DISALLOW_COPY_AND_ASSIGN(MockIDirectManipulationContent); }; TEST(DirectManipulationTest, TestGesture) { MockIDirectManipulationContent content; MockWindowBindingHandlerDelegate delegate; MockIDirectManipulationViewport viewport; const float scale = 1.5; const float pan_x = 32.0; const float pan_y = 16.0; const int DISPLAY_WIDTH = 800; const int DISPLAY_HEIGHT = 600; auto owner = std::make_unique<DirectManipulationOwner>(nullptr); owner->SetBindingHandlerDelegate(&delegate); auto handler = fml::MakeRefCounted<DirectManipulationEventHandler>(owner.get()); int32_t device_id = (int32_t) reinterpret_cast<int64_t>(handler.get()); EXPECT_CALL(viewport, GetPrimaryContent(_, _)) .WillOnce(::testing::Invoke([&content](REFIID in, void** out) { *out = &content; return S_OK; })) .RetiresOnSaturation(); EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke([scale](float* transform, DWORD size) { transform[0] = 1.0f; transform[4] = 0.0; transform[5] = 0.0; return S_OK; })) .RetiresOnSaturation(); EXPECT_CALL(delegate, OnPointerPanZoomStart(device_id)); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_RUNNING, DIRECTMANIPULATION_READY); EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke( [scale, pan_x, pan_y](float* transform, DWORD size) { transform[0] = scale; transform[4] = pan_x; transform[5] = pan_y; return S_OK; })); EXPECT_CALL(delegate, OnPointerPanZoomUpdate(device_id, pan_x, pan_y, scale, 0)); handler->OnContentUpdated((IDirectManipulationViewport*)&viewport, (IDirectManipulationContent*)&content); EXPECT_CALL(delegate, OnPointerPanZoomEnd(device_id)); EXPECT_CALL(viewport, GetViewportRect(_)) .WillOnce(::testing::Invoke([DISPLAY_WIDTH, DISPLAY_HEIGHT](RECT* rect) { rect->left = 0; rect->top = 0; rect->right = DISPLAY_WIDTH; rect->bottom = DISPLAY_HEIGHT; return S_OK; })); EXPECT_CALL(viewport, ZoomToRect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT, false)) .WillOnce(::testing::Return(S_OK)); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_INERTIA, DIRECTMANIPULATION_RUNNING); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_READY, DIRECTMANIPULATION_INERTIA); } // Verify that scale mantissa rounding works as expected TEST(DirectManipulationTest, TestRounding) { MockIDirectManipulationContent content; MockWindowBindingHandlerDelegate delegate; MockIDirectManipulationViewport viewport; const float scale = 1.5; const int DISPLAY_WIDTH = 800; const int DISPLAY_HEIGHT = 600; auto owner = std::make_unique<DirectManipulationOwner>(nullptr); owner->SetBindingHandlerDelegate(&delegate); auto handler = fml::MakeRefCounted<DirectManipulationEventHandler>(owner.get()); int32_t device_id = (int32_t) reinterpret_cast<int64_t>(handler.get()); EXPECT_CALL(viewport, GetPrimaryContent(_, _)) .WillOnce(::testing::Invoke([&content](REFIID in, void** out) { *out = &content; return S_OK; })) .RetiresOnSaturation(); EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke([scale](float* transform, DWORD size) { transform[0] = 1.0f; transform[4] = 0.0; transform[5] = 0.0; return S_OK; })) .RetiresOnSaturation(); EXPECT_CALL(delegate, OnPointerPanZoomStart(device_id)); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_RUNNING, DIRECTMANIPULATION_READY); EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke([scale](float* transform, DWORD size) { transform[0] = 1.5000001f; transform[4] = 4.0; transform[5] = 0.0; return S_OK; })) .RetiresOnSaturation(); EXPECT_CALL(delegate, OnPointerPanZoomUpdate(device_id, 4.0, 0, 1.5000001f, 0)) .Times(0); EXPECT_CALL(delegate, OnPointerPanZoomUpdate(device_id, 4.0, 0, 1.5f, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke([scale](float* transform, DWORD size) { transform[0] = 1.50000065f; transform[4] = 2.0; transform[5] = 0.0; return S_OK; })) .RetiresOnSaturation(); EXPECT_CALL(delegate, OnPointerPanZoomUpdate(device_id, 2.0, 0, 1.50000065f, 0)) .Times(0); EXPECT_CALL(delegate, OnPointerPanZoomUpdate(device_id, 2.0, 0, 1.50000047f, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(delegate, OnPointerPanZoomEnd(device_id)); EXPECT_CALL(viewport, GetViewportRect(_)) .WillOnce(::testing::Invoke([DISPLAY_WIDTH, DISPLAY_HEIGHT](RECT* rect) { rect->left = 0; rect->top = 0; rect->right = DISPLAY_WIDTH; rect->bottom = DISPLAY_HEIGHT; return S_OK; })); EXPECT_CALL(viewport, ZoomToRect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT, false)) .WillOnce(::testing::Return(S_OK)); handler->OnContentUpdated((IDirectManipulationViewport*)&viewport, (IDirectManipulationContent*)&content); handler->OnContentUpdated((IDirectManipulationViewport*)&viewport, (IDirectManipulationContent*)&content); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_INERTIA, DIRECTMANIPULATION_RUNNING); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_READY, DIRECTMANIPULATION_INERTIA); } TEST(DirectManipulationTest, TestInertiaCancelSentForUserCancel) { MockIDirectManipulationContent content; MockWindowBindingHandlerDelegate delegate; MockIDirectManipulationViewport viewport; const int DISPLAY_WIDTH = 800; const int DISPLAY_HEIGHT = 600; auto owner = std::make_unique<DirectManipulationOwner>(nullptr); owner->SetBindingHandlerDelegate(&delegate); auto handler = fml::MakeRefCounted<DirectManipulationEventHandler>(owner.get()); int32_t device_id = (int32_t) reinterpret_cast<int64_t>(handler.get()); // No need to mock the actual gesture, just start at the end. EXPECT_CALL(viewport, GetViewportRect(_)) .WillOnce(::testing::Invoke([DISPLAY_WIDTH, DISPLAY_HEIGHT](RECT* rect) { rect->left = 0; rect->top = 0; rect->right = DISPLAY_WIDTH; rect->bottom = DISPLAY_HEIGHT; return S_OK; })); EXPECT_CALL(viewport, ZoomToRect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT, false)) .WillOnce(::testing::Return(S_OK)); EXPECT_CALL(delegate, OnPointerPanZoomEnd(device_id)); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_INERTIA, DIRECTMANIPULATION_RUNNING); // Have pan_y change by 10 between inertia updates. EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke([](float* transform, DWORD size) { transform[0] = 1; transform[4] = 0; transform[5] = 100; return S_OK; })); handler->OnContentUpdated((IDirectManipulationViewport*)&viewport, (IDirectManipulationContent*)&content); EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke([](float* transform, DWORD size) { transform[0] = 1; transform[4] = 0; transform[5] = 110; return S_OK; })); handler->OnContentUpdated((IDirectManipulationViewport*)&viewport, (IDirectManipulationContent*)&content); // This looks like an interruption in the middle of synthetic inertia because // of user input. EXPECT_CALL(delegate, OnScrollInertiaCancel(device_id)); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_READY, DIRECTMANIPULATION_INERTIA); } TEST(DirectManipulationTest, TestInertiaCamcelNotSentAtInertiaEnd) { MockIDirectManipulationContent content; MockWindowBindingHandlerDelegate delegate; MockIDirectManipulationViewport viewport; const int DISPLAY_WIDTH = 800; const int DISPLAY_HEIGHT = 600; auto owner = std::make_unique<DirectManipulationOwner>(nullptr); owner->SetBindingHandlerDelegate(&delegate); auto handler = fml::MakeRefCounted<DirectManipulationEventHandler>(owner.get()); int32_t device_id = (int32_t) reinterpret_cast<int64_t>(handler.get()); // No need to mock the actual gesture, just start at the end. EXPECT_CALL(viewport, GetViewportRect(_)) .WillOnce(::testing::Invoke([DISPLAY_WIDTH, DISPLAY_HEIGHT](RECT* rect) { rect->left = 0; rect->top = 0; rect->right = DISPLAY_WIDTH; rect->bottom = DISPLAY_HEIGHT; return S_OK; })); EXPECT_CALL(viewport, ZoomToRect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT, false)) .WillOnce(::testing::Return(S_OK)); EXPECT_CALL(delegate, OnPointerPanZoomEnd(device_id)); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_INERTIA, DIRECTMANIPULATION_RUNNING); // Have no change in pan between events. EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke([](float* transform, DWORD size) { transform[0] = 1; transform[4] = 0; transform[5] = 140; return S_OK; })); handler->OnContentUpdated((IDirectManipulationViewport*)&viewport, (IDirectManipulationContent*)&content); EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke([](float* transform, DWORD size) { transform[0] = 1; transform[4] = 0; transform[5] = 140; return S_OK; })); handler->OnContentUpdated((IDirectManipulationViewport*)&viewport, (IDirectManipulationContent*)&content); // OnScrollInertiaCancel should not be called. EXPECT_CALL(delegate, OnScrollInertiaCancel(device_id)).Times(0); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_READY, DIRECTMANIPULATION_INERTIA); } // Have some initial values in the matrix, only the differences should be // reported. TEST(DirectManipulationTest, TestGestureWithInitialData) { MockIDirectManipulationContent content; MockWindowBindingHandlerDelegate delegate; MockIDirectManipulationViewport viewport; const float scale = 1.5; const float pan_x = 32.0; const float pan_y = 16.0; const int DISPLAY_WIDTH = 800; const int DISPLAY_HEIGHT = 600; auto owner = std::make_unique<DirectManipulationOwner>(nullptr); owner->SetBindingHandlerDelegate(&delegate); auto handler = fml::MakeRefCounted<DirectManipulationEventHandler>(owner.get()); int32_t device_id = (int32_t) reinterpret_cast<int64_t>(handler.get()); EXPECT_CALL(viewport, GetPrimaryContent(_, _)) .WillOnce(::testing::Invoke([&content](REFIID in, void** out) { *out = &content; return S_OK; })) .RetiresOnSaturation(); EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke([scale](float* transform, DWORD size) { transform[0] = 2.0f; transform[4] = 234.0; transform[5] = 345.0; return S_OK; })) .RetiresOnSaturation(); EXPECT_CALL(delegate, OnPointerPanZoomStart(device_id)); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_RUNNING, DIRECTMANIPULATION_READY); EXPECT_CALL(content, GetContentTransform(_, 6)) .WillOnce(::testing::Invoke( [scale, pan_x, pan_y](float* transform, DWORD size) { transform[0] = 2.0f * scale; transform[4] = 234.0 + pan_x; transform[5] = 345.0 + pan_y; return S_OK; })); EXPECT_CALL(delegate, OnPointerPanZoomUpdate(device_id, pan_x, pan_y, scale, 0)); handler->OnContentUpdated((IDirectManipulationViewport*)&viewport, (IDirectManipulationContent*)&content); EXPECT_CALL(delegate, OnPointerPanZoomEnd(device_id)); EXPECT_CALL(viewport, GetViewportRect(_)) .WillOnce(::testing::Invoke([DISPLAY_WIDTH, DISPLAY_HEIGHT](RECT* rect) { rect->left = 0; rect->top = 0; rect->right = DISPLAY_WIDTH; rect->bottom = DISPLAY_HEIGHT; return S_OK; })); EXPECT_CALL(viewport, ZoomToRect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT, false)) .WillOnce(::testing::Return(S_OK)); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_INERTIA, DIRECTMANIPULATION_RUNNING); handler->OnViewportStatusChanged((IDirectManipulationViewport*)&viewport, DIRECTMANIPULATION_READY, DIRECTMANIPULATION_INERTIA); } } // namespace testing } // namespace flutter
engine/shell/platform/windows/direct_manipulation_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/direct_manipulation_unittests.cc", "repo_id": "engine", "token_count": 9883 }
363
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/event_watcher.h" namespace flutter { EventWatcher::EventWatcher(std::function<void()> callback) : callback_(callback) { handle_ = CreateEvent(NULL, TRUE, FALSE, NULL); RegisterWaitForSingleObject(&handle_for_wait_, handle_, &CallbackForWait, reinterpret_cast<void*>(this), INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD); } EventWatcher::~EventWatcher() { UnregisterWait(handle_for_wait_); CloseHandle(handle_); } HANDLE EventWatcher::GetHandle() { return handle_; } // static VOID CALLBACK EventWatcher::CallbackForWait(PVOID context, BOOLEAN) { EventWatcher* self = reinterpret_cast<EventWatcher*>(context); ResetEvent(self->handle_); self->callback_(); } } // namespace flutter
engine/shell/platform/windows/event_watcher.cc/0
{ "file_path": "engine/shell/platform/windows/event_watcher.cc", "repo_id": "engine", "token_count": 365 }
364
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOW_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOW_H_ #include <string> #include <vector> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/alert_platform_node_delegate.h" #include "flutter/shell/platform/common/geometry.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/windows/direct_manipulation.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" #include "flutter/shell/platform/windows/keyboard_manager.h" #include "flutter/shell/platform/windows/sequential_id_generator.h" #include "flutter/shell/platform/windows/text_input_manager.h" #include "flutter/shell/platform/windows/window_binding_handler.h" #include "flutter/shell/platform/windows/windows_lifecycle_manager.h" #include "flutter/shell/platform/windows/windows_proc_table.h" #include "flutter/shell/platform/windows/windowsx_shim.h" #include "flutter/third_party/accessibility/ax/platform/ax_fragment_root_delegate_win.h" #include "flutter/third_party/accessibility/ax/platform/ax_fragment_root_win.h" #include "flutter/third_party/accessibility/ax/platform/ax_platform_node_win.h" #include "flutter/third_party/accessibility/gfx/native_widget_types.h" namespace flutter { // A win32 flutter child window used as implementations for flutter view. In // the future, there will likely be a CoreWindow-based FlutterWindow as well. // At the point may make sense to dependency inject the native window rather // than inherit. class FlutterWindow : public KeyboardManager::WindowDelegate, public WindowBindingHandler { public: // Create flutter Window for use as child window FlutterWindow(int width, int height, std::shared_ptr<WindowsProcTable> windows_proc_table = nullptr, std::unique_ptr<TextInputManager> text_input_manager = nullptr); virtual ~FlutterWindow(); // Initializes as a child window with size using |width| and |height| and // |title| to identify the windowclass. Does not show window, window must be // parented into window hierarchy by caller. void InitializeChild(const char* title, unsigned int width, unsigned int height); // |KeyboardManager::WindowDelegate| virtual BOOL Win32PeekMessage(LPMSG lpMsg, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg) override; // |KeyboardManager::WindowDelegate| virtual uint32_t Win32MapVkToChar(uint32_t virtual_key) override; // |KeyboardManager::WindowDelegate| virtual UINT Win32DispatchMessage(UINT Msg, WPARAM wParam, LPARAM lParam) override; // Called when the DPI changes either when a // user drags the window between monitors of differing DPI or when the user // manually changes the scale factor. virtual void OnDpiScale(unsigned int dpi); // Called when a resize occurs. virtual void OnResize(unsigned int width, unsigned int height); // Called when a paint is requested. virtual void OnPaint(); // Called when the pointer moves within the // window bounds. virtual void OnPointerMove(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id, int modifiers_state); // Called when the a mouse button, determined by |button|, goes down. virtual void OnPointerDown(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id, UINT button); // Called when the a mouse button, determined by |button|, goes from // down to up virtual void OnPointerUp(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id, UINT button); // Called when the mouse leaves the window. virtual void OnPointerLeave(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id); // Called when the cursor should be set for the client area. virtual void OnSetCursor(); // |WindowBindingHandlerDelegate| virtual void OnText(const std::u16string& text) override; // |WindowBindingHandlerDelegate| virtual void OnKey(int key, int scancode, int action, char32_t character, bool extended, bool was_down, KeyEventCallback callback) override; // Called when IME composing begins. virtual void OnComposeBegin(); // Called when IME composing text is committed. virtual void OnComposeCommit(); // Called when IME composing ends. virtual void OnComposeEnd(); // Called when IME composing text or cursor position changes. virtual void OnComposeChange(const std::u16string& text, int cursor_pos); // |FlutterWindowBindingHandler| virtual void OnCursorRectUpdated(const Rect& rect) override; // |FlutterWindowBindingHandler| virtual void OnResetImeComposing() override; // Called when accessibility support is enabled or disabled. virtual void OnUpdateSemanticsEnabled(bool enabled); // Called when mouse scrollwheel input occurs. virtual void OnScroll(double delta_x, double delta_y, FlutterPointerDeviceKind device_kind, int32_t device_id); // Returns the root view accessibility node, or nullptr if none. virtual gfx::NativeViewAccessible GetNativeViewAccessible(); // |FlutterWindowBindingHandler| virtual void SetView(WindowBindingHandlerDelegate* view) override; // |FlutterWindowBindingHandler| virtual HWND GetWindowHandle() override; // |FlutterWindowBindingHandler| virtual float GetDpiScale() override; // |FlutterWindowBindingHandler| virtual PhysicalWindowBounds GetPhysicalWindowBounds() override; // |FlutterWindowBindingHandler| virtual void UpdateFlutterCursor(const std::string& cursor_name) override; // |FlutterWindowBindingHandler| virtual void SetFlutterCursor(HCURSOR cursor) override; // |FlutterWindowBindingHandler| virtual bool OnBitmapSurfaceCleared() override; // |FlutterWindowBindingHandler| virtual bool OnBitmapSurfaceUpdated(const void* allocation, size_t row_bytes, size_t height) override; // |FlutterWindowBindingHandler| virtual PointerLocation GetPrimaryPointerLocation() override; // Called when a theme change message is issued. virtual void OnThemeChange(); // |WindowBindingHandler| virtual AlertPlatformNodeDelegate* GetAlertDelegate() override; // |WindowBindingHandler| virtual ui::AXPlatformNodeWin* GetAlert() override; // Called to obtain a pointer to the fragment root delegate. virtual ui::AXFragmentRootDelegateWin* GetAxFragmentRootDelegate(); // Called on a resize or focus event. virtual void OnWindowStateEvent(WindowStateEvent event); protected: // Base constructor for mocks. FlutterWindow(); // Win32's DefWindowProc. // // Used as the fallback behavior of HandleMessage. Exposed for dependency // injection. virtual LRESULT Win32DefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); // Converts a c string to a wide unicode string. std::wstring NarrowToWide(const char* source); // Processes and route salient window messages for mouse handling, // size change and DPI. Delegates handling of these to member overloads that // inheriting classes can handle. LRESULT HandleMessage(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; // Called when the OS requests a COM object. // // The primary use of this function is to supply Windows with wrapped // semantics objects for use by Windows accessibility. virtual LRESULT OnGetObject(UINT const message, WPARAM const wparam, LPARAM const lparam); // Called when a window is activated in order to configure IME support for // multi-step text input. virtual void OnImeSetContext(UINT const message, WPARAM const wparam, LPARAM const lparam); // Called when multi-step text input begins when using an IME. virtual void OnImeStartComposition(UINT const message, WPARAM const wparam, LPARAM const lparam); // Called when edits/commit of multi-step text input occurs when using an IME. virtual void OnImeComposition(UINT const message, WPARAM const wparam, LPARAM const lparam); // Called when multi-step text input ends when using an IME. virtual void OnImeEndComposition(UINT const message, WPARAM const wparam, LPARAM const lparam); // Called when the user triggers an IME-specific request such as input // reconversion, where an existing input sequence is returned to composing // mode to select an alternative candidate conversion. virtual void OnImeRequest(UINT const message, WPARAM const wparam, LPARAM const lparam); // Called when the app ends IME composing, such as when the text input client // is cleared or changed. virtual void AbortImeComposing(); // Called when the cursor rect has been updated. // // |rect| is in Win32 window coordinates. virtual void UpdateCursorRect(const Rect& rect); UINT GetCurrentDPI(); UINT GetCurrentWidth(); UINT GetCurrentHeight(); // Returns the current pixel per scroll tick value. virtual float GetScrollOffsetMultiplier(); // Delegate to a alert_node_ used to set the announcement text. std::unique_ptr<AlertPlatformNodeDelegate> alert_delegate_; // Accessibility node that represents an alert. std::unique_ptr<ui::AXPlatformNodeWin> alert_node_; // Handles running DirectManipulation on the window to receive trackpad // gestures. std::unique_ptr<DirectManipulationOwner> direct_manipulation_owner_; private: // OS callback called by message pump. Handles the WM_NCCREATE message which // is passed when the non-client area is being created and enables automatic // non-client DPI scaling so that the non-client area automatically // responsponds to changes in DPI. All other messages are handled by // MessageHandler. static LRESULT CALLBACK WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; // WM_DPICHANGED_BEFOREPARENT defined in more recent Windows // SDK static const long kWmDpiChangedBeforeParent = 0x02E2; // Timer identifier for DirectManipulation gesture polling. static const int kDirectManipulationTimer = 1; // Release OS resources associated with the window. void Destroy(); // Registers a window class with default style attributes, cursor and // icon. WNDCLASS RegisterWindowClass(std::wstring& title); // Retrieves a class instance pointer for |window| static FlutterWindow* GetThisFromHandle(HWND const window) noexcept; // Activates tracking for a "mouse leave" event. void TrackMouseLeaveEvent(HWND hwnd); // Stores new width and height and calls |OnResize| to notify inheritors void HandleResize(UINT width, UINT height); // Updates the cached scroll_offset_multiplier_ value based off OS settings. void UpdateScrollOffsetMultiplier(); // Creates the ax_fragment_root_, alert_delegate_ and alert_node_ if they do // not yet exist. // Once set, they are not reset to nullptr. void CreateAxFragmentRoot(); // A pointer to a FlutterWindowsView that can be used to update engine // windowing and input state. WindowBindingHandlerDelegate* binding_handler_delegate_ = nullptr; // The last cursor set by Flutter. Defaults to the arrow cursor. HCURSOR current_cursor_; // The cursor rect set by Flutter. RECT cursor_rect_; // The window receives resize and focus messages before its view is set, so // these values cache the state of the window in the meantime so that the // proper application lifecycle state can be updated once the view is set. bool restored_ = false; bool focused_ = false; int current_dpi_ = 0; int current_width_ = 0; int current_height_ = 0; // Holds the conversion factor from lines scrolled to pixels scrolled. float scroll_offset_multiplier_; // Member variable to hold window handle. HWND window_handle_ = nullptr; // Member variable to hold the window title. std::wstring window_class_name_; // Set to true to be notified when the mouse leaves the window. bool tracking_mouse_leave_ = false; // Keeps track of the last key code produced by a WM_KEYDOWN or WM_SYSKEYDOWN // message. int keycode_for_char_message_ = 0; // Keeps track of the last mouse coordinates by a WM_MOUSEMOVE message. double mouse_x_ = 0; double mouse_y_ = 0; // Generates touch point IDs for touch events. SequentialIdGenerator touch_id_generator_; // Abstracts Windows APIs that may not be available on all supported versions // of Windows. std::shared_ptr<WindowsProcTable> windows_proc_table_; // Manages IME state. std::unique_ptr<TextInputManager> text_input_manager_; // Manages IME state. std::unique_ptr<KeyboardManager> keyboard_manager_; // Used for temporarily storing the WM_TOUCH-provided touch points. std::vector<TOUCHINPUT> touch_points_; // Implements IRawElementProviderFragmentRoot when UIA is enabled. std::unique_ptr<ui::AXFragmentRootWin> ax_fragment_root_; // Allow WindowAXFragmentRootDelegate to access protected method. friend class WindowAXFragmentRootDelegate; FML_DISALLOW_COPY_AND_ASSIGN(FlutterWindow); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOW_H_
engine/shell/platform/windows/flutter_window.h/0
{ "file_path": "engine/shell/platform/windows/flutter_window.h", "repo_id": "engine", "token_count": 5420 }
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. #include "flutter/shell/platform/windows/keyboard_key_channel_handler.h" #include <windows.h> #include "flutter/fml/logging.h" #include "flutter/shell/platform/common/json_message_codec.h" #include "flutter/shell/platform/windows/keyboard_utils.h" namespace flutter { namespace { static constexpr char kChannelName[] = "flutter/keyevent"; static constexpr char kKeyCodeKey[] = "keyCode"; static constexpr char kScanCodeKey[] = "scanCode"; static constexpr char kCharacterCodePointKey[] = "characterCodePoint"; static constexpr char kModifiersKey[] = "modifiers"; static constexpr char kKeyMapKey[] = "keymap"; static constexpr char kTypeKey[] = "type"; static constexpr char kHandledKey[] = "handled"; static constexpr char kWindowsKeyMap[] = "windows"; static constexpr char kKeyUp[] = "keyup"; static constexpr char kKeyDown[] = "keydown"; // The maximum number of pending events to keep before // emitting a warning on the console about unhandled events. static constexpr int kMaxPendingEvents = 1000; // The bit for a scancode indicating the key is extended. // // Win32 defines some keys to be "extended", such as ShiftRight, which shares // the same scancode as its non-extended counterpart, such as ShiftLeft. In // Chromium's scancode table, from which Flutter's physical key list is // derived, these keys are marked with this bit. See // https://chromium.googlesource.com/codesearch/chromium/src/+/refs/heads/main/ui/events/keycodes/dom/dom_code_data.inc static constexpr int kScancodeExtended = 0xe000; // Re-definition of the modifiers for compatibility with the Flutter framework. // These have to be in sync with the framework's RawKeyEventDataWindows // modifiers definition. // https://github.com/flutter/flutter/blob/19ff596979e407c484a32f4071420fca4f4c885f/packages/flutter/lib/src/services/raw_keyboard_windows.dart#L203 static constexpr int kShift = 1 << 0; static constexpr int kShiftLeft = 1 << 1; static constexpr int kShiftRight = 1 << 2; static constexpr int kControl = 1 << 3; static constexpr int kControlLeft = 1 << 4; static constexpr int kControlRight = 1 << 5; static constexpr int kAlt = 1 << 6; static constexpr int kAltLeft = 1 << 7; static constexpr int kAltRight = 1 << 8; static constexpr int kWinLeft = 1 << 9; static constexpr int kWinRight = 1 << 10; static constexpr int kCapsLock = 1 << 11; static constexpr int kNumLock = 1 << 12; static constexpr int kScrollLock = 1 << 13; /// Calls GetKeyState() an all modifier keys and packs the result in an int, /// with the re-defined values declared above for compatibility with the Flutter /// framework. int GetModsForKeyState() { int mods = 0; if (GetKeyState(VK_SHIFT) < 0) mods |= kShift; if (GetKeyState(VK_LSHIFT) < 0) mods |= kShiftLeft; if (GetKeyState(VK_RSHIFT) < 0) mods |= kShiftRight; if (GetKeyState(VK_CONTROL) < 0) mods |= kControl; if (GetKeyState(VK_LCONTROL) < 0) mods |= kControlLeft; if (GetKeyState(VK_RCONTROL) < 0) mods |= kControlRight; if (GetKeyState(VK_MENU) < 0) mods |= kAlt; if (GetKeyState(VK_LMENU) < 0) mods |= kAltLeft; if (GetKeyState(VK_RMENU) < 0) mods |= kAltRight; if (GetKeyState(VK_LWIN) < 0) mods |= kWinLeft; if (GetKeyState(VK_RWIN) < 0) mods |= kWinRight; if (GetKeyState(VK_CAPITAL) < 0) mods |= kCapsLock; if (GetKeyState(VK_NUMLOCK) < 0) mods |= kNumLock; if (GetKeyState(VK_SCROLL) < 0) mods |= kScrollLock; return mods; } } // namespace KeyboardKeyChannelHandler::KeyboardKeyChannelHandler( flutter::BinaryMessenger* messenger) : channel_( std::make_unique<flutter::BasicMessageChannel<rapidjson::Document>>( messenger, kChannelName, &flutter::JsonMessageCodec::GetInstance())) {} KeyboardKeyChannelHandler::~KeyboardKeyChannelHandler() = default; void KeyboardKeyChannelHandler::SyncModifiersIfNeeded(int modifiers_state) { // Do nothing. } std::map<uint64_t, uint64_t> KeyboardKeyChannelHandler::GetPressedState() { // Returns an empty state because it will never be called. // KeyboardKeyEmbedderHandler is the only KeyboardKeyHandlerDelegate to handle // GetPressedState() calls. std::map<uint64_t, uint64_t> empty_state; return empty_state; } void KeyboardKeyChannelHandler::KeyboardHook( int key, int scancode, int action, char32_t character, bool extended, bool was_down, std::function<void(bool)> callback) { // TODO: Translate to a cross-platform key code system rather than passing // the native key code. rapidjson::Document event(rapidjson::kObjectType); auto& allocator = event.GetAllocator(); event.AddMember(kKeyCodeKey, key, allocator); event.AddMember(kScanCodeKey, scancode | (extended ? kScancodeExtended : 0), allocator); event.AddMember(kCharacterCodePointKey, UndeadChar(character), allocator); event.AddMember(kKeyMapKey, kWindowsKeyMap, allocator); event.AddMember(kModifiersKey, GetModsForKeyState(), allocator); switch (action) { case WM_SYSKEYDOWN: case WM_KEYDOWN: event.AddMember(kTypeKey, kKeyDown, allocator); break; case WM_SYSKEYUP: case WM_KEYUP: event.AddMember(kTypeKey, kKeyUp, allocator); break; default: FML_LOG(WARNING) << "Unknown key event action: " << action; callback(false); return; } channel_->Send(event, [callback = std::move(callback)](const uint8_t* reply, size_t reply_size) { auto decoded = flutter::JsonMessageCodec::GetInstance().DecodeMessage( reply, reply_size); bool handled = decoded ? (*decoded)[kHandledKey].GetBool() : false; callback(handled); }); } } // namespace flutter
engine/shell/platform/windows/keyboard_key_channel_handler.cc/0
{ "file_path": "engine/shell/platform/windows/keyboard_key_channel_handler.cc", "repo_id": "engine", "token_count": 2119 }
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_WINDOWS_PLATFORM_HANDLER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_PLATFORM_HANDLER_H_ #include <Windows.h> #include <functional> #include <memory> #include <optional> #include <variant> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/method_channel.h" #include "rapidjson/document.h" namespace flutter { class FlutterWindowsEngine; class ScopedClipboardInterface; // Indicates whether an exit request may be canceled by the framework. // These values must be kept in sync with kExitTypeNames in platform_handler.cc enum class AppExitType { required, cancelable, }; // Handler for internal system channels. class PlatformHandler { public: explicit PlatformHandler( BinaryMessenger* messenger, FlutterWindowsEngine* engine, std::optional<std::function<std::unique_ptr<ScopedClipboardInterface>()>> scoped_clipboard_provider = std::nullopt); virtual ~PlatformHandler(); // String values used for encoding/decoding exit requests. static constexpr char kExitTypeCancelable[] = "cancelable"; static constexpr char kExitTypeRequired[] = "required"; // Send a request to the framework to test if a cancelable exit request // should be canceled or honored. hwnd is std::nullopt for a request to quit // the process, otherwise it holds the HWND of the window that initiated the // quit request. virtual void RequestAppExit(std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, AppExitType exit_type, UINT exit_code); protected: // Gets plain text from the clipboard and provides it to |result| as the // value in a dictionary with the given |key|. virtual void GetPlainText( std::unique_ptr<MethodResult<rapidjson::Document>> result, std::string_view key); // Provides a boolean to |result| as the value in a dictionary at key // "value" representing whether or not the clipboard has a non-empty string. virtual void GetHasStrings( std::unique_ptr<MethodResult<rapidjson::Document>> result); // Sets the clipboard's plain text to |text|, and reports the result (either // an error, or null for success) to |result|. virtual void SetPlainText( const std::string& text, std::unique_ptr<MethodResult<rapidjson::Document>> result); virtual void SystemSoundPlay( const std::string& sound_type, std::unique_ptr<MethodResult<rapidjson::Document>> result); // Handle a request from the framework to exit the application. virtual void SystemExitApplication( AppExitType exit_type, UINT exit_code, std::unique_ptr<MethodResult<rapidjson::Document>> result); // Actually quit the application with the provided exit code. hwnd is // std::nullopt for a request to quit the process, otherwise it holds the HWND // of the window that initiated the quit request. virtual void QuitApplication(std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, UINT exit_code); // Callback from when the cancelable exit request response request is // answered by the framework. hwnd is std::nullopt for a request to quit the // process, otherwise it holds the HWND of the window that initiated the quit // request. virtual void RequestAppExitSuccess(std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, const rapidjson::Document* result, UINT exit_code); // A error type to use for error responses. static constexpr char kClipboardError[] = "Clipboard error"; static constexpr char kSoundTypeAlert[] = "SystemSoundType.alert"; private: // Called when a method is called on |channel_|; void HandleMethodCall( const MethodCall<rapidjson::Document>& method_call, std::unique_ptr<MethodResult<rapidjson::Document>> result); // The MethodChannel used for communication with the Flutter engine. std::unique_ptr<MethodChannel<rapidjson::Document>> channel_; // A reference to the Flutter engine. FlutterWindowsEngine* engine_; // A scoped clipboard provider that can be passed in for mocking in tests. // Use this to acquire clipboard in each operation to avoid blocking clipboard // unnecessarily. See flutter/flutter#103205. std::function<std::unique_ptr<ScopedClipboardInterface>()> scoped_clipboard_provider_; FML_DISALLOW_COPY_AND_ASSIGN(PlatformHandler); }; // A public interface for ScopedClipboard, so that it can be injected into // PlatformHandler. class ScopedClipboardInterface { public: virtual ~ScopedClipboardInterface(){}; // Attempts to open the clipboard for the given window, returning the error // code in the case of failure and 0 otherwise. virtual int Open(HWND window) = 0; // Returns true if there is string data available to get. virtual bool HasString() = 0; // Returns string data from the clipboard. // // If getting a string fails, returns the error code. // // Open(...) must have succeeded to call this method. virtual std::variant<std::wstring, int> GetString() = 0; // Sets the string content of the clipboard, returning the error code on // failure and 0 otherwise. // // Open(...) must have succeeded to call this method. virtual int SetString(const std::wstring string) = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_PLATFORM_HANDLER_H_
engine/shell/platform/windows/platform_handler.h/0
{ "file_path": "engine/shell/platform/windows/platform_handler.h", "repo_id": "engine", "token_count": 2049 }
367
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/task_runner.h" #include <atomic> #include <utility> namespace flutter { TaskRunner::TaskRunner(CurrentTimeProc get_current_time, const TaskExpiredCallback& on_task_expired) : get_current_time_(get_current_time), on_task_expired_(std::move(on_task_expired)) { main_thread_id_ = GetCurrentThreadId(); task_runner_window_ = TaskRunnerWindow::GetSharedInstance(); task_runner_window_->AddDelegate(this); } TaskRunner::~TaskRunner() { task_runner_window_->RemoveDelegate(this); } std::chrono::nanoseconds TaskRunner::ProcessTasks() { const TaskTimePoint now = GetCurrentTimeForTask(); std::vector<Task> expired_tasks; // Process expired tasks. { std::lock_guard<std::mutex> lock(task_queue_mutex_); while (!task_queue_.empty()) { const auto& top = task_queue_.top(); // If this task (and all tasks after this) has not yet expired, there is // nothing more to do. Quit iterating. if (top.fire_time > now) { break; } // Make a record of the expired task. Do NOT service the task here // because we are still holding onto the task queue mutex. We don't want // other threads to block on posting tasks onto this thread till we are // done processing expired tasks. expired_tasks.push_back(task_queue_.top()); // Remove the tasks from the delayed tasks queue. task_queue_.pop(); } } // Fire expired tasks. { // Flushing tasks here without holing onto the task queue mutex. for (const auto& task : expired_tasks) { if (auto flutter_task = std::get_if<FlutterTask>(&task.variant)) { on_task_expired_(flutter_task); } else if (auto closure = std::get_if<TaskClosure>(&task.variant)) (*closure)(); } } // Calculate duration to sleep for on next iteration. { std::lock_guard<std::mutex> lock(task_queue_mutex_); const auto next_wake = task_queue_.empty() ? TaskTimePoint::max() : task_queue_.top().fire_time; return std::min(next_wake - now, std::chrono::nanoseconds::max()); } } TaskRunner::TaskTimePoint TaskRunner::TimePointFromFlutterTime( uint64_t flutter_target_time_nanos) const { const auto now = GetCurrentTimeForTask(); const auto flutter_duration = flutter_target_time_nanos - get_current_time_(); return now + std::chrono::nanoseconds(flutter_duration); } void TaskRunner::PostFlutterTask(FlutterTask flutter_task, uint64_t flutter_target_time_nanos) { Task task; task.fire_time = TimePointFromFlutterTime(flutter_target_time_nanos); task.variant = flutter_task; EnqueueTask(std::move(task)); } void TaskRunner::PostTask(TaskClosure closure) { Task task; task.fire_time = GetCurrentTimeForTask(); task.variant = std::move(closure); EnqueueTask(std::move(task)); } void TaskRunner::EnqueueTask(Task task) { static std::atomic_uint64_t sGlobalTaskOrder(0); task.order = ++sGlobalTaskOrder; { std::lock_guard<std::mutex> lock(task_queue_mutex_); task_queue_.push(task); // Make sure the queue mutex is unlocked before waking up the loop. In case // the wake causes this thread to be descheduled for the primary thread to // process tasks, the acquisition of the lock on that thread while holding // the lock here momentarily till the end of the scope is a pessimization. } WakeUp(); } bool TaskRunner::RunsTasksOnCurrentThread() const { return GetCurrentThreadId() == main_thread_id_; } void TaskRunner::WakeUp() { task_runner_window_->WakeUp(); } } // namespace flutter
engine/shell/platform/windows/task_runner.cc/0
{ "file_path": "engine/shell/platform/windows/task_runner.cc", "repo_id": "engine", "token_count": 1393 }
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. #include "flutter/shell/platform/windows/testing/mock_window.h" namespace flutter { namespace testing { MockWindow::MockWindow() : FlutterWindow(1, 1){}; MockWindow::MockWindow(std::unique_ptr<WindowsProcTable> window_proc_table, std::unique_ptr<TextInputManager> text_input_manager) : FlutterWindow(1, 1, std::move(window_proc_table), std::move(text_input_manager)){}; MockWindow::~MockWindow() = default; UINT MockWindow::GetDpi() { return GetCurrentDPI(); } LRESULT MockWindow::Win32DefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { return kWmResultDefault; } void MockWindow::SetDirectManipulationOwner( std::unique_ptr<DirectManipulationOwner> owner) { direct_manipulation_owner_ = std::move(owner); } LRESULT MockWindow::InjectWindowMessage(UINT const message, WPARAM const wparam, LPARAM const lparam) { return HandleMessage(message, wparam, lparam); } void MockWindow::InjectMessageList(int count, const Win32Message* messages) { for (int message_id = 0; message_id < count; message_id += 1) { const Win32Message& message = messages[message_id]; LRESULT result = InjectWindowMessage(message.message, message.wParam, message.lParam); if (message.expected_result != kWmResultDontCheck) { EXPECT_EQ(result, message.expected_result); } } } void MockWindow::CallOnImeComposition(UINT const message, WPARAM const wparam, LPARAM const lparam) { FlutterWindow::OnImeComposition(message, wparam, lparam); } } // namespace testing } // namespace flutter
engine/shell/platform/windows/testing/mock_window.cc/0
{ "file_path": "engine/shell/platform/windows/testing/mock_window.cc", "repo_id": "engine", "token_count": 932 }
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_WINDOWS_TESTING_WINDOWS_TEST_CONTEXT_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONTEXT_H_ #include <string> #include <string_view> #include <vector> #include "flutter/fml/closure.h" #include "flutter/fml/macros.h" #include "flutter/testing/test_dart_native_resolver.h" namespace flutter { namespace testing { // Context associated with the current Windows test fixture. // // Context data includes global Flutter and Dart runtime context such as the // path of Flutter's asset directory, ICU path, and resolvers for any // registered native functions. class WindowsTestContext { public: explicit WindowsTestContext(std::string_view assets_path = ""); virtual ~WindowsTestContext(); // Returns the path to assets required by the Flutter runtime. const std::wstring& GetAssetsPath() const; // Returns the path to the ICU library data file. const std::wstring& GetIcuDataPath() const; // Returns the path to the application's AOT library file. const std::wstring& GetAotLibraryPath() const; // Registers a native function callable from Dart code in test fixtures. In // the Dart test fixture, the associated function can be declared as: // // @pragma('vm:external-name', 'IdentifyingName') // external ReturnType functionName(); // // where `IdentifyingName` matches the |name| parameter to this method. void AddNativeFunction(std::string_view name, Dart_NativeFunction function); // Returns the root isolate create callback to register with the Flutter // runtime. fml::closure GetRootIsolateCallback(); private: std::wstring assets_path_; std::wstring icu_data_path_ = L"icudtl.dat"; std::wstring aot_library_path_ = L"aot.so"; std::vector<fml::closure> isolate_create_callbacks_; std::shared_ptr<TestDartNativeResolver> native_resolver_; FML_DISALLOW_COPY_AND_ASSIGN(WindowsTestContext); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONTEXT_H_
engine/shell/platform/windows/testing/windows_test_context.h/0
{ "file_path": "engine/shell/platform/windows/testing/windows_test_context.h", "repo_id": "engine", "token_count": 676 }
370