text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('CrossFrameCache', () { test('Reuse returns no object when cache empty', () { final CrossFrameCache<TestItem> cache = CrossFrameCache<TestItem>(); cache.commitFrame(); final TestItem? requestedItem = cache.reuse('item1'); expect(requestedItem, null); }); test('Reuses object across frames', () { final CrossFrameCache<TestItem> cache = CrossFrameCache<TestItem>(); final TestItem testItem1 = TestItem('item1'); cache.cache(testItem1.label, testItem1); cache.commitFrame(); TestItem? requestedItem = cache.reuse('item1'); expect(requestedItem, testItem1); requestedItem = cache.reuse('item1'); expect(requestedItem, null); }); test('Reuses objects that have same key across frames', () { final CrossFrameCache<TestItem> cache = CrossFrameCache<TestItem>(); final TestItem testItem1 = TestItem('sameLabel'); final TestItem testItem2 = TestItem('sameLabel'); final TestItem testItemX = TestItem('X'); cache.cache(testItem1.label, testItem1); cache.cache(testItemX.label, testItemX); cache.cache(testItem2.label, testItem2); cache.commitFrame(); TestItem? requestedItem = cache.reuse('sameLabel'); expect(requestedItem, testItem1); requestedItem = cache.reuse('sameLabel'); expect(requestedItem, testItem2); requestedItem = cache.reuse('sameLabel'); expect(requestedItem, null); }); test("Values don't survive beyond next frame", () { final CrossFrameCache<TestItem> cache = CrossFrameCache<TestItem>(); final TestItem testItem1 = TestItem('item1'); cache.cache(testItem1.label, testItem1); cache.commitFrame(); cache.commitFrame(); final TestItem? requestedItem = cache.reuse('item1'); expect(requestedItem, null); }); test('Values are evicted when not reused', () { final Set<TestItem> evictedItems = <TestItem>{}; final CrossFrameCache<TestItem> cache = CrossFrameCache<TestItem>(); final TestItem testItem1 = TestItem('item1'); final TestItem testItem2 = TestItem('item2'); cache.cache(testItem1.label, testItem1, (TestItem item) {evictedItems.add(item);}); cache.cache(testItem2.label, testItem2, (TestItem item) {evictedItems.add(item);}); cache.commitFrame(); expect(evictedItems.length, 0); cache.reuse('item2'); cache.commitFrame(); expect(evictedItems.contains(testItem1), isTrue); expect(evictedItems.contains(testItem2), isFalse); }); }); } class TestItem { TestItem(this.label); final String label; }
engine/lib/web_ui/test/engine/frame_reference_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/frame_reference_test.dart", "repo_id": "engine", "token_count": 1087 }
279
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('$MouseCursor', () { test('sets correct `cursor` style on root element', () { final DomElement rootViewElement = createDomElement('div'); final MouseCursor mouseCursor = MouseCursor(rootViewElement); // TODO(mdebbar): This should be `rootViewElement`. // https://github.com/flutter/flutter/issues/140226 final DomElement cursorTarget = domDocument.body!; mouseCursor.activateSystemCursor('alias'); expect(cursorTarget.style.cursor, 'alias'); mouseCursor.activateSystemCursor('move'); expect(cursorTarget.style.cursor, 'move'); mouseCursor.activateSystemCursor('precise'); expect(cursorTarget.style.cursor, 'crosshair'); mouseCursor.activateSystemCursor('resizeDownRight'); expect(cursorTarget.style.cursor, 'se-resize'); mouseCursor.activateSystemCursor('basic'); expect(cursorTarget.style.cursor, isEmpty); }); test('handles unknown cursor type', () { final DomElement rootViewElement = createDomElement('div'); final MouseCursor mouseCursor = MouseCursor(rootViewElement); // TODO(mdebbar): This should be `rootViewElement`. // https://github.com/flutter/flutter/issues/140226 final DomElement cursorTarget = domDocument.body!; mouseCursor.activateSystemCursor('unknown'); expect(cursorTarget.style.cursor, isEmpty); mouseCursor.activateSystemCursor(null); }); }); }
engine/lib/web_ui/test/engine/mouse/cursor_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/mouse/cursor_test.dart", "repo_id": "engine", "token_count": 655 }
280
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; class StubPicture implements ScenePicture { StubPicture(this.cullRect); @override final ui.Rect cullRect; @override int get approximateBytesUsed => throw UnimplementedError(); @override bool get debugDisposed => throw UnimplementedError(); @override void dispose() {} @override Future<ui.Image> toImage(int width, int height) { throw UnimplementedError(); } @override ui.Image toImageSync(int width, int height) { throw UnimplementedError(); } } class StubCompositePicture extends StubPicture { StubCompositePicture(this.children) : super( children.fold(null, (ui.Rect? previousValue, StubPicture child) { return previousValue?.expandToInclude(child.cullRect) ?? child.cullRect; })! ); final List<StubPicture> children; } class StubPictureRecorder implements ui.PictureRecorder { StubPictureRecorder(this.canvas); final StubSceneCanvas canvas; @override ui.Picture endRecording() { return StubCompositePicture(canvas.pictures); } @override bool get isRecording => throw UnimplementedError(); } class StubSceneCanvas implements SceneCanvas { List<StubPicture> pictures = <StubPicture>[]; @override void drawPicture(ui.Picture picture) { pictures.add(picture as StubPicture); } @override void clipPath(ui.Path path, {bool doAntiAlias = true}) {} @override void clipRRect(ui.RRect rrect, {bool doAntiAlias = true}) {} @override void clipRect(ui.Rect rect, {ui.ClipOp clipOp = ui.ClipOp.intersect, bool doAntiAlias = true}) {} @override void drawArc(ui.Rect rect, double startAngle, double sweepAngle, bool useCenter, ui.Paint paint) {} @override void drawAtlas(ui.Image atlas, List<ui.RSTransform> transforms, List<ui.Rect> rects, List<ui.Color>? colors, ui.BlendMode? blendMode, ui.Rect? cullRect, ui.Paint paint) {} @override void drawCircle(ui.Offset c, double radius, ui.Paint paint) {} @override void drawColor(ui.Color color, ui.BlendMode blendMode) {} @override void drawDRRect(ui.RRect outer, ui.RRect inner, ui.Paint paint) {} @override void drawImage(ui.Image image, ui.Offset offset, ui.Paint paint) {} @override void drawImageNine(ui.Image image, ui.Rect center, ui.Rect dst, ui.Paint paint) {} @override void drawImageRect(ui.Image image, ui.Rect src, ui.Rect dst, ui.Paint paint) {} @override void drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) {} @override void drawOval(ui.Rect rect, ui.Paint paint) {} @override void drawPaint(ui.Paint paint) {} @override void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) {} @override void drawPath(ui.Path path, ui.Paint paint) {} @override void drawPoints(ui.PointMode pointMode, List<ui.Offset> points, ui.Paint paint) {} @override void drawRRect(ui.RRect rrect, ui.Paint paint) {} @override void drawRawAtlas(ui.Image atlas, Float32List rstTransforms, Float32List rects, Int32List? colors, ui.BlendMode? blendMode, ui.Rect? cullRect, ui.Paint paint) {} @override void drawRawPoints(ui.PointMode pointMode, Float32List points, ui.Paint paint) {} @override void drawRect(ui.Rect rect, ui.Paint paint) {} @override void drawShadow(ui.Path path, ui.Color color, double elevation, bool transparentOccluder) {} @override void drawVertices(ui.Vertices vertices, ui.BlendMode blendMode, ui.Paint paint) {} @override ui.Rect getDestinationClipBounds() { throw UnimplementedError(); } @override ui.Rect getLocalClipBounds() { throw UnimplementedError(); } @override int getSaveCount() { throw UnimplementedError(); } @override Float64List getTransform() { throw UnimplementedError(); } @override void restore() {} @override void restoreToCount(int count) {} @override void rotate(double radians) {} @override void save() {} @override void saveLayer(ui.Rect? bounds, ui.Paint paint) {} @override void saveLayerWithFilter(ui.Rect? bounds, ui.Paint paint, ui.ImageFilter backdropFilter) {} @override void scale(double sx, [double? sy]) {} @override void skew(double sx, double sy) {} @override void transform(Float64List matrix4) {} @override void translate(double dx, double dy) {} }
engine/lib/web_ui/test/engine/scene_builder_utils.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/scene_builder_utils.dart", "repo_id": "engine", "token_count": 1584 }
281
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../../common/matchers.dart'; import '../../common/test_initialization.dart'; const MethodCodec codec = StandardMethodCodec(); void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { await bootstrapAndRunApp(withImplicitView: true); late PersistedPlatformView view; test('importing platformViewRegistry from dart:ui is deprecated', () { final void Function(String) oldPrintWarning = printWarning; final List<String> warnings = <String>[]; printWarning = (String message) { warnings.add(message); }; // ignore: unnecessary_statements ui_web.platformViewRegistry; expect(warnings, isEmpty); // ignore: unnecessary_statements ui.platformViewRegistry; expect(warnings, hasLength(1)); expect(warnings.single, contains('platformViewRegistry')); expect(warnings.single, contains('deprecated')); expect(warnings.single, contains('dart:ui_web')); printWarning = oldPrintWarning; }); group('PersistedPlatformView', () { setUp(() async { ui_web.platformViewRegistry.registerViewFactory( 'test-0', (int viewId) => createDomHTMLDivElement(), ); ui_web.platformViewRegistry.registerViewFactory( 'test-1', (int viewId) => createDomHTMLDivElement(), ); // Ensure the views are created... await Future.wait(<Future<void>>[ _createPlatformView(0, 'test-0'), _createPlatformView(1, 'test-1'), ]); view = PersistedPlatformView(0, 0, 0, 100, 100)..build(); }); group('update', () { test('throws assertion error if called with different viewIds', () { final PersistedPlatformView differentView = PersistedPlatformView(1, 1, 1, 100, 100)..build(); expect(() { view.update(differentView); }, throwsAssertionError); }); }); group('canUpdateAsMatch', () { test('returns true when viewId is the same', () { final PersistedPlatformView sameView = PersistedPlatformView(0, 1, 1, 100, 100)..build(); expect(view.canUpdateAsMatch(sameView), isTrue); }); test('returns false when viewId is different', () { final PersistedPlatformView differentView = PersistedPlatformView(1, 1, 1, 100, 100)..build(); expect(view.canUpdateAsMatch(differentView), isFalse); }); test('returns false when other view is not a PlatformView', () { final PersistedOpacity anyView = PersistedOpacity(null, 1, ui.Offset.zero)..build(); expect(view.canUpdateAsMatch(anyView), isFalse); }); }); group('createElement', () { test('creates slot element that can receive pointer events', () { final DomElement element = view.createElement(); expect(element.tagName, equalsIgnoringCase('flt-platform-view-slot')); expect(element.style.pointerEvents, 'auto'); }); }); }); } // Sends a platform message to create a Platform View with the given id and viewType. Future<void> _createPlatformView(int id, String viewType) { final Completer<void> completer = Completer<void>(); ui.PlatformDispatcher.instance.sendPlatformMessage( 'flutter/platform_views', codec.encodeMethodCall(MethodCall( 'create', <String, dynamic>{ 'id': id, 'viewType': viewType, }, )), (dynamic _) => completer.complete(), ); return completer.future; }
engine/lib/web_ui/test/engine/surface/platform_view_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/surface/platform_view_test.dart", "repo_id": "engine", "token_count": 1409 }
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. @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/full_page_embedding_strategy.dart'; void main() { internalBootstrapBrowserTest(() => doTests); } void doTests() { group('initialize', () { test('Prepares target environment', () { final DomElement target = domDocument.body!; final DomHTMLMetaElement meta = createDomHTMLMetaElement(); meta ..id = 'my_viewport_meta_for_testing' ..name = 'viewport' ..content = 'width=device-width, initial-scale=1.0, ' 'maximum-scale=1.0, user-scalable=no'; domDocument.head!.append(meta); DomElement? userMeta = domDocument.querySelector('#my_viewport_meta_for_testing'); expect(userMeta, isNotNull); // ignore: unused_local_variable final FullPageEmbeddingStrategy strategy = FullPageEmbeddingStrategy(); expect(target.getAttribute('flt-embedding'), 'full-page', reason: 'Should identify itself as a specific key=value into the target element.'); // Locate the viewport metas again... userMeta = domDocument.querySelector('#my_viewport_meta_for_testing'); final DomElement? flutterMeta = domDocument.querySelector('meta[name="viewport"]'); expect(userMeta, isNull, reason: 'Should delete previously existing viewport meta tags.'); expect(flutterMeta, isNotNull); expect(flutterMeta!.hasAttribute('flt-viewport'), isTrue, reason: 'Should install flutter viewport meta tag.'); }); }); group('attachViewRoot', () { test('Should attach glasspane into embedder target (body)', () async { final FullPageEmbeddingStrategy strategy = FullPageEmbeddingStrategy(); final DomElement glassPane = createDomElement('some-tag-for-tests'); final DomCSSStyleDeclaration style = glassPane.style; expect(glassPane.isConnected, isFalse); expect(style.position, '', reason: 'Should not have any specific position.'); expect(style.top, '', reason: 'Should not have any top/right/bottom/left positioning/inset.'); strategy.attachViewRoot(glassPane); // Assert injection into <body> expect(glassPane.isConnected, isTrue, reason: 'Should inject glassPane into the document.'); expect(glassPane.parent, domDocument.body, reason: 'Should inject glassPane into the <body>'); final DomCSSStyleDeclaration styleAfter = glassPane.style; // Assert required styling to cover the viewport expect(styleAfter.position, 'absolute', reason: 'Should be absolutely positioned.'); expect(styleAfter.top, '0px', reason: 'Should cover the whole viewport.'); expect(styleAfter.right, '0px', reason: 'Should cover the whole viewport.'); expect(styleAfter.bottom, '0px', reason: 'Should cover the whole viewport.'); expect(styleAfter.left, '0px', reason: 'Should cover the whole viewport.'); }); }); }
engine/lib/web_ui/test/engine/view_embedder/embedding_strategy/full_page_embedding_strategy_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/view_embedder/embedding_strategy/full_page_embedding_strategy_test.dart", "repo_id": "engine", "token_count": 1238 }
283
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_util' as js_util; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' hide TextStyle; import '../../common/test_initialization.dart'; import '../screenshot.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( setUpTestViewDimensions: false, ); test('Blend circles with difference and color', () async { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 400, 300)); rc.save(); rc.drawRect( const Rect.fromLTRB(0, 0, 400, 400), SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(255, 255, 255, 255)); rc.drawCircle( const Offset(100, 100), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(128, 255, 0, 0) ..blendMode = BlendMode.difference); rc.drawCircle( const Offset(170, 100), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..blendMode = BlendMode.color ..color = const Color.fromARGB(128, 0, 255, 0)); rc.drawCircle( const Offset(135, 170), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(128, 255, 0, 0)); rc.restore(); await canvasScreenshot(rc, 'canvas_blend_circle_diff_color'); }); test('Blend circle and text with multiply', () async { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 400, 300)); rc.save(); rc.drawRect( const Rect.fromLTRB(0, 0, 400, 400), SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(255, 255, 255, 255)); rc.drawCircle( const Offset(100, 100), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(128, 255, 0, 0) ..blendMode = BlendMode.difference); rc.drawCircle( const Offset(170, 100), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..blendMode = BlendMode.color ..color = const Color.fromARGB(128, 0, 255, 0)); rc.drawCircle( const Offset(135, 170), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(128, 255, 0, 0)); rc.drawImage(createTestImage(), const Offset(135.0, 130.0), SurfacePaint()..blendMode = BlendMode.multiply); rc.restore(); await canvasScreenshot(rc, 'canvas_blend_image_multiply'); }); } HtmlImage createTestImage() { const int width = 100; const int height = 50; final DomCanvasElement canvas = createDomCanvasElement(width: width, height: height); final DomCanvasRenderingContext2D ctx = canvas.context2D; ctx.fillStyle = '#E04040'; ctx.fillRect(0, 0, 33, 50); ctx.fill(); ctx.fillStyle = '#40E080'; ctx.fillRect(33, 0, 33, 50); ctx.fill(); ctx.fillStyle = '#2040E0'; ctx.fillRect(66, 0, 33, 50); ctx.fill(); final DomHTMLImageElement imageElement = createDomHTMLImageElement(); imageElement.src = js_util.callMethod<String>(canvas, 'toDataURL', <dynamic>[]); return HtmlImage(imageElement, width, height); }
engine/lib/web_ui/test/html/compositing/canvas_blend_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/compositing/canvas_blend_golden_test.dart", "repo_id": "engine", "token_count": 1520 }
284
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; 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 rects side by side with fill and stroke', () async { paintSideBySideRects(canvas); domDocument.body!.append(canvas.rootElement); await matchGoldenFile('canvas_stroke_rects.png', region: region); }); } void paintSideBySideRects(BitmapCanvas canvas) { canvas.drawRect(const Rect.fromLTRB(0, 0, 300, 300), SurfacePaintData() ..color = 0xFFFFFFFF ..style = PaintingStyle.fill); // white canvas.drawRect(const Rect.fromLTRB(0, 20, 40, 60), SurfacePaintData() ..style = PaintingStyle.fill ..color = 0x7f0000ff); canvas.drawRect(const Rect.fromLTRB(40, 20, 80, 60), SurfacePaintData() ..style = PaintingStyle.stroke ..strokeWidth = 4 ..color = 0x7fff0000); // Rotate 30 degrees (in rad: deg*pi/180) canvas.transform(Matrix4.rotationZ(30.0 * math.pi / 180.0).storage); canvas.drawRect(const Rect.fromLTRB(100, 60, 140, 100), SurfacePaintData() ..style = PaintingStyle.fill ..color = 0x7fff00ff); canvas.drawRect(const Rect.fromLTRB(140, 60, 180, 100), SurfacePaintData() ..style = PaintingStyle.stroke ..strokeWidth = 4 ..color = 0x7fffff00); }
engine/lib/web_ui/test/html/drawing/canvas_stroke_rects_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/drawing/canvas_stroke_rects_golden_test.dart", "repo_id": "engine", "token_count": 780 }
285
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' hide TextStyle; import '../common/matchers.dart'; import '../common/test_initialization.dart'; import 'screenshot.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const double screenWidth = 600.0; const double screenHeight = 800.0; const Rect screenRect = Rect.fromLTWH(0, 0, screenWidth, screenHeight); const Color black12Color = Color(0x1F000000); const Color redAccentColor = Color(0xFFFF1744); const double kDashLength = 5.0; setUpUnitTests( setUpTestViewDimensions: false, ); test('Should calculate tangent on line', () async { final Path path = Path(); path.moveTo(50, 130); path.lineTo(150, 20); final PathMetric metric = path.computeMetrics().first; final Tangent t = metric.getTangentForOffset(50.0)!; expect(t.position.dx, within(from: 83.633, distance: 0.01)); expect(t.position.dy, within(from: 93.0, distance: 0.01)); expect(t.vector.dx, within(from: 0.672, distance: 0.01)); expect(t.vector.dy, within(from: -0.739, distance: 0.01)); }); test('Should calculate tangent on cubic curve', () async { final Path path = Path(); const double p1x = 240; const double p1y = 120; const double p2x = 320; const double p2y = 25; path.moveTo(150, 20); path.quadraticBezierTo(p1x, p1y, p2x, p2y); final PathMetric metric = path.computeMetrics().first; final Tangent t = metric.getTangentForOffset(50.0)!; expect(t.position.dx, within(from: 187.25, distance: 0.01)); expect(t.position.dy, within(from: 53.33, distance: 0.01)); expect(t.vector.dx, within(from: 0.82, distance: 0.01)); expect(t.vector.dy, within(from: 0.56, distance: 0.01)); }); test('Should calculate tangent on quadratic curve', () async { final Path path = Path(); const double p0x = 150; const double p0y = 20; const double p1x = 320; const double p1y = 25; path.moveTo(150, 20); path.quadraticBezierTo(p0x, p0y, p1x, p1y); final PathMetric metric = path.computeMetrics().first; final Tangent t = metric.getTangentForOffset(50.0)!; expect(t.position.dx, within(from: 199.82, distance: 0.01)); expect(t.position.dy, within(from: 21.46, distance: 0.01)); expect(t.vector.dx, within(from: 0.99, distance: 0.01)); expect(t.vector.dy, within(from: 0.02, distance: 0.01)); }); // Test for extractPath to draw 5 pixel length dashed line using quad curve. test('Should draw dashed line on quadratic curve.', () async { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500)); final SurfacePaint paint = SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 3 ..color = black12Color; final SurfacePaint redPaint = SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = redAccentColor; final SurfacePath path = SurfacePath(); path.moveTo(50, 130); path.lineTo(150, 20); const double p1x = 240; const double p1y = 120; const double p2x = 320; const double p2y = 25; path.quadraticBezierTo(p1x, p1y, p2x, p2y); rc.drawPath(path, paint); const double t0 = 0.2; const double t1 = 0.7; final List<PathMetric> metrics = path.computeMetrics().toList(); double totalLength = 0; for (final PathMetric m in metrics) { totalLength += m.length; } final Path dashedPath = Path(); for (final PathMetric measurePath in path.computeMetrics()) { double distance = totalLength * t0; bool draw = true; while (distance < measurePath.length * t1) { const double length = kDashLength; if (draw) { dashedPath.addPath( measurePath.extractPath(distance, distance + length), Offset.zero); } distance += length; draw = !draw; } } rc.drawPath(dashedPath, redPaint); await canvasScreenshot(rc, 'path_dash_quadratic', canvasRect: screenRect); }); // Test for extractPath to draw 5 pixel length dashed line using cubic curve. test('Should draw dashed line on cubic curve.', () async { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500)); final SurfacePaint paint = SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 3 ..color = black12Color; final SurfacePaint redPaint = SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = redAccentColor; final Path path = Path(); path.moveTo(50, 130); path.lineTo(150, 20); const double p1x = 40; const double p1y = 120; const double p2x = 300; const double p2y = 130; const double p3x = 320; const double p3y = 25; path.cubicTo(p1x, p1y, p2x, p2y, p3x, p3y); rc.drawPath(path, paint); const double t0 = 0.2; const double t1 = 0.7; final List<PathMetric> metrics = path.computeMetrics().toList(); double totalLength = 0; for (final PathMetric m in metrics) { totalLength += m.length; } final Path dashedPath = Path(); for (final PathMetric measurePath in path.computeMetrics()) { double distance = totalLength * t0; bool draw = true; while (distance < measurePath.length * t1) { const double length = kDashLength; if (draw) { dashedPath.addPath( measurePath.extractPath(distance, distance + length), Offset.zero); } distance += length; draw = !draw; } } rc.drawPath(dashedPath, redPaint); await canvasScreenshot(rc, 'path_dash_cubic', canvasRect: screenRect); }); }
engine/lib/web_ui/test/html/path_metrics_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/path_metrics_golden_test.dart", "repo_id": "engine", "token_count": 2357 }
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. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../../common/test_initialization.dart'; import '../paragraph/helper.dart'; /// Some text measurements are sensitive to browser implementations. Position /// info in the following tests only pass in Chrome, they are slightly different /// on each browser. So we need to ignore position info on non-Chrome browsers /// when comparing expectations with actual output. bool get isBlink => browserEngine == BrowserEngine.blink; String fontFamilyToAttribute(String fontFamily) { fontFamily = canonicalizeFontFamily(fontFamily)!; if (browserEngine == BrowserEngine.firefox) { return fontFamily.replaceAll('"', '&quot;'); } else if (browserEngine == BrowserEngine.blink || browserEngine == BrowserEngine.webkit) { return fontFamily.replaceAll('"', ''); } return fontFamily; } void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests(withImplicitView: true); test('empty paragraph', () { final CanvasParagraph paragraph1 = rich( EngineParagraphStyle(), (CanvasParagraphBuilder builder) {}, ); expect(paragraph1.plainText, ''); expect(paragraph1.spans, hasLength(1)); expect(paragraph1.spans.single.start, 0); expect(paragraph1.spans.single.end, 0); final CanvasParagraph paragraph2 = rich( EngineParagraphStyle(), (CanvasParagraphBuilder builder) { builder.addText(''); }, ); expect(paragraph2.plainText, ''); expect(paragraph2.spans, hasLength(1)); expect(paragraph2.spans.single.start, 0); expect(paragraph2.spans.single.end, 0); }); test('Builds a text-only canvas paragraph', () { final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.addText('Hello'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.paragraphStyle, style); expect(paragraph.plainText, 'Hello'); expect(paragraph.spans, hasLength(1)); paragraph.layout(const ParagraphConstraints(width: double.infinity)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 13*5, fontSize: 13)}">' 'Hello' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); // Should break "Hello" into "Hel" and "lo". paragraph.layout(const ParagraphConstraints(width: 39.0)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 13*3, fontSize: 13)}">' 'Hel' '</flt-span>' '<flt-span style="${spanStyle(top: 13, left: 0, width: 13*2, fontSize: 13)}">' 'lo' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); final ParagraphSpan span = paragraph.spans.single; expect(getSpanText(paragraph, span), 'Hello'); expect(span.style, styleWithDefaults(fontSize: 13.0)); }); test('Correct defaults', () { final EngineParagraphStyle style = EngineParagraphStyle(); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.addText('Hello'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.paragraphStyle, style); expect(paragraph.plainText, 'Hello'); expect(paragraph.spans, hasLength(1)); paragraph.layout(const ParagraphConstraints(width: double.infinity)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 14*5)}">' 'Hello' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); final ParagraphSpan span = paragraph.spans.single; expect(span.style, styleWithDefaults()); }); test('Sets correct styles for max-lines', () { final EngineParagraphStyle style = EngineParagraphStyle(maxLines: 2); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.addText('Hello'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.paragraphStyle, style); expect(paragraph.plainText, 'Hello'); paragraph.layout(const ParagraphConstraints(width: double.infinity)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 14*5)}">' 'Hello' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); }); test('Sets correct styles for ellipsis', () { final EngineParagraphStyle style = EngineParagraphStyle(ellipsis: '...'); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.addText('HelloWorld'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.paragraphStyle, style); expect(paragraph.plainText, 'HelloWorld'); paragraph.layout(const ParagraphConstraints(width: 100.0)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 14*4)}">' 'Hell' '</flt-span>' '<flt-span style="${spanStyle(top: 0, left: 14*4, width: 14*3)}">' '...' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); }); test('Builds a single-span paragraph with complex styles', () { final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0, height: 1.5); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.pushStyle(TextStyle(fontSize: 9.0)); builder.pushStyle(TextStyle(fontWeight: FontWeight.bold)); builder.pushStyle(TextStyle(fontSize: 40.0)); builder.pop(); builder .pushStyle(TextStyle(fontStyle: FontStyle.italic, letterSpacing: 2.0)); builder.addText('Hello'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.plainText, 'Hello'); expect(paragraph.spans, hasLength(1)); paragraph.layout(const ParagraphConstraints(width: double.infinity)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: (9+2)*5, lineHeight: 1.5*9, fontSize: 9, fontWeight: 'bold', fontStyle: 'italic', letterSpacing: 2)}">' 'Hello' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); final ParagraphSpan span = paragraph.spans.single; expect(getSpanText(paragraph, span), 'Hello'); expect( span.style, styleWithDefaults( height: 1.5, fontSize: 9.0, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic, letterSpacing: 2.0, ), ); }); test('Builds a multi-span paragraph', () { final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.pushStyle(TextStyle(fontWeight: FontWeight.bold)); builder.addText('Hello'); builder.pop(); builder.pushStyle(TextStyle(fontStyle: FontStyle.italic)); builder.addText(' world'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.plainText, 'Hello world'); expect(paragraph.spans, hasLength(2)); paragraph.layout(const ParagraphConstraints(width: double.infinity)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 13*5, fontSize: 13, fontWeight: 'bold')}">' 'Hello' '</flt-span>' '<flt-span style="${spanStyle(top: 0, left: 65, width: 13*1, fontSize: 13, fontStyle: 'italic')}">' ' ' '</flt-span>' '<flt-span style="${spanStyle(top: 0, left: 78, width: 13*5, fontSize: 13, fontStyle: 'italic')}">' 'world' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); // Should break "Hello world" into 2 lines: "Hello " and "world". paragraph.layout(const ParagraphConstraints(width: 75.0)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 13*5, fontSize: 13, fontWeight: 'bold')}">' 'Hello' '</flt-span>' '<flt-span style="${spanStyle(top: 0, left: 65, width: 0, fontSize: 13, fontStyle: 'italic')}">' ' ' '</flt-span>' '<flt-span style="${spanStyle(top: 13, left: 0, width: 13*5, fontSize: 13, fontStyle: 'italic')}">' 'world' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); final ParagraphSpan hello = paragraph.spans.first; expect(getSpanText(paragraph, hello), 'Hello'); expect( hello.style, styleWithDefaults( fontSize: 13.0, fontWeight: FontWeight.bold, ), ); final ParagraphSpan world = paragraph.spans.last; expect(getSpanText(paragraph, world), ' world'); expect( world.style, styleWithDefaults( fontSize: 13.0, fontStyle: FontStyle.italic, ), ); }); test('Builds a multi-span paragraph with complex styles', () { final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.pushStyle(TextStyle(fontWeight: FontWeight.bold)); builder.pushStyle(TextStyle(height: 2.0)); builder.addText('Hello'); builder.pop(); // pop TextStyle(height: 2.0). builder.pushStyle(TextStyle(fontStyle: FontStyle.italic)); builder.addText(' world'); builder.pushStyle(TextStyle(fontWeight: FontWeight.normal)); builder.addText('!'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.plainText, 'Hello world!'); expect(paragraph.spans, hasLength(3)); paragraph.layout(const ParagraphConstraints(width: double.infinity)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 13*5, lineHeight: 2*13, fontSize: 13, fontWeight: 'bold')}">' 'Hello' '</flt-span>' '<flt-span style="${spanStyle(top: 6, left: 65, width: 13*1, fontSize: 13, fontWeight: 'bold', fontStyle: 'italic')}">' ' ' '</flt-span>' '<flt-span style="${spanStyle(top: 6, left: 78, width: 13*5, fontSize: 13, fontWeight: 'bold', fontStyle: 'italic')}">' 'world' '</flt-span>' '<flt-span style="${spanStyle(top: 6, left: 143, width: 13*1, fontSize: 13, fontWeight: 'normal', fontStyle: 'italic')}">' '!' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); final ParagraphSpan hello = paragraph.spans[0]; expect(getSpanText(paragraph, hello), 'Hello'); expect( hello.style, styleWithDefaults( fontSize: 13.0, fontWeight: FontWeight.bold, height: 2.0, ), ); final ParagraphSpan world = paragraph.spans[1]; expect(getSpanText(paragraph, world), ' world'); expect( world.style, styleWithDefaults( fontSize: 13.0, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic, ), ); final ParagraphSpan bang = paragraph.spans[2]; expect(getSpanText(paragraph, bang), '!'); expect( bang.style, styleWithDefaults( fontSize: 13.0, fontWeight: FontWeight.normal, fontStyle: FontStyle.italic, ), ); }); test('Paragraph with new lines generates correct DOM', () { final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.addText('First\nSecond '); builder.pushStyle(TextStyle(fontStyle: FontStyle.italic)); builder.addText('ThirdLongLine'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.plainText, 'First\nSecond ThirdLongLine'); expect(paragraph.spans, hasLength(2)); // There's a new line between "First" and "Second", but "Second" and // "ThirdLongLine" remain together since constraints are infinite. paragraph.layout(const ParagraphConstraints(width: double.infinity)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 13*5, fontSize: 13)}">' 'First' '</flt-span>' '<flt-span style="${spanStyle(top: 13, left: 0, width: 13*6, fontSize: 13)}">' 'Second' '</flt-span>' '<flt-span style="${spanStyle(top: 13, left: 13*6, width: 13*1, fontSize: 13)}">' ' ' '</flt-span>' '<flt-span style="${spanStyle(top: 13, left: 13*7, width: 13*13, fontSize: 13, fontStyle: 'italic')}">' 'ThirdLongLine' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); // Should break the paragraph into "First", "Second " and "ThirdLongLine". paragraph.layout(const ParagraphConstraints(width: 180.0)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: 0, left: 0, width: 13*5, fontSize: 13)}">' 'First' '</flt-span>' '<flt-span style="${spanStyle(top: 13, left: 0, width: 13*6, fontSize: 13)}">' 'Second' '</flt-span>' '<flt-span style="${spanStyle(top: 13, left: 13*6, width: 0, fontSize: 13)}">' ' ' '</flt-span>' '<flt-span style="${spanStyle(top: 26, left: 0, width: 13*13, fontSize: 13, fontStyle: 'italic')}">' 'ThirdLongLine' '</flt-span>' '</flt-paragraph>', ignorePositions: !isBlink, ); }); test('various font sizes', () { // Paragraphs and spans force the FlutterTest font in test mode. We need to // trick them into thinking they are not in test mode, so they use the // provided font family. ui_web.debugEmulateFlutterTesterEnvironment = false; final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 12.0, fontFamily: 'first'); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.addText('First '); builder.pushStyle(TextStyle(fontSize: 18.0, fontFamily: 'second')); builder.addText('Second '); builder.pushStyle(TextStyle(fontSize: 10.0, fontFamily: 'third')); builder.addText('Third'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.plainText, 'First Second Third'); expect(paragraph.spans, hasLength(3)); // The paragraph should take the font size and family from the span with the // greatest font size. paragraph.layout(const ParagraphConstraints(width: double.infinity)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 12, fontFamily: 'first')}">' 'First' '</flt-span>' '<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 12, fontFamily: 'first')}">' ' ' '</flt-span>' '<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 18, fontFamily: 'second')}">' 'Second' '</flt-span>' '<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 18, fontFamily: 'second')}">' ' ' '</flt-span>' '<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 10, fontFamily: 'third')}">' 'Third' '</flt-span>' '</flt-paragraph>', // Since we are using unknown font families, we can't predict the text // measurements. ignorePositions: true, ); ui_web.debugEmulateFlutterTesterEnvironment = true; }); // Regression test for https://github.com/flutter/flutter/issues/108431. // Set dir attribute for RTL fragments in order to let the browser // handle mirrored characters. test('Sets "dir" attribute for RTL fragment', () { final EngineParagraphStyle style = EngineParagraphStyle( fontSize: 20.0, textDirection: TextDirection.rtl, ); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); builder.addText('(1)'); final CanvasParagraph paragraph = builder.build(); expect(paragraph.paragraphStyle, style); expect(paragraph.plainText, '(1)'); paragraph.layout(const ParagraphConstraints(width: double.infinity)); expectOuterHtml( paragraph, '<flt-paragraph style="${paragraphStyle()}">' '<flt-span dir="rtl" style="${spanStyle(top: null, left: null, width: null, fontSize: 20)}">' '(' '</flt-span>' '<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 20)}">' '1' '</flt-span>' '<flt-span dir="rtl" style="${spanStyle(top: null, left: null, width: null, fontSize: 20)}">' ')' '</flt-span>' '</flt-paragraph>', ignorePositions: true, ); }); } const String defaultFontFamily = 'FlutterTest'; const num defaultFontSize = 14; String paragraphStyle() { return <String>[ 'position: absolute;', 'white-space: pre;', ].join(' '); } String spanStyle({ required num? top, required num? left, required num? width, String fontFamily = defaultFontFamily, num fontSize = defaultFontSize, String? fontWeight, String? fontStyle, num? lineHeight, num? letterSpacing, }) { return <String>[ 'font-size: ${fontSize}px;', if (fontWeight != null) 'font-weight: $fontWeight;', if (fontStyle != null) 'font-style: $fontStyle;', 'font-family: ${fontFamilyToAttribute(fontFamily)};', if (letterSpacing != null) 'letter-spacing: ${letterSpacing}px;', 'position: absolute;', if (top != null) 'top: ${top}px;', if (left != null) 'left: ${left}px;', if (width != null) 'width: ${width}px;', 'line-height: ${lineHeight ?? fontSize}px;', ].join(' '); } TextStyle styleWithDefaults({ String fontFamily = StyleManager.defaultFontFamily, double fontSize = StyleManager.defaultFontSize, FontWeight? fontWeight, FontStyle? fontStyle, double? height, double? letterSpacing, }) { return TextStyle( fontFamily: fontFamily, fontSize: fontSize, fontWeight: fontWeight, fontStyle: fontStyle, height: height, letterSpacing: letterSpacing, ); } void expectOuterHtml(CanvasParagraph paragraph, String expected, {required bool ignorePositions}) { String outerHtml = paragraph.toDomElement().outerHTML!; if (ignorePositions) { outerHtml = removeMeasurementInfo(outerHtml); expected = removeMeasurementInfo(expected); } expect(outerHtml, expected); } /// Removes CSS styles that are based on text measurement from the given html /// string. /// /// Examples: top, left, line-height, width. /// /// This is needed when the measurement is unknown or could be different /// depending on browser and environment. String removeMeasurementInfo(String outerHtml) { return outerHtml .replaceAll(RegExp(r'\s*line-height:\s*[\d\.]+px\s*;\s*'), '') .replaceAll(RegExp(r'\s*width:\s*[\d\.]+px\s*;\s*'), '') .replaceAll(RegExp(r'\s*top:\s*[\d\.]+px\s*;\s*'), '') .replaceAll(RegExp(r'\s*left:\s*[\d\.]+px\s*;\s*'), ''); }
engine/lib/web_ui/test/html/text/canvas_paragraph_builder_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/text/canvas_paragraph_builder_test.dart", "repo_id": "engine", "token_count": 7716 }
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. import 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'package:web_engine_tester/golden_tester.dart'; import '../common/test_initialization.dart'; import 'utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, setUpTestViewDimensions: false, ); const ui.Rect region = ui.Rect.fromLTWH(0, 0, 400, 600); late ui.PictureRecorder recorder; late ui.Canvas canvas; setUp(() { recorder = ui.PictureRecorder(); canvas = ui.Canvas(recorder, region); }); tearDown(() { }); test('draws points in all 3 modes', () async { final ui.Paint paint = ui.Paint(); paint.strokeWidth = 2.0; paint.color = const ui.Color(0xFF00FF00); const List<ui.Offset> points = <ui.Offset>[ ui.Offset(10, 10), ui.Offset(50, 10), ui.Offset(70, 70), ui.Offset(170, 70) ]; canvas.drawPoints(ui.PointMode.points, points, paint); const List<ui.Offset> points2 = <ui.Offset>[ ui.Offset(10, 110), ui.Offset(50, 110), ui.Offset(70, 170), ui.Offset(170, 170) ]; canvas.drawPoints(ui.PointMode.lines, points2, paint); const List<ui.Offset> points3 = <ui.Offset>[ ui.Offset(10, 210), ui.Offset(50, 210), ui.Offset(70, 270), ui.Offset(170, 270) ]; canvas.drawPoints(ui.PointMode.polygon, points3, paint); await drawPictureUsingCurrentRenderer(recorder.endRecording()); await matchGoldenFile('ui_canvas_draw_points.png', region: region); }); test('draws raw points in all 3 modes', () async { final ui.Paint paint = ui.Paint(); paint.strokeWidth = 2.0; paint.color = const ui.Color(0xFF0000FF); final Float32List points = offsetListToFloat32List(const <ui.Offset>[ ui.Offset(10, 10), ui.Offset(50, 10), ui.Offset(70, 70), ui.Offset(170, 70) ]); canvas.drawRawPoints(ui.PointMode.points, points, paint); final Float32List points2 = offsetListToFloat32List(const <ui.Offset>[ ui.Offset(10, 110), ui.Offset(50, 110), ui.Offset(70, 170), ui.Offset(170, 170) ]); canvas.drawRawPoints(ui.PointMode.lines, points2, paint); final Float32List points3 = offsetListToFloat32List(const <ui.Offset>[ ui.Offset(10, 210), ui.Offset(50, 210), ui.Offset(70, 270), ui.Offset(170, 270) ]); canvas.drawRawPoints(ui.PointMode.polygon, points3, paint); await drawPictureUsingCurrentRenderer(recorder.endRecording()); await matchGoldenFile('ui_canvas_draw_raw_points.png', region: region); }); test('Should draw points with strokeWidth', () async { final ui.Paint nullStrokePaint = ui.Paint()..color = const ui.Color(0xffff0000); canvas.drawRawPoints(ui.PointMode.lines, Float32List.fromList(<double>[ 30.0, 20.0, 200.0, 20.0]), nullStrokePaint); final ui.Paint strokePaint1 = ui.Paint() ..strokeWidth = 1.0 ..color = const ui.Color(0xff0000ff); canvas.drawRawPoints(ui.PointMode.lines, Float32List.fromList(<double>[ 30.0, 30.0, 200.0, 30.0]), strokePaint1); final ui.Paint strokePaint3 = ui.Paint() ..strokeWidth = 3.0 ..color = const ui.Color(0xff00a000); canvas.drawRawPoints(ui.PointMode.lines, Float32List.fromList(<double>[ 30.0, 40.0, 200.0, 40.0]), strokePaint3); canvas.drawRawPoints(ui.PointMode.points, Float32List.fromList(<double>[ 30.0, 50.0, 40.0, 50.0, 50.0, 50.0]), strokePaint3); await drawPictureUsingCurrentRenderer(recorder.endRecording()); await matchGoldenFile('ui_canvas_draw_points_stroke.png', region: region); }); }
engine/lib/web_ui/test/ui/canvas_draw_points_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/canvas_draw_points_golden_test.dart", "repo_id": "engine", "token_count": 1642 }
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. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/ui.dart' as ui; import '../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); test('blanks are equal to each other', () { final ui.ParagraphStyle a = ui.ParagraphStyle(); final ui.ParagraphStyle b = ui.ParagraphStyle(); expect(a, b); expect(a.hashCode, b.hashCode); }); test('each property individually equal', () { for (final String property in _populatorsA.keys) { final _ParagraphStylePropertyPopulator populator = _populatorsA[property]!; final _TestParagraphStyleBuilder aBuilder = _TestParagraphStyleBuilder(); populator(aBuilder); final ui.ParagraphStyle a = aBuilder.build(); final _TestParagraphStyleBuilder bBuilder = _TestParagraphStyleBuilder(); populator(bBuilder); final ui.ParagraphStyle b = bBuilder.build(); expect(reason: '$property property is equal', a, b); expect(reason: '$property hashCode is equal', a.hashCode, b.hashCode); } }); test('each property individually not equal', () { for (final String property in _populatorsA.keys) { final _ParagraphStylePropertyPopulator populatorA = _populatorsA[property]!; final _TestParagraphStyleBuilder aBuilder = _TestParagraphStyleBuilder(); populatorA(aBuilder); final ui.ParagraphStyle a = aBuilder.build(); final _ParagraphStylePropertyPopulator populatorB = _populatorsB[property]!; final _TestParagraphStyleBuilder bBuilder = _TestParagraphStyleBuilder(); populatorB(bBuilder); final ui.ParagraphStyle b = bBuilder.build(); expect(reason: '$property property is not equal', a, isNot(b)); expect(reason: '$property hashCode is not equal', a.hashCode, isNot(b.hashCode)); } }); test('all properties altogether equal', () { final _TestParagraphStyleBuilder aBuilder = _TestParagraphStyleBuilder(); final _TestParagraphStyleBuilder bBuilder = _TestParagraphStyleBuilder(); for (final String property in _populatorsA.keys) { final _ParagraphStylePropertyPopulator populator = _populatorsA[property]!; populator(aBuilder); populator(bBuilder); } final ui.ParagraphStyle a = aBuilder.build(); final ui.ParagraphStyle b = bBuilder.build(); expect(a, b); expect(a.hashCode, b.hashCode); }); test('all properties altogether not equal', () { final _TestParagraphStyleBuilder aBuilder = _TestParagraphStyleBuilder(); final _TestParagraphStyleBuilder bBuilder = _TestParagraphStyleBuilder(); for (final String property in _populatorsA.keys) { final _ParagraphStylePropertyPopulator populatorA = _populatorsA[property]!; populatorA(aBuilder); final _ParagraphStylePropertyPopulator populatorB = _populatorsB[property]!; populatorB(bBuilder); } final ui.ParagraphStyle a = aBuilder.build(); final ui.ParagraphStyle b = bBuilder.build(); expect(a, isNot(b)); expect(a.hashCode, isNot(b.hashCode)); }); } typedef _ParagraphStylePropertyPopulator = void Function(_TestParagraphStyleBuilder builder); final Map<String, _ParagraphStylePropertyPopulator> _populatorsA = <String, _ParagraphStylePropertyPopulator>{ 'textAlign': (_TestParagraphStyleBuilder builder) { builder.textAlign = ui.TextAlign.left; }, 'textDirection': (_TestParagraphStyleBuilder builder) { builder.textDirection = ui.TextDirection.rtl; }, 'fontWeight': (_TestParagraphStyleBuilder builder) { builder.fontWeight = ui.FontWeight.w400; }, 'fontStyle': (_TestParagraphStyleBuilder builder) { builder.fontStyle = ui.FontStyle.normal; }, 'maxLines': (_TestParagraphStyleBuilder builder) { builder.maxLines = 1; }, 'fontFamily': (_TestParagraphStyleBuilder builder) { builder.fontFamily = 'Arial'; }, 'fontSize': (_TestParagraphStyleBuilder builder) { builder.fontSize = 12; }, 'height': (_TestParagraphStyleBuilder builder) { builder.height = 13; }, 'textHeightBehavior': (_TestParagraphStyleBuilder builder) { builder.textHeightBehavior = const ui.TextHeightBehavior(); }, 'strutStyle': (_TestParagraphStyleBuilder builder) { builder.strutStyle = ui.StrutStyle(fontFamily: 'Times New Roman'); }, 'ellipsis': (_TestParagraphStyleBuilder builder) { builder.ellipsis = '...'; }, 'locale': (_TestParagraphStyleBuilder builder) { builder.locale = const ui.Locale('en', 'US'); }, }; final Map<String, _ParagraphStylePropertyPopulator> _populatorsB = <String, _ParagraphStylePropertyPopulator>{ 'textAlign': (_TestParagraphStyleBuilder builder) { builder.textAlign = ui.TextAlign.right; }, 'textDirection': (_TestParagraphStyleBuilder builder) { builder.textDirection = ui.TextDirection.ltr; }, 'fontWeight': (_TestParagraphStyleBuilder builder) { builder.fontWeight = ui.FontWeight.w600; }, 'fontStyle': (_TestParagraphStyleBuilder builder) { builder.fontStyle = ui.FontStyle.italic; }, 'maxLines': (_TestParagraphStyleBuilder builder) { builder.maxLines = 2; }, 'fontFamily': (_TestParagraphStyleBuilder builder) { builder.fontFamily = 'Noto'; }, 'fontSize': (_TestParagraphStyleBuilder builder) { builder.fontSize = 12.1; }, 'height': (_TestParagraphStyleBuilder builder) { builder.height = 13.1; }, 'textHeightBehavior': (_TestParagraphStyleBuilder builder) { builder.textHeightBehavior = const ui.TextHeightBehavior(applyHeightToFirstAscent: false); }, 'strutStyle': (_TestParagraphStyleBuilder builder) { builder.strutStyle = ui.StrutStyle(fontFamily: 'sans-serif'); }, 'ellipsis': (_TestParagraphStyleBuilder builder) { builder.ellipsis = '___'; }, 'locale': (_TestParagraphStyleBuilder builder) { builder.locale = const ui.Locale('fr', 'CA'); }, }; class _TestParagraphStyleBuilder { ui.TextAlign? textAlign; ui.TextDirection? textDirection; ui.FontWeight? fontWeight; ui.FontStyle? fontStyle; int? maxLines; String? fontFamily; double? fontSize; double? height; ui.TextHeightBehavior? textHeightBehavior; ui.StrutStyle? strutStyle; String? ellipsis; ui.Locale? locale; ui.ParagraphStyle build() { return ui.ParagraphStyle( textAlign: textAlign, textDirection: textDirection, fontWeight: fontWeight, fontStyle: fontStyle, maxLines: maxLines, fontFamily: fontFamily, fontSize: fontSize, height: height, textHeightBehavior: textHeightBehavior, strutStyle: strutStyle, ellipsis: ellipsis, locale: locale, ); } }
engine/lib/web_ui/test/ui/paragraph_style_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/paragraph_style_test.dart", "repo_id": "engine", "token_count": 2275 }
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. import("//flutter/common/config.gni") import("//flutter/testing/testing.gni") source_set("test_font") { sources = [ "test_font_data.cc", "test_font_data.h", ] deps = [ "//flutter/skia", "//flutter/third_party/txt", ] public_configs = [ "//flutter:config" ] defines = [] if (flutter_runtime_mode == "debug" || current_toolchain == host_toolchain) { # Though the test font data is small, we dont want to add to the binary size # on the device (in profile and release modes). We only add the same on the # host test shells and the debug device shell. defines += [ "EMBED_TEST_FONT_DATA=1" ] } } # Picks the libdart implementation based on the Flutter runtime mode. group("libdart") { public_deps = [] if (flutter_runtime_mode == "profile" || flutter_runtime_mode == "release") { public_deps += [ "$dart_src/runtime:libdart_precompiled_runtime" ] } else { public_deps += [ "$dart_src/runtime:libdart_jit", "//flutter/lib/snapshot", ] } } source_set("dart_plugin_registrant") { sources = [ "dart_plugin_registrant.cc", "dart_plugin_registrant.h", ] deps = [ "$dart_src/runtime:dart_api", "//flutter/fml", "//flutter/third_party/tonic", ] } source_set("runtime") { sources = [ "dart_isolate.cc", "dart_isolate.h", "dart_isolate_group_data.cc", "dart_isolate_group_data.h", "dart_service_isolate.cc", "dart_service_isolate.h", "dart_snapshot.cc", "dart_snapshot.h", "dart_timestamp_provider.cc", "dart_timestamp_provider.h", "dart_vm.cc", "dart_vm.h", "dart_vm_data.cc", "dart_vm_data.h", "dart_vm_initializer.cc", "dart_vm_initializer.h", "dart_vm_lifecycle.cc", "dart_vm_lifecycle.h", "embedder_resources.cc", "embedder_resources.h", "isolate_configuration.cc", "isolate_configuration.h", "platform_data.cc", "platform_data.h", "platform_isolate_manager.cc", "platform_isolate_manager.h", "ptrace_check.h", "runtime_controller.cc", "runtime_controller.h", "runtime_delegate.cc", "runtime_delegate.h", "service_protocol.cc", "service_protocol.h", "skia_concurrent_executor.cc", "skia_concurrent_executor.h", ] if (is_ios && flutter_runtime_mode == "debug") { # These contain references to private APIs and this TU must only be compiled in debug runtime modes. sources += [ "ptrace_check.cc" ] } public_deps = [ "//flutter/lib/gpu", "//flutter/lib/ui", "//flutter/third_party/rapidjson", ] public_configs = [ "//flutter:config" ] deps = [ ":dart_plugin_registrant", ":test_font", "$dart_src/runtime:dart_api", "$dart_src/runtime/bin:dart_io_api", "//flutter/assets", "//flutter/common", "//flutter/flow", "//flutter/fml", "//flutter/lib/io", "//flutter/shell/common:display", "//flutter/skia", "//flutter/third_party/tonic", "//flutter/third_party/txt", ] if (flutter_runtime_mode != "release" && !is_fuchsia) { # Only link in Observatory in non-release modes on non-Fuchsia. Fuchsia # instead puts Observatory into the runner's package. deps += [ "$dart_src/runtime/observatory:embedded_observatory_archive" ] } } if (enable_unittests) { test_fixtures("runtime_fixtures") { dart_main = "fixtures/runtime_test.dart" } executable("runtime_unittests") { testonly = true sources = [ "dart_isolate_unittests.cc", "dart_lifecycle_unittests.cc", "dart_service_isolate_unittests.cc", "dart_vm_unittests.cc", "platform_isolate_manager_unittests.cc", "type_conversions_unittests.cc", ] public_configs = [ "//flutter:export_dynamic_symbols" ] public_deps = [ ":libdart", ":runtime", ":runtime_fixtures", "$dart_src/runtime/bin:elf_loader", "//flutter/common", "//flutter/fml", "//flutter/lib/snapshot", "//flutter/skia", "//flutter/testing", "//flutter/testing:dart", "//flutter/testing:fixture_test", "//flutter/third_party/tonic", ] } test_fixtures("no_plugin_registrant") { dart_main = "fixtures/no_dart_plugin_registrant_test.dart" use_target_as_artifact_prefix = true } executable("no_dart_plugin_registrant_unittests") { testonly = true sources = [ "no_dart_plugin_registrant_unittests.cc" ] public_configs = [ "//flutter:export_dynamic_symbols" ] public_deps = [ ":no_plugin_registrant", "//flutter/fml", "//flutter/lib/snapshot", "//flutter/testing", "//flutter/testing:fixture_test", ] } test_fixtures("plugin_registrant") { dart_main = "fixtures/dart_tool/flutter_build/dart_plugin_registrant.dart" use_target_as_artifact_prefix = true } executable("dart_plugin_registrant_unittests") { testonly = true sources = [ "dart_plugin_registrant_unittests.cc" ] public_configs = [ "//flutter:export_dynamic_symbols" ] public_deps = [ ":plugin_registrant", "//flutter/fml", "//flutter/lib/snapshot", "//flutter/runtime:dart_plugin_registrant", "//flutter/testing", "//flutter/testing:fixture_test", ] } }
engine/runtime/BUILD.gn/0
{ "file_path": "engine/runtime/BUILD.gn", "repo_id": "engine", "token_count": 2355 }
290
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_RUNTIME_DART_TIMESTAMP_PROVIDER_H_ #define FLUTTER_RUNTIME_DART_TIMESTAMP_PROVIDER_H_ #include "flutter/fml/time/timestamp_provider.h" #include "flutter/fml/macros.h" #include "flutter/fml/time/time_point.h" namespace flutter { fml::TimePoint DartTimelineTicksSinceEpoch(); /// TimestampProvider implementation that is backed by Dart_TimelineGetTicks class DartTimestampProvider : fml::TimestampProvider { public: static DartTimestampProvider& Instance() { static DartTimestampProvider instance; return instance; } ~DartTimestampProvider() override; fml::TimePoint Now() override; private: static constexpr int64_t kNanosPerSecond = 1000000000; int64_t ConvertToNanos(int64_t ticks, int64_t frequency); DartTimestampProvider(); FML_DISALLOW_COPY_AND_ASSIGN(DartTimestampProvider); }; } // namespace flutter #endif // FLUTTER_RUNTIME_DART_TIMESTAMP_PROVIDER_H_
engine/runtime/dart_timestamp_provider.h/0
{ "file_path": "engine/runtime/dart_timestamp_provider.h", "repo_id": "engine", "token_count": 367 }
291
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/runtime/isolate_configuration.h" #include "flutter/fml/make_copyable.h" #include "flutter/runtime/dart_vm.h" namespace flutter { IsolateConfiguration::IsolateConfiguration() = default; IsolateConfiguration::~IsolateConfiguration() = default; bool IsolateConfiguration::PrepareIsolate(DartIsolate& isolate) { if (isolate.GetPhase() != DartIsolate::Phase::LibrariesSetup) { FML_DLOG(ERROR) << "Isolate was in incorrect phase to be prepared for running."; return false; } return DoPrepareIsolate(isolate); } class AppSnapshotIsolateConfiguration final : public IsolateConfiguration { public: AppSnapshotIsolateConfiguration() = default; // |IsolateConfiguration| bool DoPrepareIsolate(DartIsolate& isolate) override { return isolate.PrepareForRunningFromPrecompiledCode(); } // |IsolateConfiguration| bool IsNullSafetyEnabled(const DartSnapshot& snapshot) override { return snapshot.IsNullSafetyEnabled(nullptr); } private: FML_DISALLOW_COPY_AND_ASSIGN(AppSnapshotIsolateConfiguration); }; class KernelIsolateConfiguration : public IsolateConfiguration { public: // The kernel mapping may be nullptr if reusing the group's loaded kernel. explicit KernelIsolateConfiguration( std::unique_ptr<const fml::Mapping> kernel) : kernel_(std::move(kernel)) {} // |IsolateConfiguration| bool DoPrepareIsolate(DartIsolate& isolate) override { if (DartVM::IsRunningPrecompiledCode()) { return false; } return isolate.PrepareForRunningFromKernel(std::move(kernel_), /*child_isolate=*/false, /*last_piece=*/true); } // |IsolateConfiguration| bool IsNullSafetyEnabled(const DartSnapshot& snapshot) override { return snapshot.IsNullSafetyEnabled(kernel_.get()); } private: std::unique_ptr<const fml::Mapping> kernel_; FML_DISALLOW_COPY_AND_ASSIGN(KernelIsolateConfiguration); }; class KernelListIsolateConfiguration final : public IsolateConfiguration { public: explicit KernelListIsolateConfiguration( std::vector<std::future<std::unique_ptr<const fml::Mapping>>> kernel_pieces) : kernel_piece_futures_(std::move(kernel_pieces)) { if (kernel_piece_futures_.empty()) { FML_LOG(ERROR) << "Attempted to create kernel list configuration without " "any kernel blobs."; } } // |IsolateConfiguration| bool DoPrepareIsolate(DartIsolate& isolate) override { if (DartVM::IsRunningPrecompiledCode()) { return false; } ResolveKernelPiecesIfNecessary(); if (resolved_kernel_pieces_.empty()) { FML_DLOG(ERROR) << "No kernel pieces provided to prepare this isolate."; return false; } for (size_t i = 0; i < resolved_kernel_pieces_.size(); i++) { if (!resolved_kernel_pieces_[i]) { FML_DLOG(ERROR) << "This kernel list isolate configuration was already " "used to prepare an isolate."; return false; } const bool last_piece = i + 1 == resolved_kernel_pieces_.size(); if (!isolate.PrepareForRunningFromKernel( std::move(resolved_kernel_pieces_[i]), /*child_isolate=*/false, last_piece)) { return false; } } return true; } // |IsolateConfiguration| bool IsNullSafetyEnabled(const DartSnapshot& snapshot) override { ResolveKernelPiecesIfNecessary(); const auto kernel = resolved_kernel_pieces_.empty() ? nullptr : resolved_kernel_pieces_.front().get(); return snapshot.IsNullSafetyEnabled(kernel); } // This must be call as late as possible before accessing any of the kernel // pieces. This will delay blocking on the futures for as long as possible. So // far, only Fuchsia depends on this optimization and only on the non-AOT // configs. void ResolveKernelPiecesIfNecessary() { if (resolved_kernel_pieces_.size() == kernel_piece_futures_.size()) { return; } resolved_kernel_pieces_.clear(); for (auto& piece : kernel_piece_futures_) { // The get() call will xfer the unique pointer out and leave an empty // future in the original vector. resolved_kernel_pieces_.emplace_back(piece.get()); } } private: std::vector<std::future<std::unique_ptr<const fml::Mapping>>> kernel_piece_futures_; std::vector<std::unique_ptr<const fml::Mapping>> resolved_kernel_pieces_; FML_DISALLOW_COPY_AND_ASSIGN(KernelListIsolateConfiguration); }; static std::vector<std::string> ParseKernelListPaths( std::unique_ptr<fml::Mapping> kernel_list) { FML_DCHECK(kernel_list); std::vector<std::string> kernel_pieces_paths; const char* kernel_list_str = reinterpret_cast<const char*>(kernel_list->GetMapping()); size_t kernel_list_size = kernel_list->GetSize(); size_t piece_path_start = 0; while (piece_path_start < kernel_list_size) { size_t piece_path_end = piece_path_start; while ((piece_path_end < kernel_list_size) && (kernel_list_str[piece_path_end] != '\n')) { piece_path_end++; } std::string piece_path(&kernel_list_str[piece_path_start], piece_path_end - piece_path_start); kernel_pieces_paths.emplace_back(std::move(piece_path)); piece_path_start = piece_path_end + 1; } return kernel_pieces_paths; } static std::vector<std::future<std::unique_ptr<const fml::Mapping>>> PrepareKernelMappings(const std::vector<std::string>& kernel_pieces_paths, const std::shared_ptr<AssetManager>& asset_manager, const fml::RefPtr<fml::TaskRunner>& io_worker) { FML_DCHECK(asset_manager); std::vector<std::future<std::unique_ptr<const fml::Mapping>>> fetch_futures; for (const auto& kernel_pieces_path : kernel_pieces_paths) { std::promise<std::unique_ptr<const fml::Mapping>> fetch_promise; fetch_futures.push_back(fetch_promise.get_future()); auto fetch_task = fml::MakeCopyable([asset_manager, kernel_pieces_path, fetch_promise = std::move(fetch_promise)]() mutable { fetch_promise.set_value( asset_manager->GetAsMapping(kernel_pieces_path)); }); // Fulfill the promise on the worker if one is available or the current // thread if one is not. if (io_worker) { io_worker->PostTask(fetch_task); } else { fetch_task(); } } return fetch_futures; } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::InferFromSettings( const Settings& settings, const std::shared_ptr<AssetManager>& asset_manager, const fml::RefPtr<fml::TaskRunner>& io_worker, IsolateLaunchType launch_type) { // Running in AOT mode. if (DartVM::IsRunningPrecompiledCode()) { return CreateForAppSnapshot(); } if (launch_type == IsolateLaunchType::kExistingGroup) { return CreateForKernel(nullptr); } if (settings.application_kernels) { return CreateForKernelList(settings.application_kernels()); } if (settings.application_kernel_asset.empty() && settings.application_kernel_list_asset.empty()) { FML_DLOG(ERROR) << "application_kernel_asset or " "application_kernel_list_asset must be set"; return nullptr; } if (!asset_manager) { FML_DLOG(ERROR) << "No asset manager specified when attempting to create " "isolate configuration."; return nullptr; } // Running from kernel snapshot. Requires asset manager. { std::unique_ptr<fml::Mapping> kernel = asset_manager->GetAsMapping(settings.application_kernel_asset); if (kernel) { return CreateForKernel(std::move(kernel)); } } // Running from kernel divided into several pieces (for sharing). Requires // asset manager and io worker. if (!io_worker) { FML_DLOG(ERROR) << "No IO worker specified to load kernel pieces."; return nullptr; } { std::unique_ptr<fml::Mapping> kernel_list = asset_manager->GetAsMapping(settings.application_kernel_list_asset); if (!kernel_list) { FML_LOG(ERROR) << "Failed to load: " << settings.application_kernel_list_asset; return nullptr; } auto kernel_pieces_paths = ParseKernelListPaths(std::move(kernel_list)); auto kernel_mappings = PrepareKernelMappings(kernel_pieces_paths, asset_manager, io_worker); return CreateForKernelList(std::move(kernel_mappings)); } return nullptr; } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::CreateForAppSnapshot() { return std::make_unique<AppSnapshotIsolateConfiguration>(); } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::CreateForKernel( std::unique_ptr<const fml::Mapping> kernel) { return std::make_unique<KernelIsolateConfiguration>(std::move(kernel)); } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::CreateForKernelList( std::vector<std::unique_ptr<const fml::Mapping>> kernel_pieces) { std::vector<std::future<std::unique_ptr<const fml::Mapping>>> pieces; for (auto& piece : kernel_pieces) { if (!piece) { FML_DLOG(ERROR) << "Invalid kernel piece."; continue; } std::promise<std::unique_ptr<const fml::Mapping>> promise; pieces.push_back(promise.get_future()); promise.set_value(std::move(piece)); } return CreateForKernelList(std::move(pieces)); } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::CreateForKernelList( std::vector<std::future<std::unique_ptr<const fml::Mapping>>> kernel_pieces) { return std::make_unique<KernelListIsolateConfiguration>( std::move(kernel_pieces)); } } // namespace flutter
engine/runtime/isolate_configuration.cc/0
{ "file_path": "engine/runtime/isolate_configuration.cc", "repo_id": "engine", "token_count": 3738 }
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. #include "flutter/runtime/skia_concurrent_executor.h" #include "flutter/fml/trace_event.h" namespace flutter { SkiaConcurrentExecutor::SkiaConcurrentExecutor(const OnWorkCallback& on_work) : on_work_(on_work) {} SkiaConcurrentExecutor::~SkiaConcurrentExecutor() = default; void SkiaConcurrentExecutor::add(fml::closure work) { if (!work) { return; } on_work_([work]() { TRACE_EVENT0("flutter", "SkiaExecutor"); work(); }); } } // namespace flutter
engine/runtime/skia_concurrent_executor.cc/0
{ "file_path": "engine/runtime/skia_concurrent_executor.cc", "repo_id": "engine", "token_count": 228 }
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. #include "flutter/shell/common/shell.h" #include "flutter/benchmarking/benchmarking.h" #include "flutter/shell/common/thread_host.h" #include "flutter/testing/dart_fixture.h" #include "flutter/testing/dart_isolate_runner.h" #include "flutter/testing/testing.h" #include "fml/synchronization/count_down_latch.h" #include "runtime/dart_vm_lifecycle.h" // CREATE_NATIVE_ENTRY is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) namespace flutter::testing { class DartNativeBenchmarks : public DartFixture, public benchmark::Fixture { public: DartNativeBenchmarks() : DartFixture() {} void SetUp(const ::benchmark::State& state) {} void TearDown(const ::benchmark::State& state) {} private: FML_DISALLOW_COPY_AND_ASSIGN(DartNativeBenchmarks); }; BENCHMARK_F(DartNativeBenchmarks, TimeToFirstNativeMessageFromIsolateInNewVM) (benchmark::State& st) { while (st.KeepRunning()) { fml::AutoResetWaitableEvent latch; st.PauseTiming(); ASSERT_FALSE(DartVMRef::IsInstanceRunning()); AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY(([&latch](Dart_NativeArguments args) { latch.Signal(); }))); const auto settings = CreateSettingsForFixture(); DartVMRef vm_ref = DartVMRef::Create(settings); ThreadHost thread_host("io.flutter.test.DartNativeBenchmarks.", ThreadHost::Type::kPlatform | ThreadHost::Type::kIo | ThreadHost::Type::kUi); TaskRunners task_runners( "test", thread_host.platform_thread->GetTaskRunner(), // platform thread_host.platform_thread->GetTaskRunner(), // raster thread_host.ui_thread->GetTaskRunner(), // ui thread_host.io_thread->GetTaskRunner() // io ); { st.ResumeTiming(); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "notifyNative", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); latch.Wait(); } } } BENCHMARK_F(DartNativeBenchmarks, MultipleDartToNativeMessages) (benchmark::State& st) { while (st.KeepRunning()) { fml::CountDownLatch latch(1000); st.PauseTiming(); ASSERT_FALSE(DartVMRef::IsInstanceRunning()); AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY(([&latch](Dart_NativeArguments args) { latch.CountDown(); }))); const auto settings = CreateSettingsForFixture(); DartVMRef vm_ref = DartVMRef::Create(settings); ThreadHost thread_host("io.flutter.test.DartNativeBenchmarks.", ThreadHost::Type::kPlatform | ThreadHost::Type::kIo | ThreadHost::Type::kUi); TaskRunners task_runners( "test", thread_host.platform_thread->GetTaskRunner(), // platform thread_host.platform_thread->GetTaskRunner(), // raster thread_host.ui_thread->GetTaskRunner(), // ui thread_host.io_thread->GetTaskRunner() // io ); { st.ResumeTiming(); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "thousandCallsToNative", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); latch.Wait(); } } } } // namespace flutter::testing // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/shell/common/dart_native_benchmarks.cc/0
{ "file_path": "engine/shell/common/dart_native_benchmarks.cc", "repo_id": "engine", "token_count": 1673 }
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. #include "flutter/common/graphics/persistent_cache.h" #include <memory> #include "flutter/assets/directory_asset_bundle.h" #include "flutter/flow/layers/container_layer.h" #include "flutter/flow/layers/layer.h" #include "flutter/fml/command_line.h" #include "flutter/fml/file.h" #include "flutter/fml/log_settings.h" #include "flutter/fml/unique_fd.h" #include "flutter/shell/common/shell_test.h" #include "flutter/shell/common/switches.h" #include "flutter/shell/version/version.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { using PersistentCacheTest = ShellTest; static void CheckTextSkData(const sk_sp<SkData>& data, const std::string& expected) { std::string data_string(reinterpret_cast<const char*>(data->bytes()), data->size()); ASSERT_EQ(data_string, expected); } static void ResetAssetManager() { PersistentCache::SetAssetManager(nullptr); ASSERT_EQ(PersistentCache::GetCacheForProcess()->LoadSkSLs().size(), 0u); } static void CheckTwoSkSLsAreLoaded() { auto shaders = PersistentCache::GetCacheForProcess()->LoadSkSLs(); ASSERT_EQ(shaders.size(), 2u); } TEST_F(PersistentCacheTest, CanLoadSkSLsFromAsset) { // Avoid polluting unit tests output by hiding INFO level logging. fml::LogSettings warning_only = {fml::kLogWarning}; fml::ScopedSetLogSettings scoped_set_log_settings(warning_only); // The SkSL key is Base32 encoded. "IE" is the encoding of "A" and "II" is the // encoding of "B". // // The SkSL data is Base64 encoded. "eA==" is the encoding of "x" and "eQ==" // is the encoding of "y". const std::string kTestJson = "{\n" " \"data\": {\n" " \"IE\": \"eA==\",\n" " \"II\": \"eQ==\"\n" " }\n" "}\n"; // Temp dir for the asset. fml::ScopedTemporaryDirectory asset_dir; auto data = std::make_unique<fml::DataMapping>( std::vector<uint8_t>{kTestJson.begin(), kTestJson.end()}); fml::WriteAtomically(asset_dir.fd(), PersistentCache::kAssetFileName, *data); // 1st, test that RunConfiguration::InferFromSettings sets the asset manager. ResetAssetManager(); auto settings = CreateSettingsForFixture(); settings.assets_path = asset_dir.path(); RunConfiguration::InferFromSettings(settings); CheckTwoSkSLsAreLoaded(); // 2nd, test that the RunConfiguration constructor sets the asset manager. // (Android is directly calling that constructor without InferFromSettings.) ResetAssetManager(); auto asset_manager = std::make_shared<AssetManager>(); RunConfiguration config(nullptr, asset_manager); asset_manager->PushBack(std::make_unique<DirectoryAssetBundle>( fml::OpenDirectory(asset_dir.path().c_str(), false, fml::FilePermission::kRead), false)); CheckTwoSkSLsAreLoaded(); // 3rd, test the content of the SkSLs in the asset. { auto shaders = PersistentCache::GetCacheForProcess()->LoadSkSLs(); ASSERT_EQ(shaders.size(), 2u); // Make sure that the 2 shaders are sorted by their keys. Their keys should // be "A" and "B" (decoded from "II" and "IE"). if (shaders[0].key->bytes()[0] == 'B') { std::swap(shaders[0], shaders[1]); } CheckTextSkData(shaders[0].key, "A"); CheckTextSkData(shaders[1].key, "B"); CheckTextSkData(shaders[0].value, "x"); CheckTextSkData(shaders[1].value, "y"); } // Cleanup. fml::UnlinkFile(asset_dir.fd(), PersistentCache::kAssetFileName); } TEST_F(PersistentCacheTest, CanRemoveOldPersistentCache) { fml::ScopedTemporaryDirectory base_dir; ASSERT_TRUE(base_dir.fd().is_valid()); fml::CreateDirectory(base_dir.fd(), {"flutter_engine", GetFlutterEngineVersion(), "skia"}, fml::FilePermission::kReadWrite); constexpr char kOldEngineVersion[] = "old"; auto old_created = fml::CreateDirectory( base_dir.fd(), {"flutter_engine", kOldEngineVersion, "skia"}, fml::FilePermission::kReadWrite); ASSERT_TRUE(old_created.is_valid()); PersistentCache::SetCacheDirectoryPath(base_dir.path()); PersistentCache::ResetCacheForProcess(); auto engine_dir = fml::OpenDirectoryReadOnly(base_dir.fd(), "flutter_engine"); auto current_dir = fml::OpenDirectoryReadOnly(engine_dir, GetFlutterEngineVersion()); auto old_dir = fml::OpenDirectoryReadOnly(engine_dir, kOldEngineVersion); ASSERT_TRUE(engine_dir.is_valid()); ASSERT_TRUE(current_dir.is_valid()); ASSERT_FALSE(old_dir.is_valid()); // Cleanup fml::RemoveFilesInDirectory(base_dir.fd()); } TEST_F(PersistentCacheTest, CanPurgePersistentCache) { fml::ScopedTemporaryDirectory base_dir; ASSERT_TRUE(base_dir.fd().is_valid()); auto cache_dir = fml::CreateDirectory( base_dir.fd(), {"flutter_engine", GetFlutterEngineVersion(), "skia", GetSkiaVersion()}, fml::FilePermission::kReadWrite); PersistentCache::SetCacheDirectoryPath(base_dir.path()); PersistentCache::ResetCacheForProcess(); // Generate a dummy persistent cache. fml::DataMapping test_data(std::string("test")); ASSERT_TRUE(fml::WriteAtomically(cache_dir, "test", test_data)); auto file = fml::OpenFileReadOnly(cache_dir, "test"); ASSERT_TRUE(file.is_valid()); // Run engine with purge_persistent_cache to remove the dummy cache. auto settings = CreateSettingsForFixture(); settings.purge_persistent_cache = true; auto config = RunConfiguration::InferFromSettings(settings); std::unique_ptr<Shell> shell = CreateShell(settings); RunEngine(shell.get(), std::move(config)); // Verify that the dummy is purged. file = fml::OpenFileReadOnly(cache_dir, "test"); ASSERT_FALSE(file.is_valid()); // Cleanup fml::RemoveFilesInDirectory(base_dir.fd()); DestroyShell(std::move(shell)); } TEST_F(PersistentCacheTest, PurgeAllowsFutureSkSLCache) { sk_sp<SkData> shader_key = SkData::MakeWithCString("key"); sk_sp<SkData> shader_value = SkData::MakeWithCString("value"); std::string shader_filename = PersistentCache::SkKeyToFilePath(*shader_key); fml::ScopedTemporaryDirectory base_dir; ASSERT_TRUE(base_dir.fd().is_valid()); PersistentCache::SetCacheDirectoryPath(base_dir.path()); PersistentCache::ResetCacheForProcess(); // Run engine with purge_persistent_cache and cache_sksl. auto settings = CreateSettingsForFixture(); settings.purge_persistent_cache = true; settings.cache_sksl = true; auto config = RunConfiguration::InferFromSettings(settings); std::unique_ptr<Shell> shell = CreateShell(settings); RunEngine(shell.get(), std::move(config)); auto persistent_cache = PersistentCache::GetCacheForProcess(); ASSERT_EQ(persistent_cache->LoadSkSLs().size(), 0u); // Store the cache and verify it's valid. StorePersistentCache(persistent_cache, *shader_key, *shader_value); std::promise<bool> io_flushed; shell->GetTaskRunners().GetIOTaskRunner()->PostTask( [&io_flushed]() { io_flushed.set_value(true); }); io_flushed.get_future().get(); // Wait for the IO thread to flush the file. ASSERT_GT(persistent_cache->LoadSkSLs().size(), 0u); // Cleanup fml::RemoveFilesInDirectory(base_dir.fd()); DestroyShell(std::move(shell)); } } // namespace testing } // namespace flutter
engine/shell/common/persistent_cache_unittests.cc/0
{ "file_path": "engine/shell/common/persistent_cache_unittests.cc", "repo_id": "engine", "token_count": 2660 }
295
// Copyright 2013 The Flutter 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_RUN_CONFIGURATION_H_ #define FLUTTER_SHELL_COMMON_RUN_CONFIGURATION_H_ #include <memory> #include <string> #include "flutter/assets/asset_manager.h" #include "flutter/assets/asset_resolver.h" #include "flutter/common/settings.h" #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "flutter/fml/unique_fd.h" #include "flutter/runtime/isolate_configuration.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief Specifies all the configuration required by the runtime library /// to launch the root isolate. This object may be created on any /// thread but must be given to the |Run| call of the |Engine| on /// the UI thread. The configuration object is used to specify how /// the root isolate finds its snapshots, assets, root library and /// the "main" entrypoint. /// class RunConfiguration { public: //---------------------------------------------------------------------------- /// @brief Attempts to infer a run configuration from the settings /// object. This tries to create a run configuration with sensible /// defaults for the given Dart VM runtime mode. In JIT mode, this /// will attempt to look for the VM and isolate snapshots in the /// assets directory (must be specified in settings). In AOT mode, /// it will attempt to look for known snapshot symbols in the /// currently loaded process. The entrypoint defaults to /// the "main" method in the root library. /// /// @param[in] settings The settings object used to look for the various /// snapshots and settings. This is usually initialized /// from command line arguments. /// @param[in] io_worker An optional IO worker. Resolving and reading the /// various snapshots may be slow. Providing an IO /// worker will ensure that realization of these /// snapshots happens on a worker thread instead of the /// calling thread. Note that the work done to realize /// the snapshots may occur after this call returns. If /// is the embedder's responsibility to make sure the /// serial worker is kept alive for the lifetime of the /// shell associated with the engine that this run /// configuration is given to. /// @param[in] launch_type Whether to launch the new isolate into an existing /// group or a new one. /// /// @return A run configuration. Depending on the completeness of the /// settings, This object may potentially be invalid. /// static RunConfiguration InferFromSettings( const Settings& settings, const fml::RefPtr<fml::TaskRunner>& io_worker = nullptr, IsolateLaunchType launch_type = IsolateLaunchType::kNewGroup); //---------------------------------------------------------------------------- /// @brief Creates a run configuration with only an isolate /// configuration. There is no asset manager and default /// entrypoint and root library are used ("main" in root library). /// /// @param[in] configuration The configuration /// explicit RunConfiguration( std::unique_ptr<IsolateConfiguration> configuration); //---------------------------------------------------------------------------- /// @brief Creates a run configuration with the specified isolate /// configuration and asset manager. The default entrypoint and /// root library are used ("main" in root library). /// /// @param[in] configuration The configuration /// @param[in] asset_manager The asset manager /// RunConfiguration(std::unique_ptr<IsolateConfiguration> configuration, std::shared_ptr<AssetManager> asset_manager); //---------------------------------------------------------------------------- /// @brief Run configurations cannot be copied because it may not always /// be possible to copy the underlying isolate snapshots. If /// multiple run configurations share the same underlying /// snapshots, creating a configuration from isolate snapshots /// sharing the same underlying buffers is recommended. /// /// @param config The run configuration to move. /// RunConfiguration(RunConfiguration&& config); //---------------------------------------------------------------------------- /// @brief There are no threading restrictions on the destruction of the /// run configuration. /// ~RunConfiguration(); //---------------------------------------------------------------------------- /// @brief A valid run configuration only guarantees that the engine /// should be able to find the assets and the isolate snapshots /// when it attempts to launch the root isolate. The validity of /// the snapshot cannot be determined yet. That determination can /// only be made when the configuration is used to run the root /// isolate in the engine. However, the engine will always reject /// an invalid run configuration. /// /// @attention A valid run configuration does not mean that the root isolate /// will always be launched. It only indicates that the various /// snapshots are isolate snapshots and asset managers are present /// and accounted for. The validity of the snapshots will only be /// checked when the engine attempts to launch the root isolate. /// /// @return Returns whether the snapshots and asset manager registrations /// are valid. /// bool IsValid() const; //---------------------------------------------------------------------------- /// @brief Asset managers maintain a list of resolvers that are checked /// in order when attempting to locate an asset. This method adds /// a resolver to the end of the list. /// /// @param[in] resolver The asset resolver to add to the engine of the list /// resolvers maintained by the asset manager. /// /// @return Returns whether the resolver was successfully registered. The /// resolver must be valid for its registration to be successful. /// bool AddAssetResolver(std::unique_ptr<AssetResolver> resolver); //---------------------------------------------------------------------------- /// @brief Updates the main application entrypoint. If this is not set, /// the /// "main" method is used as the entrypoint. /// /// @param[in] entrypoint The entrypoint to use. void SetEntrypoint(std::string entrypoint); //---------------------------------------------------------------------------- /// @brief Specifies the main Dart entrypoint and the library to find /// that entrypoint in. By default, this is the "main" method in /// the root library. The root library may be specified by /// entering the empty string as the second argument. /// /// @see SetEntrypoint() /// /// @param[in] entrypoint The entrypoint /// @param[in] library The library /// void SetEntrypointAndLibrary(std::string entrypoint, std::string library); //---------------------------------------------------------------------------- /// @brief Updates the main application entrypoint arguments. /// /// @param[in] entrypoint_args The entrypoint arguments to use. void SetEntrypointArgs(std::vector<std::string> entrypoint_args); //---------------------------------------------------------------------------- /// @return The asset manager referencing all previously registered asset /// resolvers. /// std::shared_ptr<AssetManager> GetAssetManager() const; //---------------------------------------------------------------------------- /// @return The main Dart entrypoint to be used for the root isolate. /// const std::string& GetEntrypoint() const; //---------------------------------------------------------------------------- /// @return The name of the library in which the main entrypoint resides. /// If empty, the root library is used. /// const std::string& GetEntrypointLibrary() const; //---------------------------------------------------------------------------- /// @return Arguments passed as a List<String> to Dart's entrypoint /// function. /// const std::vector<std::string>& GetEntrypointArgs() const; //---------------------------------------------------------------------------- /// @brief The engine uses this to take the isolate configuration from /// the run configuration. The run configuration is no longer /// valid after this call is made. The non-copyable nature of some /// of the snapshots referenced in the isolate configuration is /// why the run configuration as a whole is not copyable. /// /// @return The run configuration if one is present. /// std::unique_ptr<IsolateConfiguration> TakeIsolateConfiguration(); private: std::unique_ptr<IsolateConfiguration> isolate_configuration_; std::shared_ptr<AssetManager> asset_manager_; std::string entrypoint_ = "main"; std::string entrypoint_library_ = ""; std::vector<std::string> entrypoint_args_; FML_DISALLOW_COPY_AND_ASSIGN(RunConfiguration); }; } // namespace flutter #endif // FLUTTER_SHELL_COMMON_RUN_CONFIGURATION_H_
engine/shell/common/run_configuration.h/0
{ "file_path": "engine/shell/common/run_configuration.h", "repo_id": "engine", "token_count": 3139 }
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. #include "flutter/shell/common/shell_test_platform_view_gl.h" #include <utility> #include <EGL/egl.h> #include "flutter/shell/gpu/gpu_surface_gl_skia.h" #include "impeller/entity/gles/entity_shaders_gles.h" #if IMPELLER_ENABLE_3D #include "impeller/scene/shaders/gles/scene_shaders_gles.h" // nogncheck #endif namespace flutter { namespace testing { static std::vector<std::shared_ptr<fml::Mapping>> ShaderLibraryMappings() { return { std::make_shared<fml::NonOwnedMapping>( impeller_entity_shaders_gles_data, impeller_entity_shaders_gles_length), #if IMPELLER_ENABLE_3D std::make_shared<fml::NonOwnedMapping>( impeller_scene_shaders_gles_data, impeller_scene_shaders_gles_length), #endif }; } ShellTestPlatformViewGL::ShellTestPlatformViewGL( PlatformView::Delegate& delegate, const TaskRunners& task_runners, std::shared_ptr<ShellTestVsyncClock> vsync_clock, CreateVsyncWaiter create_vsync_waiter, std::shared_ptr<ShellTestExternalViewEmbedder> shell_test_external_view_embedder) : ShellTestPlatformView(delegate, task_runners), gl_surface_(SkISize::Make(800, 600)), create_vsync_waiter_(std::move(create_vsync_waiter)), vsync_clock_(std::move(vsync_clock)), shell_test_external_view_embedder_( std::move(shell_test_external_view_embedder)) { if (GetSettings().enable_impeller) { auto resolver = [](const char* name) -> void* { return reinterpret_cast<void*>(::eglGetProcAddress(name)); }; // ANGLE needs this to initialize version strings checked by // impeller::ProcTableGLES. gl_surface_.MakeCurrent(); auto gl = std::make_unique<impeller::ProcTableGLES>(resolver); if (!gl->IsValid()) { FML_LOG(ERROR) << "Proc table when a shell unittests invalid."; return; } impeller_context_ = impeller::ContextGLES::Create( std::move(gl), ShaderLibraryMappings(), true); } } ShellTestPlatformViewGL::~ShellTestPlatformViewGL() = default; std::unique_ptr<VsyncWaiter> ShellTestPlatformViewGL::CreateVSyncWaiter() { return create_vsync_waiter_(); } // |ShellTestPlatformView| void ShellTestPlatformViewGL::SimulateVSync() { vsync_clock_->SimulateVSync(); } // |PlatformView| std::unique_ptr<Surface> ShellTestPlatformViewGL::CreateRenderingSurface() { return std::make_unique<GPUSurfaceGLSkia>(this, true); } // |PlatformView| std::shared_ptr<ExternalViewEmbedder> ShellTestPlatformViewGL::CreateExternalViewEmbedder() { return shell_test_external_view_embedder_; } // |PlatformView| PointerDataDispatcherMaker ShellTestPlatformViewGL::GetDispatcherMaker() { return [](DefaultPointerDataDispatcher::Delegate& delegate) { return std::make_unique<SmoothPointerDataDispatcher>(delegate); }; } // |GPUSurfaceGLDelegate| std::unique_ptr<GLContextResult> ShellTestPlatformViewGL::GLContextMakeCurrent() { return std::make_unique<GLContextDefaultResult>(gl_surface_.MakeCurrent()); } // |GPUSurfaceGLDelegate| bool ShellTestPlatformViewGL::GLContextClearCurrent() { return gl_surface_.ClearCurrent(); } // |GPUSurfaceGLDelegate| bool ShellTestPlatformViewGL::GLContextPresent( const GLPresentInfo& present_info) { return gl_surface_.Present(); } // |GPUSurfaceGLDelegate| GLFBOInfo ShellTestPlatformViewGL::GLContextFBO(GLFrameInfo frame_info) const { return GLFBOInfo{ .fbo_id = gl_surface_.GetFramebuffer(frame_info.width, frame_info.height), }; } // |GPUSurfaceGLDelegate| GPUSurfaceGLDelegate::GLProcResolver ShellTestPlatformViewGL::GetGLProcResolver() const { return [surface = &gl_surface_](const char* name) -> void* { return surface->GetProcAddress(name); }; } } // namespace testing } // namespace flutter
engine/shell/common/shell_test_platform_view_gl.cc/0
{ "file_path": "engine/shell/common/shell_test_platform_view_gl.cc", "repo_id": "engine", "token_count": 1430 }
297
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <sstream> #include <string> #include "flutter/fml/native_library.h" #include "flutter/fml/paths.h" #include "flutter/fml/size.h" #include "flutter/shell/version/version.h" // Include once for the default enum definition. #include "flutter/shell/common/switches.h" #undef FLUTTER_SHELL_COMMON_SWITCHES_H_ struct SwitchDesc { flutter::Switch sw; const std::string_view flag; const char* help; }; #undef DEF_SWITCHES_START #undef DEF_SWITCH #undef DEF_SWITCHES_END // clang-format off #define DEF_SWITCHES_START static const struct SwitchDesc gSwitchDescs[] = { #define DEF_SWITCH(p_swtch, p_flag, p_help) \ { flutter::Switch:: p_swtch, p_flag, p_help }, #define DEF_SWITCHES_END }; // clang-format on // List of common and safe VM flags to allow to be passed directly to the VM. #if FLUTTER_RELEASE // clang-format off static const std::string kAllowedDartFlags[] = { "--enable-isolate-groups", "--no-enable-isolate-groups", }; // clang-format on #else // clang-format off static const std::string kAllowedDartFlags[] = { "--enable-isolate-groups", "--no-enable-isolate-groups", "--enable_mirrors", "--enable-service-port-fallback", "--max_profile_depth", "--profile_period", "--random_seed", "--sample-buffer-duration", "--trace-kernel", "--trace-reload", "--trace-reload-verbose", "--write-service-info", "--null_assertions", "--strict_null_safety_checks", "--max_subtype_cache_entries", }; // clang-format on #endif // FLUTTER_RELEASE // Include again for struct definition. #include "flutter/shell/common/switches.h" // Define symbols for the ICU data that is linked into the Flutter library on // Android. This is a workaround for crashes seen when doing dynamic lookups // of the engine's own symbols on some older versions of Android. #if FML_OS_ANDROID extern uint8_t _binary_icudtl_dat_start[]; extern size_t _binary_icudtl_dat_size; static std::unique_ptr<fml::Mapping> GetICUStaticMapping() { return std::make_unique<fml::NonOwnedMapping>(_binary_icudtl_dat_start, _binary_icudtl_dat_size); } #endif namespace flutter { void PrintUsage(const std::string& executable_name) { std::cerr << std::endl << " " << executable_name << std::endl << std::endl; std::cerr << "Versions: " << std::endl << std::endl; std::cerr << "Flutter Engine Version: " << GetFlutterEngineVersion() << std::endl; std::cerr << "Skia Version: " << GetSkiaVersion() << std::endl; std::cerr << "Dart Version: " << GetDartVersion() << std::endl << std::endl; std::cerr << "Available Flags:" << std::endl; const uint32_t column_width = 80; const uint32_t flags_count = static_cast<uint32_t>(Switch::Sentinel); uint32_t max_width = 2; for (uint32_t i = 0; i < flags_count; i++) { auto desc = gSwitchDescs[i]; max_width = std::max<uint32_t>(desc.flag.size() + 2, max_width); } const uint32_t help_width = column_width - max_width - 3; std::cerr << std::string(column_width, '-') << std::endl; for (uint32_t i = 0; i < flags_count; i++) { auto desc = gSwitchDescs[i]; std::cerr << std::setw(max_width) << std::string("--") + std::string{desc.flag.data(), desc.flag.size()} << " : "; std::istringstream stream(desc.help); int32_t remaining = help_width; std::string word; while (stream >> word && remaining > 0) { remaining -= (word.size() + 1); if (remaining <= 0) { std::cerr << std::endl << std::string(max_width, ' ') << " " << word << " "; remaining = help_width; } else { std::cerr << word << " "; } } std::cerr << std::endl; } std::cerr << std::string(column_width, '-') << std::endl; } const std::string_view FlagForSwitch(Switch swtch) { for (uint32_t i = 0; i < static_cast<uint32_t>(Switch::Sentinel); i++) { if (gSwitchDescs[i].sw == swtch) { return gSwitchDescs[i].flag; } } return std::string_view(); } static std::vector<std::string> ParseCommaDelimited(const std::string& input) { std::istringstream ss(input); std::vector<std::string> result; std::string token; while (std::getline(ss, token, ',')) { result.push_back(token); } return result; } static bool IsAllowedDartVMFlag(const std::string& flag) { for (uint32_t i = 0; i < fml::size(kAllowedDartFlags); ++i) { const std::string& allowed = kAllowedDartFlags[i]; // Check that the prefix of the flag matches one of the allowed flags. This // is to handle cases where flags take arguments, such as in // "--max_profile_depth 1". // // We don't need to worry about cases like "--safe --sneaky_dangerous" as // the VM will discard these as a single unrecognized flag. if (flag.length() >= allowed.length() && std::equal(allowed.begin(), allowed.end(), flag.begin())) { return true; } } return false; } template <typename T> static bool GetSwitchValue(const fml::CommandLine& command_line, Switch sw, T* result) { std::string switch_string; if (!command_line.GetOptionValue(FlagForSwitch(sw), &switch_string)) { return false; } std::stringstream stream(switch_string); T value = 0; if (stream >> value) { *result = value; return true; } return false; } std::unique_ptr<fml::Mapping> GetSymbolMapping( const std::string& symbol_prefix, const std::string& native_lib_path) { const uint8_t* mapping = nullptr; intptr_t size; auto lookup_symbol = [&mapping, &size, symbol_prefix]( const fml::RefPtr<fml::NativeLibrary>& library) { mapping = library->ResolveSymbol((symbol_prefix + "_start").c_str()); size = reinterpret_cast<intptr_t>( library->ResolveSymbol((symbol_prefix + "_size").c_str())); }; fml::RefPtr<fml::NativeLibrary> library = fml::NativeLibrary::CreateForCurrentProcess(); lookup_symbol(library); if (!(mapping && size)) { // Symbol lookup for the current process fails on some devices. As a // fallback, try doing the lookup based on the path to the Flutter library. library = fml::NativeLibrary::Create(native_lib_path.c_str()); lookup_symbol(library); } FML_CHECK(mapping && size) << "Unable to resolve symbols: " << symbol_prefix; return std::make_unique<fml::NonOwnedMapping>(mapping, size); } Settings SettingsFromCommandLine(const fml::CommandLine& command_line) { Settings settings = {}; // Set executable name. if (command_line.has_argv0()) { settings.executable_name = command_line.argv0(); } // Enable the VM Service settings.enable_vm_service = !command_line.HasOption(FlagForSwitch(Switch::DisableVMService)) && // TODO(bkonyi): remove once flutter_tools no longer uses this option. // See https://github.com/dart-lang/sdk/issues/50233 !command_line.HasOption(FlagForSwitch(Switch::DisableObservatory)); // Enable mDNS VM Service Publication settings.enable_vm_service_publication = !command_line.HasOption( FlagForSwitch(Switch::DisableVMServicePublication)) && !command_line.HasOption( FlagForSwitch(Switch::DisableObservatoryPublication)); // Set VM Service Host if (command_line.HasOption(FlagForSwitch(Switch::DeviceVMServiceHost))) { command_line.GetOptionValue(FlagForSwitch(Switch::DeviceVMServiceHost), &settings.vm_service_host); } else if (command_line.HasOption( FlagForSwitch(Switch::DeviceObservatoryHost))) { // TODO(bkonyi): remove once flutter_tools no longer uses this option. // See https://github.com/dart-lang/sdk/issues/50233 command_line.GetOptionValue(FlagForSwitch(Switch::DeviceObservatoryHost), &settings.vm_service_host); } // Default the VM Service port based on --ipv6 if not set. if (settings.vm_service_host.empty()) { settings.vm_service_host = command_line.HasOption(FlagForSwitch(Switch::IPv6)) ? "::1" : "127.0.0.1"; } // Set VM Service Port if (command_line.HasOption(FlagForSwitch(Switch::DeviceVMServicePort))) { if (!GetSwitchValue(command_line, Switch::DeviceVMServicePort, &settings.vm_service_port)) { FML_LOG(INFO) << "VM Service port specified was malformed. Will default to " << settings.vm_service_port; } } else if (command_line.HasOption( FlagForSwitch(Switch::DeviceObservatoryPort))) { // TODO(bkonyi): remove once flutter_tools no longer uses this option. // See https://github.com/dart-lang/sdk/issues/50233 if (!GetSwitchValue(command_line, Switch::DeviceObservatoryPort, &settings.vm_service_port)) { FML_LOG(INFO) << "VM Service port specified was malformed. Will default to " << settings.vm_service_port; } } settings.may_insecurely_connect_to_all_domains = !command_line.HasOption( FlagForSwitch(Switch::DisallowInsecureConnections)); command_line.GetOptionValue(FlagForSwitch(Switch::DomainNetworkPolicy), &settings.domain_network_policy); // Disable need for authentication codes for VM service communication, if // specified. settings.disable_service_auth_codes = command_line.HasOption(FlagForSwitch(Switch::DisableServiceAuthCodes)); // Allow fallback to automatic port selection if binding to a specified port // fails. settings.enable_service_port_fallback = command_line.HasOption(FlagForSwitch(Switch::EnableServicePortFallback)); // Checked mode overrides. settings.disable_dart_asserts = command_line.HasOption(FlagForSwitch(Switch::DisableDartAsserts)); settings.start_paused = command_line.HasOption(FlagForSwitch(Switch::StartPaused)); settings.enable_checked_mode = command_line.HasOption(FlagForSwitch(Switch::EnableCheckedMode)); settings.enable_dart_profiling = command_line.HasOption(FlagForSwitch(Switch::EnableDartProfiling)); settings.enable_software_rendering = command_line.HasOption(FlagForSwitch(Switch::EnableSoftwareRendering)); settings.endless_trace_buffer = command_line.HasOption(FlagForSwitch(Switch::EndlessTraceBuffer)); settings.trace_startup = command_line.HasOption(FlagForSwitch(Switch::TraceStartup)); settings.enable_serial_gc = command_line.HasOption(FlagForSwitch(Switch::EnableSerialGC)); #if !FLUTTER_RELEASE settings.trace_skia = true; if (command_line.HasOption(FlagForSwitch(Switch::TraceSkia))) { // If --trace-skia is specified, then log all Skia events. settings.trace_skia_allowlist.reset(); } else { std::string trace_skia_allowlist; command_line.GetOptionValue(FlagForSwitch(Switch::TraceSkiaAllowlist), &trace_skia_allowlist); if (trace_skia_allowlist.size()) { settings.trace_skia_allowlist = ParseCommaDelimited(trace_skia_allowlist); } else { settings.trace_skia_allowlist = {"skia.shaders"}; } } #endif // !FLUTTER_RELEASE std::string trace_allowlist; command_line.GetOptionValue(FlagForSwitch(Switch::TraceAllowlist), &trace_allowlist); settings.trace_allowlist = ParseCommaDelimited(trace_allowlist); settings.trace_systrace = command_line.HasOption(FlagForSwitch(Switch::TraceSystrace)); command_line.GetOptionValue(FlagForSwitch(Switch::TraceToFile), &settings.trace_to_file); settings.skia_deterministic_rendering_on_cpu = command_line.HasOption(FlagForSwitch(Switch::SkiaDeterministicRendering)); settings.verbose_logging = command_line.HasOption(FlagForSwitch(Switch::VerboseLogging)); command_line.GetOptionValue(FlagForSwitch(Switch::FlutterAssetsDir), &settings.assets_path); std::vector<std::string_view> aot_shared_library_name = command_line.GetOptionValues(FlagForSwitch(Switch::AotSharedLibraryName)); std::vector<std::string_view> vmservice_shared_library_name = command_line.GetOptionValues( FlagForSwitch(Switch::AotVMServiceSharedLibraryName)); for (auto path : vmservice_shared_library_name) { settings.vmservice_snapshot_library_path.emplace_back(path); } std::string snapshot_asset_path; command_line.GetOptionValue(FlagForSwitch(Switch::SnapshotAssetPath), &snapshot_asset_path); std::string vm_snapshot_data_filename; command_line.GetOptionValue(FlagForSwitch(Switch::VmSnapshotData), &vm_snapshot_data_filename); command_line.GetOptionValue(FlagForSwitch(Switch::Route), &settings.route); std::string vm_snapshot_instr_filename; command_line.GetOptionValue(FlagForSwitch(Switch::VmSnapshotInstructions), &vm_snapshot_instr_filename); std::string isolate_snapshot_data_filename; command_line.GetOptionValue(FlagForSwitch(Switch::IsolateSnapshotData), &isolate_snapshot_data_filename); std::string isolate_snapshot_instr_filename; command_line.GetOptionValue( FlagForSwitch(Switch::IsolateSnapshotInstructions), &isolate_snapshot_instr_filename); if (!aot_shared_library_name.empty()) { for (std::string_view name : aot_shared_library_name) { settings.application_library_path.emplace_back(name); } } else if (!snapshot_asset_path.empty()) { settings.vm_snapshot_data_path = fml::paths::JoinPaths({snapshot_asset_path, vm_snapshot_data_filename}); settings.vm_snapshot_instr_path = fml::paths::JoinPaths( {snapshot_asset_path, vm_snapshot_instr_filename}); settings.isolate_snapshot_data_path = fml::paths::JoinPaths( {snapshot_asset_path, isolate_snapshot_data_filename}); settings.isolate_snapshot_instr_path = fml::paths::JoinPaths( {snapshot_asset_path, isolate_snapshot_instr_filename}); } command_line.GetOptionValue(FlagForSwitch(Switch::CacheDirPath), &settings.temp_directory_path); bool leak_vm = "true" == command_line.GetOptionValueWithDefault( FlagForSwitch(Switch::LeakVM), "true"); settings.leak_vm = leak_vm; if (settings.icu_initialization_required) { command_line.GetOptionValue(FlagForSwitch(Switch::ICUDataFilePath), &settings.icu_data_path); if (command_line.HasOption(FlagForSwitch(Switch::ICUSymbolPrefix))) { std::string icu_symbol_prefix, native_lib_path; command_line.GetOptionValue(FlagForSwitch(Switch::ICUSymbolPrefix), &icu_symbol_prefix); command_line.GetOptionValue(FlagForSwitch(Switch::ICUNativeLibPath), &native_lib_path); #if FML_OS_ANDROID settings.icu_mapper = GetICUStaticMapping; #else settings.icu_mapper = [icu_symbol_prefix, native_lib_path] { return GetSymbolMapping(icu_symbol_prefix, native_lib_path); }; #endif } } settings.use_test_fonts = command_line.HasOption(FlagForSwitch(Switch::UseTestFonts)); settings.use_asset_fonts = !command_line.HasOption(FlagForSwitch(Switch::DisableAssetFonts)); { std::string enable_impeller_value; if (command_line.GetOptionValue(FlagForSwitch(Switch::EnableImpeller), &enable_impeller_value)) { settings.enable_impeller = enable_impeller_value.empty() || "true" == enable_impeller_value; } } { std::string impeller_backend_value; if (command_line.GetOptionValue(FlagForSwitch(Switch::ImpellerBackend), &impeller_backend_value)) { if (!impeller_backend_value.empty()) { settings.requested_rendering_backend = impeller_backend_value; } } } settings.enable_vulkan_validation = command_line.HasOption(FlagForSwitch(Switch::EnableVulkanValidation)); settings.enable_opengl_gpu_tracing = command_line.HasOption(FlagForSwitch(Switch::EnableOpenGLGPUTracing)); settings.enable_vulkan_gpu_tracing = command_line.HasOption(FlagForSwitch(Switch::EnableVulkanGPUTracing)); settings.enable_embedder_api = command_line.HasOption(FlagForSwitch(Switch::EnableEmbedderAPI)); settings.prefetched_default_font_manager = command_line.HasOption( FlagForSwitch(Switch::PrefetchedDefaultFontManager)); std::string all_dart_flags; if (command_line.GetOptionValue(FlagForSwitch(Switch::DartFlags), &all_dart_flags)) { // Assume that individual flags are comma separated. std::vector<std::string> flags = ParseCommaDelimited(all_dart_flags); for (const auto& flag : flags) { if (!IsAllowedDartVMFlag(flag)) { FML_LOG(FATAL) << "Encountered disallowed Dart VM flag: " << flag; } settings.dart_flags.push_back(flag); } } #if !FLUTTER_RELEASE command_line.GetOptionValue(FlagForSwitch(Switch::LogTag), &settings.log_tag); #endif settings.dump_skp_on_shader_compilation = command_line.HasOption(FlagForSwitch(Switch::DumpSkpOnShaderCompilation)); settings.cache_sksl = command_line.HasOption(FlagForSwitch(Switch::CacheSkSL)); settings.purge_persistent_cache = command_line.HasOption(FlagForSwitch(Switch::PurgePersistentCache)); if (command_line.HasOption(FlagForSwitch(Switch::OldGenHeapSize))) { std::string old_gen_heap_size; command_line.GetOptionValue(FlagForSwitch(Switch::OldGenHeapSize), &old_gen_heap_size); settings.old_gen_heap_size = std::stoi(old_gen_heap_size); } if (command_line.HasOption( FlagForSwitch(Switch::ResourceCacheMaxBytesThreshold))) { std::string resource_cache_max_bytes_threshold; command_line.GetOptionValue( FlagForSwitch(Switch::ResourceCacheMaxBytesThreshold), &resource_cache_max_bytes_threshold); settings.resource_cache_max_bytes_threshold = std::stoi(resource_cache_max_bytes_threshold); } if (command_line.HasOption(FlagForSwitch(Switch::MsaaSamples))) { std::string msaa_samples; command_line.GetOptionValue(FlagForSwitch(Switch::MsaaSamples), &msaa_samples); if (msaa_samples == "0") { settings.msaa_samples = 0; } else if (msaa_samples == "1") { settings.msaa_samples = 1; } else if (msaa_samples == "2") { settings.msaa_samples = 2; } else if (msaa_samples == "4") { settings.msaa_samples = 4; } else if (msaa_samples == "8") { settings.msaa_samples = 8; } else if (msaa_samples == "16") { settings.msaa_samples = 16; } else { FML_DLOG(ERROR) << "Invalid value for --msaa-samples: '" << msaa_samples << "' (expected 0, 1, 2, 4, 8, or 16)."; } } return settings; } } // namespace flutter
engine/shell/common/switches.cc/0
{ "file_path": "engine/shell/common/switches.cc", "repo_id": "engine", "token_count": 7772 }
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. declare_args() { shell_enable_gl = !is_fuchsia && !is_mac # The logic for enabling Vulkan and Metal is in tools/gn. shell_enable_metal = false shell_enable_vulkan = false shell_enable_software = true } declare_args() { test_enable_gl = shell_enable_gl test_enable_metal = shell_enable_metal # The Vulkan unittests are combined with the GL unittests. test_enable_vulkan = is_fuchsia || shell_enable_gl test_enable_software = shell_enable_software }
engine/shell/config.gni/0
{ "file_path": "engine/shell/config.gni", "repo_id": "engine", "token_count": 200 }
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. #include "flutter/shell/gpu/gpu_surface_software.h" #include <memory> #include "flutter/fml/logging.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { GPUSurfaceSoftware::GPUSurfaceSoftware(GPUSurfaceSoftwareDelegate* delegate, bool render_to_surface) : delegate_(delegate), render_to_surface_(render_to_surface), weak_factory_(this) {} GPUSurfaceSoftware::~GPUSurfaceSoftware() = default; // |Surface| bool GPUSurfaceSoftware::IsValid() { return delegate_ != nullptr; } // |Surface| std::unique_ptr<SurfaceFrame> GPUSurfaceSoftware::AcquireFrame( const SkISize& logical_size) { SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true; // TODO(38466): Refactor GPU surface APIs take into account the fact that an // external view embedder may want to render to the root surface. if (!render_to_surface_) { return std::make_unique<SurfaceFrame>( nullptr, framebuffer_info, [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { return true; }, logical_size); } if (!IsValid()) { return nullptr; } const auto size = SkISize::Make(logical_size.width(), logical_size.height()); sk_sp<SkSurface> backing_store = delegate_->AcquireBackingStore(size); if (backing_store == nullptr) { return nullptr; } if (size != SkISize::Make(backing_store->width(), backing_store->height())) { return nullptr; } // If the surface has been scaled, we need to apply the inverse scaling to the // underlying canvas so that coordinates are mapped to the same spot // irrespective of surface scaling. SkCanvas* canvas = backing_store->getCanvas(); canvas->resetMatrix(); SurfaceFrame::SubmitCallback on_submit = [self = weak_factory_.GetWeakPtr()](const SurfaceFrame& surface_frame, DlCanvas* canvas) -> bool { // If the surface itself went away, there is nothing more to do. if (!self || !self->IsValid() || canvas == nullptr) { return false; } canvas->Flush(); return self->delegate_->PresentBackingStore(surface_frame.SkiaSurface()); }; return std::make_unique<SurfaceFrame>(backing_store, framebuffer_info, on_submit, logical_size); } // |Surface| SkMatrix GPUSurfaceSoftware::GetRootTransformation() const { // This backend does not currently support root surface transformations. Just // return identity. SkMatrix matrix; matrix.reset(); return matrix; } // |Surface| GrDirectContext* GPUSurfaceSoftware::GetContext() { // There is no GrContext associated with a software surface. return nullptr; } } // namespace flutter
engine/shell/gpu/gpu_surface_software.cc/0
{ "file_path": "engine/shell/gpu/gpu_surface_software.cc", "repo_id": "engine", "token_count": 1048 }
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_ANDROID_CONTEXT_GL_IMPELLER_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_GL_IMPELLER_H_ #include "flutter/fml/macros.h" #include "flutter/impeller/toolkit/egl/display.h" #include "flutter/shell/platform/android/context/android_context.h" namespace flutter { class AndroidContextGLImpeller : public AndroidContext { public: AndroidContextGLImpeller(std::unique_ptr<impeller::egl::Display> display, bool enable_gpu_tracing); ~AndroidContextGLImpeller(); // |AndroidContext| bool IsValid() const override; bool ResourceContextMakeCurrent(impeller::egl::Surface* offscreen_surface); bool ResourceContextClearCurrent(); std::unique_ptr<impeller::egl::Surface> CreateOffscreenSurface(); bool OnscreenContextMakeCurrent(impeller::egl::Surface* onscreen_surface); bool OnscreenContextClearCurrent(); std::unique_ptr<impeller::egl::Surface> CreateOnscreenSurface( EGLNativeWindowType window); private: class ReactorWorker; std::shared_ptr<ReactorWorker> reactor_worker_; std::unique_ptr<impeller::egl::Display> display_; std::unique_ptr<impeller::egl::Config> onscreen_config_; std::unique_ptr<impeller::egl::Config> offscreen_config_; std::unique_ptr<impeller::egl::Context> onscreen_context_; std::unique_ptr<impeller::egl::Context> offscreen_context_; bool is_valid_ = false; FML_DISALLOW_COPY_AND_ASSIGN(AndroidContextGLImpeller); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_GL_IMPELLER_H_
engine/shell/platform/android/android_context_gl_impeller.h/0
{ "file_path": "engine/shell/platform/android/android_context_gl_impeller.h", "repo_id": "engine", "token_count": 627 }
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. #define FML_USED_ON_EMBEDDER #include "flutter/shell/platform/android/android_shell_holder.h" #include <pthread.h> #include <sys/resource.h> #include <sys/time.h> #include <memory> #include <optional> #include <sstream> #include <string> #include <utility> #include "flutter/fml/cpu_affinity.h" #include "flutter/fml/logging.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/native_library.h" #include "flutter/fml/platform/android/jni_util.h" #include "flutter/lib/ui/painting/image_generator_registry.h" #include "flutter/shell/common/rasterizer.h" #include "flutter/shell/common/run_configuration.h" #include "flutter/shell/common/thread_host.h" #include "flutter/shell/platform/android/android_display.h" #include "flutter/shell/platform/android/android_image_generator.h" #include "flutter/shell/platform/android/context/android_context.h" #include "flutter/shell/platform/android/platform_view_android.h" namespace flutter { /// Inheriting ThreadConfigurer and use Android platform thread API to configure /// the thread priorities static void AndroidPlatformThreadConfigSetter( const fml::Thread::ThreadConfig& config) { // set thread name fml::Thread::SetCurrentThreadName(config); // set thread priority switch (config.priority) { case fml::Thread::ThreadPriority::kBackground: { fml::RequestAffinity(fml::CpuAffinity::kEfficiency); if (::setpriority(PRIO_PROCESS, 0, 10) != 0) { FML_LOG(ERROR) << "Failed to set IO task runner priority"; } break; } case fml::Thread::ThreadPriority::kDisplay: { fml::RequestAffinity(fml::CpuAffinity::kPerformance); if (::setpriority(PRIO_PROCESS, 0, -1) != 0) { FML_LOG(ERROR) << "Failed to set UI task runner priority"; } break; } case fml::Thread::ThreadPriority::kRaster: { fml::RequestAffinity(fml::CpuAffinity::kPerformance); // Android describes -8 as "most important display threads, for // compositing the screen and retrieving input events". Conservatively // set the raster thread to slightly lower priority than it. if (::setpriority(PRIO_PROCESS, 0, -5) != 0) { // Defensive fallback. Depending on the OEM, it may not be possible // to set priority to -5. if (::setpriority(PRIO_PROCESS, 0, -2) != 0) { FML_LOG(ERROR) << "Failed to set raster task runner priority"; } } break; } default: fml::RequestAffinity(fml::CpuAffinity::kNotPerformance); if (::setpriority(PRIO_PROCESS, 0, 0) != 0) { FML_LOG(ERROR) << "Failed to set priority"; } } } static PlatformData GetDefaultPlatformData() { PlatformData platform_data; platform_data.lifecycle_state = "AppLifecycleState.detached"; return platform_data; } AndroidShellHolder::AndroidShellHolder( const flutter::Settings& settings, std::shared_ptr<PlatformViewAndroidJNI> jni_facade) : settings_(settings), jni_facade_(jni_facade) { static size_t thread_host_count = 1; auto thread_label = std::to_string(thread_host_count++); auto mask = ThreadHost::Type::kUi | ThreadHost::Type::kRaster | ThreadHost::Type::kIo; flutter::ThreadHost::ThreadHostConfig host_config( thread_label, mask, AndroidPlatformThreadConfigSetter); host_config.ui_config = fml::Thread::ThreadConfig( flutter::ThreadHost::ThreadHostConfig::MakeThreadName( flutter::ThreadHost::Type::kUi, thread_label), fml::Thread::ThreadPriority::kDisplay); host_config.raster_config = fml::Thread::ThreadConfig( flutter::ThreadHost::ThreadHostConfig::MakeThreadName( flutter::ThreadHost::Type::kRaster, thread_label), fml::Thread::ThreadPriority::kRaster); host_config.io_config = fml::Thread::ThreadConfig( flutter::ThreadHost::ThreadHostConfig::MakeThreadName( flutter::ThreadHost::Type::kIo, thread_label), fml::Thread::ThreadPriority::kNormal); thread_host_ = std::make_shared<ThreadHost>(host_config); fml::WeakPtr<PlatformViewAndroid> weak_platform_view; Shell::CreateCallback<PlatformView> on_create_platform_view = [&jni_facade, &weak_platform_view](Shell& shell) { std::unique_ptr<PlatformViewAndroid> platform_view_android; platform_view_android = std::make_unique<PlatformViewAndroid>( shell, // delegate shell.GetTaskRunners(), // task runners jni_facade, // JNI interop shell.GetSettings() .enable_software_rendering, // use software rendering shell.GetSettings().msaa_samples // msaa sample count ); weak_platform_view = platform_view_android->GetWeakPtr(); return platform_view_android; }; Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) { return std::make_unique<Rasterizer>(shell); }; // The current thread will be used as the platform thread. Ensure that the // message loop is initialized. fml::MessageLoop::EnsureInitializedForCurrentThread(); fml::RefPtr<fml::TaskRunner> raster_runner; fml::RefPtr<fml::TaskRunner> ui_runner; fml::RefPtr<fml::TaskRunner> io_runner; fml::RefPtr<fml::TaskRunner> platform_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); raster_runner = thread_host_->raster_thread->GetTaskRunner(); ui_runner = thread_host_->ui_thread->GetTaskRunner(); io_runner = thread_host_->io_thread->GetTaskRunner(); flutter::TaskRunners task_runners(thread_label, // label platform_runner, // platform raster_runner, // raster ui_runner, // ui io_runner // io ); shell_ = Shell::Create(GetDefaultPlatformData(), // window data task_runners, // task runners settings_, // settings on_create_platform_view, // platform view create callback on_create_rasterizer // rasterizer create callback ); if (shell_) { shell_->GetDartVM()->GetConcurrentMessageLoop()->PostTaskToAllWorkers([]() { if (::setpriority(PRIO_PROCESS, gettid(), 1) != 0) { FML_LOG(ERROR) << "Failed to set Workers task runner priority"; } }); shell_->RegisterImageDecoder( [runner = task_runners.GetIOTaskRunner()](sk_sp<SkData> buffer) { return AndroidImageGenerator::MakeFromData(std::move(buffer), runner); }, -1); FML_DLOG(INFO) << "Registered Android SDK image decoder (API level 28+)"; } platform_view_ = weak_platform_view; FML_DCHECK(platform_view_); is_valid_ = shell_ != nullptr; } AndroidShellHolder::AndroidShellHolder( const Settings& settings, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade, const std::shared_ptr<ThreadHost>& thread_host, std::unique_ptr<Shell> shell, std::unique_ptr<APKAssetProvider> apk_asset_provider, const fml::WeakPtr<PlatformViewAndroid>& platform_view) : settings_(settings), jni_facade_(jni_facade), platform_view_(platform_view), thread_host_(thread_host), shell_(std::move(shell)), apk_asset_provider_(std::move(apk_asset_provider)) { FML_DCHECK(jni_facade); FML_DCHECK(shell_); FML_DCHECK(shell_->IsSetup()); FML_DCHECK(platform_view_); FML_DCHECK(thread_host_); is_valid_ = shell_ != nullptr; } AndroidShellHolder::~AndroidShellHolder() { shell_.reset(); thread_host_.reset(); } bool AndroidShellHolder::IsValid() const { return is_valid_; } const flutter::Settings& AndroidShellHolder::GetSettings() const { return settings_; } std::unique_ptr<AndroidShellHolder> AndroidShellHolder::Spawn( std::shared_ptr<PlatformViewAndroidJNI> jni_facade, const std::string& entrypoint, const std::string& libraryUrl, const std::string& initial_route, const std::vector<std::string>& entrypoint_args) const { FML_DCHECK(shell_ && shell_->IsSetup()) << "A new Shell can only be spawned " "if the current Shell is properly constructed"; // Pull out the new PlatformViewAndroid from the new Shell to feed to it to // the new AndroidShellHolder. // // It's a weak pointer because it's owned by the Shell (which we're also) // making below. And the AndroidShellHolder then owns the Shell. fml::WeakPtr<PlatformViewAndroid> weak_platform_view; // Take out the old AndroidContext to reuse inside the PlatformViewAndroid // of the new Shell. PlatformViewAndroid* android_platform_view = platform_view_.get(); // There's some indirection with platform_view_ being a weak pointer but // we just checked that the shell_ exists above and a valid shell is the // owner of the platform view so this weak pointer always exists. FML_DCHECK(android_platform_view); std::shared_ptr<flutter::AndroidContext> android_context = android_platform_view->GetAndroidContext(); FML_DCHECK(android_context); // This is a synchronous call, so the captures don't have race checks. Shell::CreateCallback<PlatformView> on_create_platform_view = [&jni_facade, android_context, &weak_platform_view](Shell& shell) { std::unique_ptr<PlatformViewAndroid> platform_view_android; platform_view_android = std::make_unique<PlatformViewAndroid>( shell, // delegate shell.GetTaskRunners(), // task runners jni_facade, // JNI interop android_context // Android context ); weak_platform_view = platform_view_android->GetWeakPtr(); return platform_view_android; }; Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) { return std::make_unique<Rasterizer>(shell); }; // TODO(xster): could be worth tracing this to investigate whether // the IsolateConfiguration could be cached somewhere. auto config = BuildRunConfiguration(entrypoint, libraryUrl, entrypoint_args); if (!config) { // If the RunConfiguration was null, the kernel blob wasn't readable. // Fail the whole thing. return nullptr; } std::unique_ptr<flutter::Shell> shell = shell_->Spawn(std::move(config.value()), initial_route, on_create_platform_view, on_create_rasterizer); return std::unique_ptr<AndroidShellHolder>(new AndroidShellHolder( GetSettings(), jni_facade, thread_host_, std::move(shell), apk_asset_provider_->Clone(), weak_platform_view)); } void AndroidShellHolder::Launch( std::unique_ptr<APKAssetProvider> apk_asset_provider, const std::string& entrypoint, const std::string& libraryUrl, const std::vector<std::string>& entrypoint_args) { if (!IsValid()) { return; } apk_asset_provider_ = std::move(apk_asset_provider); auto config = BuildRunConfiguration(entrypoint, libraryUrl, entrypoint_args); if (!config) { return; } UpdateDisplayMetrics(); shell_->RunEngine(std::move(config.value())); } Rasterizer::Screenshot AndroidShellHolder::Screenshot( Rasterizer::ScreenshotType type, bool base64_encode) { if (!IsValid()) { return {nullptr, SkISize::MakeEmpty(), "", Rasterizer::ScreenshotFormat::kUnknown}; } return shell_->Screenshot(type, base64_encode); } fml::WeakPtr<PlatformViewAndroid> AndroidShellHolder::GetPlatformView() { FML_DCHECK(platform_view_); return platform_view_; } void AndroidShellHolder::NotifyLowMemoryWarning() { FML_DCHECK(shell_); shell_->NotifyLowMemoryWarning(); } std::optional<RunConfiguration> AndroidShellHolder::BuildRunConfiguration( const std::string& entrypoint, const std::string& libraryUrl, const std::vector<std::string>& entrypoint_args) const { std::unique_ptr<IsolateConfiguration> isolate_configuration; if (flutter::DartVM::IsRunningPrecompiledCode()) { isolate_configuration = IsolateConfiguration::CreateForAppSnapshot(); } else { std::unique_ptr<fml::Mapping> kernel_blob = fml::FileMapping::CreateReadOnly( GetSettings().application_kernel_asset); if (!kernel_blob) { FML_DLOG(ERROR) << "Unable to load the kernel blob asset."; return std::nullopt; } isolate_configuration = IsolateConfiguration::CreateForKernel(std::move(kernel_blob)); } RunConfiguration config(std::move(isolate_configuration)); config.AddAssetResolver(apk_asset_provider_->Clone()); { if (!entrypoint.empty() && !libraryUrl.empty()) { config.SetEntrypointAndLibrary(entrypoint, libraryUrl); } else if (!entrypoint.empty()) { config.SetEntrypoint(entrypoint); } if (!entrypoint_args.empty()) { config.SetEntrypointArgs(entrypoint_args); } } return config; } void AndroidShellHolder::UpdateDisplayMetrics() { std::vector<std::unique_ptr<Display>> displays; displays.push_back(std::make_unique<AndroidDisplay>(jni_facade_)); shell_->OnDisplayUpdates(std::move(displays)); } } // namespace flutter
engine/shell/platform/android/android_shell_holder.cc/0
{ "file_path": "engine/shell/platform/android/android_shell_holder.cc", "repo_id": "engine", "token_count": 5009 }
302
// Copyright 2013 The Flutter 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/context/android_context.h" namespace flutter { AndroidContext::AndroidContext(AndroidRenderingAPI rendering_api) : rendering_api_(rendering_api) {} AndroidContext::~AndroidContext() { if (main_context_) { main_context_->releaseResourcesAndAbandonContext(); } if (impeller_context_) { impeller_context_->Shutdown(); } }; AndroidRenderingAPI AndroidContext::RenderingApi() const { return rendering_api_; } bool AndroidContext::IsValid() const { return true; } void AndroidContext::SetMainSkiaContext( const sk_sp<GrDirectContext>& main_context) { main_context_ = main_context; } sk_sp<GrDirectContext> AndroidContext::GetMainSkiaContext() const { return main_context_; } std::shared_ptr<impeller::Context> AndroidContext::GetImpellerContext() const { return impeller_context_; } void AndroidContext::SetImpellerContext( const std::shared_ptr<impeller::Context>& context) { impeller_context_ = context; } } // namespace flutter
engine/shell/platform/android/context/android_context.cc/0
{ "file_path": "engine/shell/platform/android/context/android_context.cc", "repo_id": "engine", "token_count": 382 }
303
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_H_ #include <unordered_map> #include "flutter/fml/platform/android/scoped_java_ref.h" #include "flutter/shell/platform/android/image_external_texture.h" #include "flutter/impeller/renderer/backend/gles/context_gles.h" #include "flutter/impeller/renderer/backend/gles/gles.h" #include "flutter/impeller/renderer/backend/gles/texture_gles.h" #include "flutter/impeller/toolkit/egl/egl.h" #include "flutter/impeller/toolkit/egl/image.h" #include "flutter/impeller/toolkit/gles/texture.h" #include "flutter/shell/platform/android/android_context_gl_skia.h" namespace flutter { class ImageExternalTextureGL : public ImageExternalTexture { public: ImageExternalTextureGL( int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& image_textury_entry, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade); protected: void Attach(PaintContext& context) override; void Detach() override; void ProcessFrame(PaintContext& context, const SkRect& bounds) override; void UpdateImage(JavaLocalRef& hardware_buffer, const SkRect& bounds, PaintContext& context); virtual sk_sp<flutter::DlImage> CreateDlImage( PaintContext& context, const SkRect& bounds, std::optional<HardwareBufferKey> id, impeller::UniqueEGLImageKHR&& egl_image) = 0; impeller::UniqueEGLImageKHR CreateEGLImage(AHardwareBuffer* buffer); struct GlEntry { impeller::UniqueEGLImageKHR egl_image; impeller::UniqueGLTexture texture; }; // Each GL entry is keyed off of the currently active // hardware buffers and evicted when the hardware buffer // is removed from the LRU cache. std::unordered_map<HardwareBufferKey, GlEntry> gl_entries_; FML_DISALLOW_COPY_AND_ASSIGN(ImageExternalTextureGL); }; class ImageExternalTextureGLSkia : public ImageExternalTextureGL { public: ImageExternalTextureGLSkia( const std::shared_ptr<AndroidContextGLSkia>& context, int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& image_textury_entry, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade); private: void Attach(PaintContext& context) override; void Detach() override; void BindImageToTexture(const impeller::UniqueEGLImageKHR& image, GLuint tex); sk_sp<flutter::DlImage> CreateDlImage( PaintContext& context, const SkRect& bounds, std::optional<HardwareBufferKey> id, impeller::UniqueEGLImageKHR&& egl_image) override; FML_DISALLOW_COPY_AND_ASSIGN(ImageExternalTextureGLSkia); }; class ImageExternalTextureGLImpeller : public ImageExternalTextureGL { public: ImageExternalTextureGLImpeller( const std::shared_ptr<impeller::ContextGLES>& context, int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& hardware_buffer_texture_entry, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade); private: void Attach(PaintContext& context) override; void Detach() override; sk_sp<flutter::DlImage> CreateDlImage( PaintContext& context, const SkRect& bounds, std::optional<HardwareBufferKey> id, impeller::UniqueEGLImageKHR&& egl_image) override; const std::shared_ptr<impeller::ContextGLES> impeller_context_; FML_DISALLOW_COPY_AND_ASSIGN(ImageExternalTextureGLImpeller); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_H_
engine/shell/platform/android/image_external_texture_gl.h/0
{ "file_path": "engine/shell/platform/android/image_external_texture_gl.h", "repo_id": "engine", "token_count": 1368 }
304
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.app; import android.app.Activity; import android.content.Context; import android.content.Intent; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugin.platform.PlatformViewRegistry; import io.flutter.plugin.platform.PlatformViewsController; import io.flutter.view.FlutterMain; import io.flutter.view.FlutterNativeView; import io.flutter.view.FlutterView; import io.flutter.view.TextureRegistry; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** @deprecated See https://flutter.dev/go/android-project-migration for migration instructions. */ @Deprecated public class FlutterPluginRegistry implements PluginRegistry, PluginRegistry.RequestPermissionsResultListener, PluginRegistry.ActivityResultListener, PluginRegistry.NewIntentListener, PluginRegistry.WindowFocusChangedListener, PluginRegistry.UserLeaveHintListener, PluginRegistry.ViewDestroyListener { private static final String TAG = "FlutterPluginRegistry"; private Activity mActivity; private Context mAppContext; private FlutterNativeView mNativeView; private FlutterView mFlutterView; private final PlatformViewsController mPlatformViewsController; private final Map<String, Object> mPluginMap = new LinkedHashMap<>(0); private final List<RequestPermissionsResultListener> mRequestPermissionsResultListeners = new ArrayList<>(0); private final List<ActivityResultListener> mActivityResultListeners = new ArrayList<>(0); private final List<NewIntentListener> mNewIntentListeners = new ArrayList<>(0); private final List<UserLeaveHintListener> mUserLeaveHintListeners = new ArrayList<>(0); private final List<WindowFocusChangedListener> mWindowFocusChangedListeners = new ArrayList<>(0); private final List<ViewDestroyListener> mViewDestroyListeners = new ArrayList<>(0); public FlutterPluginRegistry(FlutterNativeView nativeView, Context context) { mNativeView = nativeView; mAppContext = context; mPlatformViewsController = new PlatformViewsController(); } public FlutterPluginRegistry(FlutterEngine engine, Context context) { // TODO(mattcarroll): implement use of engine instead of nativeView. mAppContext = context; mPlatformViewsController = new PlatformViewsController(); } @Override public boolean hasPlugin(String key) { return mPluginMap.containsKey(key); } @Override @SuppressWarnings("unchecked") public <T> T valuePublishedByPlugin(String pluginKey) { return (T) mPluginMap.get(pluginKey); } @Override public Registrar registrarFor(String pluginKey) { if (mPluginMap.containsKey(pluginKey)) { throw new IllegalStateException("Plugin key " + pluginKey + " is already in use"); } mPluginMap.put(pluginKey, null); return new FlutterRegistrar(pluginKey); } public void attach(FlutterView flutterView, Activity activity) { mFlutterView = flutterView; mActivity = activity; mPlatformViewsController.attach(activity, flutterView, flutterView.getDartExecutor()); } public void detach() { mPlatformViewsController.detach(); mPlatformViewsController.onDetachedFromJNI(); mFlutterView = null; mActivity = null; } public void onPreEngineRestart() { mPlatformViewsController.onPreEngineRestart(); } public PlatformViewsController getPlatformViewsController() { return mPlatformViewsController; } private class FlutterRegistrar implements Registrar { private final String pluginKey; FlutterRegistrar(String pluginKey) { this.pluginKey = pluginKey; } @Override public Activity activity() { return mActivity; } @Override public Context context() { return mAppContext; } @Override public Context activeContext() { return (mActivity != null) ? mActivity : mAppContext; } @Override public BinaryMessenger messenger() { return mNativeView; } @Override public TextureRegistry textures() { return mFlutterView; } @Override public PlatformViewRegistry platformViewRegistry() { return mPlatformViewsController.getRegistry(); } @Override public FlutterView view() { return mFlutterView; } @Override public String lookupKeyForAsset(String asset) { return FlutterMain.getLookupKeyForAsset(asset); } @Override public String lookupKeyForAsset(String asset, String packageName) { return FlutterMain.getLookupKeyForAsset(asset, packageName); } @Override public Registrar publish(Object value) { mPluginMap.put(pluginKey, value); return this; } @Override public Registrar addRequestPermissionsResultListener( RequestPermissionsResultListener listener) { mRequestPermissionsResultListeners.add(listener); return this; } @Override public Registrar addActivityResultListener(ActivityResultListener listener) { mActivityResultListeners.add(listener); return this; } @Override public Registrar addNewIntentListener(NewIntentListener listener) { mNewIntentListeners.add(listener); return this; } @Override public Registrar addUserLeaveHintListener(UserLeaveHintListener listener) { mUserLeaveHintListeners.add(listener); return this; } @Override public Registrar addWindowFocusChangedListener(WindowFocusChangedListener listener) { mWindowFocusChangedListeners.add(listener); return this; } @Override public Registrar addViewDestroyListener(ViewDestroyListener listener) { mViewDestroyListeners.add(listener); return this; } } @Override public boolean onRequestPermissionsResult( int requestCode, String[] permissions, int[] grantResults) { for (RequestPermissionsResultListener listener : mRequestPermissionsResultListeners) { if (listener.onRequestPermissionsResult(requestCode, permissions, grantResults)) { return true; } } return false; } @Override public boolean onActivityResult(int requestCode, int resultCode, Intent data) { for (ActivityResultListener listener : mActivityResultListeners) { if (listener.onActivityResult(requestCode, resultCode, data)) { return true; } } return false; } @Override public boolean onNewIntent(Intent intent) { for (NewIntentListener listener : mNewIntentListeners) { if (listener.onNewIntent(intent)) { return true; } } return false; } @Override public void onUserLeaveHint() { for (UserLeaveHintListener listener : mUserLeaveHintListeners) { listener.onUserLeaveHint(); } } @Override public void onWindowFocusChanged(boolean hasFocus) { for (WindowFocusChangedListener listener : mWindowFocusChangedListeners) { listener.onWindowFocusChanged(hasFocus); } } @Override public boolean onViewDestroy(FlutterNativeView view) { boolean handled = false; for (ViewDestroyListener listener : mViewDestroyListeners) { if (listener.onViewDestroy(view)) { handled = true; } } return handled; } public void destroy() { mPlatformViewsController.onDetachedFromJNI(); } }
engine/shell/platform/android/io/flutter/app/FlutterPluginRegistry.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/app/FlutterPluginRegistry.java", "repo_id": "engine", "token_count": 2500 }
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.embedding.android; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * The resulting Flutter key events generated by {@link KeyEmbedderResponder}, and are sent through * the messenger after being marshalled with {@link #toBytes()}. * * <p>This class is the Java adaption of {@code KeyData} and {@code KeyDataPacket} in the C engine. * Changes made to either side must also be made to the other. * * <p>Each {@link KeyData} corresponds to a {@code ui.KeyData} in the framework. */ public class KeyData { private static final String TAG = "KeyData"; /** * The channel that key data should be sent through. * * <p>Must be kept in sync with kFlutterKeyDataChannel in embedder.cc */ public static final String CHANNEL = "flutter/keydata"; // The number of fields except for `character`. // If this value changes, update the code in the following files: // // * key_data.h (kKeyDataFieldCount) // * platform_dispatcher.dart (_kKeyDataFieldCount) private static final int FIELD_COUNT = 6; private static final int BYTES_PER_FIELD = 8; /** The action type of the key data. */ public enum Type { kDown(0), kUp(1), kRepeat(2); private long value; private Type(long value) { this.value = value; } public long getValue() { return value; } static Type fromLong(long value) { switch ((int) value) { case 0: return kDown; case 1: return kUp; case 2: return kRepeat; default: throw new AssertionError("Unexpected Type value"); } } } /** The device type of the key data. */ public enum DeviceType { kKeyboard(0), kDirectionalPad(1), kGamepad(2), kJoystick(3), kHdmi(4); private final long value; private DeviceType(long value) { this.value = value; } public long getValue() { return value; } static DeviceType fromLong(long value) { switch ((int) value) { case 0: return kKeyboard; case 1: return kDirectionalPad; case 2: return kGamepad; case 3: return kJoystick; case 4: return kHdmi; default: throw new AssertionError("Unexpected DeviceType value"); } } } /** Creates an empty {@link KeyData}. */ public KeyData() {} /** * Unmarshal fields from a buffer. * * <p>For the binary format, see {@code lib/ui/window/key_data_packet.h}. */ public KeyData(@NonNull ByteBuffer buffer) { final long charSize = buffer.getLong(); this.timestamp = buffer.getLong(); this.type = Type.fromLong(buffer.getLong()); this.physicalKey = buffer.getLong(); this.logicalKey = buffer.getLong(); this.synthesized = buffer.getLong() != 0; this.deviceType = DeviceType.fromLong(buffer.getLong()); if (buffer.remaining() != charSize) { throw new AssertionError( String.format( "Unexpected char length: charSize is %d while buffer has position %d, capacity %d, limit %d", charSize, buffer.position(), buffer.capacity(), buffer.limit())); } this.character = null; if (charSize != 0) { final byte[] strBytes = new byte[(int) charSize]; buffer.get(strBytes, 0, (int) charSize); try { this.character = new String(strBytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError("UTF-8 unsupported"); } } } long timestamp; Type type; long physicalKey; long logicalKey; boolean synthesized; DeviceType deviceType; /** The character of this key data encoded in UTF-8. */ @Nullable String character; /** * Marshal the key data to a new byte buffer. * * <p>For the binary format, see {@code lib/ui/window/key_data_packet.h}. * * @return the marshalled bytes. */ ByteBuffer toBytes() { byte[] charBytes; try { charBytes = character == null ? null : character.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError("UTF-8 not supported"); } final int charSize = charBytes == null ? 0 : charBytes.length; final ByteBuffer packet = ByteBuffer.allocateDirect((1 + FIELD_COUNT) * BYTES_PER_FIELD + charSize); packet.order(ByteOrder.LITTLE_ENDIAN); packet.putLong(charSize); packet.putLong(timestamp); packet.putLong(type.getValue()); packet.putLong(physicalKey); packet.putLong(logicalKey); packet.putLong(synthesized ? 1L : 0L); packet.putLong(deviceType.getValue()); if (charBytes != null) { packet.put(charBytes); } return packet; } }
engine/shell/platform/android/io/flutter/embedding/android/KeyData.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/android/KeyData.java", "repo_id": "engine", "token_count": 1921 }
306
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.dart; import android.content.res.AssetManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import io.flutter.FlutterInjector; import io.flutter.Log; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.loader.FlutterLoader; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.StringCodec; import io.flutter.util.TraceSection; import io.flutter.view.FlutterCallbackInformation; import java.nio.ByteBuffer; import java.util.List; /** * Configures, bootstraps, and starts executing Dart code. * * <p>To specify a top-level Dart function to execute, use a {@link DartEntrypoint} to tell {@link * DartExecutor} where to find the Dart code to execute, and which Dart function to use as the * entrypoint. To execute the entrypoint, pass the {@link DartEntrypoint} to {@link * #executeDartEntrypoint(DartEntrypoint)}. * * <p>To specify a Dart callback to execute, use a {@link DartCallback}. A given Dart callback must * be registered with the Dart VM to be invoked by a {@link DartExecutor}. To execute the callback, * pass the {@link DartCallback} to {@link #executeDartCallback(DartCallback)}. * * <p>Once started, a {@link DartExecutor} cannot be stopped. The associated Dart code will execute * until it completes, or until the {@link io.flutter.embedding.engine.FlutterEngine} that owns this * {@link DartExecutor} is destroyed. */ public class DartExecutor implements BinaryMessenger { private static final String TAG = "DartExecutor"; @NonNull private final FlutterJNI flutterJNI; @NonNull private final AssetManager assetManager; @NonNull private final DartMessenger dartMessenger; @NonNull private final BinaryMessenger binaryMessenger; private boolean isApplicationRunning = false; @Nullable private String isolateServiceId; @Nullable private IsolateServiceIdListener isolateServiceIdListener; private final BinaryMessenger.BinaryMessageHandler isolateChannelMessageHandler = new BinaryMessenger.BinaryMessageHandler() { @Override public void onMessage(ByteBuffer message, final BinaryReply callback) { isolateServiceId = StringCodec.INSTANCE.decodeMessage(message); if (isolateServiceIdListener != null) { isolateServiceIdListener.onIsolateServiceIdAvailable(isolateServiceId); } } }; public DartExecutor(@NonNull FlutterJNI flutterJNI, @NonNull AssetManager assetManager) { this.flutterJNI = flutterJNI; this.assetManager = assetManager; this.dartMessenger = new DartMessenger(flutterJNI); dartMessenger.setMessageHandler("flutter/isolate", isolateChannelMessageHandler); this.binaryMessenger = new DefaultBinaryMessenger(dartMessenger); // The JNI might already be attached if coming from a spawned engine. If so, correctly report // that this DartExecutor is already running. if (flutterJNI.isAttached()) { isApplicationRunning = true; } } /** * Invoked when the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@link * DartExecutor} attaches to JNI. * * <p>When attached to JNI, this {@link DartExecutor} begins handling 2-way communication to/from * the Dart execution context. This communication is facilitate via 2 APIs: * * <ul> * <li>{@link BinaryMessenger}, which sends messages to Dart * <li>{@link PlatformMessageHandler}, which receives messages from Dart * </ul> */ public void onAttachedToJNI() { Log.v( TAG, "Attached to JNI. Registering the platform message handler for this Dart execution" + " context."); flutterJNI.setPlatformMessageHandler(dartMessenger); } /** * Invoked when the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@link * DartExecutor} detaches from JNI. * * <p>When detached from JNI, this {@link DartExecutor} stops handling 2-way communication to/from * the Dart execution context. */ public void onDetachedFromJNI() { Log.v( TAG, "Detached from JNI. De-registering the platform message handler for this Dart execution" + " context."); flutterJNI.setPlatformMessageHandler(null); } /** * Is this {@link DartExecutor} currently executing Dart code? * * @return true if Dart code is being executed, false otherwise */ public boolean isExecutingDart() { return isApplicationRunning; } /** * Starts executing Dart code based on the given {@code dartEntrypoint}. * * <p>See {@link DartEntrypoint} for configuration options. * * @param dartEntrypoint specifies which Dart function to run, and where to find it */ public void executeDartEntrypoint(@NonNull DartEntrypoint dartEntrypoint) { executeDartEntrypoint(dartEntrypoint, null); } /** * Starts executing Dart code based on the given {@code dartEntrypoint} and the {@code * dartEntrypointArgs}. * * <p>See {@link DartEntrypoint} for configuration options. * * @param dartEntrypoint specifies which Dart function to run, and where to find it * @param dartEntrypointArgs Arguments passed as a list of string to Dart's entrypoint function. */ public void executeDartEntrypoint( @NonNull DartEntrypoint dartEntrypoint, @Nullable List<String> dartEntrypointArgs) { if (isApplicationRunning) { Log.w(TAG, "Attempted to run a DartExecutor that is already running."); return; } try (TraceSection e = TraceSection.scoped("DartExecutor#executeDartEntrypoint")) { Log.v(TAG, "Executing Dart entrypoint: " + dartEntrypoint); flutterJNI.runBundleAndSnapshotFromLibrary( dartEntrypoint.pathToBundle, dartEntrypoint.dartEntrypointFunctionName, dartEntrypoint.dartEntrypointLibrary, assetManager, dartEntrypointArgs); isApplicationRunning = true; } } /** * Starts executing Dart code based on the given {@code dartCallback}. * * <p>See {@link DartCallback} for configuration options. * * @param dartCallback specifies which Dart callback to run, and where to find it */ public void executeDartCallback(@NonNull DartCallback dartCallback) { if (isApplicationRunning) { Log.w(TAG, "Attempted to run a DartExecutor that is already running."); return; } try (TraceSection e = TraceSection.scoped("DartExecutor#executeDartCallback")) { Log.v(TAG, "Executing Dart callback: " + dartCallback); flutterJNI.runBundleAndSnapshotFromLibrary( dartCallback.pathToBundle, dartCallback.callbackHandle.callbackName, dartCallback.callbackHandle.callbackLibraryPath, dartCallback.androidAssetManager, null); isApplicationRunning = true; } } /** * Returns a {@link BinaryMessenger} that can be used to send messages to, and receive messages * from, Dart code that this {@code DartExecutor} is executing. */ @NonNull public BinaryMessenger getBinaryMessenger() { return binaryMessenger; } // ------ START BinaryMessenger (Deprecated: use getBinaryMessenger() instead) ----- /** @deprecated Use {@link #getBinaryMessenger()} instead. */ @Deprecated @UiThread @Override public TaskQueue makeBackgroundTaskQueue(TaskQueueOptions options) { return binaryMessenger.makeBackgroundTaskQueue(options); } /** @deprecated Use {@link #getBinaryMessenger()} instead. */ @Deprecated @Override @UiThread public void send(@NonNull String channel, @Nullable ByteBuffer message) { binaryMessenger.send(channel, message); } /** @deprecated Use {@link #getBinaryMessenger()} instead. */ @Deprecated @Override @UiThread public void send( @NonNull String channel, @Nullable ByteBuffer message, @Nullable BinaryMessenger.BinaryReply callback) { binaryMessenger.send(channel, message, callback); } /** @deprecated Use {@link #getBinaryMessenger()} instead. */ @Deprecated @Override @UiThread public void setMessageHandler( @NonNull String channel, @Nullable BinaryMessenger.BinaryMessageHandler handler) { binaryMessenger.setMessageHandler(channel, handler); } /** @deprecated Use {@link #getBinaryMessenger()} instead. */ @Deprecated @Override @UiThread public void setMessageHandler( @NonNull String channel, @Nullable BinaryMessenger.BinaryMessageHandler handler, @Nullable TaskQueue taskQueue) { binaryMessenger.setMessageHandler(channel, handler, taskQueue); } /** @deprecated Use {@link #getBinaryMessenger()} instead. */ @Deprecated @Override public void enableBufferingIncomingMessages() { dartMessenger.enableBufferingIncomingMessages(); } /** @deprecated Use {@link #getBinaryMessenger()} instead. */ @Deprecated @Override public void disableBufferingIncomingMessages() { dartMessenger.disableBufferingIncomingMessages(); } // ------ END BinaryMessenger ----- /** * Returns the number of pending channel callback replies. * * <p>When sending messages to the Flutter application using {@link BinaryMessenger#send(String, * ByteBuffer, io.flutter.plugin.common.BinaryMessenger.BinaryReply)}, developers can optionally * specify a reply callback if they expect a reply from the Flutter application. * * <p>This method tracks all the pending callbacks that are waiting for response, and is supposed * to be called from the main thread (as other methods). Calling from a different thread could * possibly capture an indeterministic internal state, so don't do it. * * <p>Currently, it's mainly useful for a testing framework like Espresso to determine whether all * the async channel callbacks are handled and the app is idle. */ @UiThread public int getPendingChannelResponseCount() { return dartMessenger.getPendingChannelResponseCount(); } /** * Returns an identifier for this executor's primary isolate. This identifier can be used in * queries to the Dart service protocol. */ @Nullable public String getIsolateServiceId() { return isolateServiceId; } /** Callback interface invoked when the isolate identifier becomes available. */ public interface IsolateServiceIdListener { void onIsolateServiceIdAvailable(@NonNull String isolateServiceId); } /** * Set a listener that will be notified when an isolate identifier is available for this * executor's primary isolate. */ public void setIsolateServiceIdListener(@Nullable IsolateServiceIdListener listener) { isolateServiceIdListener = listener; if (isolateServiceIdListener != null && isolateServiceId != null) { isolateServiceIdListener.onIsolateServiceIdAvailable(isolateServiceId); } } /** * Notify the Dart VM of a low memory event, or that the application is in a state such that now * is an appropriate time to free resources, such as going to the background. * * <p>This does not notify a Flutter application about memory pressure. For that, use the {@link * io.flutter.embedding.engine.systemchannels.SystemChannel#sendMemoryPressureWarning}. * * <p>Calling this method may cause jank or latency in the application. Avoid calling it during * critical periods like application startup or periods of animation. */ public void notifyLowMemoryWarning() { if (flutterJNI.isAttached()) { flutterJNI.notifyLowMemoryWarning(); } } /** * Configuration options that specify which Dart entrypoint function is executed and where to find * that entrypoint and other assets required for Dart execution. */ public static class DartEntrypoint { /** * Create a DartEntrypoint pointing to the default Flutter assets location with a default Dart * entrypoint. */ @NonNull public static DartEntrypoint createDefault() { FlutterLoader flutterLoader = FlutterInjector.instance().flutterLoader(); if (!flutterLoader.initialized()) { throw new AssertionError( "DartEntrypoints can only be created once a FlutterEngine is created."); } return new DartEntrypoint(flutterLoader.findAppBundlePath(), "main"); } /** The path within the AssetManager where the app will look for assets. */ @NonNull public final String pathToBundle; /** The library or file location that contains the Dart entrypoint function. */ @Nullable public final String dartEntrypointLibrary; /** The name of a Dart function to execute. */ @NonNull public final String dartEntrypointFunctionName; public DartEntrypoint( @NonNull String pathToBundle, @NonNull String dartEntrypointFunctionName) { this.pathToBundle = pathToBundle; dartEntrypointLibrary = null; this.dartEntrypointFunctionName = dartEntrypointFunctionName; } public DartEntrypoint( @NonNull String pathToBundle, @NonNull String dartEntrypointLibrary, @NonNull String dartEntrypointFunctionName) { this.pathToBundle = pathToBundle; this.dartEntrypointLibrary = dartEntrypointLibrary; this.dartEntrypointFunctionName = dartEntrypointFunctionName; } @Override @NonNull public String toString() { return "DartEntrypoint( bundle path: " + pathToBundle + ", function: " + dartEntrypointFunctionName + " )"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DartEntrypoint that = (DartEntrypoint) o; if (!pathToBundle.equals(that.pathToBundle)) return false; return dartEntrypointFunctionName.equals(that.dartEntrypointFunctionName); } @Override public int hashCode() { int result = pathToBundle.hashCode(); result = 31 * result + dartEntrypointFunctionName.hashCode(); return result; } } /** * Configuration options that specify which Dart callback function is executed and where to find * that callback and other assets required for Dart execution. */ public static class DartCallback { /** Standard Android AssetManager, provided from some {@code Context} or {@code Resources}. */ public final AssetManager androidAssetManager; /** The path within the AssetManager where the app will look for assets. */ public final String pathToBundle; /** A Dart callback that was previously registered with the Dart VM. */ public final FlutterCallbackInformation callbackHandle; public DartCallback( @NonNull AssetManager androidAssetManager, @NonNull String pathToBundle, @NonNull FlutterCallbackInformation callbackHandle) { this.androidAssetManager = androidAssetManager; this.pathToBundle = pathToBundle; this.callbackHandle = callbackHandle; } @Override @NonNull public String toString() { return "DartCallback( bundle path: " + pathToBundle + ", library path: " + callbackHandle.callbackLibraryPath + ", function: " + callbackHandle.callbackName + " )"; } } private static class DefaultBinaryMessenger implements BinaryMessenger { private final DartMessenger messenger; private DefaultBinaryMessenger(@NonNull DartMessenger messenger) { this.messenger = messenger; } public TaskQueue makeBackgroundTaskQueue(TaskQueueOptions options) { return messenger.makeBackgroundTaskQueue(options); } /** * Sends the given {@code message} from Android to Dart over the given {@code channel}. * * @param channel the name of the logical channel used for the message. * @param message the message payload, a direct-allocated {@link ByteBuffer} with the message * bytes */ @Override @UiThread public void send(@NonNull String channel, @Nullable ByteBuffer message) { messenger.send(channel, message, null); } /** * Sends the given {@code messages} from Android to Dart over the given {@code channel} and then * has the provided {@code callback} invoked when the Dart side responds. * * @param channel the name of the logical channel used for the message. * @param message the message payload, a direct-allocated {@link ByteBuffer} with the message * bytes between position zero and current position, or null. * @param callback a callback invoked when the Dart application responds to the message */ @Override @UiThread public void send( @NonNull String channel, @Nullable ByteBuffer message, @Nullable BinaryMessenger.BinaryReply callback) { messenger.send(channel, message, callback); } /** * Sets the given {@link io.flutter.plugin.common.BinaryMessenger.BinaryMessageHandler} as the * singular handler for all incoming messages received from the Dart side of this Dart execution * context. * * @param channel the name of the channel. * @param handler a {@link BinaryMessageHandler} to be invoked on incoming messages, or null. */ @Override @UiThread public void setMessageHandler( @NonNull String channel, @Nullable BinaryMessenger.BinaryMessageHandler handler) { messenger.setMessageHandler(channel, handler); } @Override @UiThread public void setMessageHandler( @NonNull String channel, @Nullable BinaryMessenger.BinaryMessageHandler handler, @Nullable TaskQueue taskQueue) { messenger.setMessageHandler(channel, handler, taskQueue); } @Override public void enableBufferingIncomingMessages() { messenger.enableBufferingIncomingMessages(); } @Override public void disableBufferingIncomingMessages() { messenger.disableBufferingIncomingMessages(); } } }
engine/shell/platform/android/io/flutter/embedding/engine/dart/DartExecutor.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/dart/DartExecutor.java", "repo_id": "engine", "token_count": 5846 }
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. package io.flutter.embedding.engine.plugins.activity; import android.app.Activity; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.PluginRegistry; /** * Binding that gives {@link ActivityAware} plugins access to an associated {@link * android.app.Activity} and the {@link android.app.Activity}'s lifecycle methods. * * <p>To obtain an instance of an {@code ActivityPluginBinding} in a Flutter plugin, implement the * {@link ActivityAware} interface. A binding is provided in {@link * ActivityAware#onAttachedToActivity(ActivityPluginBinding)} and {@link * ActivityAware#onReattachedToActivityForConfigChanges(ActivityPluginBinding)}. */ public interface ActivityPluginBinding { /** * Returns the {@link android.app.Activity} that is currently attached to the {@link * io.flutter.embedding.engine.FlutterEngine} that owns this {@code ActivityPluginBinding}. */ @NonNull Activity getActivity(); /** * Returns the {@code Lifecycle} associated with the attached {@code Activity}. * * <p>Use the flutter_plugin_android_lifecycle plugin to turn the returned {@code Object} into a * {@code Lifecycle} object. See * (https://github.com/flutter/plugins/tree/master/packages/flutter_plugin_android_lifecycle). * Flutter plugins that rely on {@code Lifecycle} are forced to use the * flutter_plugin_android_lifecycle plugin so that the version of the Android Lifecycle library is * exposed to pub, which allows Flutter to manage different versions library over time. */ @NonNull Object getLifecycle(); /** * Adds a listener that is invoked whenever the associated {@link android.app.Activity}'s {@code * onRequestPermissionsResult(...)} method is invoked. */ void addRequestPermissionsResultListener( @NonNull PluginRegistry.RequestPermissionsResultListener listener); /** * Removes a listener that was added in {@link * #addRequestPermissionsResultListener(PluginRegistry.RequestPermissionsResultListener)}. */ void removeRequestPermissionsResultListener( @NonNull PluginRegistry.RequestPermissionsResultListener listener); /** * Adds a listener that is invoked whenever the associated {@link android.app.Activity}'s {@code * onActivityResult(...)} method is invoked. */ void addActivityResultListener(@NonNull PluginRegistry.ActivityResultListener listener); /** * Removes a listener that was added in {@link * #addActivityResultListener(PluginRegistry.ActivityResultListener)}. */ void removeActivityResultListener(@NonNull PluginRegistry.ActivityResultListener listener); /** * Adds a listener that is invoked whenever the associated {@link android.app.Activity}'s {@code * onNewIntent(...)} method is invoked. */ void addOnNewIntentListener(@NonNull PluginRegistry.NewIntentListener listener); /** * Removes a listener that was added in {@link * #addOnNewIntentListener(PluginRegistry.NewIntentListener)}. */ void removeOnNewIntentListener(@NonNull PluginRegistry.NewIntentListener listener); /** * Adds a listener that is invoked whenever the associated {@link android.app.Activity}'s {@code * onUserLeaveHint()} method is invoked. */ void addOnUserLeaveHintListener(@NonNull PluginRegistry.UserLeaveHintListener listener); /** * Removes a listener that was added in {@link * #addOnUserLeaveHintListener(PluginRegistry.UserLeaveHintListener)}. */ void removeOnUserLeaveHintListener(@NonNull PluginRegistry.UserLeaveHintListener listener); /** * Adds a listener that is invoked whenever the associated {@link android.app.Activity}'s {@code * onWindowFocusChanged()} method is invoked. */ void addOnWindowFocusChangedListener(@NonNull PluginRegistry.WindowFocusChangedListener listener); /** * Removes a listener that was added in {@link * #addOnWindowFocusChangedListener(PluginRegistry.WindowFocusChangedListener)}. */ void removeOnWindowFocusChangedListener( @NonNull PluginRegistry.WindowFocusChangedListener listener); /** * Adds a listener that is invoked when the associated {@code Activity} or {@code Fragment} saves * and restores instance state. */ void addOnSaveStateListener(@NonNull OnSaveInstanceStateListener listener); /** * Removes a listener that was added in {@link * #addOnSaveStateListener(OnSaveInstanceStateListener)}. */ void removeOnSaveStateListener(@NonNull OnSaveInstanceStateListener listener); interface OnSaveInstanceStateListener { /** * Invoked when the associated {@code Activity} or {@code Fragment} executes {@link * Activity#onSaveInstanceState(Bundle)}. */ void onSaveInstanceState(@NonNull Bundle bundle); /** * Invoked when the associated {@code Activity} executes {@link * android.app.Activity#onCreate(Bundle)} or associated {@code Fragment} executes {@code * Fragment#onCreate(Bundle)}. */ void onRestoreInstanceState(@Nullable Bundle bundle); } }
engine/shell/platform/android/io/flutter/embedding/engine/plugins/activity/ActivityPluginBinding.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/activity/ActivityPluginBinding.java", "repo_id": "engine", "token_count": 1530 }
308
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.renderer; import android.view.Surface; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Owns a {@code Surface} that {@code FlutterRenderer} would like to paint. * * <p>{@code RenderSurface} is responsible for providing a {@code Surface} to a given {@code * FlutterRenderer} when requested, and then notify that {@code FlutterRenderer} when the {@code * Surface} changes, or is destroyed. * * <p>The behavior of providing a {@code Surface} is delegated to this interface because the timing * of a {@code Surface}'s availability is determined by Android. Therefore, an accessor method would * not fulfill the requirements. Therefore, a {@code RenderSurface} is given a {@code * FlutterRenderer}, which the {@code RenderSurface} is expected to notify as a {@code Surface} * becomes available, changes, or is destroyed. */ public interface RenderSurface { /** * Returns the {@code FlutterRenderer} that is attached to this {@code RenderSurface}, or null if * no {@code FlutterRenderer} is currently attached. */ @Nullable FlutterRenderer getAttachedRenderer(); /** * Instructs this {@code RenderSurface} to give its {@code Surface} to the given {@code * FlutterRenderer} so that Flutter can paint pixels on it. * * <p>After this call, {@code RenderSurface} is expected to invoke the following methods on {@link * FlutterRenderer} at the appropriate times: * * <ol> * <li>{@link FlutterRenderer#startRenderingToSurface(Surface, boolean)} * <li>{@link FlutterRenderer#surfaceChanged(int, int)}} * <li>{@link FlutterRenderer#stopRenderingToSurface()} * </ol> */ void attachToRenderer(@NonNull FlutterRenderer renderer); /** * Instructs this {@code RenderSurface} to stop forwarding {@code Surface} notifications to the * {@code FlutterRenderer} that was previously connected with {@link * #attachToRenderer(FlutterRenderer)}. * * <p>This {@code RenderSurface} should also clean up any references related to the previously * connected {@code FlutterRenderer}. */ void detachFromRenderer(); /** * Instructs this {@code RenderSurface} to stop forwarding {@code Surface} notifications to the * {@code FlutterRenderer} that was previously connected with {@link * #attachToRenderer(FlutterRenderer)}. */ void pause(); /** * Instructs this {@code RenderSurface} to resume forwarding {@code Surface} notifications to the * {@code FlutterRenderer} that was previously connected with {@link * #attachToRenderer(FlutterRenderer)}. */ void resume(); }
engine/shell/platform/android/io/flutter/embedding/engine/renderer/RenderSurface.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/renderer/RenderSurface.java", "repo_id": "engine", "token_count": 882 }
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. package io.flutter.embedding.engine.systemchannels; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.Log; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.StandardMethodCodec; import java.util.ArrayList; /** * {@link SpellCheckChannel} is a platform channel that is used by the framework to initiate spell * check in the embedding and for the embedding to send back the results. * * <p>When there is new text to be spell checked, the framework will send to the embedding the * message {@code SpellCheck.initiateSpellCheck} with the {@code String} locale to spell check with * and the {@code String} of text to spell check as arguments. In response, the {@link * io.flutter.plugin.editing.SpellCheckPlugin} will make a call to Android's spell check service to * fetch spell check results for the specified text. * * <p>Once the spell check results are received by the {@link * io.flutter.plugin.editing.SpellCheckPlugin}, it will send back to the framework the {@code * ArrayList<HashMap<String,Object>>} of spell check results (see {@link * io.flutter.plugin.editing.SpellCheckPlugin#onGetSentenceSuggestions} for details). The {@link * io.flutter.plugin.editing.SpellCheckPlugin} only handles one request to fetch spell check results * at a time; see {@link io.flutter.plugin.editing.SpellCheckPlugin#initiateSpellCheck} for details. * * <p>{@link io.flutter.plugin.editing.SpellCheckPlugin} implements {@link SpellCheckMethodHandler} * to initiate spell check. Implement {@link SpellCheckMethodHandler} to respond to spell check * requests. */ public class SpellCheckChannel { private static final String TAG = "SpellCheckChannel"; public final MethodChannel channel; private SpellCheckMethodHandler spellCheckMethodHandler; @NonNull public final MethodChannel.MethodCallHandler parsingMethodHandler = new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) { if (spellCheckMethodHandler == null) { Log.v( TAG, "No SpellCheckeMethodHandler registered, call not forwarded to spell check API."); return; } String method = call.method; Object args = call.arguments; Log.v(TAG, "Received '" + method + "' message."); switch (method) { case "SpellCheck.initiateSpellCheck": try { final ArrayList<String> argumentList = (ArrayList<String>) args; String locale = argumentList.get(0); String text = argumentList.get(1); spellCheckMethodHandler.initiateSpellCheck(locale, text, result); } catch (IllegalStateException exception) { result.error("error", exception.getMessage(), null); } break; default: result.notImplemented(); break; } } }; public SpellCheckChannel(@NonNull DartExecutor dartExecutor) { channel = new MethodChannel(dartExecutor, "flutter/spellcheck", StandardMethodCodec.INSTANCE); channel.setMethodCallHandler(parsingMethodHandler); } /** * Sets the {@link SpellCheckMethodHandler} which receives all requests to spell check the * specified text sent through this channel. */ public void setSpellCheckMethodHandler( @Nullable SpellCheckMethodHandler spellCheckMethodHandler) { this.spellCheckMethodHandler = spellCheckMethodHandler; } public interface SpellCheckMethodHandler { /** * Requests that spell check is initiated for the specified text, which will respond to the * {@code result} with either success if spell check results are received or error if the * request is skipped. */ void initiateSpellCheck( @NonNull String locale, @NonNull String text, @NonNull MethodChannel.Result result); } }
engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/SpellCheckChannel.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/SpellCheckChannel.java", "repo_id": "engine", "token_count": 1440 }
310
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.common; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.nio.ByteBuffer; /** * A codec for method calls and enveloped results. * * <p>Method calls are encoded as binary messages with enough structure that the codec can extract a * method name String and an arguments Object. These data items are used to populate a {@link * MethodCall}. * * <p>All operations throw {@link IllegalArgumentException}, if conversion fails. */ public interface MethodCodec { /** * Encodes a message call into binary. * * @param methodCall a {@link MethodCall}. * @return a {@link ByteBuffer} containing the encoding between position 0 and the current * position. */ @NonNull ByteBuffer encodeMethodCall(@NonNull MethodCall methodCall); /** * Decodes a message call from binary. * * @param methodCall the binary encoding of the method call as a {@link ByteBuffer}. * @return a {@link MethodCall} representation of the bytes between the given buffer's current * position and its limit. */ @NonNull MethodCall decodeMethodCall(@NonNull ByteBuffer methodCall); /** * Encodes a successful result into a binary envelope message. * * @param result The result value, possibly null. * @return a {@link ByteBuffer} containing the encoding between position 0 and the current * position. */ @NonNull ByteBuffer encodeSuccessEnvelope(@Nullable Object result); /** * Encodes an error result into a binary envelope message. * * @param errorCode An error code String. * @param errorMessage An error message String, possibly null. * @param errorDetails Error details, possibly null. Consider supporting {@link Throwable} in your * codec. This is the most common value passed to this field. * @return a {@link ByteBuffer} containing the encoding between position 0 and the current * position. */ @NonNull ByteBuffer encodeErrorEnvelope( @NonNull String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails); /** * Encodes an error result into a binary envelope message with the native stacktrace. * * @param errorCode An error code String. * @param errorMessage An error message String, possibly null. * @param errorDetails Error details, possibly null. Consider supporting {@link Throwable} in your * codec. This is the most common value passed to this field. * @param errorStacktrace Platform stacktrace for the error. possibly null. * @return a {@link ByteBuffer} containing the encoding between position 0 and the current * position. */ @NonNull ByteBuffer encodeErrorEnvelopeWithStacktrace( @NonNull String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails, @Nullable String errorStacktrace); /** * Decodes a result envelope from binary. * * @param envelope the binary encoding of a result envelope as a {@link ByteBuffer}. * @return the enveloped result Object. * @throws FlutterException if the envelope was an error envelope. */ @NonNull Object decodeEnvelope(@NonNull ByteBuffer envelope); }
engine/shell/platform/android/io/flutter/plugin/common/MethodCodec.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/common/MethodCodec.java", "repo_id": "engine", "token_count": 966 }
311
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.platform; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.android.FlutterImageView; /** A host view for Flutter content displayed over a platform view. */ public class PlatformOverlayView extends FlutterImageView { @Nullable private AccessibilityEventsDelegate accessibilityDelegate; public PlatformOverlayView( @NonNull Context context, int width, int height, @NonNull AccessibilityEventsDelegate accessibilityDelegate) { super(context, width, height, FlutterImageView.SurfaceKind.overlay); this.accessibilityDelegate = accessibilityDelegate; } public PlatformOverlayView(@NonNull Context context) { this(context, 1, 1, null); } public PlatformOverlayView(@NonNull Context context, @NonNull AttributeSet attrs) { this(context, 1, 1, null); } @Override public boolean onHoverEvent(@NonNull MotionEvent event) { // This view doesn't have any accessibility information of its own, but anything drawn in // this view is visible above the platform view it is overlaying, so should respond to // accessibility exploration events. Forward those events to the accessibility delegate in // a special mode that will stop as soon as it reaches a platform view, so that it will not // find widgets that behind the platform view. If no such widget is found, treat the event // as unhandled so that it can fall through to the platform view. if (accessibilityDelegate != null && accessibilityDelegate.onAccessibilityHoverEvent(event, true)) { return true; } return super.onHoverEvent(event); } }
engine/shell/platform/android/io/flutter/plugin/platform/PlatformOverlayView.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/PlatformOverlayView.java", "repo_id": "engine", "token_count": 554 }
312
// Copyright 2013 The Flutter 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.hardware.display.DisplayManager; import android.view.Choreographer; import android.view.Display; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.engine.FlutterJNI; // TODO(mattcarroll): add javadoc. public class VsyncWaiter { class DisplayListener implements DisplayManager.DisplayListener { DisplayListener(DisplayManager displayManager) { this.displayManager = displayManager; } private DisplayManager displayManager; void register() { displayManager.registerDisplayListener(this, null); } @Override public void onDisplayAdded(int displayId) {} @Override public void onDisplayRemoved(int displayId) {} @Override public void onDisplayChanged(int displayId) { if (displayId == Display.DEFAULT_DISPLAY) { final Display primaryDisplay = displayManager.getDisplay(Display.DEFAULT_DISPLAY); float fps = primaryDisplay.getRefreshRate(); VsyncWaiter.this.refreshPeriodNanos = (long) (1000000000.0 / fps); VsyncWaiter.this.flutterJNI.setRefreshRateFPS(fps); } } } private static VsyncWaiter instance; private static DisplayListener listener; private long refreshPeriodNanos = -1; private FlutterJNI flutterJNI; private FrameCallback frameCallback = new FrameCallback(0); @NonNull public static VsyncWaiter getInstance(float fps, @NonNull FlutterJNI flutterJNI) { if (instance == null) { instance = new VsyncWaiter(flutterJNI); } flutterJNI.setRefreshRateFPS(fps); instance.refreshPeriodNanos = (long) (1000000000.0 / fps); return instance; } @NonNull public static VsyncWaiter getInstance( @NonNull DisplayManager displayManager, @NonNull FlutterJNI flutterJNI) { if (instance == null) { instance = new VsyncWaiter(flutterJNI); } if (listener == null) { listener = instance.new DisplayListener(displayManager); listener.register(); } if (instance.refreshPeriodNanos == -1) { final Display primaryDisplay = displayManager.getDisplay(Display.DEFAULT_DISPLAY); float fps = primaryDisplay.getRefreshRate(); instance.refreshPeriodNanos = (long) (1000000000.0 / fps); flutterJNI.setRefreshRateFPS(fps); } return instance; } // For tests, to reset the singleton between tests. @VisibleForTesting public static void reset() { instance = null; listener = null; } private class FrameCallback implements Choreographer.FrameCallback { private long cookie; FrameCallback(long cookie) { this.cookie = cookie; } @Override public void doFrame(long frameTimeNanos) { long delay = System.nanoTime() - frameTimeNanos; if (delay < 0) { delay = 0; } flutterJNI.onVsync(delay, refreshPeriodNanos, cookie); frameCallback = this; } } private final FlutterJNI.AsyncWaitForVsyncDelegate asyncWaitForVsyncDelegate = new FlutterJNI.AsyncWaitForVsyncDelegate() { private Choreographer.FrameCallback obtainFrameCallback(final long cookie) { if (frameCallback != null) { frameCallback.cookie = cookie; FrameCallback ret = frameCallback; frameCallback = null; return ret; } return new FrameCallback(cookie); } @Override public void asyncWaitForVsync(long cookie) { Choreographer.getInstance().postFrameCallback(obtainFrameCallback(cookie)); } }; private VsyncWaiter(@NonNull FlutterJNI flutterJNI) { this.flutterJNI = flutterJNI; } public void init() { flutterJNI.setAsyncWaitForVsyncDelegate(asyncWaitForVsyncDelegate); } }
engine/shell/platform/android/io/flutter/view/VsyncWaiter.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/view/VsyncWaiter.java", "repo_id": "engine", "token_count": 1425 }
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. #include "flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h" #include "flutter/shell/platform/android/jni/jni_mock.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace flutter { namespace testing { TEST(PlatformViewShell, UpdateSemanticsDoesFlutterViewUpdateSemantics) { auto jni_mock = std::make_shared<JNIMock>(); auto delegate = std::make_unique<PlatformViewAndroidDelegate>(jni_mock); flutter::SemanticsNodeUpdates update; flutter::SemanticsNode node0; node0.id = 0; node0.identifier = "identifier"; node0.label = "label"; node0.tooltip = "tooltip"; update.insert(std::make_pair(0, node0)); std::vector<uint8_t> expected_buffer(192); std::vector<std::vector<uint8_t>> expected_string_attribute_args(0); size_t position = 0; int32_t* buffer_int32 = reinterpret_cast<int32_t*>(&expected_buffer[0]); float* buffer_float32 = reinterpret_cast<float*>(&expected_buffer[0]); std::vector<std::string> expected_strings; buffer_int32[position++] = node0.id; buffer_int32[position++] = node0.flags; buffer_int32[position++] = node0.actions; buffer_int32[position++] = node0.maxValueLength; buffer_int32[position++] = node0.currentValueLength; buffer_int32[position++] = node0.textSelectionBase; buffer_int32[position++] = node0.textSelectionExtent; buffer_int32[position++] = node0.platformViewId; buffer_int32[position++] = node0.scrollChildren; buffer_int32[position++] = node0.scrollIndex; buffer_float32[position++] = static_cast<float>(node0.scrollPosition); buffer_float32[position++] = static_cast<float>(node0.scrollExtentMax); buffer_float32[position++] = static_cast<float>(node0.scrollExtentMin); buffer_int32[position++] = expected_strings.size(); // node0.identifier expected_strings.push_back(node0.identifier); buffer_int32[position++] = expected_strings.size(); // node0.label expected_strings.push_back(node0.label); buffer_int32[position++] = -1; // node0.labelAttributes buffer_int32[position++] = -1; // node0.value buffer_int32[position++] = -1; // node0.valueAttributes buffer_int32[position++] = -1; // node0.increasedValue buffer_int32[position++] = -1; // node0.increasedValueAttributes buffer_int32[position++] = -1; // node0.decreasedValue buffer_int32[position++] = -1; // node0.decreasedValueAttributes buffer_int32[position++] = -1; // node0.hint buffer_int32[position++] = -1; // node0.hintAttributes buffer_int32[position++] = expected_strings.size(); // node0.tooltip expected_strings.push_back(node0.tooltip); buffer_int32[position++] = node0.textDirection; buffer_float32[position++] = node0.rect.left(); buffer_float32[position++] = node0.rect.top(); buffer_float32[position++] = node0.rect.right(); buffer_float32[position++] = node0.rect.bottom(); node0.transform.getColMajor(&buffer_float32[position]); position += 16; buffer_int32[position++] = 0; // node0.childrenInTraversalOrder.size(); buffer_int32[position++] = 0; // node0.customAccessibilityActions.size(); EXPECT_CALL(*jni_mock, FlutterViewUpdateSemantics(expected_buffer, expected_strings, expected_string_attribute_args)); // Creates empty custom actions. flutter::CustomAccessibilityActionUpdates actions; delegate->UpdateSemantics(update, actions); } TEST(PlatformViewShell, UpdateSemanticsDoesFlutterViewUpdateSemanticsWithStringAttribtes) { auto jni_mock = std::make_shared<JNIMock>(); auto delegate = std::make_unique<PlatformViewAndroidDelegate>(jni_mock); flutter::SemanticsNodeUpdates update; flutter::SemanticsNode node0; std::shared_ptr<SpellOutStringAttribute> spell_out_attribute = std::make_shared<SpellOutStringAttribute>(); spell_out_attribute->start = 2; spell_out_attribute->end = 4; spell_out_attribute->type = flutter::StringAttributeType::kSpellOut; std::shared_ptr<LocaleStringAttribute> locale_attribute = std::make_shared<LocaleStringAttribute>(); locale_attribute->start = 1; locale_attribute->end = 3; locale_attribute->type = flutter::StringAttributeType::kLocale; locale_attribute->locale = "en-US"; node0.id = 0; node0.identifier = "identifier"; node0.label = "label"; node0.labelAttributes.push_back(spell_out_attribute); node0.hint = "hint"; node0.hintAttributes.push_back(locale_attribute); update.insert(std::make_pair(0, node0)); std::vector<uint8_t> expected_buffer(224); std::vector<std::vector<uint8_t>> expected_string_attribute_args; size_t position = 0; int32_t* buffer_int32 = reinterpret_cast<int32_t*>(&expected_buffer[0]); float* buffer_float32 = reinterpret_cast<float*>(&expected_buffer[0]); std::vector<std::string> expected_strings; buffer_int32[position++] = node0.id; buffer_int32[position++] = node0.flags; buffer_int32[position++] = node0.actions; buffer_int32[position++] = node0.maxValueLength; buffer_int32[position++] = node0.currentValueLength; buffer_int32[position++] = node0.textSelectionBase; buffer_int32[position++] = node0.textSelectionExtent; buffer_int32[position++] = node0.platformViewId; buffer_int32[position++] = node0.scrollChildren; buffer_int32[position++] = node0.scrollIndex; buffer_float32[position++] = static_cast<float>(node0.scrollPosition); buffer_float32[position++] = static_cast<float>(node0.scrollExtentMax); buffer_float32[position++] = static_cast<float>(node0.scrollExtentMin); buffer_int32[position++] = expected_strings.size(); // node0.identifier expected_strings.push_back(node0.identifier); buffer_int32[position++] = expected_strings.size(); // node0.label expected_strings.push_back(node0.label); buffer_int32[position++] = 1; // node0.labelAttributes buffer_int32[position++] = 2; // node0.labelAttributes[0].start buffer_int32[position++] = 4; // node0.labelAttributes[0].end buffer_int32[position++] = 0; // node0.labelAttributes[0].type buffer_int32[position++] = -1; // node0.labelAttributes[0].args buffer_int32[position++] = -1; // node0.value buffer_int32[position++] = -1; // node0.valueAttributes buffer_int32[position++] = -1; // node0.increasedValue buffer_int32[position++] = -1; // node0.increasedValueAttributes buffer_int32[position++] = -1; // node0.decreasedValue buffer_int32[position++] = -1; // node0.decreasedValueAttributes buffer_int32[position++] = expected_strings.size(); // node0.hint expected_strings.push_back(node0.hint); buffer_int32[position++] = 1; // node0.hintAttributes buffer_int32[position++] = 1; // node0.hintAttributes[0].start buffer_int32[position++] = 3; // node0.hintAttributes[0].end buffer_int32[position++] = 1; // node0.hintAttributes[0].type buffer_int32[position++] = expected_string_attribute_args.size(); // node0.hintAttributes[0].args expected_string_attribute_args.push_back( {locale_attribute->locale.begin(), locale_attribute->locale.end()}); buffer_int32[position++] = -1; // node0.tooltip buffer_int32[position++] = node0.textDirection; buffer_float32[position++] = node0.rect.left(); buffer_float32[position++] = node0.rect.top(); buffer_float32[position++] = node0.rect.right(); buffer_float32[position++] = node0.rect.bottom(); node0.transform.getColMajor(&buffer_float32[position]); position += 16; buffer_int32[position++] = 0; // node0.childrenInTraversalOrder.size(); buffer_int32[position++] = 0; // node0.customAccessibilityActions.size(); EXPECT_CALL(*jni_mock, FlutterViewUpdateSemantics(expected_buffer, expected_strings, expected_string_attribute_args)); // Creates empty custom actions. flutter::CustomAccessibilityActionUpdates actions; delegate->UpdateSemantics(update, actions); } TEST(PlatformViewShell, UpdateSemanticsDoesFlutterViewUpdateCustomAccessibilityActions) { auto jni_mock = std::make_shared<JNIMock>(); auto delegate = std::make_unique<PlatformViewAndroidDelegate>(jni_mock); flutter::CustomAccessibilityActionUpdates actions; flutter::CustomAccessibilityAction action0; action0.id = 0; action0.overrideId = 1; action0.label = "label"; action0.hint = "hint"; actions.insert(std::make_pair(0, action0)); std::vector<uint8_t> expected_actions_buffer(16); int32_t* actions_buffer_int32 = reinterpret_cast<int32_t*>(&expected_actions_buffer[0]); std::vector<std::string> expected_action_strings; actions_buffer_int32[0] = action0.id; actions_buffer_int32[1] = action0.overrideId; actions_buffer_int32[2] = expected_action_strings.size(); expected_action_strings.push_back(action0.label); actions_buffer_int32[3] = expected_action_strings.size(); expected_action_strings.push_back(action0.hint); EXPECT_CALL(*jni_mock, FlutterViewUpdateCustomAccessibilityActions( expected_actions_buffer, expected_action_strings)); // Creates empty update. flutter::SemanticsNodeUpdates update; delegate->UpdateSemantics(update, actions); } } // namespace testing } // namespace flutter
engine/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate_unittests.cc/0
{ "file_path": "engine/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate_unittests.cc", "repo_id": "engine", "token_count": 3310 }
314
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_GL_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_GL_H_ #include "flutter/shell/platform/android/surface_texture_external_texture.h" #include "flutter/impeller/renderer/backend/gles/context_gles.h" #include "flutter/impeller/renderer/backend/gles/gles.h" #include "flutter/impeller/renderer/backend/gles/texture_gles.h" #include "flutter/impeller/toolkit/egl/egl.h" #include "flutter/impeller/toolkit/egl/image.h" #include "flutter/impeller/toolkit/gles/texture.h" #include "flutter/impeller/renderer/backend/gles/context_gles.h" namespace flutter { class SurfaceTextureExternalTextureGL : public SurfaceTextureExternalTexture { public: SurfaceTextureExternalTextureGL( int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& surface_texture, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade); ~SurfaceTextureExternalTextureGL() override; private: virtual void ProcessFrame(PaintContext& context, const SkRect& bounds) override; virtual void Detach() override; GLuint texture_name_ = 0; FML_DISALLOW_COPY_AND_ASSIGN(SurfaceTextureExternalTextureGL); }; class SurfaceTextureExternalTextureImpellerGL : public SurfaceTextureExternalTexture { public: 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); ~SurfaceTextureExternalTextureImpellerGL() override; private: virtual void ProcessFrame(PaintContext& context, const SkRect& bounds) override; virtual void Detach() override; const std::shared_ptr<impeller::ContextGLES> impeller_context_; std::shared_ptr<impeller::TextureGLES> texture_; FML_DISALLOW_COPY_AND_ASSIGN(SurfaceTextureExternalTextureImpellerGL); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_GL_H_
engine/shell/platform/android/surface_texture_external_texture_gl.h/0
{ "file_path": "engine/shell/platform/android/surface_texture_external_texture_gl.h", "repo_id": "engine", "token_count": 833 }
315
package io.flutter.embedding.android; import static org.robolectric.util.reflector.Reflector.reflector; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import androidx.annotation.Nullable; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import org.robolectric.shadows.ShadowResources; import org.robolectric.util.reflector.Direct; import org.robolectric.util.reflector.ForType; @SuppressWarnings("deprecation") // getDrawableInt @Implements(Resources.class) public class SplashShadowResources extends ShadowResources { @RealObject private Resources resources; public static final int SPLASH_DRAWABLE_ID = 191919; public static final int THEMED_SPLASH_DRAWABLE_ID = 212121; @ForType(Resources.class) interface ResourcesReflector { @Direct Drawable getDrawable(int id, Resources.Theme theme); @Direct Drawable getDrawable(int id); } @Implementation protected Drawable getDrawable(int id) { if (id == SPLASH_DRAWABLE_ID) { return new ColorDrawable(Color.BLUE); } return reflector(Resources.class, resources).getDrawable(id); } @Implementation protected Drawable getDrawable(int id, @Nullable Resources.Theme theme) { if (id == THEMED_SPLASH_DRAWABLE_ID) { // We pretend the drawable contains theme references. It can't be parsed without the app // theme. if (theme == null) { throw new Resources.NotFoundException( "Cannot parse drawable due to missing theme references."); } return new ColorDrawable(Color.GRAY); } return reflector(Resources.class, resources).getDrawable(id, theme); } }
engine/shell/platform/android/test/io/flutter/embedding/android/SplashShadowResources.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/android/SplashShadowResources.java", "repo_id": "engine", "token_count": 611 }
316
package io.flutter.embedding.engine.plugins.shim; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding; import io.flutter.embedding.engine.plugins.PluginRegistry; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class ShimPluginRegistryTest { @Mock private FlutterEngine mockFlutterEngine; @Mock private FlutterPluginBinding mockFlutterPluginBinding; @Mock private ActivityPluginBinding mockActivityPluginBinding; @Mock private PluginRegistry mockPluginRegistry; @Mock private Context mockApplicationContext; @Mock private Activity mockActivity; @Before public void setup() { MockitoAnnotations.openMocks(this); when(mockFlutterEngine.getPlugins()).thenReturn(mockPluginRegistry); when(mockFlutterPluginBinding.getApplicationContext()).thenReturn(mockApplicationContext); when(mockActivityPluginBinding.getActivity()).thenReturn(mockActivity); } @SuppressWarnings("deprecation") // Test is intentionally verifying deprecated behavior. @Test public void itSuppliesOldAPIsViaTheNewFlutterPluginBinding() { ShimPluginRegistry registryUnderTest = new ShimPluginRegistry(mockFlutterEngine); // Fully qualifed name because imports can not have deprecation supression. // This is the consumption side of the old plugins. io.flutter.plugin.common.PluginRegistry.Registrar registrarUnderTest = registryUnderTest.registrarFor("test"); ArgumentCaptor<FlutterPlugin> shimAggregateCaptor = ArgumentCaptor.forClass(FlutterPlugin.class); // A single shim aggregate was added as a new plugin to the FlutterEngine's PluginRegistry. verify(mockPluginRegistry).add(shimAggregateCaptor.capture()); // This is really a ShimRegistrarAggregate acting as a FlutterPlugin which is the // intermediate consumption side of the new plugin inside the shim. FlutterPlugin shimAggregateUnderTest = shimAggregateCaptor.getValue(); // The FlutterPluginBinding is the supply side of the new plugin. shimAggregateUnderTest.onAttachedToEngine(mockFlutterPluginBinding); // Consume something from the old plugin API. assertEquals(mockApplicationContext, registrarUnderTest.context()); // Check that the value comes from the supply side of the new plugin. verify(mockFlutterPluginBinding).getApplicationContext(); } @SuppressWarnings("deprecation") // Test is intentionally verifying deprecated behavior. @Test public void itSuppliesMultipleOldPlugins() { ShimPluginRegistry registryUnderTest = new ShimPluginRegistry(mockFlutterEngine); // Fully qualifed name because imports can not have deprecation supression. io.flutter.plugin.common.PluginRegistry.Registrar registrarUnderTest1 = registryUnderTest.registrarFor("test1"); io.flutter.plugin.common.PluginRegistry.Registrar registrarUnderTest2 = registryUnderTest.registrarFor("test2"); ArgumentCaptor<FlutterPlugin> shimAggregateCaptor = ArgumentCaptor.forClass(FlutterPlugin.class); verify(mockPluginRegistry).add(shimAggregateCaptor.capture()); // There's only one aggregate for many old plugins. FlutterPlugin shimAggregateUnderTest = shimAggregateCaptor.getValue(); // The FlutterPluginBinding is the supply side of the new plugin. shimAggregateUnderTest.onAttachedToEngine(mockFlutterPluginBinding); // Since the 2 old plugins are supplied by the same intermediate FlutterPlugin, they should // get the same value. assertEquals(registrarUnderTest1.context(), registrarUnderTest2.context()); verify(mockFlutterPluginBinding, times(2)).getApplicationContext(); } @SuppressWarnings("deprecation") // Test is intentionally verifying deprecated behavior. @Test public void itCanOnlySupplyActivityBindingWhenUpstreamActivityIsAttached() { ShimPluginRegistry registryUnderTest = new ShimPluginRegistry(mockFlutterEngine); io.flutter.plugin.common.PluginRegistry.Registrar registrarUnderTest = registryUnderTest.registrarFor("test"); ArgumentCaptor<FlutterPlugin> shimAggregateCaptor = ArgumentCaptor.forClass(FlutterPlugin.class); verify(mockPluginRegistry).add(shimAggregateCaptor.capture()); FlutterPlugin shimAggregateAsPlugin = shimAggregateCaptor.getValue(); ActivityAware shimAggregateAsActivityAware = (ActivityAware) shimAggregateCaptor.getValue(); // Nothing is retrievable when nothing is attached. assertNull(registrarUnderTest.context()); assertNull(registrarUnderTest.activity()); shimAggregateAsPlugin.onAttachedToEngine(mockFlutterPluginBinding); assertEquals(mockApplicationContext, registrarUnderTest.context()); assertNull(registrarUnderTest.activity()); shimAggregateAsActivityAware.onAttachedToActivity(mockActivityPluginBinding); // Now context is the activity context. assertEquals(mockActivity, registrarUnderTest.activeContext()); assertEquals(mockActivity, registrarUnderTest.activity()); shimAggregateAsActivityAware.onDetachedFromActivityForConfigChanges(); assertEquals(mockApplicationContext, registrarUnderTest.activeContext()); assertNull(registrarUnderTest.activity()); shimAggregateAsActivityAware.onReattachedToActivityForConfigChanges(mockActivityPluginBinding); assertEquals(mockActivity, registrarUnderTest.activeContext()); assertEquals(mockActivity, registrarUnderTest.activity()); shimAggregateAsActivityAware.onDetachedFromActivity(); assertEquals(mockApplicationContext, registrarUnderTest.activeContext()); assertNull(registrarUnderTest.activity()); // Attach an activity again. shimAggregateAsActivityAware.onAttachedToActivity(mockActivityPluginBinding); assertEquals(mockActivity, registrarUnderTest.activeContext()); assertEquals(mockActivity, registrarUnderTest.activity()); // Now rip out the whole engine. shimAggregateAsPlugin.onDetachedFromEngine(mockFlutterPluginBinding); // And everything should have been made unavailable. assertNull(registrarUnderTest.activeContext()); assertNull(registrarUnderTest.activity()); } }
engine/shell/platform/android/test/io/flutter/embedding/engine/plugins/shim/ShimPluginRegistryTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/plugins/shim/ShimPluginRegistryTest.java", "repo_id": "engine", "token_count": 2144 }
317
package io.flutter.plugin.common; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.content.res.AssetManager; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.dart.DartExecutor; import java.nio.ByteBuffer; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatcher; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class MethodChannelTest { @Test public void resizeChannelBufferMessageIsWellformed() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); String channel = "flutter/test"; MethodChannel rawChannel = new MethodChannel(dartExecutor, channel); int newSize = 3; rawChannel.resizeChannelBuffer(newSize); // Created from the following Dart code: // MethodCall methodCall = const MethodCall('resize', ['flutter/test', 3]); // const StandardMethodCodec().encodeMethodCall(methodCall).buffer.asUint8List(); final byte[] expected = { 7, 6, 114, 101, 115, 105, 122, 101, 12, 2, 7, 12, 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 3, 3, 0, 0, 0 }; // Verify that the correct message was sent to FlutterJNI. ArgumentMatcher<ByteBuffer> packetMatcher = new ByteBufferContentMatcher(ByteBuffer.wrap(expected)); verify(mockFlutterJNI, times(1)) .dispatchPlatformMessage( eq(BasicMessageChannel.CHANNEL_BUFFERS_CHANNEL), argThat(packetMatcher), anyInt(), anyInt()); } @Test public void overflowChannelBufferMessageIsWellformed() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); String channel = "flutter/test"; MethodChannel rawChannel = new MethodChannel(dartExecutor, channel); rawChannel.setWarnsOnChannelOverflow(false); // Created from the following Dart code: // MethodCall methodCall = const MethodCall('overflow', ['flutter/test', true]); // const StandardMethodCodec().encodeMethodCall(methodCall).buffer.asUint8List(); final byte[] expected = { 7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 12, 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 1 }; // Verify that the correct message was sent to FlutterJNI. ArgumentMatcher<ByteBuffer> packetMatcher = new ByteBufferContentMatcher(ByteBuffer.wrap(expected)); verify(mockFlutterJNI, times(1)) .dispatchPlatformMessage( eq(BasicMessageChannel.CHANNEL_BUFFERS_CHANNEL), argThat(packetMatcher), anyInt(), anyInt()); } } // Custom ByteBuffer matcher which calls rewind on both buffers before calling equals. // ByteBuffer.equals might return true when comparing byte buffers with different content if // both have no remaining elements. class ByteBufferContentMatcher implements ArgumentMatcher<ByteBuffer> { private ByteBuffer expected; public ByteBufferContentMatcher(ByteBuffer expected) { this.expected = expected; } @Override public boolean matches(ByteBuffer received) { expected.rewind(); received.rewind(); return received.equals(expected); } }
engine/shell/platform/android/test/io/flutter/plugin/common/MethodChannelTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/common/MethodChannelTest.java", "repo_id": "engine", "token_count": 1301 }
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. package io.flutter.plugin.platform; import static io.flutter.Build.API_LEVELS; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import android.annotation.TargetApi; import android.content.Context; import android.hardware.display.DisplayManager; import android.view.Display; import android.view.inputmethod.InputMethodManager; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) @TargetApi(API_LEVELS.API_28) public class SingleViewPresentationTest { @Test @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_30) public void returnsOuterContextInputMethodManager() { // There's a bug in Android Q caused by the IMM being instanced per display. // https://github.com/flutter/flutter/issues/38375. We need the context returned by // SingleViewPresentation to be consistent from its instantiation instead of defaulting to // what the system would have returned at call time. // It's not possible to set up the exact same conditions as the unit test in the bug here, // but we can make sure that we're wrapping the Context passed in at instantiation time and // returning the same InputMethodManager from it. This test passes in a Spy context instance // that initially returns a mock. Without the bugfix this test falls back to Robolectric's // system service instead of the spy's and fails. // Create an SVP under test with a Context that returns a local IMM mock. Context context = spy(ApplicationProvider.getApplicationContext()); InputMethodManager expected = mock(InputMethodManager.class); when(context.getSystemService(Context.INPUT_METHOD_SERVICE)).thenReturn(expected); DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); SingleViewPresentation svp = new SingleViewPresentation(context, dm.getDisplay(0), null, null, null, false); // Get the IMM from the SVP's context. InputMethodManager actual = (InputMethodManager) svp.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); // This should be the mocked instance from construction, not the IMM from the greater // Android OS (or Robolectric's shadow, in this case). assertEquals(expected, actual); } @Test @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_30) public void returnsOuterContextInputMethodManager_createDisplayContext() { // The IMM should also persist across display contexts created from the base context. // Create an SVP under test with a Context that returns a local IMM mock. Context context = spy(ApplicationProvider.getApplicationContext()); InputMethodManager expected = mock(InputMethodManager.class); when(context.getSystemService(Context.INPUT_METHOD_SERVICE)).thenReturn(expected); Display display = ((DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE)).getDisplay(0); SingleViewPresentation svp = new SingleViewPresentation(context, display, null, null, null, false); // Get the IMM from the SVP's context. InputMethodManager actual = (InputMethodManager) svp.getContext() .createDisplayContext(display) .getSystemService(Context.INPUT_METHOD_SERVICE); // This should be the mocked instance from construction, not the IMM from the greater // Android OS (or Robolectric's shadow, in this case). assertEquals(expected, actual); } }
engine/shell/platform/android/test/io/flutter/plugin/platform/SingleViewPresentationTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/platform/SingleViewPresentationTest.java", "repo_id": "engine", "token_count": 1212 }
319
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application> <activity android:name="io.flutter.embedding.android.FlutterFragmentActivity" /> <activity android:name="io.flutter.embedding.android.FlutterFragmentActivityTest$FlutterFragmentActivityWithProvidedEngine" /> </application> </manifest>
engine/shell/platform/android/test_runner/src/main/AndroidManifest.xml/0
{ "file_path": "engine/shell/platform/android/test_runner/src/main/AndroidManifest.xml", "repo_id": "engine", "token_count": 107 }
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. // This file contains the implementations of any class in the wrapper that // - is not fully inline, and // - is necessary for all clients of the wrapper (either app or plugin). // It exists instead of the usual structure of having some_class_name.cc files // so that changes to the set of things that need non-header implementations // are not breaking changes for the template. // // If https://github.com/flutter/flutter/issues/57146 is fixed, this can be // removed in favor of the normal structure since templates will no longer // manually include files. #include <cassert> #include <iostream> #include <variant> #include "binary_messenger_impl.h" #include "include/flutter/engine_method_result.h" #include "include/flutter/method_channel.h" #include "include/flutter/standard_method_codec.h" #include "texture_registrar_impl.h" namespace flutter { // ========== binary_messenger_impl.h ========== namespace { using FlutterDesktopMessengerScopedLock = std::unique_ptr<FlutterDesktopMessenger, decltype(&FlutterDesktopMessengerUnlock)>; // Passes |message| to |user_data|, which must be a BinaryMessageHandler, along // with a BinaryReply that will send a response on |message|'s response handle. // // This serves as an adaptor between the function-pointer-based message callback // interface provided by the C API and the std::function-based message handler // interface of BinaryMessenger. void ForwardToHandler(FlutterDesktopMessengerRef messenger, const FlutterDesktopMessage* message, void* user_data) { auto* response_handle = message->response_handle; auto messenger_ptr = std::shared_ptr<FlutterDesktopMessenger>( FlutterDesktopMessengerAddRef(messenger), &FlutterDesktopMessengerRelease); BinaryReply reply_handler = [messenger_ptr, response_handle]( const uint8_t* reply, size_t reply_size) mutable { // Note: This lambda can be called on any thread. auto lock = FlutterDesktopMessengerScopedLock( FlutterDesktopMessengerLock(messenger_ptr.get()), &FlutterDesktopMessengerUnlock); if (!FlutterDesktopMessengerIsAvailable(messenger_ptr.get())) { // Drop reply if it comes in after the engine is destroyed. return; } if (!response_handle) { std::cerr << "Error: Response can be set only once. Ignoring " "duplicate response." << std::endl; return; } FlutterDesktopMessengerSendResponse(messenger_ptr.get(), response_handle, reply, reply_size); // The engine frees the response handle once // FlutterDesktopSendMessageResponse is called. response_handle = nullptr; }; const BinaryMessageHandler& message_handler = *static_cast<BinaryMessageHandler*>(user_data); message_handler(message->message, message->message_size, std::move(reply_handler)); } } // namespace BinaryMessengerImpl::BinaryMessengerImpl( FlutterDesktopMessengerRef core_messenger) : messenger_(core_messenger) {} BinaryMessengerImpl::~BinaryMessengerImpl() = default; void BinaryMessengerImpl::Send(const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply) const { if (reply == nullptr) { FlutterDesktopMessengerSend(messenger_, channel.c_str(), message, message_size); return; } struct Captures { BinaryReply reply; }; auto captures = new Captures(); captures->reply = reply; auto message_reply = [](const uint8_t* data, size_t data_size, void* user_data) { auto captures = reinterpret_cast<Captures*>(user_data); captures->reply(data, data_size); delete captures; }; bool result = FlutterDesktopMessengerSendWithReply( messenger_, channel.c_str(), message, message_size, message_reply, captures); if (!result) { delete captures; } } void BinaryMessengerImpl::SetMessageHandler(const std::string& channel, BinaryMessageHandler handler) { if (!handler) { handlers_.erase(channel); FlutterDesktopMessengerSetCallback(messenger_, channel.c_str(), nullptr, nullptr); return; } // Save the handler, to keep it alive. handlers_[channel] = std::move(handler); BinaryMessageHandler* message_handler = &handlers_[channel]; // Set an adaptor callback that will invoke the handler. FlutterDesktopMessengerSetCallback(messenger_, channel.c_str(), ForwardToHandler, message_handler); } // ========== engine_method_result.h ========== namespace internal { ReplyManager::ReplyManager(BinaryReply reply_handler) : reply_handler_(std::move(reply_handler)) { assert(reply_handler_); } ReplyManager::~ReplyManager() { if (reply_handler_) { // Warn, rather than send a not-implemented response, since the engine may // no longer be valid at this point. std::cerr << "Warning: Failed to respond to a message. This is a memory leak." << std::endl; } } void ReplyManager::SendResponseData(const std::vector<uint8_t>* data) { if (!reply_handler_) { std::cerr << "Error: Only one of Success, Error, or NotImplemented can be " "called," << " and it can be called exactly once. Ignoring duplicate result." << std::endl; return; } const uint8_t* message = data && !data->empty() ? data->data() : nullptr; size_t message_size = data ? data->size() : 0; reply_handler_(message, message_size); reply_handler_ = nullptr; } } // namespace internal // ========== method_channel.h ========== namespace { constexpr char kControlChannelName[] = "dev.flutter/channel-buffers"; constexpr char kResizeMethod[] = "resize"; constexpr char kOverflowMethod[] = "overflow"; } // namespace namespace internal { void ResizeChannel(BinaryMessenger* messenger, std::string name, int new_size) { auto control_channel = std::make_unique<MethodChannel<EncodableValue>>( messenger, kControlChannelName, &StandardMethodCodec::GetInstance()); // The deserialization logic handles only 32 bits values, see // https://github.com/flutter/engine/blob/93e8901490e78c7ba7e319cce4470d9c6478c6dc/lib/ui/channel_buffers.dart#L495. control_channel->InvokeMethod( kResizeMethod, std::make_unique<EncodableValue>(EncodableList{ EncodableValue(name), EncodableValue(static_cast<int32_t>(new_size)), })); } void SetChannelWarnsOnOverflow(BinaryMessenger* messenger, std::string name, bool warns) { auto control_channel = std::make_unique<MethodChannel<EncodableValue>>( messenger, kControlChannelName, &StandardMethodCodec::GetInstance()); control_channel->InvokeMethod(kOverflowMethod, std::make_unique<EncodableValue>(EncodableList{ EncodableValue(name), EncodableValue(!warns), })); } } // namespace internal // ========== texture_registrar_impl.h ========== TextureRegistrarImpl::TextureRegistrarImpl( FlutterDesktopTextureRegistrarRef texture_registrar_ref) : texture_registrar_ref_(texture_registrar_ref) {} TextureRegistrarImpl::~TextureRegistrarImpl() = default; int64_t TextureRegistrarImpl::RegisterTexture(TextureVariant* texture) { FlutterDesktopTextureInfo info = {}; if (auto pixel_buffer_texture = std::get_if<PixelBufferTexture>(texture)) { info.type = kFlutterDesktopPixelBufferTexture; info.pixel_buffer_config.user_data = pixel_buffer_texture; info.pixel_buffer_config.callback = [](size_t width, size_t height, void* user_data) -> const FlutterDesktopPixelBuffer* { auto texture = static_cast<PixelBufferTexture*>(user_data); return texture->CopyPixelBuffer(width, height); }; } else if (auto gpu_surface_texture = std::get_if<GpuSurfaceTexture>(texture)) { info.type = kFlutterDesktopGpuSurfaceTexture; info.gpu_surface_config.struct_size = sizeof(FlutterDesktopGpuSurfaceTextureConfig); info.gpu_surface_config.type = gpu_surface_texture->surface_type(); info.gpu_surface_config.user_data = gpu_surface_texture; info.gpu_surface_config.callback = [](size_t width, size_t height, void* user_data) -> const FlutterDesktopGpuSurfaceDescriptor* { auto texture = static_cast<GpuSurfaceTexture*>(user_data); return texture->ObtainDescriptor(width, height); }; } else { std::cerr << "Attempting to register unknown texture variant." << std::endl; return -1; } int64_t texture_id = FlutterDesktopTextureRegistrarRegisterExternalTexture( texture_registrar_ref_, &info); return texture_id; } // namespace flutter bool TextureRegistrarImpl::MarkTextureFrameAvailable(int64_t texture_id) { return FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable( texture_registrar_ref_, texture_id); } void TextureRegistrarImpl::UnregisterTexture(int64_t texture_id, std::function<void()> callback) { if (callback == nullptr) { FlutterDesktopTextureRegistrarUnregisterExternalTexture( texture_registrar_ref_, texture_id, nullptr, nullptr); return; } struct Captures { std::function<void()> callback; }; auto captures = new Captures(); captures->callback = std::move(callback); FlutterDesktopTextureRegistrarUnregisterExternalTexture( texture_registrar_ref_, texture_id, [](void* opaque) { auto captures = reinterpret_cast<Captures*>(opaque); captures->callback(); delete captures; }, captures); } bool TextureRegistrarImpl::UnregisterTexture(int64_t texture_id) { UnregisterTexture(texture_id, nullptr); return true; } } // namespace flutter
engine/shell/platform/common/client_wrapper/core_implementations.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/core_implementations.cc", "repo_id": "engine", "token_count": 3974 }
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_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CHANNEL_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CHANNEL_H_ #include <iostream> #include <string> #include "basic_message_channel.h" #include "binary_messenger.h" #include "engine_method_result.h" #include "method_call.h" #include "method_codec.h" #include "method_result.h" namespace flutter { class EncodableValue; // A handler for receiving a method call from the Flutter engine. // // Implementations must asynchronously call exactly one of the methods on // |result| to indicate the result of the method call. template <typename T> using MethodCallHandler = std::function<void(const MethodCall<T>& call, std::unique_ptr<MethodResult<T>> result)>; // A channel for communicating with the Flutter engine using invocation of // asynchronous methods. template <typename T = EncodableValue> class MethodChannel { public: // Creates an instance that sends and receives method calls on the channel // named |name|, encoded with |codec| and dispatched via |messenger|. MethodChannel(BinaryMessenger* messenger, const std::string& name, const MethodCodec<T>* codec) : messenger_(messenger), name_(name), codec_(codec) {} ~MethodChannel() = default; // Prevent copying. MethodChannel(MethodChannel const&) = delete; MethodChannel& operator=(MethodChannel const&) = delete; // Sends a message to the Flutter engine on this channel. // // If |result| is provided, one of its methods will be invoked with the // response from the engine. void InvokeMethod(const std::string& method, std::unique_ptr<T> arguments, std::unique_ptr<MethodResult<T>> result = nullptr) { MethodCall<T> method_call(method, std::move(arguments)); std::unique_ptr<std::vector<uint8_t>> message = codec_->EncodeMethodCall(method_call); if (!result) { messenger_->Send(name_, message->data(), message->size(), nullptr); return; } // std::function requires a copyable lambda, so convert to a shared pointer. // This is safe since only one copy of the shared_pointer will ever be // accessed. std::shared_ptr<MethodResult<T>> shared_result(result.release()); const auto* codec = codec_; std::string channel_name = name_; BinaryReply reply_handler = [shared_result, codec, channel_name]( const uint8_t* reply, size_t reply_size) { if (reply_size == 0) { shared_result->NotImplemented(); return; } // Use this channel's codec to decode and handle the // reply. bool decoded = codec->DecodeAndProcessResponseEnvelope( reply, reply_size, shared_result.get()); if (!decoded) { std::cerr << "Unable to decode reply to method " "invocation on channel " << channel_name << std::endl; shared_result->NotImplemented(); } }; messenger_->Send(name_, message->data(), message->size(), std::move(reply_handler)); } // Registers a handler that should be called any time a method call is // received on this channel. A null handler will remove any previous handler. // // The handler will be owned by the underlying BinaryMessageHandler. // Destroying the MethodChannel will not unregister the handler, so // the caller is responsible for unregistering explicitly if the handler // stops being valid before the engine is destroyed. void SetMethodCallHandler(MethodCallHandler<T> handler) const { if (!handler) { messenger_->SetMessageHandler(name_, nullptr); return; } const auto* codec = codec_; std::string channel_name = name_; BinaryMessageHandler binary_handler = [handler, codec, channel_name]( const uint8_t* message, size_t message_size, BinaryReply reply) { // Use this channel's codec to decode the call and build a result handler. auto result = std::make_unique<EngineMethodResult<T>>(std::move(reply), codec); std::unique_ptr<MethodCall<T>> method_call = codec->DecodeMethodCall(message, message_size); if (!method_call) { std::cerr << "Unable to construct method call from message on channel " << channel_name << std::endl; result->NotImplemented(); return; } handler(*method_call, std::move(result)); }; messenger_->SetMessageHandler(name_, std::move(binary_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. void Resize(int new_size) { internal::ResizeChannel(messenger_, name_, new_size); } // Defines 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. void SetWarnsOnOverflow(bool warns) { internal::SetChannelWarnsOnOverflow(messenger_, name_, warns); } private: BinaryMessenger* messenger_; std::string name_; const MethodCodec<T>* codec_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CHANNEL_H_
engine/shell/platform/common/client_wrapper/include/flutter/method_channel.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/method_channel.h", "repo_id": "engine", "token_count": 2131 }
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. // This file contains what would normally be standard_codec_serializer.cc, // standard_message_codec.cc, and standard_method_codec.cc. They are grouped // together to simplify use of the client wrapper, since the common case is // that any client that needs one of these files needs all three. #include <cassert> #include <cstring> #include <iostream> #include <map> #include <string> #include <vector> #include "byte_buffer_streams.h" #include "include/flutter/standard_codec_serializer.h" #include "include/flutter/standard_message_codec.h" #include "include/flutter/standard_method_codec.h" namespace flutter { // ===== standard_codec_serializer.h ===== namespace { // The order/values here must match the constants in message_codecs.dart. enum class EncodedType { kNull = 0, kTrue, kFalse, kInt32, kInt64, kLargeInt, // No longer used. If encountered, treat as kString. kFloat64, kString, kUInt8List, kInt32List, kInt64List, kFloat64List, kList, kMap, kFloat32List, }; // Returns the encoded type that should be written when serializing |value|. EncodedType EncodedTypeForValue(const EncodableValue& value) { switch (value.index()) { case 0: return EncodedType::kNull; case 1: return std::get<bool>(value) ? EncodedType::kTrue : EncodedType::kFalse; case 2: return EncodedType::kInt32; case 3: return EncodedType::kInt64; case 4: return EncodedType::kFloat64; case 5: return EncodedType::kString; case 6: return EncodedType::kUInt8List; case 7: return EncodedType::kInt32List; case 8: return EncodedType::kInt64List; case 9: return EncodedType::kFloat64List; case 10: return EncodedType::kList; case 11: return EncodedType::kMap; case 13: return EncodedType::kFloat32List; } assert(false); return EncodedType::kNull; } } // namespace StandardCodecSerializer::StandardCodecSerializer() = default; StandardCodecSerializer::~StandardCodecSerializer() = default; const StandardCodecSerializer& StandardCodecSerializer::GetInstance() { static StandardCodecSerializer sInstance; return sInstance; }; EncodableValue StandardCodecSerializer::ReadValue( ByteStreamReader* stream) const { uint8_t type = stream->ReadByte(); return ReadValueOfType(type, stream); } void StandardCodecSerializer::WriteValue(const EncodableValue& value, ByteStreamWriter* stream) const { stream->WriteByte(static_cast<uint8_t>(EncodedTypeForValue(value))); // TODO(cbracken): Consider replacing this with std::visit. switch (value.index()) { case 0: case 1: // Null and bool are encoded directly in the type. break; case 2: stream->WriteInt32(std::get<int32_t>(value)); break; case 3: stream->WriteInt64(std::get<int64_t>(value)); break; case 4: stream->WriteAlignment(8); stream->WriteDouble(std::get<double>(value)); break; case 5: { const auto& string_value = std::get<std::string>(value); size_t size = string_value.size(); WriteSize(size, stream); if (size > 0) { stream->WriteBytes( reinterpret_cast<const uint8_t*>(string_value.data()), size); } break; } case 6: WriteVector(std::get<std::vector<uint8_t>>(value), stream); break; case 7: WriteVector(std::get<std::vector<int32_t>>(value), stream); break; case 8: WriteVector(std::get<std::vector<int64_t>>(value), stream); break; case 9: WriteVector(std::get<std::vector<double>>(value), stream); break; case 10: { const auto& list = std::get<EncodableList>(value); WriteSize(list.size(), stream); for (const auto& item : list) { WriteValue(item, stream); } break; } case 11: { const auto& map = std::get<EncodableMap>(value); WriteSize(map.size(), stream); for (const auto& pair : map) { WriteValue(pair.first, stream); WriteValue(pair.second, stream); } break; } case 12: std::cerr << "Unhandled custom type in StandardCodecSerializer::WriteValue. " << "Custom types require codec extensions." << std::endl; break; case 13: { WriteVector(std::get<std::vector<float>>(value), stream); break; } } } EncodableValue StandardCodecSerializer::ReadValueOfType( uint8_t type, ByteStreamReader* stream) const { switch (static_cast<EncodedType>(type)) { case EncodedType::kNull: return EncodableValue(); case EncodedType::kTrue: return EncodableValue(true); case EncodedType::kFalse: return EncodableValue(false); case EncodedType::kInt32: return EncodableValue(stream->ReadInt32()); case EncodedType::kInt64: return EncodableValue(stream->ReadInt64()); case EncodedType::kFloat64: stream->ReadAlignment(8); return EncodableValue(stream->ReadDouble()); case EncodedType::kLargeInt: case EncodedType::kString: { size_t size = ReadSize(stream); std::string string_value; string_value.resize(size); stream->ReadBytes(reinterpret_cast<uint8_t*>(&string_value[0]), size); return EncodableValue(string_value); } case EncodedType::kUInt8List: return ReadVector<uint8_t>(stream); case EncodedType::kInt32List: return ReadVector<int32_t>(stream); case EncodedType::kInt64List: return ReadVector<int64_t>(stream); case EncodedType::kFloat64List: return ReadVector<double>(stream); case EncodedType::kList: { size_t length = ReadSize(stream); EncodableList list_value; list_value.reserve(length); for (size_t i = 0; i < length; ++i) { list_value.push_back(ReadValue(stream)); } return EncodableValue(list_value); } case EncodedType::kMap: { size_t length = ReadSize(stream); EncodableMap map_value; for (size_t i = 0; i < length; ++i) { EncodableValue key = ReadValue(stream); EncodableValue value = ReadValue(stream); map_value.emplace(std::move(key), std::move(value)); } return EncodableValue(map_value); } case EncodedType::kFloat32List: { return ReadVector<float>(stream); } } std::cerr << "Unknown type in StandardCodecSerializer::ReadValueOfType: " << static_cast<int>(type) << std::endl; return EncodableValue(); } size_t StandardCodecSerializer::ReadSize(ByteStreamReader* stream) const { uint8_t byte = stream->ReadByte(); if (byte < 254) { return byte; } else if (byte == 254) { uint16_t value = 0; stream->ReadBytes(reinterpret_cast<uint8_t*>(&value), 2); return value; } else { uint32_t value = 0; stream->ReadBytes(reinterpret_cast<uint8_t*>(&value), 4); return value; } } void StandardCodecSerializer::WriteSize(size_t size, ByteStreamWriter* stream) const { if (size < 254) { stream->WriteByte(static_cast<uint8_t>(size)); } else if (size <= 0xffff) { stream->WriteByte(254); uint16_t value = static_cast<uint16_t>(size); stream->WriteBytes(reinterpret_cast<uint8_t*>(&value), 2); } else { stream->WriteByte(255); uint32_t value = static_cast<uint32_t>(size); stream->WriteBytes(reinterpret_cast<uint8_t*>(&value), 4); } } template <typename T> EncodableValue StandardCodecSerializer::ReadVector( ByteStreamReader* stream) const { size_t count = ReadSize(stream); std::vector<T> vector; vector.resize(count); uint8_t type_size = static_cast<uint8_t>(sizeof(T)); if (type_size > 1) { stream->ReadAlignment(type_size); } stream->ReadBytes(reinterpret_cast<uint8_t*>(vector.data()), count * type_size); return EncodableValue(vector); } template <typename T> void StandardCodecSerializer::WriteVector(const std::vector<T> vector, ByteStreamWriter* stream) const { size_t count = vector.size(); WriteSize(count, stream); if (count == 0) { return; } uint8_t type_size = static_cast<uint8_t>(sizeof(T)); if (type_size > 1) { stream->WriteAlignment(type_size); } stream->WriteBytes(reinterpret_cast<const uint8_t*>(vector.data()), count * type_size); } // ===== standard_message_codec.h ===== // static const StandardMessageCodec& StandardMessageCodec::GetInstance( const StandardCodecSerializer* serializer) { if (!serializer) { serializer = &StandardCodecSerializer::GetInstance(); } static auto* sInstances = new std::map<const StandardCodecSerializer*, std::unique_ptr<StandardMessageCodec>>; auto it = sInstances->find(serializer); if (it == sInstances->end()) { // Uses new due to private constructor (to prevent API clients from // accidentally passing temporary codec instances to channels). auto emplace_result = sInstances->emplace( serializer, std::unique_ptr<StandardMessageCodec>( new StandardMessageCodec(serializer))); it = emplace_result.first; } return *(it->second); } StandardMessageCodec::StandardMessageCodec( const StandardCodecSerializer* serializer) : serializer_(serializer) {} StandardMessageCodec::~StandardMessageCodec() = default; std::unique_ptr<EncodableValue> StandardMessageCodec::DecodeMessageInternal( const uint8_t* binary_message, size_t message_size) const { if (!binary_message) { return std::make_unique<EncodableValue>(); } ByteBufferStreamReader stream(binary_message, message_size); return std::make_unique<EncodableValue>(serializer_->ReadValue(&stream)); } std::unique_ptr<std::vector<uint8_t>> StandardMessageCodec::EncodeMessageInternal( const EncodableValue& message) const { auto encoded = std::make_unique<std::vector<uint8_t>>(); ByteBufferStreamWriter stream(encoded.get()); serializer_->WriteValue(message, &stream); return encoded; } // ===== standard_method_codec.h ===== // static const StandardMethodCodec& StandardMethodCodec::GetInstance( const StandardCodecSerializer* serializer) { if (!serializer) { serializer = &StandardCodecSerializer::GetInstance(); } static auto* sInstances = new std::map<const StandardCodecSerializer*, std::unique_ptr<StandardMethodCodec>>; auto it = sInstances->find(serializer); if (it == sInstances->end()) { // Uses new due to private constructor (to prevent API clients from // accidentally passing temporary codec instances to channels). auto emplace_result = sInstances->emplace( serializer, std::unique_ptr<StandardMethodCodec>( new StandardMethodCodec(serializer))); it = emplace_result.first; } return *(it->second); } StandardMethodCodec::StandardMethodCodec( const StandardCodecSerializer* serializer) : serializer_(serializer) {} StandardMethodCodec::~StandardMethodCodec() = default; std::unique_ptr<MethodCall<EncodableValue>> StandardMethodCodec::DecodeMethodCallInternal(const uint8_t* message, size_t message_size) const { ByteBufferStreamReader stream(message, message_size); EncodableValue method_name_value = serializer_->ReadValue(&stream); const auto* method_name = std::get_if<std::string>(&method_name_value); if (!method_name) { std::cerr << "Invalid method call; method name is not a string." << std::endl; return nullptr; } auto arguments = std::make_unique<EncodableValue>(serializer_->ReadValue(&stream)); return std::make_unique<MethodCall<EncodableValue>>(*method_name, std::move(arguments)); } std::unique_ptr<std::vector<uint8_t>> StandardMethodCodec::EncodeMethodCallInternal( const MethodCall<EncodableValue>& method_call) const { auto encoded = std::make_unique<std::vector<uint8_t>>(); ByteBufferStreamWriter stream(encoded.get()); serializer_->WriteValue(EncodableValue(method_call.method_name()), &stream); if (method_call.arguments()) { serializer_->WriteValue(*method_call.arguments(), &stream); } else { serializer_->WriteValue(EncodableValue(), &stream); } return encoded; } std::unique_ptr<std::vector<uint8_t>> StandardMethodCodec::EncodeSuccessEnvelopeInternal( const EncodableValue* result) const { auto encoded = std::make_unique<std::vector<uint8_t>>(); ByteBufferStreamWriter stream(encoded.get()); stream.WriteByte(0); if (result) { serializer_->WriteValue(*result, &stream); } else { serializer_->WriteValue(EncodableValue(), &stream); } return encoded; } std::unique_ptr<std::vector<uint8_t>> StandardMethodCodec::EncodeErrorEnvelopeInternal( const std::string& error_code, const std::string& error_message, const EncodableValue* error_details) const { auto encoded = std::make_unique<std::vector<uint8_t>>(); ByteBufferStreamWriter stream(encoded.get()); stream.WriteByte(1); serializer_->WriteValue(EncodableValue(error_code), &stream); if (error_message.empty()) { serializer_->WriteValue(EncodableValue(), &stream); } else { serializer_->WriteValue(EncodableValue(error_message), &stream); } if (error_details) { serializer_->WriteValue(*error_details, &stream); } else { serializer_->WriteValue(EncodableValue(), &stream); } return encoded; } bool StandardMethodCodec::DecodeAndProcessResponseEnvelopeInternal( const uint8_t* response, size_t response_size, MethodResult<EncodableValue>* result) const { ByteBufferStreamReader stream(response, response_size); uint8_t flag = stream.ReadByte(); switch (flag) { case 0: { EncodableValue value = serializer_->ReadValue(&stream); if (value.IsNull()) { result->Success(); } else { result->Success(value); } return true; } case 1: { EncodableValue code = serializer_->ReadValue(&stream); EncodableValue message = serializer_->ReadValue(&stream); EncodableValue details = serializer_->ReadValue(&stream); const std::string& message_string = message.IsNull() ? "" : std::get<std::string>(message); if (details.IsNull()) { result->Error(std::get<std::string>(code), message_string); } else { result->Error(std::get<std::string>(code), message_string, details); } return true; } default: return false; } } } // namespace flutter
engine/shell/platform/common/client_wrapper/standard_codec.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/standard_codec.cc", "repo_id": "engine", "token_count": 5755 }
323
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/common/geometry.h" #include "gtest/gtest.h" namespace flutter { TEST(Point, SetsCoordinates) { Point point(-30.0, 42.0); EXPECT_DOUBLE_EQ(-30.0, point.x()); EXPECT_DOUBLE_EQ(42.0, point.y()); } TEST(Size, SetsDimensions) { Size size(20.0, 42.0); EXPECT_DOUBLE_EQ(20.0, size.width()); EXPECT_DOUBLE_EQ(42.0, size.height()); } TEST(Size, ClampsDimensionsPositive) { Size size(-20.0, -42.0); EXPECT_DOUBLE_EQ(0.0, size.width()); EXPECT_DOUBLE_EQ(0.0, size.height()); } TEST(Rect, SetsOriginAndSize) { Point origin(-30.0, 42.0); Size size(20.0, 22.0); Rect rect(origin, size); EXPECT_EQ(origin, rect.origin()); EXPECT_EQ(size, rect.size()); } TEST(Rect, ReturnsLTRB) { Point origin(-30.0, 42.0); Size size(20.0, 22.0); Rect rect(origin, size); EXPECT_DOUBLE_EQ(-30.0, rect.left()); EXPECT_DOUBLE_EQ(42.0, rect.top()); EXPECT_DOUBLE_EQ(-10.0, rect.right()); EXPECT_DOUBLE_EQ(64.0, rect.bottom()); } TEST(Rect, ReturnsWidthHeight) { Point origin(-30.0, 42.0); Size size(20.0, 22.0); Rect rect(origin, size); EXPECT_DOUBLE_EQ(20.0, rect.width()); EXPECT_DOUBLE_EQ(22.0, rect.height()); } } // namespace flutter
engine/shell/platform/common/geometry_unittests.cc/0
{ "file_path": "engine/shell/platform/common/geometry_unittests.cc", "repo_id": "engine", "token_count": 591 }
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_COMMON_PUBLIC_FLUTTER_MESSENGER_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MESSENGER_H_ #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include "flutter_export.h" #if defined(__cplusplus) extern "C" { #endif // defined(__cplusplus) // Opaque reference to a Flutter engine messenger. typedef struct FlutterDesktopMessenger* FlutterDesktopMessengerRef; // Opaque handle for tracking responses to messages. typedef struct _FlutterPlatformMessageResponseHandle FlutterDesktopMessageResponseHandle; // The callback expected as a response of a binary message. typedef void (*FlutterDesktopBinaryReply)(const uint8_t* data, size_t data_size, void* user_data); // A message received from Flutter. typedef struct { // Size of this struct as created by Flutter. size_t struct_size; // The name of the channel used for this message. const char* channel; // The raw message data. const uint8_t* message; // The length of |message|. size_t message_size; // The response handle. If non-null, the receiver of this message must call // FlutterDesktopSendMessageResponse exactly once with this handle. const FlutterDesktopMessageResponseHandle* response_handle; } FlutterDesktopMessage; // Function pointer type for message handler callback registration. // // The user data will be whatever was passed to FlutterDesktopSetMessageHandler // for the channel the message is received on. typedef void (*FlutterDesktopMessageCallback)( FlutterDesktopMessengerRef /* messenger */, const FlutterDesktopMessage* /* message*/, void* /* user data */); // Sends a binary message to the Flutter side on the specified channel. FLUTTER_EXPORT bool FlutterDesktopMessengerSend( FlutterDesktopMessengerRef messenger, const char* channel, const uint8_t* message, const size_t message_size); // Sends a binary message to the Flutter side on the specified channel. // The |reply| callback will be executed when a response is received. FLUTTER_EXPORT bool FlutterDesktopMessengerSendWithReply( FlutterDesktopMessengerRef messenger, const char* channel, const uint8_t* message, const size_t message_size, const FlutterDesktopBinaryReply reply, void* user_data); // Sends a reply to a FlutterDesktopMessage for the given response handle. // // Once this has been called, |handle| is invalid and must not be used again. FLUTTER_EXPORT void FlutterDesktopMessengerSendResponse( FlutterDesktopMessengerRef messenger, const FlutterDesktopMessageResponseHandle* handle, const uint8_t* data, size_t data_length); // Registers a callback function for incoming binary messages from the Flutter // side on the specified channel. // // Replaces any existing callback. Provide a null handler to unregister the // existing callback. // // If |user_data| is provided, it will be passed in |callback| calls. FLUTTER_EXPORT void FlutterDesktopMessengerSetCallback( FlutterDesktopMessengerRef messenger, const char* channel, FlutterDesktopMessageCallback callback, void* user_data); // Increments the reference count for the |messenger|. // // Operation is thread-safe. // // See also: |FlutterDesktopMessengerRelease| FLUTTER_EXPORT FlutterDesktopMessengerRef FlutterDesktopMessengerAddRef( FlutterDesktopMessengerRef messenger); // Decrements the reference count for the |messenger|. // // Operation is thread-safe. // // See also: |FlutterDesktopMessengerAddRef| FLUTTER_EXPORT void FlutterDesktopMessengerRelease( FlutterDesktopMessengerRef messenger); // Returns `true` if the |FlutterDesktopMessengerRef| still references a running // engine. // // This check should be made inside of a |FlutterDesktopMessengerLock| and // before any other calls are made to the FlutterDesktopMessengerRef when using // it from a thread other than the platform thread. FLUTTER_EXPORT bool FlutterDesktopMessengerIsAvailable( FlutterDesktopMessengerRef messenger); // Locks the `FlutterDesktopMessengerRef` ensuring that // |FlutterDesktopMessengerIsAvailable| does not change while locked. // // All calls to the FlutterDesktopMessengerRef from threads other than the // platform thread should happen inside of a lock. // // Operation is thread-safe. // // Returns the |messenger| value. // // See also: |FlutterDesktopMessengerUnlock| FLUTTER_EXPORT FlutterDesktopMessengerRef FlutterDesktopMessengerLock( FlutterDesktopMessengerRef messenger); // Unlocks the `FlutterDesktopMessengerRef`. // // Operation is thread-safe. // // See also: |FlutterDesktopMessengerLock| FLUTTER_EXPORT void FlutterDesktopMessengerUnlock( FlutterDesktopMessengerRef messenger); #if defined(__cplusplus) } // extern "C" #endif #endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MESSENGER_H_
engine/shell/platform/common/public/flutter_messenger.h/0
{ "file_path": "engine/shell/platform/common/public/flutter_messenger.h", "repo_id": "engine", "token_count": 1552 }
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. assert(is_mac || is_ios) import("//flutter/common/config.gni") import("//flutter/testing/testing.gni") import("framework_common.gni") source_set("common") { cflags_objc = flutter_cflags_objc cflags_objcc = flutter_cflags_objcc sources = [ "buffer_conversions.h", "buffer_conversions.mm", "command_line.h", "command_line.mm", ] deps = [ ":availability_version_check", "//flutter/fml", ] public_configs = [ "//flutter:config" ] } # Provides an implementation for _availability_version_check. # # This is required due to an upstream compiler builtin (runtime) change # that marked this function as weakly-linked via __attribute__((weak import)) # As such, no linking failure occurs when the function is unavailable at # link time. Since the symbol is no longer linked in, App Store review blocks # publishing due to relying on a private symbol. Instead we link in our own # implementation, which provides the exact implementation used in clang prior # to the upstream change. # # See: Upstream clang change: https://reviews.llvm.org/D150397 # See: https://github.com/flutter/flutter/issues/133777 source_set("availability_version_check") { cflags_objc = flutter_cflags_objc cflags_objcc = flutter_cflags_objcc sources = [ "availability_version_check.cc" ] deps = [ "//flutter/fml" ] public_configs = [ "//flutter:config" ] } test_fixtures("availability_version_check_fixtures") { fixtures = [] } executable("availability_version_check_unittests") { testonly = true sources = [ "availability_version_check_unittests.cc" ] deps = [ ":availability_version_check", ":availability_version_check_fixtures", "//flutter/fml", "//flutter/testing", ] public_configs = [ "//flutter:config" ] } # Shared framework headers end up in the same folder as platform-specific # framework headers when consumed by clients, so the include paths assume they # are next to each other. config("framework_relative_headers") { include_dirs = [ "framework/Headers" ] } # Framework code shared between iOS and macOS. source_set("framework_common") { cflags_objc = flutter_cflags_objc_arc cflags_objcc = flutter_cflags_objcc_arc sources = [ "framework/Source/FlutterBinaryMessengerRelay.mm", "framework/Source/FlutterChannels.mm", "framework/Source/FlutterCodecs.mm", "framework/Source/FlutterNSBundleUtils.h", "framework/Source/FlutterNSBundleUtils.mm", "framework/Source/FlutterStandardCodec.mm", "framework/Source/FlutterStandardCodecHelper.cc", "framework/Source/FlutterStandardCodec_Internal.h", ] public = framework_common_headers public += [ "framework/Source/FlutterNSBundleUtils.h" ] defines = [ "FLUTTER_FRAMEWORK" ] public_configs = [ "//flutter:config", ":framework_relative_headers", ] deps = [ "//flutter/fml" ] } test_fixtures("framework_common_fixtures") { fixtures = [] } # Unit tests for channels. executable("framework_common_unittests") { testonly = true sources = [ "framework/Source/FlutterBinaryMessengerRelayTest.mm", "framework/Source/FlutterTestUtils.mm", "framework/Source/flutter_codecs_unittest.mm", "framework/Source/flutter_standard_codec_unittest.mm", ] cflags_objcc = flutter_cflags_objcc_arc ldflags = [ "-ObjC" ] deps = [ ":framework_common", ":framework_common_fixtures", "$dart_src/runtime:libdart_jit", "//flutter/testing", "//flutter/third_party/ocmock:ocmock", ] public_configs = [ "//flutter:config" ] }
engine/shell/platform/darwin/common/BUILD.gn/0
{ "file_path": "engine/shell/platform/darwin/common/BUILD.gn", "repo_id": "engine", "token_count": 1279 }
326
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" #import <OCMock/OCMock.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/common/framework/Source/FlutterTestUtils.h" #import "flutter/shell/platform/darwin/ios/flutter_task_queue_dispatch.h" #import "flutter/testing/testing.h" #include "gtest/gtest.h" FLUTTER_ASSERT_ARC @interface FlutterBinaryMessengerRelayTest : NSObject @end @implementation FlutterBinaryMessengerRelayTest - (void)testCreate { id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); FlutterBinaryMessengerRelay* relay = [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; EXPECT_NE(relay, nil); EXPECT_EQ(messenger, relay.parent); } - (void)testPassesCallOn { id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); FlutterBinaryMessengerRelay* relay = [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; char messageData[] = {'a', 'a', 'r', 'o', 'n'}; NSData* message = [NSData dataWithBytes:messageData length:sizeof(messageData)]; NSString* channel = @"foobar"; [relay sendOnChannel:channel message:message binaryReply:nil]; OCMVerify([messenger sendOnChannel:channel message:message binaryReply:nil]); } - (void)testDoesntPassCallOn { id messenger = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); FlutterBinaryMessengerRelay* relay = [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; char messageData[] = {'a', 'a', 'r', 'o', 'n'}; NSData* message = [NSData dataWithBytes:messageData length:sizeof(messageData)]; NSString* channel = @"foobar"; relay.parent = nil; [relay sendOnChannel:channel message:message binaryReply:nil]; } - (void)testSetMessageHandlerWithTaskQueue { id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); FlutterBinaryMessengerRelay* relay = [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; NSString* channel = @"foobar"; NSObject<FlutterTaskQueue>* taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); FlutterBinaryMessageHandler handler = ^(NSData* _Nullable, FlutterBinaryReply _Nonnull) { }; [relay setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:taskQueue]; OCMVerify([messenger setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:taskQueue]); } - (void)testMakeBackgroundTaskQueue { id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); FlutterBinaryMessengerRelay* relay = [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; [relay makeBackgroundTaskQueue]; OCMVerify([messenger makeBackgroundTaskQueue]); } @end TEST(FlutterBinaryMessengerRelayTest, Create) { ASSERT_FALSE(FLTThrowsObjcException(^{ [[FlutterBinaryMessengerRelayTest alloc] testCreate]; })); } TEST(FlutterBinaryMessengerRelayTest, PassesCallOn) { ASSERT_FALSE(FLTThrowsObjcException(^{ [[FlutterBinaryMessengerRelayTest alloc] testPassesCallOn]; })); } TEST(FlutterBinaryMessengerRelayTest, DoesntPassCallOn) { ASSERT_FALSE(FLTThrowsObjcException(^{ [[FlutterBinaryMessengerRelayTest alloc] testDoesntPassCallOn]; })); } TEST(FlutterBinaryMessengerRelayTest, SetMessageHandlerWithTaskQueue) { ASSERT_FALSE(FLTThrowsObjcException(^{ [[FlutterBinaryMessengerRelayTest alloc] testSetMessageHandlerWithTaskQueue]; })); } TEST(FlutterBinaryMessengerRelayTest, SetMakeBackgroundTaskQueue) { ASSERT_FALSE(FLTThrowsObjcException(^{ [[FlutterBinaryMessengerRelayTest alloc] testMakeBackgroundTaskQueue]; })); }
engine/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelayTest.mm/0
{ "file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelayTest.mm", "repo_id": "engine", "token_count": 1381 }
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. assert(is_ios || is_mac) import("//flutter/common/config.gni") import("//flutter/impeller/tools/impeller.gni") source_set("graphics") { cflags_objc = flutter_cflags_objc_arc cflags_objcc = flutter_cflags_objcc_arc sources = [ "FlutterDarwinContextMetalSkia.h", "FlutterDarwinContextMetalSkia.mm", "FlutterDarwinExternalTextureMetal.h", "FlutterDarwinExternalTextureMetal.mm", ] deps = [ "//flutter/common/graphics", "//flutter/display_list", "//flutter/fml", "//flutter/shell/common", "//flutter/shell/platform/darwin/common:framework_common", ] if (impeller_supports_rendering) { sources += [ "FlutterDarwinContextMetalImpeller.h", "FlutterDarwinContextMetalImpeller.mm", ] deps += [ "//flutter/impeller" ] } frameworks = [ "CoreVideo.framework" ] public_deps = [ "//flutter/skia" ] public_configs = [ "//flutter:config" ] }
engine/shell/platform/darwin/graphics/BUILD.gn/0
{ "file_path": "engine/shell/platform/darwin/graphics/BUILD.gn", "repo_id": "engine", "token_count": 419 }
328
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGIN_H_ #import <UIKit/UIKit.h> #import <UserNotifications/UNUserNotificationCenter.h> #import "FlutterBinaryMessenger.h" #import "FlutterChannels.h" #import "FlutterCodecs.h" #import "FlutterPlatformViews.h" #import "FlutterTexture.h" NS_ASSUME_NONNULL_BEGIN @protocol FlutterPluginRegistrar; @protocol FlutterPluginRegistry; #pragma mark - /** * Protocol for listener of events from the UIApplication, typically a FlutterPlugin. */ @protocol FlutterApplicationLifeCycleDelegate <UNUserNotificationCenterDelegate> @optional /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `NO` if this vetos application launch. */ - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `NO` if this vetos application launch. */ - (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. */ - (void)applicationDidBecomeActive:(UIApplication*)application; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. */ - (void)applicationWillResignActive:(UIApplication*)application; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. */ - (void)applicationDidEnterBackground:(UIApplication*)application; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. */ - (void)applicationWillEnterForeground:(UIApplication*)application; /** Called if this has been registered for `UIApplicationDelegate` callbacks. */ - (void)applicationWillTerminate:(UIApplication*)application; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. */ - (void)application:(UIApplication*)application didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings API_DEPRECATED( "See -[UIApplicationDelegate application:didRegisterUserNotificationSettings:] deprecation", ios(8.0, 10.0)); /** * Called if this has been registered for `UIApplicationDelegate` callbacks. */ - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. */ - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `YES` if this handles the request. */ - (BOOL)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler; /** * Calls all plugins registered for `UIApplicationDelegate` callbacks. */ - (void)application:(UIApplication*)application didReceiveLocalNotification:(UILocalNotification*)notification API_DEPRECATED( "See -[UIApplicationDelegate application:didReceiveLocalNotification:] deprecation", ios(4.0, 10.0)); /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `YES` if this handles the request. */ - (BOOL)application:(UIApplication*)application openURL:(NSURL*)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `YES` if this handles the request. */ - (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `YES` if this handles the request. */ - (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `YES` if this handles the request. */ - (BOOL)application:(UIApplication*)application performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem completionHandler:(void (^)(BOOL succeeded))completionHandler API_AVAILABLE(ios(9.0)); /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `YES` if this handles the request. */ - (BOOL)application:(UIApplication*)application handleEventsForBackgroundURLSession:(nonnull NSString*)identifier completionHandler:(nonnull void (^)(void))completionHandler; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `YES` if this handles the request. */ - (BOOL)application:(UIApplication*)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler; /** * Called if this has been registered for `UIApplicationDelegate` callbacks. * * @return `YES` if this handles the request. */ - (BOOL)application:(UIApplication*)application continueUserActivity:(NSUserActivity*)userActivity restorationHandler:(void (^)(NSArray*))restorationHandler; @end #pragma mark - /** * A plugin registration callback. * * Used for registering plugins with additional instances of * `FlutterPluginRegistry`. * * @param registry The registry to register plugins with. */ typedef void (*FlutterPluginRegistrantCallback)(NSObject<FlutterPluginRegistry>* registry); #pragma mark - /** * Implemented by the iOS part of a Flutter plugin. * * Defines a set of optional callback methods and a method to set up the plugin * and register it to be called by other application components. */ @protocol FlutterPlugin <NSObject, FlutterApplicationLifeCycleDelegate> @required /** * Registers this plugin using the context information and callback registration * methods exposed by the given registrar. * * The registrar is obtained from a `FlutterPluginRegistry` which keeps track of * the identity of registered plugins and provides basic support for cross-plugin * coordination. * * The caller of this method, a plugin registrant, is usually autogenerated by * Flutter tooling based on declared plugin dependencies. The generated registrant * asks the registry for a registrar for each plugin, and calls this method to * allow the plugin to initialize itself and register callbacks with application * objects available through the registrar protocol. * * @param registrar A helper providing application context and methods for * registering callbacks. */ + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar; @optional /** * Set a callback for registering plugins to an additional `FlutterPluginRegistry`, * including headless `FlutterEngine` instances. * * This method is typically called from within an application's `AppDelegate` at * startup to allow for plugins which create additional `FlutterEngine` instances * to register the application's plugins. * * @param callback A callback for registering some set of plugins with a * `FlutterPluginRegistry`. */ + (void)setPluginRegistrantCallback:(FlutterPluginRegistrantCallback)callback; @optional /** * Called if this plugin has been registered to receive `FlutterMethodCall`s. * * @param call The method call command object. * @param result A callback for submitting the result of the call. */ - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; @optional /** * Called when a plugin is being removed from a `FlutterEngine`, which is * usually the result of the `FlutterEngine` being deallocated. This method * provides the opportunity to do necessary cleanup. * * You will only receive this method if you registered your plugin instance with * the `FlutterEngine` via `-[FlutterPluginRegistry publish:]`. * * @param registrar The registrar that was used to publish the plugin. * */ - (void)detachFromEngineForRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar; @end #pragma mark - /** * How the UIGestureRecognizers of a platform view are blocked. * * UIGestureRecognizers of platform views can be blocked based on decisions made by the * Flutter Framework (e.g. When an interact-able widget is covering the platform view). */ typedef enum { // NOLINTBEGIN(readability-identifier-naming) /** * Flutter blocks all the UIGestureRecognizers on the platform view as soon as it * decides they should be blocked. * * With this policy, only the `touchesBegan` method for all the UIGestureRecognizers is guaranteed * to be called. */ FlutterPlatformViewGestureRecognizersBlockingPolicyEager, /** * Flutter blocks the platform view's UIGestureRecognizers from recognizing only after * touchesEnded was invoked. * * This results in the platform view's UIGestureRecognizers seeing the entire touch sequence, * but never recognizing the gesture (and never invoking actions). */ FlutterPlatformViewGestureRecognizersBlockingPolicyWaitUntilTouchesEnded, // NOLINTEND(readability-identifier-naming) } FlutterPlatformViewGestureRecognizersBlockingPolicy; #pragma mark - /** * Registration context for a single `FlutterPlugin`, providing a one stop shop * for the plugin to access contextual information and register callbacks for * various application events. * * Registrars are obtained from a `FlutterPluginRegistry` which keeps track of * the identity of registered plugins and provides basic support for cross-plugin * coordination. */ @protocol FlutterPluginRegistrar <NSObject> /** * Returns a `FlutterBinaryMessenger` for creating Dart/iOS communication * channels to be used by the plugin. * * @return The messenger. */ - (NSObject<FlutterBinaryMessenger>*)messenger; /** * Returns a `FlutterTextureRegistry` for registering textures * provided by the plugin. * * @return The texture registry. */ - (NSObject<FlutterTextureRegistry>*)textures; /** * Registers a `FlutterPlatformViewFactory` for creation of platform views. * * Plugins expose `UIView` for embedding in Flutter apps by registering a view factory. * * @param factory The view factory that will be registered. * @param factoryId A unique identifier for the factory, the Dart code of the Flutter app can use * this identifier to request creation of a `UIView` by the registered factory. */ - (void)registerViewFactory:(NSObject<FlutterPlatformViewFactory>*)factory withId:(NSString*)factoryId; /** * Registers a `FlutterPlatformViewFactory` for creation of platform views. * * Plugins can expose a `UIView` for embedding in Flutter apps by registering a view factory. * * @param factory The view factory that will be registered. * @param factoryId A unique identifier for the factory, the Dart code of the Flutter app can use * this identifier to request creation of a `UIView` by the registered factory. * @param gestureRecognizersBlockingPolicy How UIGestureRecognizers on the platform views are * blocked. * */ - (void)registerViewFactory:(NSObject<FlutterPlatformViewFactory>*)factory withId:(NSString*)factoryId gestureRecognizersBlockingPolicy: (FlutterPlatformViewGestureRecognizersBlockingPolicy)gestureRecognizersBlockingPolicy; /** * Publishes a value for external use of the plugin. * * Plugins may publish a single value, such as an instance of the * plugin's main class, for situations where external control or * interaction is needed. * * The published value will be available from the `FlutterPluginRegistry`. * Repeated calls overwrite any previous publication. * * @param value The value to be published. */ - (void)publish:(NSObject*)value; /** * Registers the plugin as a receiver of incoming method calls from the Dart side * on the specified `FlutterMethodChannel`. * * @param delegate The receiving object, such as the plugin's main class. * @param channel The channel */ - (void)addMethodCallDelegate:(NSObject<FlutterPlugin>*)delegate channel:(FlutterMethodChannel*)channel; /** * Registers the plugin as a receiver of `UIApplicationDelegate` calls. * * @param delegate The receiving object, such as the plugin's main class. */ - (void)addApplicationDelegate:(NSObject<FlutterPlugin>*)delegate NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in plugins used in app extensions"); /** * Returns the file name for the given asset. * The returned file name can be used to access the asset in the application's main bundle. * * @param asset The name of the asset. The name can be hierarchical. * @return the file name to be used for lookup in the main bundle. */ - (NSString*)lookupKeyForAsset:(NSString*)asset; /** * Returns the file name for the given asset which originates from the specified package. * The returned file name can be used to access the asset in the application's main bundle. * * * @param asset The name of the asset. The name can be hierarchical. * @param package The name of the package from which the asset originates. * @return the file name to be used for lookup in the main bundle. */ - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package; @end #pragma mark - /** * A registry of Flutter iOS plugins. * * Plugins are identified by unique string keys, typically the name of the * plugin's main class. The registry tracks plugins by this key, mapping it to * a value published by the plugin during registration, if any. This provides a * very basic means of cross-plugin coordination with loose coupling between * unrelated plugins. * * Plugins typically need contextual information and the ability to register * callbacks for various application events. To keep the API of the registry * focused, these facilities are not provided directly by the registry, but by * a `FlutterPluginRegistrar`, created by the registry in exchange for the unique * key of the plugin. * * There is no implied connection between the registry and the registrar. * Specifically, callbacks registered by the plugin via the registrar may be * relayed directly to the underlying iOS application objects. */ @protocol FlutterPluginRegistry <NSObject> /** * Returns a registrar for registering a plugin. * * @param pluginKey The unique key identifying the plugin. */ - (nullable NSObject<FlutterPluginRegistrar>*)registrarForPlugin:(NSString*)pluginKey; /** * Returns whether the specified plugin has been registered. * * @param pluginKey The unique key identifying the plugin. * @return `YES` if `registrarForPlugin` has been called with `pluginKey`. */ - (BOOL)hasPlugin:(NSString*)pluginKey; /** * Returns a value published by the specified plugin. * * @param pluginKey The unique key identifying the plugin. * @return An object published by the plugin, if any. Will be `NSNull` if * nothing has been published. Will be `nil` if the plugin has not been * registered. */ - (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginKey; @end #pragma mark - /** * Implement this in the `UIAppDelegate` of your app to enable Flutter plugins to register * themselves to the application life cycle events. * * For plugins to receive events from `UNUserNotificationCenter`, register this as the * `UNUserNotificationCenterDelegate`. */ @protocol FlutterAppLifeCycleProvider <UNUserNotificationCenterDelegate> /** * Called when registering a new `FlutterApplicaitonLifeCycleDelegate`. * * See also: `-[FlutterAppDelegate addApplicationLifeCycleDelegate:]` */ - (void)addApplicationLifeCycleDelegate:(NSObject<FlutterApplicationLifeCycleDelegate>*)delegate; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGIN_H_
engine/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h", "repo_id": "engine", "token_count": 4667 }
329
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTVMSERVICEPUBLISHER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTVMSERVICEPUBLISHER_H_ #import <Foundation/Foundation.h> @interface FlutterDartVMServicePublisher : NSObject - (instancetype)initWithEnableVMServicePublication:(BOOL)enableVMServicePublication NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; + (instancetype)new NS_UNAVAILABLE; @property(nonatomic, retain, readonly) NSURL* url; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTVMSERVICEPUBLISHER_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.h", "repo_id": "engine", "token_count": 309 }
330
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" #include "flutter/display_list/effects/dl_image_filter.h" #include "flutter/fml/platform/darwin/cf_utils.h" #import "flutter/shell/platform/darwin/ios/ios_surface.h" static constexpr int kMaxPointsInVerb = 4; static constexpr NSUInteger kFlutterClippingMaskViewPoolCapacity = 5; namespace flutter { 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) : overlay_view(overlay_view), overlay_view_wrapper(overlay_view_wrapper), ios_surface(std::move(ios_surface)), surface(std::move(surface)){}; FlutterPlatformViewLayer::~FlutterPlatformViewLayer() = default; FlutterPlatformViewsController::FlutterPlatformViewsController() : layer_pool_(std::make_unique<FlutterPlatformViewLayerPool>()), weak_factory_(std::make_unique<fml::WeakPtrFactory<FlutterPlatformViewsController>>(this)) { mask_view_pool_.reset( [[FlutterClippingMaskViewPool alloc] initWithCapacity:kFlutterClippingMaskViewPoolCapacity]); }; FlutterPlatformViewsController::~FlutterPlatformViewsController() = default; fml::WeakPtr<flutter::FlutterPlatformViewsController> FlutterPlatformViewsController::GetWeakPtr() { return weak_factory_->GetWeakPtr(); } CATransform3D GetCATransform3DFromSkMatrix(const SkMatrix& matrix) { // Skia only supports 2D transform so we don't map z. CATransform3D transform = CATransform3DIdentity; transform.m11 = matrix.getScaleX(); transform.m21 = matrix.getSkewX(); transform.m41 = matrix.getTranslateX(); transform.m14 = matrix.getPerspX(); transform.m12 = matrix.getSkewY(); transform.m22 = matrix.getScaleY(); transform.m42 = matrix.getTranslateY(); transform.m24 = matrix.getPerspY(); return transform; } void ResetAnchor(CALayer* layer) { // Flow uses (0, 0) to apply transform matrix so we need to match that in Quartz. layer.anchorPoint = CGPointZero; layer.position = CGPointZero; } CGRect GetCGRectFromSkRect(const SkRect& clipSkRect) { return CGRectMake(clipSkRect.fLeft, clipSkRect.fTop, clipSkRect.fRight - clipSkRect.fLeft, clipSkRect.fBottom - clipSkRect.fTop); } BOOL BlurRadiusEqualToBlurRadius(CGFloat radius1, CGFloat radius2) { const CGFloat epsilon = 0.01; return radius1 - radius2 < epsilon; } } // namespace flutter @interface PlatformViewFilter () // `YES` if the backdropFilterView has been configured at least once. @property(nonatomic) BOOL backdropFilterViewConfigured; @property(nonatomic, retain) UIVisualEffectView* backdropFilterView; // Updates the `visualEffectView` with the current filter parameters. // Also sets `self.backdropFilterView` to the updated visualEffectView. - (void)updateVisualEffectView:(UIVisualEffectView*)visualEffectView; @end @implementation PlatformViewFilter static NSObject* _gaussianBlurFilter = nil; // The index of "_UIVisualEffectBackdropView" in UIVisualEffectView's subViews. static NSInteger _indexOfBackdropView = -1; // The index of "_UIVisualEffectSubview" in UIVisualEffectView's subViews. static NSInteger _indexOfVisualEffectSubview = -1; static BOOL _preparedOnce = NO; - (instancetype)initWithFrame:(CGRect)frame blurRadius:(CGFloat)blurRadius visualEffectView:(UIVisualEffectView*)visualEffectView { if (self = [super init]) { _frame = frame; _blurRadius = blurRadius; [PlatformViewFilter prepareOnce:visualEffectView]; if (![PlatformViewFilter isUIVisualEffectViewImplementationValid]) { FML_DLOG(ERROR) << "Apple's API for UIVisualEffectView changed. Update the implementation to " "access the gaussianBlur CAFilter."; [self release]; return nil; } _backdropFilterView = [visualEffectView retain]; _backdropFilterViewConfigured = NO; } return self; } + (void)resetPreparation { _preparedOnce = NO; [_gaussianBlurFilter release]; _gaussianBlurFilter = nil; _indexOfBackdropView = -1; _indexOfVisualEffectSubview = -1; } + (void)prepareOnce:(UIVisualEffectView*)visualEffectView { if (_preparedOnce) { return; } for (NSUInteger i = 0; i < visualEffectView.subviews.count; i++) { UIView* view = visualEffectView.subviews[i]; if ([NSStringFromClass([view class]) hasSuffix:@"BackdropView"]) { _indexOfBackdropView = i; for (NSObject* filter in view.layer.filters) { if ([[filter valueForKey:@"name"] isEqual:@"gaussianBlur"] && [[filter valueForKey:@"inputRadius"] isKindOfClass:[NSNumber class]]) { _gaussianBlurFilter = [filter retain]; break; } } } else if ([NSStringFromClass([view class]) hasSuffix:@"VisualEffectSubview"]) { _indexOfVisualEffectSubview = i; } } _preparedOnce = YES; } + (BOOL)isUIVisualEffectViewImplementationValid { return _indexOfBackdropView > -1 && _indexOfVisualEffectSubview > -1 && _gaussianBlurFilter; } - (void)dealloc { [_backdropFilterView release]; _backdropFilterView = nil; [super dealloc]; } - (UIVisualEffectView*)backdropFilterView { FML_DCHECK(_backdropFilterView); if (!self.backdropFilterViewConfigured) { [self updateVisualEffectView:_backdropFilterView]; self.backdropFilterViewConfigured = YES; } return _backdropFilterView; } - (void)updateVisualEffectView:(UIVisualEffectView*)visualEffectView { NSObject* gaussianBlurFilter = [[_gaussianBlurFilter copy] autorelease]; FML_DCHECK(gaussianBlurFilter); UIView* backdropView = visualEffectView.subviews[_indexOfBackdropView]; [gaussianBlurFilter setValue:@(_blurRadius) forKey:@"inputRadius"]; backdropView.layer.filters = @[ gaussianBlurFilter ]; UIView* visualEffectSubview = visualEffectView.subviews[_indexOfVisualEffectSubview]; visualEffectSubview.layer.backgroundColor = UIColor.clearColor.CGColor; visualEffectView.frame = _frame; if (_backdropFilterView != visualEffectView) { _backdropFilterView = [visualEffectView retain]; } } @end @interface ChildClippingView () @property(retain, nonatomic) NSArray<PlatformViewFilter*>* filters; @property(retain, nonatomic) NSMutableArray<UIVisualEffectView*>* backdropFilterSubviews; @end @implementation ChildClippingView // The ChildClippingView's frame is the bounding rect of the platform view. we only want touches to // be hit tested and consumed by this view if they are inside the embedded platform view which could // be smaller the embedded platform view is rotated. - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event { for (UIView* view in self.subviews) { if ([view pointInside:[self convertPoint:point toView:view] withEvent:event]) { return YES; } } return NO; } - (void)applyBlurBackdropFilters:(NSArray<PlatformViewFilter*>*)filters { FML_DCHECK(self.filters.count == self.backdropFilterSubviews.count); if (self.filters.count == 0 && filters.count == 0) { return; } self.filters = filters; NSUInteger index = 0; for (index = 0; index < self.filters.count; index++) { UIVisualEffectView* backdropFilterView; PlatformViewFilter* filter = self.filters[index]; if (self.backdropFilterSubviews.count <= index) { backdropFilterView = filter.backdropFilterView; [self addSubview:backdropFilterView]; [self.backdropFilterSubviews addObject:backdropFilterView]; } else { [filter updateVisualEffectView:self.backdropFilterSubviews[index]]; } } for (NSUInteger i = self.backdropFilterSubviews.count; i > index; i--) { [self.backdropFilterSubviews[i - 1] removeFromSuperview]; [self.backdropFilterSubviews removeLastObject]; } } - (void)dealloc { [_filters release]; _filters = nil; [_backdropFilterSubviews release]; _backdropFilterSubviews = nil; [super dealloc]; } - (NSMutableArray*)backdropFilterSubviews { if (!_backdropFilterSubviews) { _backdropFilterSubviews = [[NSMutableArray alloc] init]; } return _backdropFilterSubviews; } @end @interface FlutterClippingMaskView () // A `CATransform3D` matrix represnts a scale transform that revese UIScreen.scale. // // The transform matrix passed in clipRect/clipRRect/clipPath methods are in device coordinate // space. The transfrom matrix concats `reverseScreenScale` to create a transform matrix in the iOS // logical coordinates (points). // // See https://developer.apple.com/documentation/uikit/uiscreen/1617836-scale?language=objc for // information about screen scale. @property(nonatomic) CATransform3D reverseScreenScale; - (fml::CFRef<CGPathRef>)getTransformedPath:(CGPathRef)path matrix:(CATransform3D)matrix; @end @implementation FlutterClippingMaskView { std::vector<fml::CFRef<CGPathRef>> paths_; } - (instancetype)initWithFrame:(CGRect)frame { return [self initWithFrame:frame screenScale:[UIScreen mainScreen].scale]; } - (instancetype)initWithFrame:(CGRect)frame screenScale:(CGFloat)screenScale { if (self = [super initWithFrame:frame]) { self.backgroundColor = UIColor.clearColor; _reverseScreenScale = CATransform3DMakeScale(1 / screenScale, 1 / screenScale, 1); } return self; } - (void)reset { paths_.clear(); [self setNeedsDisplay]; } // In some scenarios, when we add this view as a maskView of the ChildClippingView, iOS added // this view as a subview of the ChildClippingView. // This results this view blocking touch events on the ChildClippingView. // So we should always ignore any touch events sent to this view. // See https://github.com/flutter/flutter/issues/66044 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event { return NO; } - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); // For mask view, only the alpha channel is used. CGContextSetAlpha(context, 1); for (size_t i = 0; i < paths_.size(); i++) { CGContextAddPath(context, paths_.at(i)); CGContextClip(context); } CGContextFillRect(context, rect); CGContextRestoreGState(context); } - (void)clipRect:(const SkRect&)clipSkRect matrix:(const SkMatrix&)matrix { CGRect clipRect = flutter::GetCGRectFromSkRect(clipSkRect); CGPathRef path = CGPathCreateWithRect(clipRect, nil); // The `matrix` is based on the physical pixels, convert it to UIKit points. CATransform3D matrixInPoints = CATransform3DConcat(flutter::GetCATransform3DFromSkMatrix(matrix), _reverseScreenScale); paths_.push_back([self getTransformedPath:path matrix:matrixInPoints]); } - (void)clipRRect:(const SkRRect&)clipSkRRect matrix:(const SkMatrix&)matrix { CGPathRef pathRef = nullptr; switch (clipSkRRect.getType()) { case SkRRect::kEmpty_Type: { break; } case SkRRect::kRect_Type: { [self clipRect:clipSkRRect.rect() matrix:matrix]; return; } case SkRRect::kOval_Type: case SkRRect::kSimple_Type: { CGRect clipRect = flutter::GetCGRectFromSkRect(clipSkRRect.rect()); pathRef = CGPathCreateWithRoundedRect(clipRect, clipSkRRect.getSimpleRadii().x(), clipSkRRect.getSimpleRadii().y(), nil); break; } case SkRRect::kNinePatch_Type: case SkRRect::kComplex_Type: { CGMutablePathRef mutablePathRef = CGPathCreateMutable(); // Complex types, we manually add each corner. SkRect clipSkRect = clipSkRRect.rect(); SkVector topLeftRadii = clipSkRRect.radii(SkRRect::kUpperLeft_Corner); SkVector topRightRadii = clipSkRRect.radii(SkRRect::kUpperRight_Corner); SkVector bottomRightRadii = clipSkRRect.radii(SkRRect::kLowerRight_Corner); SkVector bottomLeftRadii = clipSkRRect.radii(SkRRect::kLowerLeft_Corner); // Start drawing RRect // Move point to the top left corner adding the top left radii's x. CGPathMoveToPoint(mutablePathRef, nil, clipSkRect.fLeft + topLeftRadii.x(), clipSkRect.fTop); // Move point horizontally right to the top right corner and add the top right curve. CGPathAddLineToPoint(mutablePathRef, nil, clipSkRect.fRight - topRightRadii.x(), clipSkRect.fTop); CGPathAddCurveToPoint(mutablePathRef, nil, clipSkRect.fRight, clipSkRect.fTop, clipSkRect.fRight, clipSkRect.fTop + topRightRadii.y(), clipSkRect.fRight, clipSkRect.fTop + topRightRadii.y()); // Move point vertically down to the bottom right corner and add the bottom right curve. CGPathAddLineToPoint(mutablePathRef, nil, clipSkRect.fRight, clipSkRect.fBottom - bottomRightRadii.y()); CGPathAddCurveToPoint(mutablePathRef, nil, clipSkRect.fRight, clipSkRect.fBottom, clipSkRect.fRight - bottomRightRadii.x(), clipSkRect.fBottom, clipSkRect.fRight - bottomRightRadii.x(), clipSkRect.fBottom); // Move point horizontally left to the bottom left corner and add the bottom left curve. CGPathAddLineToPoint(mutablePathRef, nil, clipSkRect.fLeft + bottomLeftRadii.x(), clipSkRect.fBottom); CGPathAddCurveToPoint(mutablePathRef, nil, clipSkRect.fLeft, clipSkRect.fBottom, clipSkRect.fLeft, clipSkRect.fBottom - bottomLeftRadii.y(), clipSkRect.fLeft, clipSkRect.fBottom - bottomLeftRadii.y()); // Move point vertically up to the top left corner and add the top left curve. CGPathAddLineToPoint(mutablePathRef, nil, clipSkRect.fLeft, clipSkRect.fTop + topLeftRadii.y()); CGPathAddCurveToPoint(mutablePathRef, nil, clipSkRect.fLeft, clipSkRect.fTop, clipSkRect.fLeft + topLeftRadii.x(), clipSkRect.fTop, clipSkRect.fLeft + topLeftRadii.x(), clipSkRect.fTop); CGPathCloseSubpath(mutablePathRef); pathRef = mutablePathRef; break; } } // The `matrix` is based on the physical pixels, convert it to UIKit points. CATransform3D matrixInPoints = CATransform3DConcat(flutter::GetCATransform3DFromSkMatrix(matrix), _reverseScreenScale); // TODO(cyanglaz): iOS does not seem to support hard edge on CAShapeLayer. It clearly stated that // the CAShaperLayer will be drawn antialiased. Need to figure out a way to do the hard edge // clipping on iOS. paths_.push_back([self getTransformedPath:pathRef matrix:matrixInPoints]); } - (void)clipPath:(const SkPath&)path matrix:(const SkMatrix&)matrix { if (!path.isValid()) { return; } if (path.isEmpty()) { return; } CGMutablePathRef pathRef = CGPathCreateMutable(); // Loop through all verbs and translate them into CGPath SkPath::Iter iter(path, true); SkPoint pts[kMaxPointsInVerb]; SkPath::Verb verb = iter.next(pts); SkPoint last_pt_from_last_verb = SkPoint::Make(0, 0); while (verb != SkPath::kDone_Verb) { if (verb == SkPath::kLine_Verb || verb == SkPath::kQuad_Verb || verb == SkPath::kConic_Verb || verb == SkPath::kCubic_Verb) { FML_DCHECK(last_pt_from_last_verb == pts[0]); } switch (verb) { case SkPath::kMove_Verb: { CGPathMoveToPoint(pathRef, nil, pts[0].x(), pts[0].y()); last_pt_from_last_verb = pts[0]; break; } case SkPath::kLine_Verb: { CGPathAddLineToPoint(pathRef, nil, pts[1].x(), pts[1].y()); last_pt_from_last_verb = pts[1]; break; } case SkPath::kQuad_Verb: { CGPathAddQuadCurveToPoint(pathRef, nil, pts[1].x(), pts[1].y(), pts[2].x(), pts[2].y()); last_pt_from_last_verb = pts[2]; break; } case SkPath::kConic_Verb: { // Conic is not available in quartz, we use quad to approximate. // TODO(cyanglaz): Better approximate the conic path. // https://github.com/flutter/flutter/issues/35062 CGPathAddQuadCurveToPoint(pathRef, nil, pts[1].x(), pts[1].y(), pts[2].x(), pts[2].y()); last_pt_from_last_verb = pts[2]; break; } case SkPath::kCubic_Verb: { CGPathAddCurveToPoint(pathRef, nil, pts[1].x(), pts[1].y(), pts[2].x(), pts[2].y(), pts[3].x(), pts[3].y()); last_pt_from_last_verb = pts[3]; break; } case SkPath::kClose_Verb: { CGPathCloseSubpath(pathRef); break; } case SkPath::kDone_Verb: { break; } } verb = iter.next(pts); } // The `matrix` is based on the physical pixels, convert it to UIKit points. CATransform3D matrixInPoints = CATransform3DConcat(flutter::GetCATransform3DFromSkMatrix(matrix), _reverseScreenScale); paths_.push_back([self getTransformedPath:pathRef matrix:matrixInPoints]); } - (fml::CFRef<CGPathRef>)getTransformedPath:(CGPathRef)path matrix:(CATransform3D)matrix { CGAffineTransform affine = CGAffineTransformMake(matrix.m11, matrix.m12, matrix.m21, matrix.m22, matrix.m41, matrix.m42); CGPathRef transformedPath = CGPathCreateCopyByTransformingPath(path, &affine); CGPathRelease(path); return fml::CFRef<CGPathRef>(transformedPath); } @end @interface FlutterClippingMaskViewPool () // The maximum number of `FlutterClippingMaskView` the pool can contain. // This prevents the pool to grow infinately and limits the maximum memory a pool can use. @property(assign, nonatomic) NSUInteger capacity; // The pool contains the views that are available to use. // The number of items in the pool must not excceds `capacity`. @property(retain, nonatomic) NSMutableSet<FlutterClippingMaskView*>* pool; @end @implementation FlutterClippingMaskViewPool : NSObject - (instancetype)initWithCapacity:(NSInteger)capacity { if (self = [super init]) { // Most of cases, there are only one PlatformView in the scene. // Thus init with the capacity of 1. _pool = [[NSMutableSet alloc] initWithCapacity:1]; _capacity = capacity; } return self; } - (FlutterClippingMaskView*)getMaskViewWithFrame:(CGRect)frame { FML_DCHECK(self.pool.count <= self.capacity); if (self.pool.count == 0) { // The pool is empty, alloc a new one. return [[[FlutterClippingMaskView alloc] initWithFrame:frame screenScale:[UIScreen mainScreen].scale] autorelease]; } FlutterClippingMaskView* maskView = [[[self.pool anyObject] retain] autorelease]; maskView.frame = frame; [maskView reset]; [self.pool removeObject:maskView]; return maskView; } - (void)insertViewToPoolIfNeeded:(FlutterClippingMaskView*)maskView { FML_DCHECK(![self.pool containsObject:maskView]); FML_DCHECK(self.pool.count <= self.capacity); if (self.pool.count == self.capacity) { return; } [self.pool addObject:maskView]; } - (void)dealloc { [_pool release]; [super dealloc]; } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.mm", "repo_id": "engine", "token_count": 7239 }
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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRYRELAY_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRYRELAY_H_ #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG FLUTTER_DARWIN_EXPORT #endif /** * Wrapper around a weakly held collection of registered textures. * * Avoids a retain cycle between plugins and the engine. */ @interface FlutterTextureRegistryRelay : NSObject <FlutterTextureRegistry> /** * A weak reference to a FlutterEngine that will be passed texture registration. */ @property(nonatomic, assign) NSObject<FlutterTextureRegistry>* parent; - (instancetype)initWithParent:(NSObject<FlutterTextureRegistry>*)parent; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRYRELAY_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h", "repo_id": "engine", "token_count": 392 }
332
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWRESPONDER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWRESPONDER_H_ #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @protocol FlutterViewResponder <NSObject> @property(nonatomic, strong) UIView* view; - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event; - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event; - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event; - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event; - (void)touchesEstimatedPropertiesUpdated:(NSSet*)touches; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWRESPONDER_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h", "repo_id": "engine", "token_count": 362 }
333
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <OCMock/OCMock.h> #import <XCTest/XCTest.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" #import "flutter/shell/platform/darwin/ios/platform_view_ios.h" FLUTTER_ASSERT_ARC @class MockPlatformView; __weak static MockPlatformView* gMockPlatformView = nil; @interface MockPlatformView : UIView @end @implementation MockPlatformView - (instancetype)init { self = [super init]; if (self) { gMockPlatformView = self; } return self; } - (void)dealloc { gMockPlatformView = nil; } @end @interface MockFlutterPlatformView : NSObject <FlutterPlatformView> @property(nonatomic, strong) UIView* view; @end @implementation MockFlutterPlatformView - (instancetype)init { if (self = [super init]) { _view = [[MockPlatformView alloc] init]; } return self; } @end @interface MockFlutterPlatformFactory : NSObject <FlutterPlatformViewFactory> @end @implementation MockFlutterPlatformFactory - (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args { return [[MockFlutterPlatformView alloc] init]; } @end namespace flutter { namespace { class MockDelegate : public PlatformView::Delegate { public: void OnPlatformViewCreated(std::unique_ptr<Surface> surface) override {} void OnPlatformViewDestroyed() override {} void OnPlatformViewScheduleFrame() override {} void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override {} void OnPlatformViewSetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics) override {} const flutter::Settings& OnPlatformViewGetSettings() const override { return settings_; } void OnPlatformViewDispatchPlatformMessage(std::unique_ptr<PlatformMessage> message) override {} void OnPlatformViewDispatchPointerDataPacket(std::unique_ptr<PointerDataPacket> packet) override { } void OnPlatformViewDispatchSemanticsAction(int32_t id, SemanticsAction action, fml::MallocMapping args) override {} void OnPlatformViewSetSemanticsEnabled(bool enabled) override {} void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override {} void OnPlatformViewRegisterTexture(std::shared_ptr<Texture> texture) override {} void OnPlatformViewUnregisterTexture(int64_t texture_id) override {} void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override {} void LoadDartDeferredLibrary(intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> snapshot_instructions) override { } void LoadDartDeferredLibraryError(intptr_t loading_unit_id, const std::string error_message, bool transient) override {} void UpdateAssetResolverByType(std::unique_ptr<flutter::AssetResolver> updated_asset_resolver, flutter::AssetResolver::AssetResolverType type) override {} flutter::Settings settings_; }; class MockIosDelegate : public AccessibilityBridge::IosDelegate { public: bool IsFlutterViewControllerPresentingModalViewController( FlutterViewController* view_controller) override { return result_IsFlutterViewControllerPresentingModalViewController_; }; void PostAccessibilityNotification(UIAccessibilityNotifications notification, id argument) override { if (on_PostAccessibilityNotification_) { on_PostAccessibilityNotification_(notification, argument); } } std::function<void(UIAccessibilityNotifications, id)> on_PostAccessibilityNotification_; bool result_IsFlutterViewControllerPresentingModalViewController_ = false; }; } // namespace } // namespace flutter namespace { fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) { auto thread = std::make_unique<fml::Thread>(name); auto runner = thread->GetTaskRunner(); return runner; } } // namespace @interface AccessibilityBridgeTest : XCTestCase @end @implementation AccessibilityBridgeTest - (void)testCreate { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view=*/nil, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil); XCTAssertTrue(bridge.get()); } - (void)testUpdateSemanticsEmpty { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController viewIfLoaded]).andReturn(mockFlutterView); OCMExpect([mockFlutterView setAccessibilityElements:[OCMArg isNil]]); auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil); flutter::SemanticsNodeUpdates nodes; flutter::CustomAccessibilityActionUpdates actions; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); OCMVerifyAll(mockFlutterView); } - (void)testUpdateSemanticsOneNode { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); std::string label = "some label"; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil); OCMExpect([mockFlutterView setAccessibilityElements:[OCMArg checkWithBlock:^BOOL(NSArray* value) { if ([value count] != 1) { return NO; } else { SemanticsObjectContainer* container = value[0]; SemanticsObject* object = container.semanticsObject; return object.uid == kRootNodeId && object.bridge.get() == bridge.get() && object.node.label == label; } }]]); flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode semantics_node; semantics_node.id = kRootNodeId; semantics_node.label = label; nodes[kRootNodeId] = semantics_node; flutter::CustomAccessibilityActionUpdates actions; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); OCMVerifyAll(mockFlutterView); } - (void)testIsVoiceOverRunning { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); OCMStub([mockFlutterViewController isVoiceOverRunning]).andReturn(YES); __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil); XCTAssertTrue(bridge->isVoiceOverRunning()); } - (void)testSemanticsDeallocated { @autoreleasepool { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); std::string label = "some label"; flutterPlatformViewsController->SetFlutterView(mockFlutterView); MockFlutterPlatformFactory* factory = [[MockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); auto bridge = std::make_unique<flutter::AccessibilityBridge>( /*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/flutterPlatformViewsController); flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode semantics_node; semantics_node.id = 2; semantics_node.platformViewId = 2; semantics_node.label = label; nodes[kRootNodeId] = semantics_node; flutter::CustomAccessibilityActionUpdates actions; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); XCTAssertNotNil(gMockPlatformView); flutterPlatformViewsController->Reset(); } XCTAssertNil(gMockPlatformView); } - (void)testSemanticsDeallocatedWithoutLoadingView { id engine = OCMClassMock([FlutterEngine class]); FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; @autoreleasepool { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); MockFlutterPlatformFactory* factory = [[MockFlutterPlatformFactory alloc] init]; flutterPlatformViewsController->RegisterViewFactory( factory, @"MockFlutterPlatformView", FlutterPlatformViewGestureRecognizersBlockingPolicyEager); FlutterResult result = ^(id result) { }; flutterPlatformViewsController->OnMethodCall( [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"id" : @2, @"viewType" : @"MockFlutterPlatformView"}], result); auto bridge = std::make_unique<flutter::AccessibilityBridge>( /*view_controller=*/flutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/flutterPlatformViewsController); XCTAssertNotNil(gMockPlatformView); flutterPlatformViewsController->Reset(); platform_view->NotifyDestroyed(); } XCTAssertNil(gMockPlatformView); XCTAssertNil(flutterViewController.viewIfLoaded); [flutterViewController deregisterNotifications]; } - (void)testReplacedSemanticsDoesNotCleanupChildren { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id engine = OCMClassMock([FlutterEngine class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine opaque:YES enableWideGamut:NO]; OCMStub([mockFlutterViewController view]).andReturn(flutterView); std::string label = "some label"; auto bridge = std::make_unique<flutter::AccessibilityBridge>( /*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/flutterPlatformViewsController); @autoreleasepool { flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode parent; parent.id = 0; parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); parent.label = "label"; parent.value = "value"; parent.hint = "hint"; flutter::SemanticsNode node; node.id = 1; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.label = "label"; node.value = "value"; node.hint = "hint"; node.scrollExtentMax = 100.0; node.scrollPosition = 0.0; parent.childrenInTraversalOrder.push_back(1); parent.childrenInHitTestOrder.push_back(1); flutter::SemanticsNode child; child.id = 2; child.rect = SkRect::MakeXYWH(0, 0, 100, 200); child.label = "label"; child.value = "value"; child.hint = "hint"; node.childrenInTraversalOrder.push_back(2); node.childrenInHitTestOrder.push_back(2); nodes[0] = parent; nodes[1] = node; nodes[2] = child; flutter::CustomAccessibilityActionUpdates actions; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); // Add implicit scroll from node 1 to cause replacement. flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_node; new_node.id = 1; new_node.rect = SkRect::MakeXYWH(0, 0, 100, 200); new_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); new_node.actions = flutter::kHorizontalScrollSemanticsActions; new_node.label = "label"; new_node.value = "value"; new_node.hint = "hint"; new_node.scrollExtentMax = 100.0; new_node.scrollPosition = 0.0; new_node.childrenInTraversalOrder.push_back(2); new_node.childrenInHitTestOrder.push_back(2); new_nodes[1] = new_node; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); } /// The old node should be deallocated at this moment. Procced to check /// accessibility tree integrity. id rootContainer = flutterView.accessibilityElements[0]; XCTAssertTrue([rootContainer accessibilityElementCount] == 2); // one for root, one for scrollable. id scrollableContainer = [rootContainer accessibilityElementAtIndex:1]; XCTAssertTrue([scrollableContainer accessibilityElementCount] == 2); // one for scrollable, one for scrollable child. id child = [scrollableContainer accessibilityElementAtIndex:1]; /// Replacing node 1 should not accidentally clean up its child's container. XCTAssertNotNil([child accessibilityContainer]); } - (void)testScrollableSemanticsDeallocated { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id engine = OCMClassMock([FlutterEngine class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine opaque:YES enableWideGamut:NO]; OCMStub([mockFlutterViewController view]).andReturn(flutterView); std::string label = "some label"; @autoreleasepool { auto bridge = std::make_unique<flutter::AccessibilityBridge>( /*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/flutterPlatformViewsController); flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode parent; parent.id = 0; parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); parent.label = "label"; parent.value = "value"; parent.hint = "hint"; flutter::SemanticsNode node; node.id = 1; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kHorizontalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.label = "label"; node.value = "value"; node.hint = "hint"; node.scrollExtentMax = 100.0; node.scrollPosition = 0.0; parent.childrenInTraversalOrder.push_back(1); parent.childrenInHitTestOrder.push_back(1); nodes[0] = parent; nodes[1] = node; flutter::CustomAccessibilityActionUpdates actions; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); XCTAssertTrue([flutterView.subviews count] == 1); XCTAssertTrue([flutterView.subviews[0] isKindOfClass:[FlutterSemanticsScrollView class]]); XCTAssertTrue([flutterView.subviews[0].accessibilityLabel isEqualToString:@"label"]); // Remove the scrollable from the tree. flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_parent; new_parent.id = 0; new_parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); new_parent.label = "label"; new_parent.value = "value"; new_parent.hint = "hint"; new_nodes[0] = new_parent; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); } XCTAssertTrue([flutterView.subviews count] == 0); } - (void)testBridgeReplacesSemanticsNode { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/flutterPlatformViewsController, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id engine = OCMClassMock([FlutterEngine class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine opaque:YES enableWideGamut:NO]; OCMStub([mockFlutterViewController view]).andReturn(flutterView); std::string label = "some label"; @autoreleasepool { auto bridge = std::make_unique<flutter::AccessibilityBridge>( /*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/flutterPlatformViewsController); flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode parent; parent.id = 0; parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); parent.label = "label"; parent.value = "value"; parent.hint = "hint"; flutter::SemanticsNode node; node.id = 1; node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node.actions = flutter::kHorizontalScrollSemanticsActions; node.rect = SkRect::MakeXYWH(0, 0, 100, 200); node.label = "label"; node.value = "value"; node.hint = "hint"; node.scrollExtentMax = 100.0; node.scrollPosition = 0.0; parent.childrenInTraversalOrder.push_back(1); parent.childrenInHitTestOrder.push_back(1); nodes[0] = parent; nodes[1] = node; flutter::CustomAccessibilityActionUpdates actions; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); XCTAssertTrue([flutterView.subviews count] == 1); XCTAssertTrue([flutterView.subviews[0] isKindOfClass:[FlutterSemanticsScrollView class]]); XCTAssertTrue([flutterView.subviews[0].accessibilityLabel isEqualToString:@"label"]); // Remove implicit scroll from node 1. flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_node; new_node.id = 1; new_node.rect = SkRect::MakeXYWH(0, 0, 100, 200); new_node.label = "label"; new_node.value = "value"; new_node.hint = "hint"; new_node.scrollExtentMax = 100.0; new_node.scrollPosition = 0.0; new_nodes[1] = new_node; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); } XCTAssertTrue([flutterView.subviews count] == 0); } - (void)testAnnouncesRouteChanges { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode node1; node1.id = 1; node1.label = "node1"; node1.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute); node1.childrenInTraversalOrder = {2, 3}; node1.childrenInHitTestOrder = {2, 3}; nodes[node1.id] = node1; flutter::SemanticsNode node2; node2.id = 2; node2.label = "node2"; nodes[node2.id] = node2; flutter::SemanticsNode node3; node3.id = 3; node3.flags = static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); node3.label = "node3"; nodes[node3.id] = node3; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute); root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 1ul); XCTAssertEqualObjects(accessibility_notifications[0][@"argument"], @"node3"); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityScreenChangedNotification); } - (void)testRadioButtonIsNotSwitchButton { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id engine = OCMClassMock([FlutterEngine class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine opaque:YES enableWideGamut:NO]; OCMStub([mockFlutterViewController view]).andReturn(flutterView); auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup) | static_cast<int32_t>(flutter::SemanticsFlags::kIsEnabled) | static_cast<int32_t>(flutter::SemanticsFlags::kHasCheckedState) | static_cast<int32_t>(flutter::SemanticsFlags::kHasEnabledState); nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); SemanticsObjectContainer* rootContainer = flutterView.accessibilityElements[0]; FlutterSemanticsObject* rootNode = [rootContainer accessibilityElementAtIndex:0]; XCTAssertTrue((rootNode.accessibilityTraits & UIAccessibilityTraitButton) > 0); XCTAssertNil(rootNode.accessibilityValue); } - (void)testLayoutChangeWithNonAccessibilityElement { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode node1; node1.id = 1; node1.label = "node1"; node1.childrenInTraversalOrder = {2, 3}; node1.childrenInHitTestOrder = {2, 3}; nodes[node1.id] = node1; flutter::SemanticsNode node2; node2.id = 2; node2.label = "node2"; nodes[node2.id] = node2; flutter::SemanticsNode node3; node3.id = 3; node3.label = "node3"; nodes[node3.id] = node3; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); // Simulates the focusing on the node 1. bridge->AccessibilityObjectDidBecomeFocused(1); // In this update, we make node 1 unfocusable and trigger the // layout change. The accessibility bridge should send layoutchange // notification with the first focusable node under node 1 flutter::CustomAccessibilityActionUpdates new_actions; flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_node1; new_node1.id = 1; new_node1.childrenInTraversalOrder = {2}; new_node1.childrenInHitTestOrder = {2}; new_nodes[new_node1.id] = new_node1; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/new_actions); XCTAssertEqual([accessibility_notifications count], 1ul); SemanticsObject* focusObject = accessibility_notifications[0][@"argument"]; // Since node 1 is no longer focusable (no label), it will focus node 2 instead. XCTAssertEqual([focusObject uid], 2); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityLayoutChangedNotification); } - (void)testLayoutChangeDoesCallNativeAccessibility { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode node1; node1.id = 1; node1.label = "node1"; nodes[node1.id] = node1; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); // Simulates the focusing on the node 0. bridge->AccessibilityObjectDidBecomeFocused(0); // Remove node 1 to trigger a layout change notification flutter::CustomAccessibilityActionUpdates new_actions; flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.label = "root"; new_root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); new_nodes[new_root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/new_actions); XCTAssertEqual([accessibility_notifications count], 1ul); id focusObject = accessibility_notifications[0][@"argument"]; // Make sure the focused item is not specificed when it stays the same. // See: https://github.com/flutter/flutter/issues/104176 XCTAssertEqualObjects(focusObject, [NSNull null]); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityLayoutChangedNotification); } - (void)testLayoutChangeDoesCallNativeAccessibilityWhenFocusChanged { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode node1; node1.id = 1; node1.label = "node1"; nodes[node1.id] = node1; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); // Simulates the focusing on the node 1. bridge->AccessibilityObjectDidBecomeFocused(1); // Remove node 1 to trigger a layout change notification, and focus should be one root flutter::CustomAccessibilityActionUpdates new_actions; flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.label = "root"; new_root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); new_nodes[new_root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/new_actions); XCTAssertEqual([accessibility_notifications count], 1ul); SemanticsObject* focusObject2 = accessibility_notifications[0][@"argument"]; // Bridge should ask accessibility to focus on root because node 1 is moved from screen. XCTAssertTrue([focusObject2 isKindOfClass:[FlutterSemanticsScrollView class]]); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityLayoutChangedNotification); } - (void)testScrollableSemanticsContainerReturnsCorrectChildren { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); OCMExpect([mockFlutterView setAccessibilityElements:[OCMArg checkWithBlock:^BOOL(NSArray* value) { if ([value count] != 1) { return NO; } SemanticsObjectContainer* container = value[0]; SemanticsObject* object = container.semanticsObject; FlutterScrollableSemanticsObject* scrollable = (FlutterScrollableSemanticsObject*)object.children[0]; id nativeScrollable = scrollable.nativeAccessibility; SemanticsObjectContainer* scrollableContainer = [nativeScrollable accessibilityContainer]; return [scrollableContainer indexOfAccessibilityElement:nativeScrollable] == 1; }]]); auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode node1; node1.id = 1; node1.label = "node1"; node1.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); nodes[node1.id] = node1; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); OCMVerifyAll(mockFlutterView); } - (void)testAnnouncesRouteChangesAndLayoutChangeInOneUpdate { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode node1; node1.id = 1; node1.label = "node1"; node1.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); nodes[node1.id] = node1; flutter::SemanticsNode node3; node3.id = 3; node3.label = "node3"; nodes[node3.id] = node3; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.childrenInTraversalOrder = {1, 3}; root_node.childrenInHitTestOrder = {1, 3}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 1ul); XCTAssertEqualObjects(accessibility_notifications[0][@"argument"], @"node1"); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityScreenChangedNotification); // Simulates the focusing on the node 0. bridge->AccessibilityObjectDidBecomeFocused(0); flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_node1; new_node1.id = 1; new_node1.label = "new_node1"; new_node1.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); new_node1.childrenInTraversalOrder = {2}; new_node1.childrenInHitTestOrder = {2}; new_nodes[new_node1.id] = new_node1; flutter::SemanticsNode new_node2; new_node2.id = 2; new_node2.label = "new_node2"; new_node2.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); new_nodes[new_node2.id] = new_node2; flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.label = "root"; new_root_node.childrenInTraversalOrder = {1}; new_root_node.childrenInHitTestOrder = {1}; new_nodes[new_root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 3ul); XCTAssertEqualObjects(accessibility_notifications[1][@"argument"], @"new_node2"); XCTAssertEqual([accessibility_notifications[1][@"notification"] unsignedIntValue], UIAccessibilityScreenChangedNotification); SemanticsObject* focusObject = accessibility_notifications[2][@"argument"]; XCTAssertEqual([focusObject uid], 0); XCTAssertEqual([accessibility_notifications[2][@"notification"] unsignedIntValue], UIAccessibilityLayoutChangedNotification); } - (void)testAnnouncesRouteChangesWhenAddAdditionalRoute { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode node1; node1.id = 1; node1.label = "node1"; node1.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); nodes[node1.id] = node1; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute); root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 1ul); XCTAssertEqualObjects(accessibility_notifications[0][@"argument"], @"node1"); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityScreenChangedNotification); flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_node1; new_node1.id = 1; new_node1.label = "new_node1"; new_node1.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); new_node1.childrenInTraversalOrder = {2}; new_node1.childrenInHitTestOrder = {2}; new_nodes[new_node1.id] = new_node1; flutter::SemanticsNode new_node2; new_node2.id = 2; new_node2.label = "new_node2"; new_node2.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); new_nodes[new_node2.id] = new_node2; flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute); new_root_node.childrenInTraversalOrder = {1}; new_root_node.childrenInHitTestOrder = {1}; new_nodes[new_root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 2ul); XCTAssertEqualObjects(accessibility_notifications[1][@"argument"], @"new_node2"); XCTAssertEqual([accessibility_notifications[1][@"notification"] unsignedIntValue], UIAccessibilityScreenChangedNotification); } - (void)testAnnouncesRouteChangesRemoveRouteInMiddle { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode node1; node1.id = 1; node1.label = "node1"; node1.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); node1.childrenInTraversalOrder = {2}; node1.childrenInHitTestOrder = {2}; nodes[node1.id] = node1; flutter::SemanticsNode node2; node2.id = 2; node2.label = "node2"; node2.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); nodes[node2.id] = node2; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute); root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 1ul); XCTAssertEqualObjects(accessibility_notifications[0][@"argument"], @"node2"); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityScreenChangedNotification); flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_node1; new_node1.id = 1; new_node1.label = "new_node1"; new_node1.childrenInTraversalOrder = {2}; new_node1.childrenInHitTestOrder = {2}; new_nodes[new_node1.id] = new_node1; flutter::SemanticsNode new_node2; new_node2.id = 2; new_node2.label = "new_node2"; new_node2.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); new_nodes[new_node2.id] = new_node2; flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute); new_root_node.childrenInTraversalOrder = {1}; new_root_node.childrenInHitTestOrder = {1}; new_nodes[new_root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 2ul); XCTAssertEqualObjects(accessibility_notifications[1][@"argument"], @"new_node2"); XCTAssertEqual([accessibility_notifications[1][@"notification"] unsignedIntValue], UIAccessibilityScreenChangedNotification); } - (void)testHandleEvent { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); NSDictionary<NSString*, id>* annotatedEvent = @{@"type" : @"focus", @"nodeId" : @123}; bridge->HandleEvent(annotatedEvent); XCTAssertEqual([accessibility_notifications count], 1ul); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityLayoutChangedNotification); } - (void)testAccessibilityObjectDidBecomeFocused { flutter::MockDelegate mock_delegate; auto thread = std::make_unique<fml::Thread>("AccessibilityBridgeTest"); auto thread_task_runner = thread->GetTaskRunner(); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id engine = OCMClassMock([FlutterEngine class]); id flutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([flutterViewController engine]).andReturn(engine); OCMStub([engine binaryMessenger]).andReturn(messenger); FlutterBinaryMessengerConnection connection = 123; OCMStub([messenger setMessageHandlerOnChannel:@"flutter/accessibility" binaryMessageHandler:[OCMArg any]]) .andReturn(connection); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); fml::AutoResetWaitableEvent latch; thread_task_runner->PostTask([&] { auto weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterViewController>>(flutterViewController); platform_view->SetOwnerViewController(weakFactory->GetWeakNSObject()); auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view=*/nil, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil); XCTAssertTrue(bridge.get()); OCMVerify([messenger setMessageHandlerOnChannel:@"flutter/accessibility" binaryMessageHandler:[OCMArg isNotNil]]); bridge->AccessibilityObjectDidBecomeFocused(123); NSDictionary<NSString*, id>* annotatedEvent = @{@"type" : @"didGainFocus", @"nodeId" : @123}; NSData* encodedMessage = [[FlutterStandardMessageCodec sharedInstance] encode:annotatedEvent]; OCMVerify([messenger sendOnChannel:@"flutter/accessibility" message:encodedMessage]); latch.Signal(); }); latch.Wait(); [engine stopMocking]; } - (void)testAnnouncesRouteChangesWhenNoNamesRoute { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode node1; node1.id = 1; node1.label = "node1"; node1.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); node1.childrenInTraversalOrder = {2, 3}; node1.childrenInHitTestOrder = {2, 3}; nodes[node1.id] = node1; flutter::SemanticsNode node2; node2.id = 2; node2.label = "node2"; nodes[node2.id] = node2; flutter::SemanticsNode node3; node3.id = 3; node3.label = "node3"; nodes[node3.id] = node3; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); // Notification should focus first focusable node, which is node1. XCTAssertEqual([accessibility_notifications count], 1ul); id focusObject = accessibility_notifications[0][@"argument"]; XCTAssertTrue([focusObject isKindOfClass:[NSString class]]); XCTAssertEqualObjects(focusObject, @"node1"); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityScreenChangedNotification); } - (void)testAnnouncesLayoutChangeWithNilIfLastFocusIsRemoved { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); id mockFlutterView = OCMClassMock([FlutterView class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates first_update; flutter::SemanticsNode route_node; route_node.id = 1; route_node.label = "route"; first_update[route_node.id] = route_node; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; first_update[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 0ul); // Simulates the focusing on the node 1. bridge->AccessibilityObjectDidBecomeFocused(1); flutter::SemanticsNodeUpdates second_update; // Simulates the removal of the node 1 flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.label = "root"; second_update[root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); SemanticsObject* focusObject = accessibility_notifications[0][@"argument"]; // The node 1 was removed, so the bridge will set the focus object to root. XCTAssertEqual([focusObject uid], 0); XCTAssertEqualObjects([focusObject accessibilityLabel], @"root"); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityLayoutChangedNotification); } - (void)testAnnouncesLayoutChangeWithTheSameItemFocused { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); id mockFlutterView = OCMClassMock([FlutterView class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates first_update; flutter::SemanticsNode node_one; node_one.id = 1; node_one.label = "route1"; first_update[node_one.id] = node_one; flutter::SemanticsNode node_two; node_two.id = 2; node_two.label = "route2"; first_update[node_two.id] = node_two; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.childrenInTraversalOrder = {1, 2}; root_node.childrenInHitTestOrder = {1, 2}; first_update[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 0ul); // Simulates the focusing on the node 1. bridge->AccessibilityObjectDidBecomeFocused(1); flutter::SemanticsNodeUpdates second_update; // Simulates the removal of the node 2. flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.label = "root"; new_root_node.childrenInTraversalOrder = {1}; new_root_node.childrenInHitTestOrder = {1}; second_update[root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); id focusObject = accessibility_notifications[0][@"argument"]; // Since we have focused on the node 1 right before the layout changed, the bridge should not ask // to refocus again on the same node. XCTAssertEqualObjects(focusObject, [NSNull null]); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityLayoutChangedNotification); } - (void)testAnnouncesLayoutChangeWhenFocusMovedOutside { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); id mockFlutterView = OCMClassMock([FlutterView class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates first_update; flutter::SemanticsNode node_one; node_one.id = 1; node_one.label = "route1"; first_update[node_one.id] = node_one; flutter::SemanticsNode node_two; node_two.id = 2; node_two.label = "route2"; first_update[node_two.id] = node_two; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.childrenInTraversalOrder = {1, 2}; root_node.childrenInHitTestOrder = {1, 2}; first_update[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 0ul); // Simulates the focusing on the node 1. bridge->AccessibilityObjectDidBecomeFocused(1); // Simulates that the focus move outside of flutter. bridge->AccessibilityObjectDidLoseFocus(1); flutter::SemanticsNodeUpdates second_update; // Simulates the removal of the node 2. flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.label = "root"; new_root_node.childrenInTraversalOrder = {1}; new_root_node.childrenInHitTestOrder = {1}; second_update[root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); NSNull* focusObject = accessibility_notifications[0][@"argument"]; // Since the focus is moved outside of the app right before the layout // changed, the bridge should not try to refocus anything . XCTAssertEqual(focusObject, [NSNull null]); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityLayoutChangedNotification); } - (void)testAnnouncesScrollChangeWithLastFocused { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); id mockFlutterView = OCMClassMock([FlutterView class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates first_update; flutter::SemanticsNode node_one; node_one.id = 1; node_one.label = "route1"; node_one.scrollPosition = 0.0; first_update[node_one.id] = node_one; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; first_update[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); // The first update will trigger a scroll announcement, but we are not interested in it. [accessibility_notifications removeAllObjects]; // Simulates the focusing on the node 1. bridge->AccessibilityObjectDidBecomeFocused(1); flutter::SemanticsNodeUpdates second_update; // Simulates the scrolling on the node 1. flutter::SemanticsNode new_node_one; new_node_one.id = 1; new_node_one.label = "route1"; new_node_one.scrollPosition = 1.0; second_update[new_node_one.id] = new_node_one; bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); SemanticsObject* focusObject = accessibility_notifications[0][@"argument"]; // Since we have focused on the node 1 right before the scrolling, the bridge should refocus the // node 1. XCTAssertEqual([focusObject uid], 1); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityPageScrolledNotification); } - (void)testAnnouncesScrollChangeDoesCallNativeAccessibility { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); id mockFlutterView = OCMClassMock([FlutterView class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates first_update; flutter::SemanticsNode node_one; node_one.id = 1; node_one.label = "route1"; node_one.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); node_one.scrollPosition = 0.0; first_update[node_one.id] = node_one; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; first_update[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); // The first update will trigger a scroll announcement, but we are not interested in it. [accessibility_notifications removeAllObjects]; // Simulates the focusing on the node 1. bridge->AccessibilityObjectDidBecomeFocused(1); flutter::SemanticsNodeUpdates second_update; // Simulates the scrolling on the node 1. flutter::SemanticsNode new_node_one; new_node_one.id = 1; new_node_one.label = "route1"; new_node_one.flags = static_cast<int32_t>(flutter::SemanticsFlags::kHasImplicitScrolling); new_node_one.scrollPosition = 1.0; second_update[new_node_one.id] = new_node_one; bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); SemanticsObject* focusObject = accessibility_notifications[0][@"argument"]; // Make sure refocus event is sent with the nativeAccessibility of node_one // which is a FlutterSemanticsScrollView. XCTAssertTrue([focusObject isKindOfClass:[FlutterSemanticsScrollView class]]); XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], UIAccessibilityPageScrolledNotification); } - (void)testAnnouncesIgnoresRouteChangesWhenModal { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); std::string label = "some label"; NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; ios_delegate->result_IsFlutterViewControllerPresentingModalViewController_ = true; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode route_node; route_node.id = 1; route_node.flags = static_cast<int32_t>(flutter::SemanticsFlags::kScopesRoute) | static_cast<int32_t>(flutter::SemanticsFlags::kNamesRoute); route_node.label = "route"; nodes[route_node.id] = route_node; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = label; root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 0ul); } - (void)testAnnouncesIgnoresLayoutChangeWhenModal { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; ios_delegate->result_IsFlutterViewControllerPresentingModalViewController_ = true; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode child_node; child_node.id = 1; child_node.label = "child_node"; nodes[child_node.id] = child_node; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.childrenInTraversalOrder = {1}; root_node.childrenInHitTestOrder = {1}; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); // Removes child_node to simulate a layout change. flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.label = "root"; new_nodes[new_root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 0ul); } - (void)testAnnouncesIgnoresScrollChangeWhenModal { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); NSMutableArray<NSDictionary<NSString*, id>*>* accessibility_notifications = [[NSMutableArray alloc] init]; auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); ios_delegate->on_PostAccessibilityNotification_ = [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { [accessibility_notifications addObject:@{ @"notification" : @(notification), @"argument" : argument ? argument : [NSNull null], }]; }; ios_delegate->result_IsFlutterViewControllerPresentingModalViewController_ = true; __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); flutter::CustomAccessibilityActionUpdates actions; flutter::SemanticsNodeUpdates nodes; flutter::SemanticsNode root_node; root_node.id = kRootNodeId; root_node.label = "root"; root_node.scrollPosition = 1; nodes[root_node.id] = root_node; bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); // Removes child_node to simulate a layout change. flutter::SemanticsNodeUpdates new_nodes; flutter::SemanticsNode new_root_node; new_root_node.id = kRootNodeId; new_root_node.label = "root"; new_root_node.scrollPosition = 2; new_nodes[new_root_node.id] = new_root_node; bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); XCTAssertEqual([accessibility_notifications count], 0ul); } - (void)testAccessibilityMessageAfterDeletion { flutter::MockDelegate mock_delegate; auto thread = std::make_unique<fml::Thread>("AccessibilityBridgeTest"); auto thread_task_runner = thread->GetTaskRunner(); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id engine = OCMClassMock([FlutterEngine class]); id flutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([flutterViewController engine]).andReturn(engine); OCMStub([engine binaryMessenger]).andReturn(messenger); FlutterBinaryMessengerConnection connection = 123; OCMStub([messenger setMessageHandlerOnChannel:@"flutter/accessibility" binaryMessageHandler:[OCMArg any]]) .andReturn(connection); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); fml::AutoResetWaitableEvent latch; thread_task_runner->PostTask([&] { auto weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterViewController>>(flutterViewController); platform_view->SetOwnerViewController(weakFactory->GetWeakNSObject()); auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view=*/nil, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil); XCTAssertTrue(bridge.get()); OCMVerify([messenger setMessageHandlerOnChannel:@"flutter/accessibility" binaryMessageHandler:[OCMArg isNotNil]]); bridge.reset(); latch.Signal(); }); latch.Wait(); OCMVerify([messenger cleanUpConnection:connection]); [engine stopMocking]; } - (void)testFlutterSemanticsScrollViewManagedObjectLifecycleCorrectly { flutter::MockDelegate mock_delegate; auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/mock_delegate, /*rendering_api=*/mock_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterView = OCMClassMock([FlutterView class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); auto ios_delegate = std::make_unique<flutter::MockIosDelegate>(); __block auto bridge = std::make_unique<flutter::AccessibilityBridge>(/*view_controller=*/mockFlutterViewController, /*platform_view=*/platform_view.get(), /*platform_views_controller=*/nil, /*ios_delegate=*/std::move(ios_delegate)); FlutterSemanticsScrollView* flutterSemanticsScrollView; @autoreleasepool { FlutterScrollableSemanticsObject* semanticsObject = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge->GetWeakPtr() uid:1234]; flutterSemanticsScrollView = semanticsObject.nativeAccessibility; } XCTAssertTrue(flutterSemanticsScrollView); // If the _semanticsObject is not a weak pointer this (or any other method on // flutterSemanticsScrollView) will cause an EXC_BAD_ACCESS. XCTAssertFalse([flutterSemanticsScrollView isAccessibilityElement]); } - (void)testPlatformViewDestructorDoesNotCallSemanticsAPIs { class TestDelegate : public flutter::MockDelegate { public: void OnPlatformViewSetSemanticsEnabled(bool enabled) override { set_semantics_enabled_calls++; } int set_semantics_enabled_calls = 0; }; TestDelegate test_delegate; auto thread = std::make_unique<fml::Thread>("AccessibilityBridgeTest"); auto thread_task_runner = thread->GetTaskRunner(); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); fml::AutoResetWaitableEvent latch; thread_task_runner->PostTask([&] { auto platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/test_delegate, /*rendering_api=*/test_delegate.settings_.enable_impeller ? flutter::IOSRenderingAPI::kMetal : flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>()); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); auto flutterPlatformViewsController = std::make_shared<flutter::FlutterPlatformViewsController>(); OCMStub([mockFlutterViewController platformViewsController]) .andReturn(flutterPlatformViewsController.get()); auto weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterViewController>>( mockFlutterViewController); platform_view->SetOwnerViewController(weakFactory->GetWeakNSObject()); platform_view->SetSemanticsEnabled(true); XCTAssertNotEqual(test_delegate.set_semantics_enabled_calls, 0); // Deleting PlatformViewIOS should not call OnPlatformViewSetSemanticsEnabled test_delegate.set_semantics_enabled_calls = 0; platform_view.reset(); XCTAssertEqual(test_delegate.set_semantics_enabled_calls, 0); latch.Signal(); }); latch.Wait(); } @end
engine/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm", "repo_id": "engine", "token_count": 42641 }
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_DARWIN_IOS_IOS_CONTEXT_METAL_IMPELLER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_METAL_IMPELLER_H_ #include "flutter/fml/macros.h" #include "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h" #include "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h" #include "flutter/shell/platform/darwin/ios/ios_context.h" namespace impeller { class Context; } // namespace impeller namespace flutter { class IOSContextMetalImpeller final : public IOSContext { public: explicit IOSContextMetalImpeller( const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch); ~IOSContextMetalImpeller(); fml::scoped_nsobject<FlutterDarwinContextMetalSkia> GetDarwinContext() const; IOSRenderingBackend GetBackend() const override; // |IOSContext| sk_sp<GrDirectContext> GetMainContext() const override; sk_sp<GrDirectContext> GetResourceContext() const; private: fml::scoped_nsobject<FlutterDarwinContextMetalImpeller> darwin_context_metal_impeller_; // |IOSContext| sk_sp<GrDirectContext> CreateResourceContext() override; // |IOSContext| std::unique_ptr<GLContextResult> MakeCurrent() override; // |IOSContext| std::unique_ptr<Texture> CreateExternalTexture( int64_t texture_id, fml::scoped_nsobject<NSObject<FlutterTexture>> texture) override; // |IOSContext| std::shared_ptr<impeller::Context> GetImpellerContext() const override; FML_DISALLOW_COPY_AND_ASSIGN(IOSContextMetalImpeller); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_METAL_IMPELLER_H_
engine/shell/platform/darwin/ios/ios_context_metal_impeller.h/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_context_metal_impeller.h", "repo_id": "engine", "token_count": 656 }
335
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_SOFTWARE_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_SOFTWARE_H_ #include "flutter/flow/embedded_views.h" #include "flutter/fml/macros.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" #include "flutter/shell/gpu/gpu_surface_software.h" #import "flutter/shell/platform/darwin/ios/ios_context.h" #import "flutter/shell/platform/darwin/ios/ios_surface.h" #include "third_party/skia/include/core/SkSurface.h" @class CALayer; namespace flutter { class IOSSurfaceSoftware final : public IOSSurface, public GPUSurfaceSoftwareDelegate { public: IOSSurfaceSoftware(const fml::scoped_nsobject<CALayer>& layer, std::shared_ptr<IOSContext> context); ~IOSSurfaceSoftware() override; // |IOSSurface| bool IsValid() const override; // |IOSSurface| void UpdateStorageSizeIfNecessary() override; // |IOSSurface| std::unique_ptr<Surface> CreateGPUSurface(GrDirectContext* gr_context = nullptr) override; // |GPUSurfaceSoftwareDelegate| sk_sp<SkSurface> AcquireBackingStore(const SkISize& size) override; // |GPUSurfaceSoftwareDelegate| bool PresentBackingStore(sk_sp<SkSurface> backing_store) override; private: fml::scoped_nsobject<CALayer> layer_; sk_sp<SkSurface> sk_surface_; FML_DISALLOW_COPY_AND_ASSIGN(IOSSurfaceSoftware); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_SOFTWARE_H_
engine/shell/platform/darwin/ios/ios_surface_software.h/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_surface_software.h", "repo_id": "engine", "token_count": 621 }
336
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINMACOS_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINMACOS_H_ #import <Foundation/Foundation.h> #import "FlutterAppLifecycleDelegate.h" #import "FlutterChannels.h" #import "FlutterCodecs.h" #import "FlutterMacros.h" NS_ASSUME_NONNULL_BEGIN @protocol FlutterPluginRegistrar; /** * Implemented by the platform side of a Flutter plugin. * * Defines a set of optional callback methods and a method to set up the plugin * and register it to be called by other application components. * * Currently the macOS version of FlutterPlugin has very limited functionality, but is expected to * expand over time to more closely match the functionality of the iOS FlutterPlugin. */ FLUTTER_DARWIN_EXPORT @protocol FlutterPlugin <NSObject, FlutterAppLifecycleDelegate> /** * Creates an instance of the plugin to register with |registrar| using the desired * FlutterPluginRegistrar methods. */ + (void)registerWithRegistrar:(id<FlutterPluginRegistrar>)registrar; @optional /** * Called when a message is sent from Flutter on a channel that a plugin instance has subscribed * to via -[FlutterPluginRegistrar addMethodCallDelegate:channel:]. * * The |result| callback must be called exactly once, with one of: * - FlutterMethodNotImplemented, if the method call is unknown. * - A FlutterError, if the method call was understood but there was a * problem handling it. * - Any other value (including nil) to indicate success. The value will * be returned to the Flutter caller, and must be serializable to JSON. */ - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; NS_ASSUME_NONNULL_END @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINMACOS_H_
engine/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h", "repo_id": "engine", "token_count": 626 }
337
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <objc/message.h> #import "FlutterChannelKeyResponder.h" #import "KeyCodeMap_Internal.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/embedder/embedder.h" @interface FlutterChannelKeyResponder () /** * The channel used to communicate with Flutter. */ @property(nonatomic) FlutterBasicMessageChannel* channel; /** * The |NSEvent.modifierFlags| of the last event received. * * Used to determine whether a FlagsChanged event should count as a keydown or * a keyup event. */ @property(nonatomic) uint64_t previouslyPressedFlags; @end @implementation FlutterChannelKeyResponder @synthesize layoutMap; - (nonnull instancetype)initWithChannel:(nonnull FlutterBasicMessageChannel*)channel { self = [super init]; if (self != nil) { _channel = channel; _previouslyPressedFlags = 0; } return self; } /// Checks single modifier flag from event flags and sends appropriate key event /// if it is different from the previous state. - (void)checkModifierFlag:(NSUInteger)targetMask forEventFlags:(NSEventModifierFlags)eventFlags keyCode:(NSUInteger)keyCode timestamp:(NSTimeInterval)timestamp { NSAssert((targetMask & (targetMask - 1)) == 0, @"targetMask must only have one bit set"); if ((eventFlags & targetMask) != (_previouslyPressedFlags & targetMask)) { uint64_t newFlags = (_previouslyPressedFlags & ~targetMask) | (eventFlags & targetMask); // Sets combined flag if either left or right modifier is pressed, unsets otherwise. auto updateCombinedFlag = [&](uint64_t side1, uint64_t side2, NSEventModifierFlags flag) { if (newFlags & (side1 | side2)) { newFlags |= flag; } else { newFlags &= ~flag; } }; updateCombinedFlag(flutter::kModifierFlagShiftLeft, flutter::kModifierFlagShiftRight, NSEventModifierFlagShift); updateCombinedFlag(flutter::kModifierFlagControlLeft, flutter::kModifierFlagControlRight, NSEventModifierFlagControl); updateCombinedFlag(flutter::kModifierFlagAltLeft, flutter::kModifierFlagAltRight, NSEventModifierFlagOption); updateCombinedFlag(flutter::kModifierFlagMetaLeft, flutter::kModifierFlagMetaRight, NSEventModifierFlagCommand); NSEvent* event = [NSEvent keyEventWithType:NSEventTypeFlagsChanged location:NSZeroPoint modifierFlags:newFlags timestamp:timestamp windowNumber:0 context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:keyCode]; [self handleEvent:event callback:^(BOOL){ }]; }; } - (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags timestamp:(NSTimeInterval)timestamp { modifierFlags = modifierFlags & ~0x100; if (_previouslyPressedFlags == modifierFlags) { return; } [flutter::modifierFlagToKeyCode enumerateKeysAndObjectsUsingBlock:^(NSNumber* flag, NSNumber* keyCode, BOOL* stop) { [self checkModifierFlag:[flag unsignedShortValue] forEventFlags:modifierFlags keyCode:[keyCode unsignedShortValue] timestamp:timestamp]; }]; // Caps lock is not included in the modifierFlagToKeyCode map. [self checkModifierFlag:NSEventModifierFlagCapsLock forEventFlags:modifierFlags keyCode:0x00000039 // kVK_CapsLock timestamp:timestamp]; // At the end we should end up with the same modifier flags as the event. FML_DCHECK(_previouslyPressedFlags == modifierFlags); } - (void)handleEvent:(NSEvent*)event callback:(FlutterAsyncKeyCallback)callback { // Remove the modifier bits that Flutter is not interested in. NSEventModifierFlags modifierFlags = event.modifierFlags & ~0x100; NSString* type; switch (event.type) { case NSEventTypeKeyDown: type = @"keydown"; break; case NSEventTypeKeyUp: type = @"keyup"; break; case NSEventTypeFlagsChanged: if (modifierFlags < _previouslyPressedFlags) { type = @"keyup"; } else if (modifierFlags > _previouslyPressedFlags) { type = @"keydown"; } else { // ignore duplicate modifiers; This can happen in situations like switching // between application windows when MacOS only sends the up event to new window. callback(true); return; } break; default: { NSAssert(false, @"Unexpected key event type (got %lu).", event.type); callback(false); } } _previouslyPressedFlags = modifierFlags; NSMutableDictionary* keyMessage = [@{ @"keymap" : @"macos", @"type" : type, @"keyCode" : @(event.keyCode), @"modifiers" : @(modifierFlags), } mutableCopy]; // Calling these methods on any other type of event // (e.g NSEventTypeFlagsChanged) will raise an exception. if (event.type == NSEventTypeKeyDown || event.type == NSEventTypeKeyUp) { keyMessage[@"characters"] = event.characters; keyMessage[@"charactersIgnoringModifiers"] = event.charactersIgnoringModifiers; } NSNumber* specifiedLogicalKey = layoutMap[@(event.keyCode)]; if (specifiedLogicalKey != nil) { keyMessage[@"specifiedLogicalKey"] = specifiedLogicalKey; } [self.channel sendMessage:keyMessage reply:^(id reply) { if (!reply) { return callback(true); } // Only propagate the event to other responders if the framework didn't // handle it. callback([[reply valueForKey:@"handled"] boolValue]); }]; } #pragma mark - Private @end
engine/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.mm", "repo_id": "engine", "token_count": 2649 }
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 "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #include "flutter/testing/testing.h" /** * Fake pasteboard implementation to allow tests to work in environments without a real * pasteboard. */ @interface FakePasteboard : FlutterPasteboard @end @implementation FakePasteboard { NSString* _result; } - (NSInteger)clearContents { size_t changeCount = (_result != nil) ? 1 : 0; _result = nil; return changeCount; } - (NSString*)stringForType:(NSPasteboardType)dataType { return _result; } - (BOOL)setString:(NSString*)string forType:(NSPasteboardType)dataType { _result = string; return YES; } @end namespace flutter::testing { FlutterEngineTest::FlutterEngineTest() = default; void FlutterEngineTest::SetUp() { native_resolver_ = std::make_shared<TestDartNativeResolver>(); NSString* fixtures = @(testing::GetFixturesPath()); project_ = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; project_.rootIsolateCreateCallback = FlutterEngineTest::IsolateCreateCallback; engine_ = [[FlutterEngine alloc] initWithName:@"test" project:project_ allowHeadlessExecution:true]; } void FlutterEngineTest::TearDown() { [engine_ shutDownEngine]; engine_ = nil; native_resolver_.reset(); } void FlutterEngineTest::ShutDownEngine() { [engine_ shutDownEngine]; engine_ = nil; } void FlutterEngineTest::IsolateCreateCallback(void* user_data) { native_resolver_->SetNativeResolverForIsolate(); } void FlutterEngineTest::AddNativeCallback(const char* name, Dart_NativeFunction function) { native_resolver_->AddNativeCallback({name}, function); } id CreateMockFlutterEngine(NSString* pasteboardString) { NSString* fixtures = @(testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:true]; FakePasteboard* pasteboardMock = [[FakePasteboard alloc] init]; [pasteboardMock setString:pasteboardString forType:NSPasteboardTypeString]; engine.pasteboard = pasteboardMock; id engineMock = OCMPartialMock(engine); return engineMock; } MockFlutterEngineTest::MockFlutterEngineTest() = default; void MockFlutterEngineTest::SetUp() { engine_mock_ = CreateMockFlutterEngine(@""); } void MockFlutterEngineTest::TearDown() { [engine_mock_ shutDownEngine]; [engine_mock_ stopMocking]; engine_mock_ = nil; } void MockFlutterEngineTest::ShutDownEngine() { [engine_mock_ shutDownEngine]; engine_mock_ = nil; } } // namespace flutter::testing
engine/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.mm", "repo_id": "engine", "token_count": 1201 }
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. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h" #include <QuartzCore/QuartzCore.h> #include <vector> #include "flutter/fml/logging.h" #include "flutter/shell/platform/embedder/embedder.h" #import "flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h" namespace flutter { PlatformViewLayer::PlatformViewLayer(const FlutterLayer* layer) { FML_CHECK(layer->type == kFlutterLayerContentTypePlatformView); const auto* platform_view = layer->platform_view; identifier_ = platform_view->identifier; for (size_t i = 0; i < platform_view->mutations_count; i++) { mutations_.push_back(*platform_view->mutations[i]); } offset_ = layer->offset; size_ = layer->size; } PlatformViewLayer::PlatformViewLayer(FlutterPlatformViewIdentifier identifier, const std::vector<FlutterPlatformViewMutation>& mutations, FlutterPoint offset, FlutterSize size) : identifier_(identifier), mutations_(mutations), offset_(offset), size_(size) {} } // namespace flutter @interface FlutterMutatorView () { // Each of these views clips to a CGPathRef. These views, if present, // are nested (first is child of FlutterMutatorView and last is parent of // _platformView). NSMutableArray* _pathClipViews; // View right above the platform view. Used to apply the final transform // (sans the translation) to the platform view. NSView* _platformViewContainer; NSView* _platformView; } @end /// Superview container for platform views, to which sublayer transforms are applied. @interface FlutterPlatformViewContainer : NSView @end @implementation FlutterPlatformViewContainer - (BOOL)isFlipped { // Flutter transforms assume a coordinate system with an upper-left corner origin, with y // coordinate values increasing downwards. This affects the view, view transforms, and // sublayerTransforms. return YES; } @end /// View that clips that content to a specific CGPathRef. /// Clipping is done through a CAShapeLayer mask, which avoids the need to /// rasterize the mask. @interface FlutterPathClipView : NSView @end @implementation FlutterPathClipView - (instancetype)initWithFrame:(NSRect)frameRect { if (self = [super initWithFrame:frameRect]) { self.wantsLayer = YES; } return self; } - (BOOL)isFlipped { // Flutter transforms assume a coordinate system with an upper-left corner origin, with y // coordinate values increasing downwards. This affects the view, view transforms, and // sublayerTransforms. return YES; } /// Clip the view to the given path. Offset top left corner of platform view /// in global logical coordinates. - (void)maskToPath:(CGPathRef)path withOrigin:(CGPoint)origin { CAShapeLayer* maskLayer = self.layer.mask; if (maskLayer == nil) { maskLayer = [CAShapeLayer layer]; self.layer.mask = maskLayer; } maskLayer.path = path; maskLayer.transform = CATransform3DMakeTranslation(-origin.x, -origin.y, 0); } @end namespace { CATransform3D ToCATransform3D(const FlutterTransformation& t) { CATransform3D transform = CATransform3DIdentity; transform.m11 = t.scaleX; transform.m21 = t.skewX; transform.m41 = t.transX; transform.m14 = t.pers0; transform.m12 = t.skewY; transform.m22 = t.scaleY; transform.m42 = t.transY; transform.m24 = t.pers1; return transform; } bool AffineTransformIsOnlyScaleOrTranslate(const CGAffineTransform& transform) { return transform.b == 0 && transform.c == 0; } bool IsZeroSize(const FlutterSize size) { return size.width == 0 && size.height == 0; } CGRect FromFlutterRect(const FlutterRect& rect) { return CGRectMake(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); } FlutterRect ToFlutterRect(const CGRect& rect) { return FlutterRect{ .left = rect.origin.x, .top = rect.origin.y, .right = rect.origin.x + rect.size.width, .bottom = rect.origin.y + rect.size.height, }; } /// Returns whether the point is inside ellipse with given radius (centered at 0, 0). bool PointInsideEllipse(const CGPoint& point, const FlutterSize& radius) { return (point.x * point.x) / (radius.width * radius.width) + (point.y * point.y) / (radius.height * radius.height) < 1.0; } bool RoundRectCornerIntersects(const FlutterRoundedRect& roundRect, const FlutterRect& rect) { // Inner coordinate of the top left corner of the round rect. CGPoint inner_top_left = CGPointMake(roundRect.rect.left + roundRect.upper_left_corner_radius.width, roundRect.rect.top + roundRect.upper_left_corner_radius.height); // Position of `rect` corner relative to inner_top_left. CGPoint relative_top_left = CGPointMake(rect.left - inner_top_left.x, rect.top - inner_top_left.y); // `relative_top_left` is in upper left quadrant. if (relative_top_left.x < 0 && relative_top_left.y < 0) { if (!PointInsideEllipse(relative_top_left, roundRect.upper_left_corner_radius)) { return true; } } // Inner coordinate of the top right corner of the round rect. CGPoint inner_top_right = CGPointMake(roundRect.rect.right - roundRect.upper_right_corner_radius.width, roundRect.rect.top + roundRect.upper_right_corner_radius.height); // Positon of `rect` corner relative to inner_top_right. CGPoint relative_top_right = CGPointMake(rect.right - inner_top_right.x, rect.top - inner_top_right.y); // `relative_top_right` is in top right quadrant. if (relative_top_right.x > 0 && relative_top_right.y < 0) { if (!PointInsideEllipse(relative_top_right, roundRect.upper_right_corner_radius)) { return true; } } // Inner coordinate of the bottom left corner of the round rect. CGPoint inner_bottom_left = CGPointMake(roundRect.rect.left + roundRect.lower_left_corner_radius.width, roundRect.rect.bottom - roundRect.lower_left_corner_radius.height); // Position of `rect` corner relative to inner_bottom_left. CGPoint relative_bottom_left = CGPointMake(rect.left - inner_bottom_left.x, rect.bottom - inner_bottom_left.y); // `relative_bottom_left` is in bottom left quadrant. if (relative_bottom_left.x < 0 && relative_bottom_left.y > 0) { if (!PointInsideEllipse(relative_bottom_left, roundRect.lower_left_corner_radius)) { return true; } } // Inner coordinate of the bottom right corner of the round rect. CGPoint inner_bottom_right = CGPointMake(roundRect.rect.right - roundRect.lower_right_corner_radius.width, roundRect.rect.bottom - roundRect.lower_right_corner_radius.height); // Position of `rect` corner relative to inner_bottom_right. CGPoint relative_bottom_right = CGPointMake(rect.right - inner_bottom_right.x, rect.bottom - inner_bottom_right.y); // `relative_bottom_right` is in bottom right quadrant. if (relative_bottom_right.x > 0 && relative_bottom_right.y > 0) { if (!PointInsideEllipse(relative_bottom_right, roundRect.lower_right_corner_radius)) { return true; } } return false; } CGPathRef PathFromRoundedRect(const FlutterRoundedRect& roundedRect) { if (IsZeroSize(roundedRect.lower_left_corner_radius) && IsZeroSize(roundedRect.lower_right_corner_radius) && IsZeroSize(roundedRect.upper_left_corner_radius) && IsZeroSize(roundedRect.upper_right_corner_radius)) { return CGPathCreateWithRect(FromFlutterRect(roundedRect.rect), nullptr); } CGMutablePathRef path = CGPathCreateMutable(); const auto& rect = roundedRect.rect; const auto& topLeft = roundedRect.upper_left_corner_radius; const auto& topRight = roundedRect.upper_right_corner_radius; const auto& bottomLeft = roundedRect.lower_left_corner_radius; const auto& bottomRight = roundedRect.lower_right_corner_radius; CGPathMoveToPoint(path, nullptr, rect.left + topLeft.width, rect.top); CGPathAddLineToPoint(path, nullptr, rect.right - topRight.width, rect.top); CGPathAddCurveToPoint(path, nullptr, rect.right, rect.top, rect.right, rect.top + topRight.height, rect.right, rect.top + topRight.height); CGPathAddLineToPoint(path, nullptr, rect.right, rect.bottom - bottomRight.height); CGPathAddCurveToPoint(path, nullptr, rect.right, rect.bottom, rect.right - bottomRight.width, rect.bottom, rect.right - bottomRight.width, rect.bottom); CGPathAddLineToPoint(path, nullptr, rect.left + bottomLeft.width, rect.bottom); CGPathAddCurveToPoint(path, nullptr, rect.left, rect.bottom, rect.left, rect.bottom - bottomLeft.height, rect.left, rect.bottom - bottomLeft.height); CGPathAddLineToPoint(path, nullptr, rect.left, rect.top + topLeft.height); CGPathAddCurveToPoint(path, nullptr, rect.left, rect.top, rect.left + topLeft.width, rect.top, rect.left + topLeft.width, rect.top); CGPathCloseSubpath(path); return path; } using MutationVector = std::vector<FlutterPlatformViewMutation>; /// Returns a vector of FlutterPlatformViewMutation object pointers associated with a platform view. /// The transforms sent from the engine include a transform from logical to physical coordinates. /// Since Cocoa deals only in logical points, this function prepends a scale transform that scales /// back from physical to logical coordinates to compensate. MutationVector MutationsForPlatformView(const MutationVector& mutationsIn, float scale) { MutationVector mutations(mutationsIn); mutations.insert(mutations.begin(), { .type = kFlutterPlatformViewMutationTypeTransformation, .transformation{ .scaleX = 1.0 / scale, .scaleY = 1.0 / scale, }, }); return mutations; } /// Returns the composition of all transformation mutations in the mutations vector. CATransform3D CATransformFromMutations(const MutationVector& mutations) { CATransform3D transform = CATransform3DIdentity; for (auto mutation : mutations) { switch (mutation.type) { case kFlutterPlatformViewMutationTypeTransformation: { CATransform3D mutationTransform = ToCATransform3D(mutation.transformation); transform = CATransform3DConcat(mutationTransform, transform); break; } case kFlutterPlatformViewMutationTypeClipRect: case kFlutterPlatformViewMutationTypeClipRoundedRect: case kFlutterPlatformViewMutationTypeOpacity: break; } } return transform; } /// Returns the opacity for all opacity mutations in the mutations vector. float OpacityFromMutations(const MutationVector& mutations) { float opacity = 1.0; for (auto mutation : mutations) { switch (mutation.type) { case kFlutterPlatformViewMutationTypeOpacity: opacity *= mutation.opacity; break; case kFlutterPlatformViewMutationTypeClipRect: case kFlutterPlatformViewMutationTypeClipRoundedRect: case kFlutterPlatformViewMutationTypeTransformation: break; } } return opacity; } /// Returns the clip rect generated by the intersection of clips in the mutations vector. CGRect MasterClipFromMutations(CGRect bounds, const MutationVector& mutations) { // Master clip in global logical coordinates. This is intersection of all clip rectangles // present in mutators. CGRect master_clip = bounds; // Create the initial transform. CATransform3D transform = CATransform3DIdentity; for (auto mutation : mutations) { switch (mutation.type) { case kFlutterPlatformViewMutationTypeClipRect: { CGRect rect = CGRectApplyAffineTransform(FromFlutterRect(mutation.clip_rect), CATransform3DGetAffineTransform(transform)); master_clip = CGRectIntersection(rect, master_clip); break; } case kFlutterPlatformViewMutationTypeClipRoundedRect: { CGAffineTransform affineTransform = CATransform3DGetAffineTransform(transform); CGRect rect = CGRectApplyAffineTransform(FromFlutterRect(mutation.clip_rounded_rect.rect), affineTransform); master_clip = CGRectIntersection(rect, master_clip); break; } case kFlutterPlatformViewMutationTypeTransformation: transform = CATransform3DConcat(ToCATransform3D(mutation.transformation), transform); break; case kFlutterPlatformViewMutationTypeOpacity: break; } } return master_clip; } /// A rounded rectangle and transform associated with it. typedef struct { FlutterRoundedRect rrect; CGAffineTransform transform; } ClipRoundedRect; /// Returns the set of all rounded rect paths generated by clips in the mutations vector. NSMutableArray* ClipPathFromMutations(CGRect master_clip, const MutationVector& mutations) { std::vector<ClipRoundedRect> rounded_rects; CATransform3D transform = CATransform3DIdentity; for (auto mutation : mutations) { switch (mutation.type) { case kFlutterPlatformViewMutationTypeClipRoundedRect: { CGAffineTransform affineTransform = CATransform3DGetAffineTransform(transform); rounded_rects.push_back({mutation.clip_rounded_rect, affineTransform}); break; } case kFlutterPlatformViewMutationTypeTransformation: transform = CATransform3DConcat(ToCATransform3D(mutation.transformation), transform); break; case kFlutterPlatformViewMutationTypeClipRect: { CGAffineTransform affineTransform = CATransform3DGetAffineTransform(transform); // Shearing or rotation requires path clipping. if (!AffineTransformIsOnlyScaleOrTranslate(affineTransform)) { rounded_rects.push_back( {FlutterRoundedRect{mutation.clip_rect, FlutterSize{0, 0}, FlutterSize{0, 0}, FlutterSize{0, 0}, FlutterSize{0, 0}}, affineTransform}); } break; } case kFlutterPlatformViewMutationTypeOpacity: break; } } NSMutableArray* paths = [NSMutableArray array]; for (const auto& r : rounded_rects) { bool requiresPath = !AffineTransformIsOnlyScaleOrTranslate(r.transform); if (!requiresPath) { CGAffineTransform inverse = CGAffineTransformInvert(r.transform); // Transform master clip to clip rect coordinates and check if this view intersects one of the // corners, which means we need to use path clipping. CGRect localMasterClip = CGRectApplyAffineTransform(master_clip, inverse); requiresPath = RoundRectCornerIntersects(r.rrect, ToFlutterRect(localMasterClip)); } // Only clip to rounded rectangle path if the view intersects some of the round corners. If // not, clipping to masterClip is enough. if (requiresPath) { CGPathRef path = PathFromRoundedRect(r.rrect); CGPathRef transformedPath = CGPathCreateCopyByTransformingPath(path, &r.transform); [paths addObject:(__bridge id)transformedPath]; CGPathRelease(transformedPath); CGPathRelease(path); } } return paths; } } // namespace @implementation FlutterMutatorView - (NSView*)platformView { return _platformView; } - (NSMutableArray*)pathClipViews { return _pathClipViews; } - (NSView*)platformViewContainer { return _platformViewContainer; } - (instancetype)initWithPlatformView:(NSView*)platformView { if (self = [super initWithFrame:NSZeroRect]) { _platformView = platformView; _pathClipViews = [NSMutableArray array]; self.wantsLayer = YES; self.clipsToBounds = YES; } return self; } - (NSView*)hitTest:(NSPoint)point { return nil; } - (BOOL)isFlipped { return YES; } /// Returns the scale factor to translate logical pixels to physical pixels for this view. - (CGFloat)contentsScale { return self.superview != nil ? self.superview.layer.contentsScale : 1.0; } /// Updates the nested stack of clip views that host the platform view. - (void)updatePathClipViewsWithPaths:(NSArray*)paths { // Remove path clip views depending on the number of paths. while (_pathClipViews.count > paths.count) { NSView* view = _pathClipViews.lastObject; [view removeFromSuperview]; [_pathClipViews removeLastObject]; } // Otherwise, add path clip views to the end. for (size_t i = _pathClipViews.count; i < paths.count; ++i) { NSView* superView = _pathClipViews.count == 0 ? self : _pathClipViews.lastObject; FlutterPathClipView* pathClipView = [[FlutterPathClipView alloc] initWithFrame:self.bounds]; [_pathClipViews addObject:pathClipView]; [superView addSubview:pathClipView]; } // Update bounds and apply clip paths. for (size_t i = 0; i < _pathClipViews.count; ++i) { FlutterPathClipView* pathClipView = _pathClipViews[i]; pathClipView.frame = self.bounds; [pathClipView maskToPath:(__bridge CGPathRef)[paths objectAtIndex:i] withOrigin:self.frame.origin]; } } /// Updates the PlatformView and PlatformView container views. /// /// Re-nests _platformViewContainer in the innermost clip view, applies transforms to the underlying /// CALayer, adds the platform view as a subview of the container, and sets the axis-aligned clip /// rect around the tranformed view. - (void)updatePlatformViewWithBounds:(CGRect)untransformedBounds transformedBounds:(CGRect)transformedBounds transform:(CATransform3D)transform clipRect:(CGRect)clipRect { // Create the PlatformViewContainer view if necessary. if (_platformViewContainer == nil) { _platformViewContainer = [[FlutterPlatformViewContainer alloc] initWithFrame:self.bounds]; _platformViewContainer.wantsLayer = YES; } // Nest the PlatformViewContainer view in the innermost path clip view. NSView* containerSuperview = _pathClipViews.count == 0 ? self : _pathClipViews.lastObject; [containerSuperview addSubview:_platformViewContainer]; _platformViewContainer.frame = self.bounds; // Nest the platform view in the PlatformViewContainer. [_platformViewContainer addSubview:_platformView]; _platformView.frame = untransformedBounds; // Transform for the platform view is finalTransform adjusted for bounding rect origin. CATransform3D translation = CATransform3DMakeTranslation(-transformedBounds.origin.x, -transformedBounds.origin.y, 0); transform = CATransform3DConcat(transform, translation); _platformViewContainer.layer.sublayerTransform = transform; // By default NSView clips children to frame. If masterClip is tighter than mutator view frame, // the frame is set to masterClip and child offset adjusted to compensate for the difference. if (!CGRectEqualToRect(clipRect, transformedBounds)) { FML_DCHECK(self.subviews.count == 1); auto subview = self.subviews.firstObject; FML_DCHECK(subview.frame.origin.x == 0 && subview.frame.origin.y == 0); subview.frame = CGRectMake(transformedBounds.origin.x - clipRect.origin.x, transformedBounds.origin.y - clipRect.origin.y, subview.frame.size.width, subview.frame.size.height); self.frame = clipRect; } } /// Whenever possible view will be clipped using layer bounds. /// If clipping to path is needed, CAShapeLayer(s) will be used as mask. /// Clipping to round rect only clips to path if round corners are intersected. - (void)applyFlutterLayer:(const flutter::PlatformViewLayer*)layer { // Compute the untransformed bounding rect for the platform view in logical pixels. // FlutterLayer.size is in physical pixels but Cocoa uses logical points. CGFloat scale = [self contentsScale]; MutationVector mutations = MutationsForPlatformView(layer->mutations(), scale); CATransform3D finalTransform = CATransformFromMutations(mutations); // Compute the untransformed bounding rect for the platform view in logical pixels. // FlutterLayer.size is in physical pixels but Cocoa uses logical points. CGRect untransformedBoundingRect = CGRectMake(0, 0, layer->size().width / scale, layer->size().height / scale); CGRect finalBoundingRect = CGRectApplyAffineTransform( untransformedBoundingRect, CATransform3DGetAffineTransform(finalTransform)); self.frame = finalBoundingRect; // Compute the layer opacity. self.layer.opacity = OpacityFromMutations(mutations); // Compute the master clip in global logical coordinates. CGRect masterClip = MasterClipFromMutations(finalBoundingRect, mutations); if (CGRectIsNull(masterClip)) { self.hidden = YES; return; } self.hidden = NO; /// Paths in global logical coordinates that need to be clipped to. NSMutableArray* paths = ClipPathFromMutations(masterClip, mutations); [self updatePathClipViewsWithPaths:paths]; /// Update PlatformViewContainer, PlatformView, and apply transforms and axis-aligned clip rect. [self updatePlatformViewWithBounds:untransformedBoundingRect transformedBounds:finalBoundingRect transform:finalTransform clipRect:masterClip]; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.mm", "repo_id": "engine", "token_count": 7696 }
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. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h" #import <Foundation/Foundation.h> #import <objc/message.h> #include <algorithm> #include <memory> #include "flutter/fml/platform/darwin/string_range_sanitization.h" #include "flutter/shell/platform/common/text_editing_delta.h" #include "flutter/shell/platform/common/text_input_model.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h" static NSString* const kTextInputChannel = @"flutter/textinput"; #pragma mark - TextInput channel method names // See https://api.flutter.dev/flutter/services/SystemChannels/textInput-constant.html static NSString* const kSetClientMethod = @"TextInput.setClient"; static NSString* const kShowMethod = @"TextInput.show"; static NSString* const kHideMethod = @"TextInput.hide"; static NSString* const kClearClientMethod = @"TextInput.clearClient"; static NSString* const kSetEditingStateMethod = @"TextInput.setEditingState"; static NSString* const kSetEditableSizeAndTransform = @"TextInput.setEditableSizeAndTransform"; static NSString* const kSetCaretRect = @"TextInput.setCaretRect"; static NSString* const kUpdateEditStateResponseMethod = @"TextInputClient.updateEditingState"; static NSString* const kUpdateEditStateWithDeltasResponseMethod = @"TextInputClient.updateEditingStateWithDeltas"; static NSString* const kPerformAction = @"TextInputClient.performAction"; static NSString* const kPerformSelectors = @"TextInputClient.performSelectors"; static NSString* const kMultilineInputType = @"TextInputType.multiline"; #pragma mark - TextInputConfiguration field names static NSString* const kSecureTextEntry = @"obscureText"; static NSString* const kTextInputAction = @"inputAction"; static NSString* const kEnableDeltaModel = @"enableDeltaModel"; static NSString* const kTextInputType = @"inputType"; static NSString* const kTextInputTypeName = @"name"; static NSString* const kSelectionBaseKey = @"selectionBase"; static NSString* const kSelectionExtentKey = @"selectionExtent"; static NSString* const kSelectionAffinityKey = @"selectionAffinity"; static NSString* const kSelectionIsDirectionalKey = @"selectionIsDirectional"; static NSString* const kComposingBaseKey = @"composingBase"; static NSString* const kComposingExtentKey = @"composingExtent"; static NSString* const kTextKey = @"text"; static NSString* const kTransformKey = @"transform"; static NSString* const kAssociatedAutofillFields = @"fields"; // TextInputConfiguration.autofill and sub-field names static NSString* const kAutofillProperties = @"autofill"; static NSString* const kAutofillId = @"uniqueIdentifier"; static NSString* const kAutofillEditingValue = @"editingValue"; static NSString* const kAutofillHints = @"hints"; // TextAffinity types static NSString* const kTextAffinityDownstream = @"TextAffinity.downstream"; static NSString* const kTextAffinityUpstream = @"TextAffinity.upstream"; // TextInputAction types static NSString* const kInputActionNewline = @"TextInputAction.newline"; #pragma mark - Enums /** * The affinity of the current cursor position. If the cursor is at a position * representing a soft line break, the cursor may be drawn either at the end of * the current line (upstream) or at the beginning of the next (downstream). */ typedef NS_ENUM(NSUInteger, FlutterTextAffinity) { kFlutterTextAffinityUpstream, kFlutterTextAffinityDownstream }; #pragma mark - Static functions /* * Updates a range given base and extent fields. */ static flutter::TextRange RangeFromBaseExtent(NSNumber* base, NSNumber* extent, const flutter::TextRange& range) { if (base == nil || extent == nil) { return range; } if (base.intValue == -1 && extent.intValue == -1) { return flutter::TextRange(0, 0); } return flutter::TextRange([base unsignedLongValue], [extent unsignedLongValue]); } // Returns the autofill hint content type, if specified; otherwise nil. static NSString* GetAutofillHint(NSDictionary* autofill) { NSArray<NSString*>* hints = autofill[kAutofillHints]; return hints.count > 0 ? hints[0] : nil; } // Returns the text content type for the specified TextInputConfiguration. // NSTextContentType is only available for macOS 11.0 and later. static NSTextContentType GetTextContentType(NSDictionary* configuration) API_AVAILABLE(macos(11.0)) { // Check autofill hints. NSDictionary* autofill = configuration[kAutofillProperties]; if (autofill) { NSString* hint = GetAutofillHint(autofill); if ([hint isEqualToString:@"username"]) { return NSTextContentTypeUsername; } if ([hint isEqualToString:@"password"]) { return NSTextContentTypePassword; } if ([hint isEqualToString:@"oneTimeCode"]) { return NSTextContentTypeOneTimeCode; } } // If no autofill hints, guess based on other attributes. if ([configuration[kSecureTextEntry] boolValue]) { return NSTextContentTypePassword; } return nil; } // Returns YES if configuration describes a field for which autocomplete should be enabled for // the specified TextInputConfiguration. Autocomplete is enabled by default, but will be disabled // if the field is password-related, or if the configuration contains no autofill settings. static BOOL EnableAutocompleteForTextInputConfiguration(NSDictionary* configuration) { // Disable if obscureText is set. if ([configuration[kSecureTextEntry] boolValue]) { return NO; } // Disable if autofill properties are not set. NSDictionary* autofill = configuration[kAutofillProperties]; if (autofill == nil) { return NO; } // Disable if autofill properties indicate a username/password. // See: https://github.com/flutter/flutter/issues/119824 NSString* hint = GetAutofillHint(autofill); if ([hint isEqualToString:@"password"] || [hint isEqualToString:@"username"]) { return NO; } return YES; } // Returns YES if configuration describes a field for which autocomplete should be enabled. // Autocomplete is enabled by default, but will be disabled if the field is password-related, or if // the configuration contains no autofill settings. // // In the case where the current field is part of an AutofillGroup, the configuration will have // a fields attribute with a list of TextInputConfigurations, one for each field. In the case where // any field in the group disables autocomplete, we disable it for all. static BOOL EnableAutocomplete(NSDictionary* configuration) { for (NSDictionary* field in configuration[kAssociatedAutofillFields]) { if (!EnableAutocompleteForTextInputConfiguration(field)) { return NO; } } // Check the top-level TextInputConfiguration. return EnableAutocompleteForTextInputConfiguration(configuration); } #pragma mark - NSEvent (KeyEquivalentMarker) protocol @interface NSEvent (KeyEquivalentMarker) // Internally marks that the event was received through performKeyEquivalent:. // When text editing is active, keyboard events that have modifier keys pressed // are received through performKeyEquivalent: instead of keyDown:. If such event // is passed to TextInputContext but doesn't result in a text editing action it // needs to be forwarded by FlutterKeyboardManager to the next responder. - (void)markAsKeyEquivalent; // Returns YES if the event is marked as a key equivalent. - (BOOL)isKeyEquivalent; @end @implementation NSEvent (KeyEquivalentMarker) // This field doesn't need a value because only its address is used as a unique identifier. static char markerKey; - (void)markAsKeyEquivalent { objc_setAssociatedObject(self, &markerKey, @true, OBJC_ASSOCIATION_RETAIN); } - (BOOL)isKeyEquivalent { return [objc_getAssociatedObject(self, &markerKey) boolValue] == YES; } @end #pragma mark - FlutterTextInputPlugin private interface /** * Private properties of FlutterTextInputPlugin. */ @interface FlutterTextInputPlugin () /** * A text input context, representing a connection to the Cocoa text input system. */ @property(nonatomic) NSTextInputContext* textInputContext; /** * The channel used to communicate with Flutter. */ @property(nonatomic) FlutterMethodChannel* channel; /** * The FlutterViewController to manage input for. */ @property(nonatomic, weak) FlutterViewController* flutterViewController; /** * Whether the text input is shown in the view. * * Defaults to TRUE on startup. */ @property(nonatomic) BOOL shown; /** * The current state of the keyboard and pressed keys. */ @property(nonatomic) uint64_t previouslyPressedFlags; /** * The affinity for the current cursor position. */ @property FlutterTextAffinity textAffinity; /** * ID of the text input client. */ @property(nonatomic, nonnull) NSNumber* clientID; /** * Keyboard type of the client. See available options: * https://api.flutter.dev/flutter/services/TextInputType-class.html */ @property(nonatomic, nonnull) NSString* inputType; /** * An action requested by the user on the input client. See available options: * https://api.flutter.dev/flutter/services/TextInputAction-class.html */ @property(nonatomic, nonnull) NSString* inputAction; /** * Set to true if the last event fed to the input context produced a text editing command * or text output. It is reset to false at the beginning of every key event, and is only * used while processing this event. */ @property(nonatomic) BOOL eventProducedOutput; /** * Whether to enable the sending of text input updates from the engine to the * framework as TextEditingDeltas rather than as one TextEditingValue. * For more information on the delta model, see: * https://master-api.flutter.dev/flutter/services/TextInputConfiguration/enableDeltaModel.html */ @property(nonatomic) BOOL enableDeltaModel; /** * Used to gather multiple selectors performed in one run loop turn. These * will be all sent in one platform channel call so that the framework can process * them in single microtask. */ @property(nonatomic) NSMutableArray* pendingSelectors; /** * Handles a Flutter system message on the text input channel. */ - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; /** * Updates the text input model with state received from the framework via the * TextInput.setEditingState message. */ - (void)setEditingState:(NSDictionary*)state; /** * Informs the Flutter framework of changes to the text input model's state by * sending the entire new state. */ - (void)updateEditState; /** * Informs the Flutter framework of changes to the text input model's state by * sending only the difference. */ - (void)updateEditStateWithDelta:(const flutter::TextEditingDelta)delta; /** * Updates the stringValue and selectedRange that stored in the NSTextView interface * that this plugin inherits from. * * If there is a FlutterTextField uses this plugin as its field editor, this method * will update the stringValue and selectedRange through the API of the FlutterTextField. */ - (void)updateTextAndSelection; /** * Return the string representation of the current textAffinity as it should be * sent over the FlutterMethodChannel. */ - (NSString*)textAffinityString; /** * Allow overriding run loop mode for test. */ @property(readwrite, nonatomic) NSString* customRunLoopMode; @end #pragma mark - FlutterTextInputPlugin @implementation FlutterTextInputPlugin { /** * The currently active text input model. */ std::unique_ptr<flutter::TextInputModel> _activeModel; /** * Transform for current the editable. Used to determine position of accent selection menu. */ CATransform3D _editableTransform; /** * Current position of caret in local (editable) coordinates. */ CGRect _caretRect; } - (instancetype)initWithViewController:(FlutterViewController*)viewController { // The view needs an empty frame otherwise it is visible on dark background. // https://github.com/flutter/flutter/issues/118504 self = [super initWithFrame:NSZeroRect]; self.clipsToBounds = YES; if (self != nil) { _flutterViewController = viewController; _channel = [FlutterMethodChannel methodChannelWithName:kTextInputChannel binaryMessenger:viewController.engine.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]; _shown = FALSE; // NSTextView does not support _weak reference, so this class has to // use __unsafe_unretained and manage the reference by itself. // // Since the dealloc removes the handler, the pointer should // be valid if the handler is ever called. __unsafe_unretained FlutterTextInputPlugin* unsafeSelf = self; [_channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { [unsafeSelf handleMethodCall:call result:result]; }]; _textInputContext = [[NSTextInputContext alloc] initWithClient:unsafeSelf]; _previouslyPressedFlags = 0; // Initialize with the zero matrix which is not // an affine transform. _editableTransform = CATransform3D(); _caretRect = CGRectNull; } return self; } - (BOOL)isFirstResponder { if (!self.flutterViewController.viewLoaded) { return false; } return [self.flutterViewController.view.window firstResponder] == self; } - (void)dealloc { [_channel setMethodCallHandler:nil]; } #pragma mark - Private - (void)resignAndRemoveFromSuperview { if (self.superview != nil) { [self.window makeFirstResponder:_flutterViewController.flutterView]; [self removeFromSuperview]; } } - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { BOOL handled = YES; NSString* method = call.method; if ([method isEqualToString:kSetClientMethod]) { if (!call.arguments[0] || !call.arguments[1]) { result([FlutterError errorWithCode:@"error" message:@"Missing arguments" details:@"Missing arguments while trying to set a text input client"]); return; } NSNumber* clientID = call.arguments[0]; if (clientID != nil) { NSDictionary* config = call.arguments[1]; _clientID = clientID; _inputAction = config[kTextInputAction]; _enableDeltaModel = [config[kEnableDeltaModel] boolValue]; NSDictionary* inputTypeInfo = config[kTextInputType]; _inputType = inputTypeInfo[kTextInputTypeName]; self.textAffinity = kFlutterTextAffinityUpstream; self.automaticTextCompletionEnabled = EnableAutocomplete(config); if (@available(macOS 11.0, *)) { self.contentType = GetTextContentType(config); } _activeModel = std::make_unique<flutter::TextInputModel>(); } } else if ([method isEqualToString:kShowMethod]) { // Ensure the plugin is in hierarchy. Only do this with accessibility disabled. // When accessibility is enabled cocoa will reparent the plugin inside // FlutterTextField in [FlutterTextField startEditing]. if (_client == nil) { [_flutterViewController.view addSubview:self]; } [self.window makeFirstResponder:self]; _shown = TRUE; } else if ([method isEqualToString:kHideMethod]) { [self resignAndRemoveFromSuperview]; _shown = FALSE; } else if ([method isEqualToString:kClearClientMethod]) { [self resignAndRemoveFromSuperview]; // If there's an active mark region, commit it, end composing, and clear the IME's mark text. if (_activeModel && _activeModel->composing()) { _activeModel->CommitComposing(); _activeModel->EndComposing(); } [_textInputContext discardMarkedText]; _clientID = nil; _inputAction = nil; _enableDeltaModel = NO; _inputType = nil; _activeModel = nullptr; } else if ([method isEqualToString:kSetEditingStateMethod]) { NSDictionary* state = call.arguments; [self setEditingState:state]; } else if ([method isEqualToString:kSetEditableSizeAndTransform]) { NSDictionary* state = call.arguments; [self setEditableTransform:state[kTransformKey]]; } else if ([method isEqualToString:kSetCaretRect]) { NSDictionary* rect = call.arguments; [self updateCaretRect:rect]; } else { handled = NO; } result(handled ? nil : FlutterMethodNotImplemented); } - (void)setEditableTransform:(NSArray*)matrix { CATransform3D* transform = &_editableTransform; transform->m11 = [matrix[0] doubleValue]; transform->m12 = [matrix[1] doubleValue]; transform->m13 = [matrix[2] doubleValue]; transform->m14 = [matrix[3] doubleValue]; transform->m21 = [matrix[4] doubleValue]; transform->m22 = [matrix[5] doubleValue]; transform->m23 = [matrix[6] doubleValue]; transform->m24 = [matrix[7] doubleValue]; transform->m31 = [matrix[8] doubleValue]; transform->m32 = [matrix[9] doubleValue]; transform->m33 = [matrix[10] doubleValue]; transform->m34 = [matrix[11] doubleValue]; transform->m41 = [matrix[12] doubleValue]; transform->m42 = [matrix[13] doubleValue]; transform->m43 = [matrix[14] doubleValue]; transform->m44 = [matrix[15] doubleValue]; } - (void)updateCaretRect:(NSDictionary*)dictionary { NSAssert(dictionary[@"x"] != nil && dictionary[@"y"] != nil && dictionary[@"width"] != nil && dictionary[@"height"] != nil, @"Expected a dictionary representing a CGRect, got %@", dictionary); _caretRect = CGRectMake([dictionary[@"x"] doubleValue], [dictionary[@"y"] doubleValue], [dictionary[@"width"] doubleValue], [dictionary[@"height"] doubleValue]); } - (void)setEditingState:(NSDictionary*)state { NSString* selectionAffinity = state[kSelectionAffinityKey]; if (selectionAffinity != nil) { _textAffinity = [selectionAffinity isEqualToString:kTextAffinityUpstream] ? kFlutterTextAffinityUpstream : kFlutterTextAffinityDownstream; } NSString* text = state[kTextKey]; flutter::TextRange selected_range = RangeFromBaseExtent( state[kSelectionBaseKey], state[kSelectionExtentKey], _activeModel->selection()); _activeModel->SetSelection(selected_range); flutter::TextRange composing_range = RangeFromBaseExtent( state[kComposingBaseKey], state[kComposingExtentKey], _activeModel->composing_range()); const bool wasComposing = _activeModel->composing(); _activeModel->SetText([text UTF8String], selected_range, composing_range); if (composing_range.collapsed() && wasComposing) { [_textInputContext discardMarkedText]; } [_client startEditing]; [self updateTextAndSelection]; } - (NSDictionary*)editingState { if (_activeModel == nullptr) { return nil; } NSString* const textAffinity = [self textAffinityString]; int composingBase = _activeModel->composing() ? _activeModel->composing_range().base() : -1; int composingExtent = _activeModel->composing() ? _activeModel->composing_range().extent() : -1; return @{ kSelectionBaseKey : @(_activeModel->selection().base()), kSelectionExtentKey : @(_activeModel->selection().extent()), kSelectionAffinityKey : textAffinity, kSelectionIsDirectionalKey : @NO, kComposingBaseKey : @(composingBase), kComposingExtentKey : @(composingExtent), kTextKey : [NSString stringWithUTF8String:_activeModel->GetText().c_str()] ?: [NSNull null], }; } - (void)updateEditState { if (_activeModel == nullptr) { return; } NSDictionary* state = [self editingState]; [_channel invokeMethod:kUpdateEditStateResponseMethod arguments:@[ self.clientID, state ]]; [self updateTextAndSelection]; } - (void)updateEditStateWithDelta:(const flutter::TextEditingDelta)delta { NSUInteger selectionBase = _activeModel->selection().base(); NSUInteger selectionExtent = _activeModel->selection().extent(); int composingBase = _activeModel->composing() ? _activeModel->composing_range().base() : -1; int composingExtent = _activeModel->composing() ? _activeModel->composing_range().extent() : -1; NSString* const textAffinity = [self textAffinityString]; NSDictionary* deltaToFramework = @{ @"oldText" : @(delta.old_text().c_str()), @"deltaText" : @(delta.delta_text().c_str()), @"deltaStart" : @(delta.delta_start()), @"deltaEnd" : @(delta.delta_end()), @"selectionBase" : @(selectionBase), @"selectionExtent" : @(selectionExtent), @"selectionAffinity" : textAffinity, @"selectionIsDirectional" : @(false), @"composingBase" : @(composingBase), @"composingExtent" : @(composingExtent), }; NSDictionary* deltas = @{ @"deltas" : @[ deltaToFramework ], }; [_channel invokeMethod:kUpdateEditStateWithDeltasResponseMethod arguments:@[ self.clientID, deltas ]]; [self updateTextAndSelection]; } - (void)updateTextAndSelection { NSAssert(_activeModel != nullptr, @"Flutter text model must not be null."); NSString* text = @(_activeModel->GetText().data()); int start = _activeModel->selection().base(); int extend = _activeModel->selection().extent(); NSRange selection = NSMakeRange(MIN(start, extend), ABS(start - extend)); // There may be a native text field client if VoiceOver is on. // In this case, this plugin has to update text and selection through // the client in order for VoiceOver to announce the text editing // properly. if (_client) { [_client updateString:text withSelection:selection]; } else { self.string = text; [self setSelectedRange:selection]; } } - (NSString*)textAffinityString { return (self.textAffinity == kFlutterTextAffinityUpstream) ? kTextAffinityUpstream : kTextAffinityDownstream; } - (BOOL)handleKeyEvent:(NSEvent*)event { if (event.type == NSEventTypeKeyUp || (event.type == NSEventTypeFlagsChanged && event.modifierFlags < _previouslyPressedFlags)) { return NO; } _previouslyPressedFlags = event.modifierFlags; if (!_shown) { return NO; } _eventProducedOutput = NO; BOOL res = [_textInputContext handleEvent:event]; // NSTextInputContext#handleEvent returns YES if the context handles the event. One of the reasons // the event is handled is because it's a key equivalent. But a key equivalent might produce a // text command (indicated by calling doCommandBySelector) or might not (for example, Cmd+Q). In // the latter case, this command somehow has not been executed yet and Flutter must dispatch it to // the next responder. See https://github.com/flutter/flutter/issues/106354 . // The event is also not redispatched if there is IME composition active, because it might be // handled by the IME. See https://github.com/flutter/flutter/issues/134699 // both NSEventModifierFlagNumericPad and NSEventModifierFlagFunction are set for arrow keys. bool is_navigation = event.modifierFlags & NSEventModifierFlagFunction && event.modifierFlags & NSEventModifierFlagNumericPad; bool is_navigation_in_ime = is_navigation && self.hasMarkedText; if (event.isKeyEquivalent && !is_navigation_in_ime && !_eventProducedOutput) { return NO; } return res; } #pragma mark - #pragma mark NSResponder - (void)keyDown:(NSEvent*)event { [self.flutterViewController keyDown:event]; } - (void)keyUp:(NSEvent*)event { [self.flutterViewController keyUp:event]; } - (BOOL)performKeyEquivalent:(NSEvent*)event { if ([_flutterViewController isDispatchingKeyEvent:event]) { // When NSWindow is nextResponder, keyboard manager will send to it // unhandled events (through [NSWindow keyDown:]). If event has both // control and cmd modifiers set (i.e. cmd+control+space - emoji picker) // NSWindow will then send this event as performKeyEquivalent: to first // responder, which is FlutterTextInputPlugin. If that's the case, the // plugin must not handle the event, otherwise the emoji picker would not // work (due to first responder returning YES from performKeyEquivalent:) // and there would be endless loop, because FlutterViewController will // send the event back to [keyboardManager handleEvent:]. return NO; } [event markAsKeyEquivalent]; [self.flutterViewController keyDown:event]; return YES; } - (void)flagsChanged:(NSEvent*)event { [self.flutterViewController flagsChanged:event]; } - (void)mouseDown:(NSEvent*)event { [self.flutterViewController mouseDown:event]; } - (void)mouseUp:(NSEvent*)event { [self.flutterViewController mouseUp:event]; } - (void)mouseDragged:(NSEvent*)event { [self.flutterViewController mouseDragged:event]; } - (void)rightMouseDown:(NSEvent*)event { [self.flutterViewController rightMouseDown:event]; } - (void)rightMouseUp:(NSEvent*)event { [self.flutterViewController rightMouseUp:event]; } - (void)rightMouseDragged:(NSEvent*)event { [self.flutterViewController rightMouseDragged:event]; } - (void)otherMouseDown:(NSEvent*)event { [self.flutterViewController otherMouseDown:event]; } - (void)otherMouseUp:(NSEvent*)event { [self.flutterViewController otherMouseUp:event]; } - (void)otherMouseDragged:(NSEvent*)event { [self.flutterViewController otherMouseDragged:event]; } - (void)mouseMoved:(NSEvent*)event { [self.flutterViewController mouseMoved:event]; } - (void)scrollWheel:(NSEvent*)event { [self.flutterViewController scrollWheel:event]; } - (NSTextInputContext*)inputContext { return _textInputContext; } #pragma mark - #pragma mark NSTextInputClient - (void)insertTab:(id)sender { // Implementing insertTab: makes AppKit send tab as command, instead of // insertText with '\t'. } - (void)insertText:(id)string replacementRange:(NSRange)range { if (_activeModel == nullptr) { return; } _eventProducedOutput |= true; if (range.location != NSNotFound) { // The selected range can actually have negative numbers, since it can start // at the end of the range if the user selected the text going backwards. // Cast to a signed type to determine whether or not the selection is reversed. long signedLength = static_cast<long>(range.length); long location = range.location; long textLength = _activeModel->text_range().end(); size_t base = std::clamp(location, 0L, textLength); size_t extent = std::clamp(location + signedLength, 0L, textLength); _activeModel->SetSelection(flutter::TextRange(base, extent)); } flutter::TextRange oldSelection = _activeModel->selection(); flutter::TextRange composingBeforeChange = _activeModel->composing_range(); flutter::TextRange replacedRange(-1, -1); std::string textBeforeChange = _activeModel->GetText().c_str(); std::string utf8String = [string UTF8String]; _activeModel->AddText(utf8String); if (_activeModel->composing()) { replacedRange = composingBeforeChange; _activeModel->CommitComposing(); _activeModel->EndComposing(); } else { replacedRange = range.location == NSNotFound ? flutter::TextRange(oldSelection.base(), oldSelection.extent()) : flutter::TextRange(range.location, range.location + range.length); } if (_enableDeltaModel) { [self updateEditStateWithDelta:flutter::TextEditingDelta(textBeforeChange, replacedRange, utf8String)]; } else { [self updateEditState]; } } - (void)doCommandBySelector:(SEL)selector { _eventProducedOutput |= selector != NSSelectorFromString(@"noop:"); if ([self respondsToSelector:selector]) { // Note: The more obvious [self performSelector...] doesn't give ARC enough information to // handle retain semantics properly. See https://stackoverflow.com/questions/7017281/ for more // information. IMP imp = [self methodForSelector:selector]; void (*func)(id, SEL, id) = reinterpret_cast<void (*)(id, SEL, id)>(imp); func(self, selector, nil); } if (selector == @selector(insertNewline:)) { // Already handled through text insertion (multiline) or action. return; } // Group multiple selectors received within a single run loop turn so that // the framework can process them in single microtask. NSString* name = NSStringFromSelector(selector); if (_pendingSelectors == nil) { _pendingSelectors = [NSMutableArray array]; } [_pendingSelectors addObject:name]; if (_pendingSelectors.count == 1) { __weak NSMutableArray* selectors = _pendingSelectors; __weak FlutterMethodChannel* channel = _channel; __weak NSNumber* clientID = self.clientID; CFStringRef runLoopMode = self.customRunLoopMode != nil ? (__bridge CFStringRef)self.customRunLoopMode : kCFRunLoopCommonModes; CFRunLoopPerformBlock(CFRunLoopGetMain(), runLoopMode, ^{ if (selectors.count > 0) { [channel invokeMethod:kPerformSelectors arguments:@[ clientID, selectors ]]; [selectors removeAllObjects]; } }); } } - (void)insertNewline:(id)sender { if (_activeModel == nullptr) { return; } if (_activeModel->composing()) { _activeModel->CommitComposing(); _activeModel->EndComposing(); } if ([self.inputType isEqualToString:kMultilineInputType] && [self.inputAction isEqualToString:kInputActionNewline]) { [self insertText:@"\n" replacementRange:self.selectedRange]; } [_channel invokeMethod:kPerformAction arguments:@[ self.clientID, self.inputAction ]]; } - (void)setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange { if (_activeModel == nullptr) { return; } std::string textBeforeChange = _activeModel->GetText().c_str(); if (!_activeModel->composing()) { _activeModel->BeginComposing(); } if (replacementRange.location != NSNotFound) { // According to the NSTextInputClient documentation replacementRange is // computed from the beginning of the marked text. That doesn't seem to be // the case, because in situations where the replacementRange is actually // specified (i.e. when switching between characters equivalent after long // key press) the replacementRange is provided while there is no composition. _activeModel->SetComposingRange( flutter::TextRange(replacementRange.location, replacementRange.location + replacementRange.length), 0); } flutter::TextRange composingBeforeChange = _activeModel->composing_range(); flutter::TextRange selectionBeforeChange = _activeModel->selection(); // Input string may be NSString or NSAttributedString. BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; const NSString* rawString = isAttributedString ? [string string] : string; _activeModel->UpdateComposingText( (const char16_t*)[rawString cStringUsingEncoding:NSUTF16StringEncoding], flutter::TextRange(selectedRange.location, selectedRange.location + selectedRange.length)); if (_enableDeltaModel) { std::string marked_text = [rawString UTF8String]; [self updateEditStateWithDelta:flutter::TextEditingDelta(textBeforeChange, selectionBeforeChange.collapsed() ? composingBeforeChange : selectionBeforeChange, marked_text)]; } else { [self updateEditState]; } } - (void)unmarkText { if (_activeModel == nullptr) { return; } _activeModel->CommitComposing(); _activeModel->EndComposing(); if (_enableDeltaModel) { [self updateEditStateWithDelta:flutter::TextEditingDelta(_activeModel->GetText().c_str())]; } else { [self updateEditState]; } } - (NSRange)markedRange { if (_activeModel == nullptr) { return NSMakeRange(NSNotFound, 0); } return NSMakeRange( _activeModel->composing_range().base(), _activeModel->composing_range().extent() - _activeModel->composing_range().base()); } - (BOOL)hasMarkedText { return _activeModel != nullptr && _activeModel->composing_range().length() > 0; } - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range actualRange:(NSRangePointer)actualRange { if (_activeModel == nullptr) { return nil; } if (actualRange != nil) { *actualRange = range; } NSString* text = [NSString stringWithUTF8String:_activeModel->GetText().c_str()]; NSString* substring = [text substringWithRange:range]; return [[NSAttributedString alloc] initWithString:substring attributes:nil]; } - (NSArray<NSString*>*)validAttributesForMarkedText { return @[]; } // Returns the bounding CGRect of the transformed incomingRect, in screen // coordinates. - (CGRect)screenRectFromFrameworkTransform:(CGRect)incomingRect { CGPoint points[] = { incomingRect.origin, CGPointMake(incomingRect.origin.x, incomingRect.origin.y + incomingRect.size.height), CGPointMake(incomingRect.origin.x + incomingRect.size.width, incomingRect.origin.y), CGPointMake(incomingRect.origin.x + incomingRect.size.width, incomingRect.origin.y + incomingRect.size.height)}; CGPoint origin = CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX); CGPoint farthest = CGPointMake(-CGFLOAT_MAX, -CGFLOAT_MAX); for (int i = 0; i < 4; i++) { const CGPoint point = points[i]; CGFloat x = _editableTransform.m11 * point.x + _editableTransform.m21 * point.y + _editableTransform.m41; CGFloat y = _editableTransform.m12 * point.x + _editableTransform.m22 * point.y + _editableTransform.m42; const CGFloat w = _editableTransform.m14 * point.x + _editableTransform.m24 * point.y + _editableTransform.m44; if (w == 0.0) { return CGRectZero; } else if (w != 1.0) { x /= w; y /= w; } origin.x = MIN(origin.x, x); origin.y = MIN(origin.y, y); farthest.x = MAX(farthest.x, x); farthest.y = MAX(farthest.y, y); } const NSView* fromView = self.flutterViewController.flutterView; const CGRect rectInWindow = [fromView convertRect:CGRectMake(origin.x, origin.y, farthest.x - origin.x, farthest.y - origin.y) toView:nil]; NSWindow* window = fromView.window; return window ? [window convertRectToScreen:rectInWindow] : rectInWindow; } - (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange { // This only determines position of caret instead of any arbitrary range, but it's enough // to properly position accent selection popup return !self.flutterViewController.viewLoaded || CGRectEqualToRect(_caretRect, CGRectNull) ? CGRectZero : [self screenRectFromFrameworkTransform:_caretRect]; } - (NSUInteger)characterIndexForPoint:(NSPoint)point { // TODO(cbracken): Implement. // Note: This function can't easily be implemented under the system-message architecture. return 0; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm", "repo_id": "engine", "token_count": 12098 }
341
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEW_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEW_H_ #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizer.h" #include <stdint.h> typedef int64_t FlutterViewId; /** * The view ID for APIs that don't support multi-view. * * Some single-view APIs will eventually be replaced by their multi-view * variant. During the deprecation period, the single-view APIs will coexist with * and work with the multi-view APIs as if the other views don't exist. For * backward compatibility, single-view APIs will always operate on the view with * this ID. Also, the first view assigned to the engine will also have this ID. */ constexpr FlutterViewId kFlutterImplicitViewId = 0ll; /** * Delegate for FlutterView. */ @protocol FlutterViewDelegate <NSObject> /** * Called when the view's backing store changes size. */ - (void)viewDidReshape:(nonnull NSView*)view; /** * Called to determine whether the view should accept first responder status. */ - (BOOL)viewShouldAcceptFirstResponder:(nonnull NSView*)view; @end /** * View capable of acting as a rendering target and input source for the Flutter * engine. */ @interface FlutterView : NSView /** * Initialize a FlutterView that will be rendered to using Metal rendering apis. */ - (nullable instancetype)initWithMTLDevice:(nonnull id<MTLDevice>)device commandQueue:(nonnull id<MTLCommandQueue>)commandQueue delegate:(nonnull id<FlutterViewDelegate>)delegate threadSynchronizer:(nonnull FlutterThreadSynchronizer*)threadSynchronizer viewId:(int64_t)viewId NS_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithFrame:(NSRect)frameRect pixelFormat:(nullable NSOpenGLPixelFormat*)format NS_UNAVAILABLE; - (nonnull instancetype)initWithFrame:(NSRect)frameRect NS_UNAVAILABLE; - (nullable instancetype)initWithCoder:(nonnull NSCoder*)coder NS_UNAVAILABLE; - (nonnull instancetype)init NS_UNAVAILABLE; /** * Returns SurfaceManager for this view. SurfaceManager is responsible for * providing and presenting render surfaces. */ @property(readonly, nonatomic, nonnull) FlutterSurfaceManager* surfaceManager; /** * By default, the `FlutterSurfaceManager` creates two layers to manage Flutter * content, the content layer and containing layer. To set the native background * color, onto which the Flutter content is drawn, call this method with the * NSColor which you would like to override the default, black background color * with. */ - (void)setBackgroundColor:(nonnull NSColor*)color; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEW_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterView.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterView.h", "repo_id": "engine", "token_count": 1060 }
342
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_TESTFLUTTERPLATFORMVIEW_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_TESTFLUTTERPLATFORMVIEW_H_ #import <Foundation/Foundation.h> #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" @interface TestFlutterPlatformView : NSView /// Arguments passed via the params value in the create method call. @property(nonatomic, copy) id args; @end @interface TestFlutterPlatformViewFactory : NSObject <FlutterPlatformViewFactory> @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_TESTFLUTTERPLATFORMVIEW_H_
engine/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.h", "repo_id": "engine", "token_count": 276 }
343
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/embedder_external_texture_metal.h" #include "flow/layers/layer.h" #include "flutter/fml/logging.h" #import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { static bool ValidNumTextures(int expected, int actual) { if (expected == actual) { return true; } else { FML_LOG(ERROR) << "Invalid number of textures, expected: " << expected << ", got: " << actual; return false; } } EmbedderExternalTextureMetal::EmbedderExternalTextureMetal(int64_t texture_identifier, const ExternalTextureCallback& callback) : Texture(texture_identifier), external_texture_callback_(callback) { FML_DCHECK(external_texture_callback_); } EmbedderExternalTextureMetal::~EmbedderExternalTextureMetal() = default; // |flutter::Texture| void EmbedderExternalTextureMetal::Paint(PaintContext& context, const SkRect& bounds, bool freeze, const DlImageSampling sampling) { if (last_image_ == nullptr) { last_image_ = ResolveTexture(Id(), context.gr_context, SkISize::Make(bounds.width(), bounds.height())); } DlCanvas* canvas = context.canvas; const DlPaint* paint = context.paint; if (last_image_) { SkRect image_bounds = SkRect::Make(last_image_->bounds()); if (bounds != image_bounds) { canvas->DrawImageRect(last_image_, image_bounds, bounds, sampling, paint); } else { canvas->DrawImage(last_image_, {bounds.x(), bounds.y()}, sampling, paint); } } } sk_sp<DlImage> EmbedderExternalTextureMetal::ResolveTexture(int64_t texture_id, GrDirectContext* context, const SkISize& size) { std::unique_ptr<FlutterMetalExternalTexture> texture = external_texture_callback_(texture_id, size.width(), size.height()); if (!texture) { return nullptr; } sk_sp<SkImage> image; switch (texture->pixel_format) { case FlutterMetalExternalTexturePixelFormat::kRGBA: { if (ValidNumTextures(1, texture->num_textures)) { id<MTLTexture> rgbaTex = (__bridge id<MTLTexture>)texture->textures[0]; image = [FlutterDarwinExternalTextureSkImageWrapper wrapRGBATexture:rgbaTex grContext:context width:size.width() height:size.height()]; } break; } case FlutterMetalExternalTexturePixelFormat::kYUVA: { if (ValidNumTextures(2, texture->num_textures)) { id<MTLTexture> yTex = (__bridge id<MTLTexture>)texture->textures[0]; id<MTLTexture> uvTex = (__bridge id<MTLTexture>)texture->textures[1]; SkYUVColorSpace colorSpace = texture->yuv_color_space == FlutterMetalExternalTextureYUVColorSpace::kBT601LimitedRange ? kRec601_Limited_SkYUVColorSpace : kJPEG_Full_SkYUVColorSpace; image = [FlutterDarwinExternalTextureSkImageWrapper wrapYUVATexture:yTex UVTex:uvTex YUVColorSpace:colorSpace grContext:context width:size.width() height:size.height()]; } break; } } if (!image) { FML_LOG(ERROR) << "Could not create external texture: " << texture_id; } // This image should not escape local use by EmbedderExternalTextureMetal return DlImage::Make(std::move(image)); } // |flutter::Texture| void EmbedderExternalTextureMetal::OnGrContextCreated() {} // |flutter::Texture| void EmbedderExternalTextureMetal::OnGrContextDestroyed() {} // |flutter::Texture| void EmbedderExternalTextureMetal::MarkNewFrameAvailable() { last_image_ = nullptr; } // |flutter::Texture| void EmbedderExternalTextureMetal::OnTextureUnregistered() {} } // namespace flutter
engine/shell/platform/embedder/embedder_external_texture_metal.mm/0
{ "file_path": "engine/shell/platform/embedder/embedder_external_texture_metal.mm", "repo_id": "engine", "token_count": 2232 }
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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_CACHE_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_CACHE_H_ #include <set> #include <stack> #include <tuple> #include <unordered_map> #include "flutter/fml/macros.h" #include "flutter/shell/platform/embedder/embedder_external_view.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief A cache used to reference render targets that are owned by the /// embedder but needed by th engine to render a frame. /// class EmbedderRenderTargetCache { public: EmbedderRenderTargetCache(); ~EmbedderRenderTargetCache(); std::unique_ptr<EmbedderRenderTarget> GetRenderTarget( const EmbedderExternalView::RenderTargetDescriptor& descriptor); std::set<std::unique_ptr<EmbedderRenderTarget>> ClearAllRenderTargetsInCache(); void CacheRenderTarget(std::unique_ptr<EmbedderRenderTarget> target); size_t GetCachedTargetsCount() const; private: using CachedRenderTargets = std::unordered_multimap< EmbedderExternalView::RenderTargetDescriptor, std::unique_ptr<EmbedderRenderTarget>, EmbedderExternalView::RenderTargetDescriptor::Hash, EmbedderExternalView::RenderTargetDescriptor::Equal>; CachedRenderTargets cached_render_targets_; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderRenderTargetCache); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_CACHE_H_
engine/shell/platform/embedder/embedder_render_target_cache.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_render_target_cache.h", "repo_id": "engine", "token_count": 573 }
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_EMBEDDER_EMBEDDER_SURFACE_METAL_IMPELLER_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_METAL_IMPELLER_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/shell/gpu/gpu_surface_metal_delegate.h" #include "flutter/shell/gpu/gpu_surface_metal_skia.h" #include "flutter/shell/platform/embedder/embedder_external_view_embedder.h" #include "flutter/shell/platform/embedder/embedder_surface.h" #include "fml/concurrent_message_loop.h" namespace impeller { class Context; } namespace flutter { class EmbedderSurfaceMetalImpeller final : public EmbedderSurface, public GPUSurfaceMetalDelegate { public: struct MetalDispatchTable { std::function<bool(GPUMTLTextureInfo texture)> present; // required std::function<GPUMTLTextureInfo(const SkISize& frame_size)> get_texture; // required }; EmbedderSurfaceMetalImpeller( GPUMTLDeviceHandle device, GPUMTLCommandQueueHandle command_queue, MetalDispatchTable dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder); ~EmbedderSurfaceMetalImpeller() override; private: bool valid_ = false; MetalDispatchTable metal_dispatch_table_; std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder_; std::shared_ptr<impeller::Context> context_; // |EmbedderSurface| bool IsValid() const override; // |EmbedderSurface| std::unique_ptr<Surface> CreateGPUSurface() override; // |GPUSurfaceMetalDelegate| GPUCAMetalLayerHandle GetCAMetalLayer( const SkISize& frame_size) const override; // |GPUSurfaceMetalDelegate| bool PresentDrawable(GrMTLHandle drawable) const override; // |GPUSurfaceMetalDelegate| GPUMTLTextureInfo GetMTLTexture(const SkISize& frame_size) const override; // |GPUSurfaceMetalDelegate| bool PresentTexture(GPUMTLTextureInfo texture) const override; // |EmbedderSurface| std::shared_ptr<impeller::Context> CreateImpellerContext() const override; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderSurfaceMetalImpeller); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_METAL_IMPELLER_H_
engine/shell/platform/embedder/embedder_surface_metal_impeller.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_surface_metal_impeller.h", "repo_id": "engine", "token_count": 878 }
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. #include "flutter/shell/platform/embedder/tests/embedder_test.h" #include "flutter/shell/platform/embedder/tests/embedder_test_context_software.h" #ifdef SHELL_ENABLE_GL #include "flutter/shell/platform/embedder/tests/embedder_test_context_gl.h" #endif #ifdef SHELL_ENABLE_METAL #include "flutter/shell/platform/embedder/tests/embedder_test_context_metal.h" #endif #ifdef SHELL_ENABLE_VULKAN #include "flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.h" #endif namespace flutter { namespace testing { EmbedderTest::EmbedderTest() = default; std::string EmbedderTest::GetFixturesDirectory() const { return GetFixturesPath(); } EmbedderTestContext& EmbedderTest::GetEmbedderContext( EmbedderTestContextType type) { // Setup the embedder context lazily instead of in the constructor because we // don't to do all the work if the test won't end up using context. if (!embedder_contexts_[type]) { switch (type) { case EmbedderTestContextType::kSoftwareContext: embedder_contexts_[type] = std::make_unique<EmbedderTestContextSoftware>( GetFixturesDirectory()); break; #ifdef SHELL_ENABLE_VULKAN case EmbedderTestContextType::kVulkanContext: embedder_contexts_[type] = std::make_unique<EmbedderTestContextVulkan>(GetFixturesDirectory()); break; #endif #ifdef SHELL_ENABLE_GL case EmbedderTestContextType::kOpenGLContext: embedder_contexts_[type] = std::make_unique<EmbedderTestContextGL>(GetFixturesDirectory()); break; #endif #ifdef SHELL_ENABLE_METAL case EmbedderTestContextType::kMetalContext: embedder_contexts_[type] = std::make_unique<EmbedderTestContextMetal>(GetFixturesDirectory()); break; #endif default: FML_DCHECK(false) << "Invalid context type specified."; break; } } return *embedder_contexts_[type]; } } // namespace testing } // namespace flutter
engine/shell/platform/embedder/tests/embedder_test.cc/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test.cc", "repo_id": "engine", "token_count": 816 }
347
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/tests/embedder_test_context_gl.h" #include <utility> #include "flutter/fml/make_copyable.h" #include "flutter/fml/paths.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/platform/embedder/tests/embedder_assertions.h" #include "flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.h" #include "flutter/testing/testing.h" #include "tests/embedder_test.h" #include "third_party/dart/runtime/bin/elf_loader.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { namespace testing { EmbedderTestContextGL::EmbedderTestContextGL(std::string assets_path) : EmbedderTestContext(std::move(assets_path)) {} EmbedderTestContextGL::~EmbedderTestContextGL() { SetGLGetFBOCallback(nullptr); } void EmbedderTestContextGL::SetupSurface(SkISize surface_size) { FML_CHECK(!gl_surface_); gl_surface_ = std::make_unique<TestGLSurface>(surface_size); } bool EmbedderTestContextGL::GLMakeCurrent() { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->MakeCurrent(); } bool EmbedderTestContextGL::GLClearCurrent() { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->ClearCurrent(); } bool EmbedderTestContextGL::GLPresent(FlutterPresentInfo present_info) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; gl_surface_present_count_++; GLPresentCallback callback; { std::scoped_lock lock(gl_callback_mutex_); callback = gl_present_callback_; } if (callback) { callback(present_info); } FireRootSurfacePresentCallbackIfPresent( [&]() { return gl_surface_->GetRasterSurfaceSnapshot(); }); return gl_surface_->Present(); } void EmbedderTestContextGL::SetGLGetFBOCallback(GLGetFBOCallback callback) { std::scoped_lock lock(gl_callback_mutex_); gl_get_fbo_callback_ = std::move(callback); } void EmbedderTestContextGL::SetGLPopulateExistingDamageCallback( GLPopulateExistingDamageCallback callback) { std::scoped_lock lock(gl_callback_mutex_); gl_populate_existing_damage_callback_ = std::move(callback); } void EmbedderTestContextGL::SetGLPresentCallback(GLPresentCallback callback) { std::scoped_lock lock(gl_callback_mutex_); gl_present_callback_ = std::move(callback); } uint32_t EmbedderTestContextGL::GLGetFramebuffer(FlutterFrameInfo frame_info) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; GLGetFBOCallback callback; { std::scoped_lock lock(gl_callback_mutex_); callback = gl_get_fbo_callback_; } if (callback) { callback(frame_info); } const auto size = frame_info.size; return gl_surface_->GetFramebuffer(size.width, size.height); } void EmbedderTestContextGL::GLPopulateExistingDamage( const intptr_t id, FlutterDamage* existing_damage) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; GLPopulateExistingDamageCallback callback; { std::scoped_lock lock(gl_callback_mutex_); callback = gl_populate_existing_damage_callback_; } if (callback) { callback(id, existing_damage); } } bool EmbedderTestContextGL::GLMakeResourceCurrent() { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->MakeResourceCurrent(); } void* EmbedderTestContextGL::GLGetProcAddress(const char* name) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->GetProcAddress(name); } size_t EmbedderTestContextGL::GetSurfacePresentCount() const { return gl_surface_present_count_; } EmbedderTestContextType EmbedderTestContextGL::GetContextType() const { return EmbedderTestContextType::kOpenGLContext; } uint32_t EmbedderTestContextGL::GetWindowFBOId() const { FML_CHECK(gl_surface_); return gl_surface_->GetWindowFBOId(); } void EmbedderTestContextGL::SetupCompositor() { FML_CHECK(!compositor_) << "Already set up a compositor in this context."; FML_CHECK(gl_surface_) << "Set up the GL surface before setting up a compositor."; compositor_ = std::make_unique<EmbedderTestCompositorGL>( gl_surface_->GetSurfaceSize(), gl_surface_->GetGrContext()); GLClearCurrent(); } } // namespace testing } // namespace flutter
engine/shell/platform/embedder/tests/embedder_test_context_gl.cc/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_context_gl.cc", "repo_id": "engine", "token_count": 1515 }
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. import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") config("sdk_ext_config") { include_dirs = [ "../.." ] } group("fuchsia") { public_deps = [ ":sdk_ext" ] } source_set("sdk_ext") { sources = [ "sdk_ext/fuchsia.cc", "sdk_ext/fuchsia.h", ] deps = [ "${fuchsia_sdk}/pkg/async-cpp", "../zircon", "//flutter/fml", "//flutter/third_party/tonic", ] public_deps = [ "${fuchsia_sdk}/pkg/zx" ] public_configs = [ ":sdk_ext_config" ] }
engine/shell/platform/fuchsia/dart-pkg/fuchsia/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/fuchsia/BUILD.gn", "repo_id": "engine", "token_count": 286 }
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. part of zircon; @pragma('vm:entry-point') class ZDHandle { @pragma('vm:entry-point') ZDHandle._(this._ptr) { _attachFinalizer(); } void _attachFinalizer() { // TODO (kaushikiska): fix external allocation size. final int? ret = zirconFFIBindings?.zircon_dart_handle_attach_finalizer( this, _ptr.cast(), 128); if (ret != 1) { throw Exception('Unable to attach finalizer to handle'); } } int get handle => _ptr.ref.handle; final Pointer<zircon_dart_handle_t> _ptr; bool isValid() { int? ret = zirconFFIBindings?.zircon_dart_handle_is_valid(_ptr); return ret == 1; } bool close() { assert(isValid()); if (isValid()) { int? ret = zirconFFIBindings?.zircon_dart_handle_close(_ptr); return ret == 1; } return false; } @override bool operator ==(Object other) { return other is ZDHandle && other.handle == handle; } @override int get hashCode => handle.hashCode; @override String toString() => 'ZDHandle(handle=$handle)'; } @pragma('vm:entry-point') class ZDHandlePair { @pragma('vm:entry-point') ZDHandlePair._(this._ptr) : left = ZDHandle._(_ptr.ref.left), right = ZDHandle._(_ptr.ref.right) { _attachFinalizer(); } void _attachFinalizer() { // TODO (kaushikiska): fix external allocation size. final int? ret = zirconFFIBindings ?.zircon_dart_handle_pair_attach_finalizer(this, _ptr.cast(), 128); if (ret != 1) { throw Exception('Unable to attach finalizer to handle'); } } final Pointer<zircon_dart_handle_pair_t> _ptr; final ZDHandle left; final ZDHandle right; @override String toString() => 'ZDHandlePair(left=$left, right=$right)'; }
engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_handle.dart/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_handle.dart", "repo_id": "engine", "token_count": 747 }
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 "basic_types.h" #include <cstdint> #include <cstdlib> #include "flutter/fml/logging.h" zircon_dart_byte_array_t* zircon_dart_byte_array_create(uint32_t size) { zircon_dart_byte_array_t* arr = static_cast<zircon_dart_byte_array_t*>( malloc(sizeof(zircon_dart_byte_array_t))); arr->length = size; arr->data = static_cast<uint8_t*>(malloc(size * sizeof(uint8_t))); return arr; } void zircon_dart_byte_array_set_value(zircon_dart_byte_array_t* arr, uint32_t index, uint8_t value) { FML_CHECK(arr); FML_CHECK(arr->length > index); arr->data[index] = value; } void zircon_dart_byte_array_free(zircon_dart_byte_array_t* arr) { FML_CHECK(arr); free(arr->data); free(arr); }
engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.cc", "repo_id": "engine", "token_count": 435 }
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. assert(is_fuchsia) import("//flutter/common/fuchsia_config.gni") import("//flutter/testing/testing.gni") import("//flutter/tools/fuchsia/dart.gni") import("//flutter/tools/fuchsia/fuchsia_archive.gni") import("//flutter/tools/fuchsia/fuchsia_libs.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") template("runner_sources") { assert(defined(invoker.product), "runner_sources must define product") source_set(target_name) { forward_variables_from(invoker, [ "defines" ]) sources = [ "builtin_libraries.cc", "builtin_libraries.h", "dart_component_controller.cc", "dart_component_controller.h", "dart_runner.cc", "dart_runner.h", "dart_test_component_controller.cc", "dart_test_component_controller.h", "logging.h", "service_isolate.cc", "service_isolate.h", ] dart_public_deps = [] if (!invoker.product) { dart_public_deps += [ "$dart_src/runtime/bin:dart_io_api", "//flutter/shell/platform/fuchsia/runtime/dart/utils:utils", ] } else { dart_public_deps += [ "$dart_src/runtime/bin:dart_io_api_product", "//flutter/shell/platform/fuchsia/runtime/dart/utils:utils_product", ] } public_deps = [ "${fuchsia_sdk}/fidl/fuchsia.component.runner", "${fuchsia_sdk}/fidl/fuchsia.test", "${fuchsia_sdk}/pkg/sys_cpp", "//flutter/fml", ] + dart_public_deps deps = [ "${fuchsia_sdk}/fidl/fuchsia.logger", "${fuchsia_sdk}/pkg/async", "${fuchsia_sdk}/pkg/async-cpp", "${fuchsia_sdk}/pkg/async-default", "${fuchsia_sdk}/pkg/async-loop", "${fuchsia_sdk}/pkg/async-loop-cpp", "${fuchsia_sdk}/pkg/async-loop-default", "${fuchsia_sdk}/pkg/fidl_cpp", "${fuchsia_sdk}/pkg/inspect", "${fuchsia_sdk}/pkg/inspect_component_cpp", "${fuchsia_sdk}/pkg/sys_cpp", "${fuchsia_sdk}/pkg/sys_cpp_testing", "${fuchsia_sdk}/pkg/trace", "${fuchsia_sdk}/pkg/vfs_cpp", "${fuchsia_sdk}/pkg/zx", "fidl:dart_test", "//flutter/common", "//flutter/shell/platform/fuchsia/dart-pkg/fuchsia", "//flutter/shell/platform/fuchsia/dart-pkg/zircon", "//flutter/third_party/tonic", ] } } template("runner") { assert(defined(invoker.product), "The parameter 'product' must be defined.") assert(defined(invoker.output_name), "The parameter 'output_name' must be defined") invoker_output_name = invoker.output_name extra_defines = invoker.extra_defines extra_deps = invoker.extra_deps if (is_debug) { extra_defines += [ "DEBUG" ] # Needed due to direct dart dependencies. } runner_sources(target_name + "_runner_sources") { product = invoker.product defines = extra_defines } executable(target_name) { output_name = invoker_output_name sources = [ "main.cc" ] defines = extra_defines deps = [ ":" + target_name + "_runner_sources", "${fuchsia_sdk}/pkg/inspect_component_cpp", "${fuchsia_sdk}/pkg/trace-provider-so", ] + extra_deps } } runner("dart_jit_runner_bin") { output_name = "dart_jit_runner" product = false extra_defines = [] if (flutter_runtime_mode == "profile") { extra_defines += [ "FLUTTER_PROFILE" ] } extra_deps = [ "$dart_src/runtime:libdart_jit", "$dart_src/runtime/platform:libdart_platform_jit", ] } runner("dart_jit_product_runner_bin") { output_name = "dart_jit_product_runner" product = true extra_defines = [ "DART_PRODUCT" ] extra_deps = [ "$dart_src/runtime:libdart_jit", "$dart_src/runtime/platform:libdart_platform_jit", ] } runner("dart_aot_runner_bin") { output_name = "dart_aot_runner" product = false extra_defines = [ "AOT_RUNTIME" ] if (flutter_runtime_mode == "profile") { extra_defines += [ "FLUTTER_PROFILE" ] } extra_deps = [ "$dart_src/runtime:libdart_precompiled_runtime", "$dart_src/runtime/platform:libdart_platform_precompiled_runtime", "embedder:dart_aot_snapshot_cc", ] } runner("dart_aot_product_runner_bin") { output_name = "dart_aot_product_runner" product = true extra_defines = [ "AOT_RUNTIME", "DART_PRODUCT", ] extra_deps = [ "$dart_src/runtime:libdart_precompiled_runtime", "$dart_src/runtime/platform:libdart_platform_precompiled_runtime", "embedder:dart_aot_product_snapshot_cc", ] } template("aot_runner_package") { assert(defined(invoker.product), "The parameter 'product' must be defined") product_suffix = "" if (invoker.product) { product_suffix = "_product" } fuchsia_archive(target_name) { deps = [ ":dart_aot${product_suffix}_runner_bin" ] if (!invoker.product) { deps += [ "vmservice:vmservice_snapshot", "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:dart_aot_runner", # TODO(kaushikiska): Figure out how to get the profiler symbols for `libdart_precompiled_runtime` # "$dart_src/runtime:libdart_precompiled_runtime", observatory_target, ] } binary = "dart_aot${product_suffix}_runner" cml_file = rebase_path("meta/dart_aot${product_suffix}_runner.cml") libraries = common_libs resources = [] if (!invoker.product) { vmservice_snapshot = rebase_path( get_label_info("vmservice:vmservice_snapshot", "target_gen_dir") + "/vmservice_snapshot.so") dart_profiler_symbols = rebase_path( get_label_info( "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:dart_aot_runner", "target_gen_dir") + "/dart_aot_runner.dartprofilersymbols") inputs = [ vmservice_snapshot, observatory_archive_file, dart_profiler_symbols, ] resources += [ { path = vmservice_snapshot dest = "vmservice_snapshot.so" }, { path = rebase_path(observatory_archive_file) dest = "observatory.tar" }, { path = dart_profiler_symbols dest = "dart_aot_runner.dartprofilersymbols" }, ] } } } template("jit_runner_package") { assert(defined(invoker.product), "The parameter 'product' must be defined") product_suffix = "" if (invoker.product) { product_suffix = "_product" } fuchsia_archive(target_name) { deps = [ ":dart_jit${product_suffix}_runner_bin", "kernel:kernel_core_snapshot${product_suffix}", ] if (!invoker.product) { deps += [ "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:dart_jit_runner", observatory_target, ] } binary = "dart_jit${product_suffix}_runner" cml_file = rebase_path("meta/dart_jit${product_suffix}_runner.cml") libraries = common_libs resources = [ { path = rebase_path("$target_gen_dir/kernel/vm_data${product_suffix}.bin") dest = "vm_snapshot_data.bin" }, { path = rebase_path( "$target_gen_dir/kernel/isolate_data${product_suffix}.bin") dest = "isolate_core_snapshot_data.bin" }, ] if (!invoker.product) { resources += [ { path = rebase_path(observatory_archive_file) dest = "observatory.tar" }, { path = rebase_path( get_label_info( "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:dart_jit_runner", "target_gen_dir") + "/dart_jit_runner.dartprofilersymbols") dest = "dart_jit_runner.dartprofilersymbols" }, ] } } } aot_runner_package("dart_aot_runner") { product = false } aot_runner_package("dart_aot_product_runner") { product = true } jit_runner_package("dart_jit_runner") { product = false } jit_runner_package("dart_jit_product_runner") { product = true } # "OOT" copy of the runner used by tests, to avoid conflicting with the runner # in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. aot_runner_package("oot_dart_aot_runner") { product = false } # "OOT" copy of the runner used by tests, to avoid conflicting with the runner # in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. jit_runner_package("oot_dart_jit_runner") { product = false } if (enable_unittests) { runner_sources("jit_runner_sources_for_test") { product = false } executable("dart_test_runner_unittests") { testonly = true output_name = "dart_runner_tests" sources = [ "tests/suite_impl_unittests.cc" ] # This is needed for //flutter/third_party/googletest for linking zircon # symbols. libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] deps = [ ":jit_runner_sources_for_test", "$dart_src/runtime:libdart_jit", "$dart_src/runtime/platform:libdart_platform_jit", "//flutter/fml", "//flutter/third_party/googletest:gtest_main", ] } fuchsia_test_archive("dart_runner_tests") { deps = [ ":dart_test_runner_unittests" ] binary = "$target_name" } # When adding a new dep here, please also ensure the dep is added to # testing/fuchsia/test_suites.yaml. group("tests") { testonly = true deps = [ ":dart_runner_tests", "tests/startup_integration_test", ] } }
engine/shell/platform/fuchsia/dart_runner/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/BUILD.gn", "repo_id": "engine", "token_count": 4471 }
352
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_EMBEDDER_SNAPSHOT_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_EMBEDDER_SNAPSHOT_H_ #include <cstdint> namespace dart_runner { extern uint8_t const* const vm_isolate_snapshot_buffer; extern uint8_t const* const isolate_snapshot_buffer; } // namespace dart_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_EMBEDDER_SNAPSHOT_H_
engine/shell/platform/fuchsia/dart_runner/embedder/snapshot.h/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/embedder/snapshot.h", "repo_id": "engine", "token_count": 225 }
353
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "engine.h" #include <fuchsia/accessibility/semantics/cpp/fidl.h> #include <fuchsia/media/cpp/fidl.h> #include <lib/async/cpp/task.h> #include <lib/zx/eventpair.h> #include <lib/zx/thread.h> #include <zircon/rights.h> #include <zircon/status.h> #include <zircon/types.h> #include <memory> #include "flutter/common/graphics/persistent_cache.h" #include "flutter/common/task_runners.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/fml/task_runner.h" #include "flutter/runtime/dart_vm_lifecycle.h" #include "flutter/shell/common/rasterizer.h" #include "flutter/shell/common/run_configuration.h" #include "flutter/shell/common/serialization_callbacks.h" #include "flutter/shell/common/thread_host.h" #include "third_party/skia/include/core/SkPicture.h" #include "third_party/skia/include/core/SkSerialProcs.h" #include "third_party/skia/include/gpu/GrTypes.h" #include "third_party/skia/include/ports/SkFontMgr_fuchsia.h" #include "../runtime/dart/utils/files.h" #include "../runtime/dart/utils/root_inspect_node.h" #include "focus_delegate.h" #include "fuchsia_intl.h" #include "platform_view.h" #include "software_surface_producer.h" #include "surface.h" #include "vsync_waiter.h" #include "vulkan_surface_producer.h" namespace flutter_runner { namespace { zx_koid_t GetKoid(const fuchsia::ui::views::ViewRef& view_ref) { zx_handle_t handle = view_ref.reference.get(); zx_info_handle_basic_t info; zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); return status == ZX_OK ? info.koid : ZX_KOID_INVALID; } std::unique_ptr<flutter::PlatformMessage> MakeLocalizationPlatformMessage( const fuchsia::intl::Profile& intl_profile) { return std::make_unique<flutter::PlatformMessage>( "flutter/localization", MakeLocalizationPlatformMessageData(intl_profile), nullptr); } // // Fuchsia scheduler role naming scheme employed here: // // Roles based on thread function: // <prefix>.type.{platform,ui,raster,io,profiler} // // Roles based on fml::Thread::ThreadPriority: // <prefix>.thread.{background,display,raster,normal} // void SetThreadRole( const fuchsia::media::ProfileProviderSyncPtr& profile_provider, const std::string& role) { ZX_ASSERT(profile_provider); zx::thread dup; const zx_status_t dup_status = zx::thread::self()->duplicate(ZX_RIGHT_SAME_RIGHTS, &dup); if (dup_status != ZX_OK) { FML_LOG(WARNING) << "Failed to duplicate thread handle when setting thread config: " << zx_status_get_string(dup_status) << ". Thread will run at default priority."; return; } int64_t unused_period; int64_t unused_capacity; const zx_status_t status = profile_provider->RegisterHandlerWithCapacity( std::move(dup), role, 0, 0.f, &unused_period, &unused_capacity); if (status != ZX_OK) { FML_LOG(WARNING) << "Failed to set thread role to \"" << role << "\": " << zx_status_get_string(status) << ". Thread will run at default priority."; return; } } void SetThreadConfig( const std::string& name_prefix, const fuchsia::media::ProfileProviderSyncPtr& profile_provider, const fml::Thread::ThreadConfig& config) { ZX_ASSERT(profile_provider); fml::Thread::SetCurrentThreadName(config); // Derive the role name from the prefix and priority. See comment above about // the role naming scheme. std::string role; switch (config.priority) { case fml::Thread::ThreadPriority::kBackground: role = name_prefix + ".thread.background"; break; case fml::Thread::ThreadPriority::kDisplay: role = name_prefix + ".thread.display"; break; case fml::Thread::ThreadPriority::kRaster: role = name_prefix + ".thread.raster"; break; case fml::Thread::ThreadPriority::kNormal: role = name_prefix + ".thread.normal"; break; default: FML_LOG(WARNING) << "Unknown thread priority " << static_cast<int>(config.priority) << ". Thread will run at default priority."; return; } ZX_ASSERT(!role.empty()); SetThreadRole(profile_provider, role); } } // namespace flutter::ThreadHost Engine::CreateThreadHost( const std::string& name_prefix, const std::shared_ptr<sys::ServiceDirectory>& services) { fml::Thread::SetCurrentThreadName( fml::Thread::ThreadConfig(name_prefix + ".platform")); // Default the config setter to setup the thread name only. flutter::ThreadConfigSetter config_setter = fml::Thread::SetCurrentThreadName; // Override the config setter if the media profile provider is available. if (services) { // Connect to the media profile provider to assign thread priorities using // Fuchsia's scheduler role API. Failure to connect will print a warning and // proceed with engine initialization, leaving threads created by the engine // at default priority. // // The use of std::shared_ptr here is to work around the unfortunate // requirement for flutter::ThreadConfigSetter (i.e. std::function<>) that // the target callable be copy-constructible. This awkwardly conflicts with // fuchsia::media::ProfileProviderSyncPtr being move-only. std::shared_ptr // provides copyable object that references the move-only SyncPtr. std::shared_ptr<fuchsia::media::ProfileProviderSyncPtr> media_profile_provider = std::make_shared<fuchsia::media::ProfileProviderSyncPtr>(); const zx_status_t connect_status = services->Connect(media_profile_provider->NewRequest()); if (connect_status != ZX_OK) { FML_LOG(WARNING) << "Failed to connect to " << fuchsia::media::ProfileProvider::Name_ << ": " << zx_status_get_string(connect_status) << " This is not a fatal error, but threads created by the engine " "will run at default priority, regardless of the requested " "priority."; } else { // Set the role for (this) platform thread. See comment above about the // role naming scheme. SetThreadRole(*media_profile_provider, name_prefix + ".type.platform"); // This lambda must be copyable or the assignment fails to compile, // necessitating the use of std::shared_ptr for the profile provider. config_setter = [name_prefix, media_profile_provider]( const fml::Thread::ThreadConfig& config) { SetThreadConfig(name_prefix, *media_profile_provider, config); }; } } flutter::ThreadHost::ThreadHostConfig thread_host_config{config_setter}; thread_host_config.SetRasterConfig( {flutter::ThreadHost::ThreadHostConfig::MakeThreadName( flutter::ThreadHost::Type::kRaster, name_prefix), fml::Thread::ThreadPriority::kRaster}); thread_host_config.SetUIConfig( {flutter::ThreadHost::ThreadHostConfig::MakeThreadName( flutter::ThreadHost::Type::kUi, name_prefix), fml::Thread::ThreadPriority::kDisplay}); thread_host_config.SetIOConfig( {flutter::ThreadHost::ThreadHostConfig::MakeThreadName( flutter::ThreadHost::Type::kIo, name_prefix), fml::Thread::ThreadPriority::kNormal}); return flutter::ThreadHost(thread_host_config); } Engine::Engine(Delegate& delegate, std::string thread_label, std::shared_ptr<sys::ServiceDirectory> svc, std::shared_ptr<sys::ServiceDirectory> runner_services, flutter::Settings settings, fuchsia::ui::views::ViewCreationToken view_creation_token, std::pair<fuchsia::ui::views::ViewRefControl, fuchsia::ui::views::ViewRef> view_ref_pair, UniqueFDIONS fdio_ns, fidl::InterfaceRequest<fuchsia::io::Directory> directory_request, FlutterRunnerProductConfiguration product_config, const std::vector<std::string>& dart_entrypoint_args) : delegate_(delegate), thread_label_(std::move(thread_label)), thread_host_(CreateThreadHost(thread_label_, runner_services)), view_creation_token_(std::move(view_creation_token)), memory_pressure_watcher_binding_(this), latest_memory_pressure_level_(fuchsia::memorypressure::Level::NORMAL), intercept_all_input_(product_config.get_intercept_all_input()), weak_factory_(this) { Initialize(std::move(view_ref_pair), std::move(svc), std::move(runner_services), std::move(settings), std::move(fdio_ns), std::move(directory_request), std::move(product_config), dart_entrypoint_args); } void Engine::Initialize( std::pair<fuchsia::ui::views::ViewRefControl, fuchsia::ui::views::ViewRef> view_ref_pair, std::shared_ptr<sys::ServiceDirectory> svc, std::shared_ptr<sys::ServiceDirectory> runner_services, flutter::Settings settings, UniqueFDIONS fdio_ns, fidl::InterfaceRequest<fuchsia::io::Directory> directory_request, FlutterRunnerProductConfiguration product_config, const std::vector<std::string>& dart_entrypoint_args) { // Flatland uses |view_creation_token_| for linking. FML_CHECK(view_creation_token_.value.is_valid()); // Get the task runners from the managed threads. The current thread will be // used as the "platform" thread. fml::RefPtr<fml::TaskRunner> platform_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); const flutter::TaskRunners task_runners( thread_label_, // Dart thread labels platform_task_runner, // platform thread_host_.raster_thread->GetTaskRunner(), // raster thread_host_.ui_thread->GetTaskRunner(), // ui thread_host_.io_thread->GetTaskRunner() // io ); fuchsia::ui::views::FocuserHandle focuser; fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused; fuchsia::ui::pointer::TouchSourceHandle touch_source; fuchsia::ui::pointer::MouseSourceHandle mouse_source; fuchsia::ui::composition::ViewBoundProtocols view_protocols; view_protocols.set_view_focuser(focuser.NewRequest()); view_protocols.set_view_ref_focused(view_ref_focused.NewRequest()); view_protocols.set_touch_source(touch_source.NewRequest()); view_protocols.set_mouse_source(mouse_source.NewRequest()); // Connect to Flatland. fuchsia::ui::composition::FlatlandHandle flatland; zx_status_t flatland_status = runner_services->Connect<fuchsia::ui::composition::Flatland>( flatland.NewRequest()); if (flatland_status != ZX_OK) { FML_LOG(WARNING) << "fuchsia::ui::composition::Flatland connection failed: " << zx_status_get_string(flatland_status); } // Connect to SemanticsManager service. fuchsia::accessibility::semantics::SemanticsManagerHandle semantics_manager; zx_status_t semantics_status = runner_services ->Connect<fuchsia::accessibility::semantics::SemanticsManager>( semantics_manager.NewRequest()); if (semantics_status != ZX_OK) { FML_LOG(WARNING) << "fuchsia::accessibility::semantics::SemanticsManager connection " "failed: " << zx_status_get_string(semantics_status); } // Connect to ImeService service. fuchsia::ui::input::ImeServiceHandle ime_service; zx_status_t ime_status = runner_services->Connect<fuchsia::ui::input::ImeService>( ime_service.NewRequest()); if (ime_status != ZX_OK) { FML_LOG(WARNING) << "fuchsia::ui::input::ImeService connection failed: " << zx_status_get_string(ime_status); } // Connect to Keyboard service. fuchsia::ui::input3::KeyboardHandle keyboard; zx_status_t keyboard_status = runner_services->Connect<fuchsia::ui::input3::Keyboard>( keyboard.NewRequest()); FML_DCHECK(keyboard_status == ZX_OK) << "fuchsia::ui::input3::Keyboard connection failed: " << zx_status_get_string(keyboard_status); // Connect to Pointerinjector service. fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry; zx_status_t pointerinjector_registry_status = runner_services->Connect<fuchsia::ui::pointerinjector::Registry>( pointerinjector_registry.NewRequest()); if (pointerinjector_registry_status != ZX_OK) { FML_LOG(WARNING) << "fuchsia::ui::pointerinjector::Registry connection failed: " << zx_status_get_string(pointerinjector_registry_status); } // Make clones of the `ViewRef` before sending it to various places. fuchsia::ui::views::ViewRef platform_view_ref; view_ref_pair.second.Clone(&platform_view_ref); fuchsia::ui::views::ViewRef accessibility_view_ref; view_ref_pair.second.Clone(&accessibility_view_ref); fuchsia::ui::views::ViewRef isolate_view_ref; view_ref_pair.second.Clone(&isolate_view_ref); // Session is terminated on the raster thread, but we must terminate ourselves // on the platform thread. // // This handles the fidl error callback when the Session connection is // broken. The SessionListener interface also has an OnError method, which is // invoked on the platform thread (in PlatformView). fml::closure session_error_callback = [task_runner = platform_task_runner, weak = weak_factory_.GetWeakPtr()]() { task_runner->PostTask([weak]() { if (weak) { FML_LOG(ERROR) << "Terminating from session_error_callback"; weak->Terminate(); } }); }; // Set up the session connection and other Scenic helpers on the raster // thread. We also need to wait for the external view embedder to be set up // before creating the shell. fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; fml::AutoResetWaitableEvent view_embedder_latch; auto session_inspect_node = dart_utils::RootInspectNode::CreateRootChild("vsync_stats"); task_runners.GetRasterTaskRunner()->PostTask(fml::MakeCopyable( [this, &view_embedder_latch, session_inspect_node = std::move(session_inspect_node), flatland = std::move(flatland), session_error_callback = std::move(session_error_callback), view_creation_token = std::move(view_creation_token_), view_protocols = std::move(view_protocols), request = parent_viewport_watcher.NewRequest(), view_ref_pair = std::move(view_ref_pair), software_rendering = product_config.software_rendering()]() mutable { if (software_rendering) { surface_producer_ = std::make_shared<SoftwareSurfaceProducer>(); } else { surface_producer_ = std::make_shared<VulkanSurfaceProducer>(); } flatland_connection_ = std::make_shared<FlatlandConnection>( thread_label_, std::move(flatland), std::move(session_error_callback), [](auto) {}); fuchsia::ui::views::ViewIdentityOnCreation view_identity = { .view_ref = std::move(view_ref_pair.second), .view_ref_control = std::move(view_ref_pair.first)}; view_embedder_ = std::make_shared<ExternalViewEmbedder>( std::move(view_creation_token), std::move(view_identity), std::move(view_protocols), std::move(request), flatland_connection_, surface_producer_, intercept_all_input_); view_embedder_latch.Signal(); })); view_embedder_latch.Wait(); AccessibilityBridge::SetSemanticsEnabledCallback set_semantics_enabled_callback = [this](bool enabled) { auto platform_view = shell_->GetPlatformView(); if (platform_view) { platform_view->SetSemanticsEnabled(enabled); } }; AccessibilityBridge::DispatchSemanticsActionCallback dispatch_semantics_action_callback = [this](int32_t node_id, flutter::SemanticsAction action) { auto platform_view = shell_->GetPlatformView(); if (platform_view) { platform_view->DispatchSemanticsAction(node_id, action, {}); } }; const std::string accessibility_inspect_name = std::to_string(GetKoid(accessibility_view_ref)); accessibility_bridge_ = std::make_unique<AccessibilityBridge>( std::move(set_semantics_enabled_callback), std::move(dispatch_semantics_action_callback), std::move(semantics_manager), std::move(accessibility_view_ref), dart_utils::RootInspectNode::CreateRootChild( std::move(accessibility_inspect_name))); OnEnableWireframeCallback on_enable_wireframe_callback = std::bind( &Engine::DebugWireframeSettingsChanged, this, std::placeholders::_1); OnCreateViewCallback on_create_view_callback = std::bind( &Engine::CreateView, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5); OnUpdateViewCallback on_update_view_callback = std::bind( &Engine::UpdateView, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4); OnDestroyViewCallback on_destroy_view_callback = std::bind( &Engine::DestroyView, this, std::placeholders::_1, std::placeholders::_2); OnCreateSurfaceCallback on_create_surface_callback = std::bind(&Engine::CreateSurface, this); // SessionListener has a OnScenicError method; invoke this callback on the // platform thread when that happens. The Session itself should also be // disconnected when this happens, and it will also attempt to terminate. fit::closure on_session_listener_error_callback = [task_runner = platform_task_runner, weak = weak_factory_.GetWeakPtr()]() { task_runner->PostTask([weak]() { if (weak) { FML_LOG(ERROR) << "Terminating from " "on_session_listener_error_callback"; weak->Terminate(); } }); }; // Launch the engine in the appropriate configuration. // Note: this initializes the Asset Manager on the global PersistantCache // so it must be called before WarmupSkps() is called below. auto run_configuration = flutter::RunConfiguration::InferFromSettings( settings, task_runners.GetIOTaskRunner()); run_configuration.SetEntrypointArgs(std::move(dart_entrypoint_args)); OnSemanticsNodeUpdateCallback on_semantics_node_update_callback = [this](flutter::SemanticsNodeUpdates updates, float pixel_ratio) { accessibility_bridge_->AddSemanticsNodeUpdate(updates, pixel_ratio); }; OnRequestAnnounceCallback on_request_announce_callback = [this](const std::string& message) { accessibility_bridge_->RequestAnnounce(message); }; // Setup the callback that will instantiate the platform view. flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view = fml::MakeCopyable( [this, view_ref = std::move(platform_view_ref), parent_viewport_watcher = std::move(parent_viewport_watcher), ime_service = std::move(ime_service), keyboard = std::move(keyboard), focuser = std::move(focuser), view_ref_focused = std::move(view_ref_focused), touch_source = std::move(touch_source), mouse_source = std::move(mouse_source), pointerinjector_registry = std::move(pointerinjector_registry), on_session_listener_error_callback = std::move(on_session_listener_error_callback), on_enable_wireframe_callback = std::move(on_enable_wireframe_callback), on_create_view_callback = std::move(on_create_view_callback), on_update_view_callback = std::move(on_update_view_callback), on_destroy_view_callback = std::move(on_destroy_view_callback), on_create_surface_callback = std::move(on_create_surface_callback), on_semantics_node_update_callback = std::move(on_semantics_node_update_callback), on_request_announce_callback = std::move(on_request_announce_callback), external_view_embedder = GetExternalViewEmbedder(), await_vsync_callback = [this](FireCallbackCallback cb) { flatland_connection_->AwaitVsync(cb); }, await_vsync_for_secondary_callback_callback = [this](FireCallbackCallback cb) { flatland_connection_->AwaitVsyncForSecondaryCallback(cb); }, product_config, svc](flutter::Shell& shell) mutable { OnShaderWarmupCallback on_shader_warmup_callback = nullptr; if (product_config.enable_shader_warmup()) { FML_DCHECK(surface_producer_); if (product_config.enable_shader_warmup_dart_hooks()) { on_shader_warmup_callback = [this, &shell]( const std::vector<std::string>& skp_names, std::function<void(uint32_t)> completion_callback, uint64_t width, uint64_t height) { WarmupSkps( shell.GetDartVM() ->GetConcurrentMessageLoop() ->GetTaskRunner() .get(), shell.GetTaskRunners().GetRasterTaskRunner().get(), surface_producer_, SkISize::Make(width, height), flutter::PersistentCache::GetCacheForProcess() ->asset_manager(), skp_names, completion_callback); }; } else { WarmupSkps(shell.GetDartVM() ->GetConcurrentMessageLoop() ->GetTaskRunner() .get(), shell.GetTaskRunners().GetRasterTaskRunner().get(), surface_producer_, SkISize::Make(1024, 600), flutter::PersistentCache::GetCacheForProcess() ->asset_manager(), std::nullopt, std::nullopt); } } return std::make_unique<flutter_runner::PlatformView>( shell, shell.GetTaskRunners(), std::move(view_ref), std::move(external_view_embedder), std::move(ime_service), std::move(keyboard), std::move(touch_source), std::move(mouse_source), std::move(focuser), std::move(view_ref_focused), std::move(parent_viewport_watcher), std::move(pointerinjector_registry), std::move(on_enable_wireframe_callback), std::move(on_create_view_callback), std::move(on_update_view_callback), std::move(on_destroy_view_callback), std::move(on_create_surface_callback), std::move(on_semantics_node_update_callback), std::move(on_request_announce_callback), std::move(on_shader_warmup_callback), std::move(await_vsync_callback), std::move(await_vsync_for_secondary_callback_callback), std::move(svc)); }); // Setup the callback that will instantiate the rasterizer. flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer = [](flutter::Shell& shell) { return std::make_unique<flutter::Rasterizer>(shell); }; settings.root_isolate_create_callback = std::bind(&Engine::OnMainIsolateStart, this); settings.root_isolate_shutdown_callback = std::bind([weak = weak_factory_.GetWeakPtr(), runner = task_runners.GetPlatformTaskRunner()]() { runner->PostTask([weak = std::move(weak)] { if (weak) { weak->OnMainIsolateShutdown(); } }); }); // Connect and set up the system font provider. fuchsia::fonts::ProviderSyncPtr sync_font_provider; runner_services->Connect(sync_font_provider.NewRequest()); settings.font_initialization_data = sync_font_provider.Unbind().TakeChannel().release(); { TRACE_EVENT0("flutter", "CreateShell"); shell_ = flutter::Shell::Create( flutter::PlatformData(), // default window data std::move(task_runners), // host task runners std::move(settings), // shell launch settings std::move(on_create_platform_view), // platform view create callback std::move(on_create_rasterizer) // rasterizer create callback ); } if (!shell_) { FML_LOG(ERROR) << "Could not launch the shell."; return; } // Shell has been created. Before we run the engine, set up the isolate // configurator. isolate_configurator_ = std::make_unique<IsolateConfigurator>( std::move(fdio_ns), directory_request.TakeChannel(), std::move(isolate_view_ref.reference)); // This platform does not get a separate surface platform view creation // notification. Fire one eagerly. shell_->GetPlatformView()->NotifyCreated(); // Connect to the memory pressure provider. If the connection fails, the // initialization of the engine will simply proceed, printing a warning // message. The engine will be fully functional, except that the Flutter // shell will not be notified when memory is low. { memory_pressure_provider_.set_error_handler([](zx_status_t status) { FML_LOG(WARNING) << "Failed to connect to " << fuchsia::memorypressure::Provider::Name_ << ": " << zx_status_get_string(status) << " This is not a fatal error, but the heap will not be " << " compacted when memory is low."; }); // Note that we're using the runner's services, not the component's. // The Flutter Shell should be notified when memory is low regardless of // whether the component has direct access to the // fuchsia.memorypressure.Provider service. ZX_ASSERT(runner_services->Connect( memory_pressure_provider_.NewRequest()) == ZX_OK); FML_VLOG(1) << "Registering memorypressure watcher"; // Register for changes, which will make the request for the initial // memory level. memory_pressure_provider_->RegisterWatcher( memory_pressure_watcher_binding_.NewBinding()); } // Connect to the intl property provider. If the connection fails, the // initialization of the engine will simply proceed, printing a warning // message. The engine will be fully functional, except that the user's // locale preferences would not be communicated to flutter engine. { intl_property_provider_.set_error_handler([](zx_status_t status) { FML_LOG(WARNING) << "Failed to connect to " << fuchsia::intl::PropertyProvider::Name_ << ": " << zx_status_get_string(status) << " This is not a fatal error, but the user locale " << " preferences will not be forwarded to flutter apps"; }); // Note that we're using the runner's services, not the component's. // Flutter locales should be updated regardless of whether the component has // direct access to the fuchsia.intl.PropertyProvider service. ZX_ASSERT(runner_services->Connect(intl_property_provider_.NewRequest()) == ZX_OK); auto get_profile_callback = [weak = weak_factory_.GetWeakPtr()]( const fuchsia::intl::Profile& profile) { if (!weak) { return; } if (!profile.has_locales()) { FML_LOG(WARNING) << "Got intl Profile without locales"; } auto message = MakeLocalizationPlatformMessage(profile); FML_VLOG(1) << "Sending LocalizationPlatformMessage"; weak->shell_->GetPlatformView()->DispatchPlatformMessage( std::move(message)); }; FML_VLOG(1) << "Requesting intl Profile"; // Make the initial request intl_property_provider_->GetProfile(get_profile_callback); // And register for changes intl_property_provider_.events().OnChange = [this, runner_services, get_profile_callback]() { FML_VLOG(1) << fuchsia::intl::PropertyProvider::Name_ << ": OnChange"; runner_services->Connect(intl_property_provider_.NewRequest()); intl_property_provider_->GetProfile(get_profile_callback); }; } auto on_run_failure = [weak = weak_factory_.GetWeakPtr()]() { // The engine could have been killed by the caller right after the // constructor was called but before it could run on the UI thread. if (weak) { FML_LOG(ERROR) << "Terminating from on_run_failure"; weak->Terminate(); } }; shell_->GetTaskRunners().GetUITaskRunner()->PostTask( fml::MakeCopyable([engine = shell_->GetEngine(), // run_configuration = std::move(run_configuration), // on_run_failure // ]() mutable { if (!engine) { return; } if (engine->Run(std::move(run_configuration)) == flutter::Engine::RunStatus::Failure) { on_run_failure(); } })); } Engine::~Engine() { shell_.reset(); // Destroy rendering objects on the raster thread. fml::AutoResetWaitableEvent view_embedder_latch; thread_host_.raster_thread->GetTaskRunner()->PostTask( fml::MakeCopyable([this, &view_embedder_latch]() mutable { view_embedder_.reset(); flatland_connection_.reset(); surface_producer_.reset(); view_embedder_latch.Signal(); })); view_embedder_latch.Wait(); } std::optional<uint32_t> Engine::GetEngineReturnCode() const { if (!shell_) { return std::nullopt; } std::optional<uint32_t> code; fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( shell_->GetTaskRunners().GetUITaskRunner(), [&latch, &code, engine = shell_->GetEngine()]() { if (engine) { code = engine->GetUIIsolateReturnCode(); } latch.Signal(); }); latch.Wait(); return code; } void Engine::OnMainIsolateStart() { if (!isolate_configurator_ || !isolate_configurator_->ConfigureCurrentIsolate()) { FML_LOG(ERROR) << "Could not configure some native embedder bindings for a " "new root isolate."; } } void Engine::OnMainIsolateShutdown() { Terminate(); } void Engine::Terminate() { delegate_.OnEngineTerminate(this); // Warning. Do not do anything after this point as the delegate may have // collected this object. } void Engine::DebugWireframeSettingsChanged(bool enabled) { FML_CHECK(shell_); shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask([]() { // TODO(fxbug.dev/116000): Investigate if we can add flatland wireframe code // for debugging. }); } void Engine::CreateView(int64_t view_id, ViewCallback on_view_created, ViewCreatedCallback on_view_bound, bool hit_testable, bool focusable) { FML_CHECK(shell_); shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask( [this, view_id, hit_testable, focusable, on_view_created = std::move(on_view_created), on_view_bound = std::move(on_view_bound)]() { FML_CHECK(view_embedder_); view_embedder_->CreateView(view_id, std::move(on_view_created), std::move(on_view_bound)); view_embedder_->SetViewProperties(view_id, SkRect::MakeEmpty(), hit_testable, focusable); }); } void Engine::UpdateView(int64_t view_id, SkRect occlusion_hint, bool hit_testable, bool focusable) { FML_CHECK(shell_); shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask( [this, view_id, occlusion_hint, hit_testable, focusable]() { FML_CHECK(view_embedder_); view_embedder_->SetViewProperties(view_id, occlusion_hint, hit_testable, focusable); }); } void Engine::DestroyView(int64_t view_id, ViewIdCallback on_view_unbound) { FML_CHECK(shell_); shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask( [this, view_id, on_view_unbound = std::move(on_view_unbound)]() { FML_CHECK(view_embedder_); view_embedder_->DestroyView(view_id, std::move(on_view_unbound)); }); } std::unique_ptr<flutter::Surface> Engine::CreateSurface() { return std::make_unique<Surface>(thread_label_, GetExternalViewEmbedder(), surface_producer_->gr_context()); } std::shared_ptr<flutter::ExternalViewEmbedder> Engine::GetExternalViewEmbedder() { FML_CHECK(view_embedder_); return view_embedder_; } #if !defined(DART_PRODUCT) void Engine::WriteProfileToTrace() const { Dart_Port main_port = shell_->GetEngine()->GetUIIsolateMainPort(); char* error = NULL; bool success = Dart_WriteProfileToTimeline(main_port, &error); if (!success) { FML_LOG(ERROR) << "Failed to write Dart profile to trace: " << error; free(error); } } #endif // !defined(DART_PRODUCT) void Engine::WarmupSkps( fml::BasicTaskRunner* concurrent_task_runner, fml::BasicTaskRunner* raster_task_runner, std::shared_ptr<SurfaceProducer> surface_producer, SkISize size, std::shared_ptr<flutter::AssetManager> asset_manager, std::optional<const std::vector<std::string>> skp_names, std::optional<std::function<void(uint32_t)>> maybe_completion_callback, bool synchronous) { // Wrap the optional validity checks up in a lambda to simplify the various // callsites below auto completion_callback = [maybe_completion_callback](uint32_t skp_count) { if (maybe_completion_callback.has_value() && maybe_completion_callback.value()) { maybe_completion_callback.value()(skp_count); } }; // We use this bizzare raw pointer to a smart pointer thing here because we // want to keep the surface alive until all gpu work is done and the // callbacks skia takes for this are function pointers so we are unable to // use a lambda that captures the smart pointer. We need two levels of // indirection because it needs to be the same across all invocations of the // raster task lambda from a single invocation of WarmupSkps, but be // different across different invocations of WarmupSkps (so we cant // statically initialialize it in the lambda itself). Basically the result // of a mashup of wierd call dynamics, multithreading, and lifecycle // management with C style Skia callbacks. std::unique_ptr<SurfaceProducerSurface>* skp_warmup_surface = new std::unique_ptr<SurfaceProducerSurface>(nullptr); // tell concurrent task runner to deserialize all skps available from // the asset manager concurrent_task_runner->PostTask([raster_task_runner, size, skp_warmup_surface, surface_producer, asset_manager, skp_names, completion_callback, synchronous]() { TRACE_DURATION("flutter", "DeserializeSkps"); std::vector<std::unique_ptr<fml::Mapping>> skp_mappings; if (skp_names) { for (auto& skp_name : skp_names.value()) { auto skp_mapping = asset_manager->GetAsMapping(skp_name); if (skp_mapping) { skp_mappings.push_back(std::move(skp_mapping)); } else { FML_LOG(ERROR) << "Failed to get mapping for " << skp_name; } } } else { skp_mappings = asset_manager->GetAsMappings(".*\\.skp$", "shaders"); } if (skp_mappings.empty()) { FML_LOG(WARNING) << "Engine::WarmupSkps got zero SKP mappings, returning early"; completion_callback(0); return; } size_t total_size = 0; for (auto& mapping : skp_mappings) { total_size += mapping->GetSize(); } FML_LOG(INFO) << "Shader warmup got " << skp_mappings.size() << " skp's with a total size of " << total_size << " bytes"; std::vector<sk_sp<SkPicture>> pictures; unsigned int i = 0; for (auto& mapping : skp_mappings) { std::unique_ptr<SkMemoryStream> stream = SkMemoryStream::MakeDirect(mapping->GetMapping(), mapping->GetSize()); SkDeserialProcs procs = {0}; procs.fImageProc = flutter::DeserializeImageWithoutData; procs.fTypefaceProc = flutter::DeserializeTypefaceWithoutData; sk_sp<SkPicture> picture = SkPicture::MakeFromStream(stream.get(), &procs); if (!picture) { FML_LOG(ERROR) << "Failed to deserialize picture " << i; continue; } // Tell raster task runner to warmup have the compositor // context warm up the newly deserialized picture raster_task_runner->PostTask([picture, skp_warmup_surface, size, surface_producer, completion_callback, i, count = skp_mappings.size(), synchronous] { TRACE_DURATION("flutter", "WarmupSkp"); if (*skp_warmup_surface == nullptr) { skp_warmup_surface->reset( surface_producer->ProduceOffscreenSurface(size).release()); if (*skp_warmup_surface == nullptr) { FML_LOG(ERROR) << "Failed to create offscreen warmup surface"; // Tell client that zero shaders were warmed up because warmup // failed. completion_callback(0); return; } } // Do the actual warmup (*skp_warmup_surface) ->GetSkiaSurface() ->getCanvas() ->drawPicture(picture); if (i == count - 1) { // We call this here instead of inside fFinishedProc below because // we want to unblock the dart animation code as soon as the // raster thread is free to enque work, rather than waiting for // the GPU work itself to finish. completion_callback(count); } if (surface_producer->gr_context()) { if (i < count - 1) { // For all but the last skp we fire and forget surface_producer->gr_context()->flushAndSubmit(); } else { // For the last skp we provide a callback that frees the warmup // surface and calls the completion callback struct GrFlushInfo flush_info; flush_info.fFinishedContext = skp_warmup_surface; flush_info.fFinishedProc = [](void* skp_warmup_surface) { delete static_cast<std::unique_ptr<SurfaceProducerSurface>*>( skp_warmup_surface); }; surface_producer->gr_context()->flush(flush_info); surface_producer->gr_context()->submit( synchronous ? GrSyncCpu::kYes : GrSyncCpu::kNo); } } else { if (i == count - 1) { delete skp_warmup_surface; } } }); i++; } }); } void Engine::OnLevelChanged( fuchsia::memorypressure::Level level, fuchsia::memorypressure::Watcher::OnLevelChangedCallback callback) { // The callback must be invoked immediately to acknowledge the message. // This is the "Throttle push using acknowledgements" pattern: // https://fuchsia.dev/fuchsia-src/concepts/api/fidl#throttle_push_using_acknowledgements callback(); FML_LOG(WARNING) << "memorypressure watcher: OnLevelChanged from " << static_cast<int>(latest_memory_pressure_level_) << " to " << static_cast<int>(level); if (latest_memory_pressure_level_ == fuchsia::memorypressure::Level::NORMAL && (level == fuchsia::memorypressure::Level::WARNING || level == fuchsia::memorypressure::Level::CRITICAL)) { FML_LOG(WARNING) << "memorypressure watcher: notifying Flutter that memory is low"; shell_->NotifyLowMemoryWarning(); } latest_memory_pressure_level_ = level; } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/engine.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/engine.cc", "repo_id": "engine", "token_count": 16585 }
354
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fuchsia/intl/cpp/fidl.h> #include "flutter/fml/icu_util.h" #include "gtest/gtest.h" #include "fuchsia_intl.h" using fuchsia::intl::CalendarId; using fuchsia::intl::LocaleId; using fuchsia::intl::Profile; using fuchsia::intl::TemperatureUnit; using fuchsia::intl::TimeZoneId; namespace flutter_runner { namespace { class FuchsiaIntlTest : public testing::Test { public: static void SetUpTestCase() { testing::Test::SetUpTestCase(); // The icudtl data must be present as a resource in the package for this // load to succeed. fml::icu::InitializeICU("/pkg/data/icudtl.dat"); } }; TEST_F(FuchsiaIntlTest, MakeLocalizationPlatformMessageData_SimpleLocale) { Profile profile{}; profile.set_locales({LocaleId{.id = "en-US"}}); const std::string expected = R"({"method":"setLocale","args":["en","US","",""]})"; const auto actual = MakeLocalizationPlatformMessageData(profile); ASSERT_EQ(expected, std::string(actual.GetMapping(), actual.GetMapping() + actual.GetSize())); } TEST_F(FuchsiaIntlTest, MakeLocalizationPlatformMessageData_OneLocale) { Profile profile{}; profile .set_locales({LocaleId{.id = "en-US-u-ca-gregory-fw-sun-hc-h12-ms-" "ussystem-nu-latn-tz-usnyc"}}) .set_calendars({CalendarId{.id = "und-u-gregory"}}) .set_time_zones({TimeZoneId{.id = "America/New_York"}}) .set_temperature_unit(TemperatureUnit::FAHRENHEIT); const std::string expected = R"({"method":"setLocale","args":["en","US","",""]})"; const auto actual = MakeLocalizationPlatformMessageData(profile); ASSERT_EQ(expected, std::string(actual.GetMapping(), actual.GetMapping() + actual.GetSize())); } TEST_F(FuchsiaIntlTest, MakeLocalizationPlatformMessageData_MultipleLocales) { Profile profile{}; profile .set_locales({LocaleId{.id = "en-US-u-ca-gregory-fw-sun-hc-h12-ms-" "ussystem-nu-latn-tz-usnyc"}, LocaleId{.id = "sl-Latn-IT-nedis"}, LocaleId{.id = "zh-Hans"}, LocaleId{.id = "sr-Cyrl-CS"}}) .set_calendars({CalendarId{.id = "und-u-gregory"}}) .set_time_zones({TimeZoneId{.id = "America/New_York"}}) .set_temperature_unit(TemperatureUnit::FAHRENHEIT); const std::string expected = R"({"method":"setLocale","args":["en","US","","","sl","IT","Latn","nedis",)" R"("zh","","Hans","","sr","CS","Cyrl",""]})"; const auto actual = MakeLocalizationPlatformMessageData(profile); ASSERT_EQ(expected, std::string(actual.GetMapping(), actual.GetMapping() + actual.GetSize())); } } // namespace } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/fuchsia_intl_unittest.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/fuchsia_intl_unittest.cc", "repo_id": "engine", "token_count": 1250 }
355
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "runner.h" #include <fcntl.h> #include <fuchsia/mem/cpp/fidl.h> #include <lib/async/cpp/task.h> #include <lib/async/default.h> #include <lib/inspect/cpp/inspect.h> #include <lib/sys/cpp/component_context.h> #include <lib/trace-engine/instrumentation.h> #include <lib/vfs/cpp/pseudo_dir.h> #include <zircon/status.h> #include <zircon/types.h> #include <cstdint> #include <sstream> #include <utility> #include "flutter/fml/make_copyable.h" #include "flutter/lib/ui/text/font_collection.h" #include "flutter/runtime/dart_vm.h" #include "runtime/dart/utils/files.h" #include "runtime/dart/utils/root_inspect_node.h" #include "runtime/dart/utils/vmo.h" #include "runtime/dart/utils/vmservice_object.h" #include "third_party/icu/source/common/unicode/udata.h" #include "third_party/skia/include/core/SkGraphics.h" namespace flutter_runner { namespace { static constexpr char kIcuDataPath[] = "/pkg/data/icudtl.dat"; // Environment variable containing the path to the directory containing the // timezone files. static constexpr char kICUTZEnv[] = "ICU_TIMEZONE_FILES_DIR"; // The data directory containing ICU timezone data files. static constexpr char kICUTZDataDir[] = "/config/data/tzdata/icu/44/le"; // Map the memory into the process and return a pointer to the memory. uintptr_t GetICUData(const fuchsia::mem::Buffer& icu_data) { uint64_t data_size = icu_data.size; if (data_size > std::numeric_limits<size_t>::max()) return 0u; uintptr_t data = 0u; zx_status_t status = zx::vmar::root_self()->map(ZX_VM_PERM_READ, 0, icu_data.vmo, 0, static_cast<size_t>(data_size), &data); if (status == ZX_OK) { return data; } return 0u; } // Initializes the timezone data if available. Timezone data file in Fuchsia // is at a fixed directory path. Returns true on success. As a side effect // sets the value of the environment variable "ICU_TIMEZONE_FILES_DIR" to a // fixed value which is fuchsia-specific. bool InitializeTZData() { // We need the ability to change the env variable for testing, so not // overwriting if set. setenv(kICUTZEnv, kICUTZDataDir, 0 /* No overwrite */); const std::string tzdata_dir = getenv(kICUTZEnv); // Try opening the path to check if present. No need to verify that it is a // directory since ICU loading will return an error if the TZ data path is // wrong. int fd = openat(AT_FDCWD, tzdata_dir.c_str(), O_RDONLY); if (fd < 0) { FML_LOG(INFO) << "Could not open: '" << tzdata_dir << "', proceeding without loading the timezone database: " << strerror(errno); return false; } if (close(fd)) { FML_LOG(WARNING) << "Could not close: " << tzdata_dir << ": " << strerror(errno); } return true; } // Return value indicates if initialization was successful. bool InitializeICU() { const char* data_path = kIcuDataPath; fuchsia::mem::Buffer icu_data; if (!dart_utils::VmoFromFilename(data_path, false, &icu_data)) { return false; } uintptr_t data = GetICUData(icu_data); if (!data) { return false; } // If the loading fails, soldier on. The loading is optional as we don't // want to crash the engine in transition. InitializeTZData(); // Pass the data to ICU. UErrorCode err = U_ZERO_ERROR; udata_setCommonData(reinterpret_cast<const char*>(data), &err); if (err != U_ZERO_ERROR) { FML_LOG(ERROR) << "error loading ICU data: " << err; return false; } return true; } } // namespace static void SetProcessName() { std::stringstream stream; #if defined(DART_PRODUCT) stream << "io.flutter.product_runner."; #else stream << "io.flutter.runner."; #endif if (flutter::DartVM::IsRunningPrecompiledCode()) { stream << "aot"; } else { stream << "jit"; } const auto name = stream.str(); zx::process::self()->set_property(ZX_PROP_NAME, name.c_str(), name.size()); } static void SetThreadName(const std::string& thread_name) { zx::thread::self()->set_property(ZX_PROP_NAME, thread_name.c_str(), thread_name.size()); } #if !defined(DART_PRODUCT) // Register native symbol information for the Dart VM's profiler. static void RegisterProfilerSymbols(const char* symbols_path, const char* dso_name) { std::string* symbols = new std::string(); if (dart_utils::ReadFileToString(symbols_path, symbols)) { Dart_AddSymbols(dso_name, symbols->data(), symbols->size()); } else { FML_LOG(ERROR) << "Failed to load " << symbols_path; } } #endif // !defined(DART_PRODUCT) Runner::Runner(fml::RefPtr<fml::TaskRunner> task_runner, sys::ComponentContext* context) : task_runner_(task_runner), context_(context) { #if !defined(DART_PRODUCT) // The VM service isolate uses the process-wide namespace. It writes the // vm service protocol port under /tmp. The VMServiceObject exposes that // port number to The Hub. context_->outgoing()->debug_dir()->AddEntry( dart_utils::VMServiceObject::kPortDirName, std::make_unique<dart_utils::VMServiceObject>()); inspect::Inspector* inspector = dart_utils::RootInspectNode::GetInspector(); inspector->GetRoot().CreateLazyValues( "vmservice_port", [&]() { inspect::Inspector inspector; dart_utils::VMServiceObject::LazyEntryVector out; dart_utils::VMServiceObject().GetContents(&out); std::string name = ""; if (!out.empty()) { name = out[0].name; } inspector.GetRoot().CreateString("vm_service_port", name, &inspector); return fpromise::make_ok_promise(inspector); }, inspector); SetupTraceObserver(); #endif // !defined(DART_PRODUCT) SkGraphics::Init(); SetupICU(); SetProcessName(); SetThreadName("io.flutter.runner.main"); context_->outgoing() ->AddPublicService<fuchsia::component::runner::ComponentRunner>( std::bind(&Runner::RegisterComponentV2, this, std::placeholders::_1)); #if !defined(DART_PRODUCT) if (Dart_IsPrecompiledRuntime()) { RegisterProfilerSymbols("pkg/data/flutter_aot_runner.dartprofilersymbols", ""); } else { RegisterProfilerSymbols("pkg/data/flutter_jit_runner.dartprofilersymbols", ""); } #endif // !defined(DART_PRODUCT) } Runner::~Runner() { context_->outgoing() ->RemovePublicService<fuchsia::component::runner::ComponentRunner>(); #if !defined(DART_PRODUCT) trace_observer_->Stop(); #endif // !defined(DART_PRODUCT) } // CF v2 lifecycle methods. void Runner::RegisterComponentV2( fidl::InterfaceRequest<fuchsia::component::runner::ComponentRunner> request) { active_components_v2_bindings_.AddBinding(this, std::move(request)); } void Runner::Start( fuchsia::component::runner::ComponentStartInfo start_info, fidl::InterfaceRequest<fuchsia::component::runner::ComponentController> controller) { // TRACE_DURATION currently requires that the string data does not change // in the traced scope. Since |package| gets moved in the ComponentV2::Create // call below, we cannot ensure that |package.resolved_url| does not move or // change, so we make a copy to pass to TRACE_DURATION. // TODO(PT-169): Remove this copy when TRACE_DURATION reads string arguments // eagerly. const std::string url_copy = start_info.resolved_url(); TRACE_EVENT1("flutter", "Start", "url", url_copy.c_str()); // Notes on component termination: Components typically terminate on the // thread on which they were created. This usually means the thread was // specifically created to host the component. But we want to ensure that // access to the active components collection is made on the same thread. So // we capture the runner in the termination callback. There is no risk of // there being multiple component runner instances in the process at the same // time. So it is safe to use the raw pointer. ComponentV2::TerminationCallback termination_callback = [component_runner = this](const ComponentV2* component) { component_runner->task_runner_->PostTask( [component_runner, component]() { component_runner->OnComponentV2Terminate(component); }); }; ActiveComponentV2 active_component = ComponentV2::Create( std::move(termination_callback), std::move(start_info), context_->svc() /* runner_incoming_services */, std::move(controller)); auto key = active_component.component.get(); active_components_v2_[key] = std::move(active_component); } void Runner::OnComponentV2Terminate(const ComponentV2* component) { auto active_component_it = active_components_v2_.find(component); if (active_component_it == active_components_v2_.end()) { FML_LOG(INFO) << "The remote end of the component runner tried to terminate an " "component that has already been terminated, possibly because we " "initiated the termination"; return; } ActiveComponentV2& active_component = active_component_it->second; // Grab the items out of the entry because we will have to rethread the // destruction. std::unique_ptr<ComponentV2> component_to_destroy = std::move(active_component.component); std::unique_ptr<fml::Thread> component_thread = std::move(active_component.platform_thread); // Delete the entry. active_components_v2_.erase(component); // Post the task to destroy the component and quit its message loop. component_thread->GetTaskRunner()->PostTask(fml::MakeCopyable( [instance = std::move(component_to_destroy), thread = component_thread.get()]() mutable { instance.reset(); })); // Terminate and join the thread's message loop. component_thread->Join(); } void Runner::SetupICU() { // Exposes the TZ data setup for testing. Failing here is not fatal. Runner::SetupTZDataInternal(); if (!Runner::SetupICUInternal()) { FML_LOG(ERROR) << "Could not initialize ICU data."; } } // static bool Runner::SetupICUInternal() { return InitializeICU(); } // static bool Runner::SetupTZDataInternal() { return InitializeTZData(); } #if !defined(DART_PRODUCT) void Runner::SetupTraceObserver() { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask(task_runner_, [&]() { // Running this initialization code on task_runner_ ensures that the call to // `async_get_default_dispatcher()` will capture the correct dispatcher. trace_observer_ = std::make_unique<trace::TraceObserver>(); trace_observer_->Start(async_get_default_dispatcher(), [runner = this]() { if (!trace_is_category_enabled("dart:profiler")) { return; } if (trace_state() == TRACE_STARTED) { runner->prolonged_context_ = trace_acquire_prolonged_context(); Dart_StartProfiling(); } else if (trace_state() == TRACE_STOPPING) { auto write_profile_trace_for_components = [](auto& components) { for (auto& it : components) { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( it.second.platform_thread->GetTaskRunner(), [&]() { it.second.component->WriteProfileToTrace(); latch.Signal(); }); latch.Wait(); } }; write_profile_trace_for_components(runner->active_components_v2_); Dart_StopProfiling(); trace_release_prolonged_context(runner->prolonged_context_); } }); latch.Signal(); }); latch.Wait(); } #endif // !defined(DART_PRODUCT) } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/runner.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/runner.cc", "repo_id": "engine", "token_count": 4416 }
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. assert(is_fuchsia) import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") group("fakes") { testonly = true public_deps = [ ":focus", ":pointer", "scenic", ] } source_set("focus") { testonly = true sources = [ "focuser.h", "platform_message.h", "touch_source.h", "view_ref_focused.h", ] deps = [ "${fuchsia_sdk}/pkg/sys_cpp_testing", "//flutter/lib/ui", "//flutter/testing", "//flutter/third_party/rapidjson", ] } source_set("pointer") { testonly = true sources = [ "mock_injector_registry.h" ] deps = [ "${fuchsia_sdk}/pkg/sys_cpp_testing", "//flutter/lib/ui", "//flutter/testing", "//flutter/third_party/rapidjson", ] }
engine/shell/platform/fuchsia/flutter/tests/fakes/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/BUILD.gn", "repo_id": "engine", "token_count": 382 }
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. assert(is_fuchsia) import("//flutter/tools/fuchsia/fuchsia_archive.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") group("tests") { testonly = true deps = [ ":flutter-embedder-test" ] } executable("flutter-embedder-test-bin") { testonly = true output_name = "flutter-embedder-test" sources = [ "flutter-embedder-test.cc" ] # This is needed for //flutter/third_party/googletest for linking zircon # symbols. libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] deps = [ "${fuchsia_sdk}/fidl/fuchsia.inspect", "${fuchsia_sdk}/fidl/fuchsia.logger", "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", "${fuchsia_sdk}/fidl/fuchsia.ui.app", "${fuchsia_sdk}/fidl/fuchsia.ui.composition", "${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton", "${fuchsia_sdk}/fidl/fuchsia.ui.observation.geometry", "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", "${fuchsia_sdk}/fidl/fuchsia.ui.test.scene", "${fuchsia_sdk}/pkg/async", "${fuchsia_sdk}/pkg/async-loop-testing", "${fuchsia_sdk}/pkg/fidl_cpp", "${fuchsia_sdk}/pkg/sys_component_cpp_testing", "${fuchsia_sdk}/pkg/zx", "//flutter/fml", "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:check_view", "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:screenshot", "//flutter/third_party/googletest:gtest", "//flutter/third_party/googletest:gtest_main", ] } fuchsia_test_archive("flutter-embedder-test") { deps = [ ":flutter-embedder-test-bin", "child-view:package", "parent-view:package", # "OOT" copies of the runners used by tests, to avoid conflicting with the # runners in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. "//flutter/shell/platform/fuchsia/flutter:oot_flutter_jit_runner", ] binary = "$target_name" cml_file = rebase_path("meta/$target_name.cml") }
engine/shell/platform/fuchsia/flutter/tests/integration/embedder/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/embedder/BUILD.gn", "repo_id": "engine", "token_count": 913 }
358
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:typed_data'; import 'dart:ui'; import 'dart:zircon'; void main() { print('Launching mouse-input-view'); MyApp app = MyApp(); app.run(); } class MyApp { static const _red = Color.fromARGB(255, 244, 67, 54); static const _orange = Color.fromARGB(255, 255, 152, 0); static const _yellow = Color.fromARGB(255, 255, 235, 59); static const _green = Color.fromARGB(255, 76, 175, 80); static const _blue = Color.fromARGB(255, 33, 150, 143); static const _purple = Color.fromARGB(255, 156, 39, 176); final List<Color> _colors = <Color>[ _red, _orange, _yellow, _green, _blue, _purple, ]; // Each tap will increment the counter, we then determine what color to choose int _touchCounter = 0; void run() { // Set up window callbacks. window.onPointerDataPacket = (PointerDataPacket packet) { this.pointerDataPacket(packet); }; window.onMetricsChanged = () { window.scheduleFrame(); }; window.onBeginFrame = (Duration duration) { this.beginFrame(duration); }; // The child view should be attached to Scenic now. // Ready to build the scene. window.scheduleFrame(); } void beginFrame(Duration duration) { // Convert physical screen size of device to values final pixelRatio = window.devicePixelRatio; final size = window.physicalSize / pixelRatio; final physicalBounds = Offset.zero & size * pixelRatio; // Set up Canvas that uses the screen size final recorder = PictureRecorder(); final canvas = Canvas(recorder, physicalBounds); canvas.scale(pixelRatio, pixelRatio); // Draw something // Color of the screen is set initially to the first value in _colors // Incrementing _touchCounter will change screen color final paint = Paint()..color = _colors[_touchCounter % _colors.length]; canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); // Build the scene final picture = recorder.endRecording(); final sceneBuilder = SceneBuilder() ..pushClipRect(physicalBounds) ..addPicture(Offset.zero, picture) ..pop(); window.render(sceneBuilder.build()); } void pointerDataPacket(PointerDataPacket packet) async { int nowNanos = System.clockGetMonotonic(); for (PointerData data in packet.data) { print('mouse-input-view received input: ${data.toStringFull()}'); if (data.kind == PointerDeviceKind.mouse) { if (data.change == PointerChange.down) { _touchCounter++; } _reportMouseInput( localX: data.physicalX, localY: data.physicalY, buttons: data.buttons, phase: data.change.name, timeReceived: nowNanos, wheelXPhysicalPixel: data.scrollDeltaX, wheelYPhysicalPixel: data.scrollDeltaY, ); } } window.scheduleFrame(); } void _reportMouseInput( {required double localX, required double localY, required int timeReceived, required int buttons, required String phase, required double wheelXPhysicalPixel, required double wheelYPhysicalPixel}) { print('mouse-input-view reporting mouse input to MouseInputListener'); final message = ByteData.sublistView(utf8.encode(json.encode({ 'method': 'MouseInputListener.ReportMouseInput', 'local_x': localX, 'local_y': localY, 'time_received': timeReceived, 'component_name': 'touch-input-view', 'buttons': buttons, 'phase': phase, 'wheel_x_physical_pixel': wheelXPhysicalPixel, 'wheel_y_physical_pixel': wheelYPhysicalPixel, }))); PlatformDispatcher.instance .sendPlatformMessage('fuchsia/input_test', message, null); } }
engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/lib/mouse-input-view.dart/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/lib/mouse-input-view.dart", "repo_id": "engine", "token_count": 1476 }
359
{ "families": [ { "family": "Roboto", "fallback": true, "fallback_group": "sans-serif", "fonts": [ { "asset": "Roboto-Regular.ttf" } ] }, { "family": "Roboto Slab", "aliases": [ "RobotoSlab" ], "fallback": true, "fallback_group": "serif", "fonts": [ { "asset": "RobotoSlab-Regular.ttf" } ] } ] }
engine/shell/platform/fuchsia/flutter/tests/test_manifest.json/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/test_manifest.json", "repo_id": "engine", "token_count": 424 }
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 "vulkan_surface_producer.h" #include <lib/async/cpp/task.h> #include <lib/async/default.h> #include <memory> #include <string> #include <vector> #include "flutter/fml/trace_event.h" #include "flutter/vulkan/vulkan_skia_proc_table.h" #include "flutter_vma/flutter_skia_vma.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSemaphore.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" #include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h" #include "third_party/skia/include/gpu/ganesh/vk/GrVkDirectContext.h" #include "third_party/skia/include/gpu/vk/GrVkBackendContext.h" #include "third_party/skia/include/gpu/vk/GrVkExtensions.h" #include "third_party/skia/include/gpu/vk/GrVkTypes.h" namespace flutter_runner { namespace { // Tuning advice: // If you see the following 3 things happening simultaneously in a trace: // * Over budget ("flutter", "GPURasterizer::Draw") durations // * Many ("skia", "GrGpu::createTexture") events within the // "GPURasterizer::Draw"s // * The Skia GPU resource cache is full, as indicated by the // "SkiaCacheBytes" field in the ("flutter", "SurfacePool") trace counter // (compare it to the bytes value here) // then you should consider increasing the size of the GPU resource cache. constexpr size_t kGrCacheMaxByteSize = 1024 * 600 * 12 * 4; } // namespace VulkanSurfaceProducer::VulkanSurfaceProducer() { valid_ = Initialize(); if (!valid_) { FML_LOG(FATAL) << "VulkanSurfaceProducer: Initialization failed"; } } VulkanSurfaceProducer::~VulkanSurfaceProducer() { // Make sure queue is idle before we start destroying surfaces if (valid_) { VkResult wait_result = VK_CALL_LOG_ERROR( vk_->QueueWaitIdle(logical_device_->GetQueueHandle())); FML_DCHECK(wait_result == VK_SUCCESS); } }; bool VulkanSurfaceProducer::Initialize() { vk_ = fml::MakeRefCounted<vulkan::VulkanProcTable>(); std::vector<std::string> extensions = { VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME, }; // On Fuchsia, the validation layers need to be packaged as part of the // flutter_runner in order to work. As a result, we can use the presence // of the layers to mean that we want the layers enabled. application_ = std::make_unique<vulkan::VulkanApplication>( *vk_, "FlutterRunner", std::move(extensions), VK_MAKE_VERSION(1, 0, 0), VK_MAKE_VERSION(1, 1, 0), true /* enable_validation_layers */); if (!application_->IsValid() || !vk_->AreInstanceProcsSetup()) { // Make certain the application instance was created and it set up the // instance proc table entries. FML_LOG(ERROR) << "VulkanSurfaceProducer: Instance proc addresses have not " "been set up."; return false; } // Create the device. logical_device_ = application_->AcquireFirstCompatibleLogicalDevice(); if (logical_device_ == nullptr || !logical_device_->IsValid() || !vk_->AreDeviceProcsSetup()) { // Make certain the device was created and it set up the device proc table // entries. FML_LOG(ERROR) << "VulkanSurfaceProducer: Device proc addresses have not been set up."; return false; } if (!vk_->HasAcquiredMandatoryProcAddresses()) { FML_LOG(ERROR) << "VulkanSurfaceProducer: Failed to acquire mandatory proc addresses."; return false; } if (!vk_->IsValid()) { FML_LOG(ERROR) << "VulkanSurfaceProducer: VulkanProcTable invalid"; return false; } auto getProc = CreateSkiaGetProc(vk_); if (getProc == nullptr) { FML_LOG(ERROR) << "VulkanSurfaceProducer: Failed to create skia getProc."; return false; } uint32_t skia_features = 0; if (!logical_device_->GetPhysicalDeviceFeaturesSkia(&skia_features)) { FML_LOG(ERROR) << "VulkanSurfaceProducer: Failed to get physical device features."; return false; } memory_allocator_ = flutter::FlutterSkiaVulkanMemoryAllocator::Make( application_->GetAPIVersion(), application_->GetInstance(), logical_device_->GetPhysicalDeviceHandle(), logical_device_->GetHandle(), vk_, true); GrVkBackendContext backend_context; backend_context.fInstance = application_->GetInstance(); backend_context.fPhysicalDevice = logical_device_->GetPhysicalDeviceHandle(); backend_context.fDevice = logical_device_->GetHandle(); backend_context.fQueue = logical_device_->GetQueueHandle(); backend_context.fGraphicsQueueIndex = logical_device_->GetGraphicsQueueIndex(); backend_context.fMinAPIVersion = application_->GetAPIVersion(); backend_context.fMaxAPIVersion = application_->GetAPIVersion(); backend_context.fFeatures = skia_features; backend_context.fGetProc = std::move(getProc); backend_context.fOwnsInstanceAndDevice = false; backend_context.fMemoryAllocator = memory_allocator_; // The memory_requirements_2 extension is required on Fuchsia as the AMD // memory allocator used by Skia benefit from it. const char* device_extensions[] = { VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME, }; const int device_extensions_count = sizeof(device_extensions) / sizeof(device_extensions[0]); GrVkExtensions vk_extensions; vk_extensions.init(backend_context.fGetProc, backend_context.fInstance, backend_context.fPhysicalDevice, 0, nullptr, device_extensions_count, device_extensions); backend_context.fVkExtensions = &vk_extensions; GrContextOptions options; options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo; context_ = GrDirectContexts::MakeVulkan(backend_context, options); if (context_ == nullptr) { FML_LOG(ERROR) << "VulkanSurfaceProducer: Failed to create GrDirectContext."; return false; } // Use local limits specified in this file above instead of flutter defaults. context_->setResourceCacheLimit(kGrCacheMaxByteSize); surface_pool_ = std::make_unique<VulkanSurfacePool>(*this, context_); return true; } void VulkanSurfaceProducer::SubmitSurfaces( std::vector<std::unique_ptr<SurfaceProducerSurface>> surfaces) { TRACE_EVENT0("flutter", "VulkanSurfaceProducer::SubmitSurfaces"); // Do a single flush for all canvases derived from the context. { TRACE_EVENT0("flutter", "GrDirectContext::flushAndSignalSemaphores"); context_->flushAndSubmit(); } if (!TransitionSurfacesToExternal(surfaces)) FML_LOG(ERROR) << "TransitionSurfacesToExternal failed"; // Submit surface for (auto& surface : surfaces) { SubmitSurface(std::move(surface)); } // Buffer management. surface_pool_->AgeAndCollectOldBuffers(); // If no further surface production has taken place for 10 frames (TODO: // Don't hardcode refresh rate here), then shrink our surface pool to fit. constexpr auto kShouldShrinkThreshold = zx::msec(10 * 16.67); async::PostDelayedTask( async_get_default_dispatcher(), [self = weak_factory_.GetWeakPtr(), kShouldShrinkThreshold] { if (!self) { return; } auto time_since_last_produce = async::Now(async_get_default_dispatcher()) - self->last_produce_time_; if (time_since_last_produce >= kShouldShrinkThreshold) { self->surface_pool_->ShrinkToFit(); } }, kShouldShrinkThreshold); } bool VulkanSurfaceProducer::TransitionSurfacesToExternal( const std::vector<std::unique_ptr<SurfaceProducerSurface>>& surfaces) { for (auto& surface : surfaces) { auto vk_surface = static_cast<VulkanSurface*>(surface.get()); if (!vk_surface) { continue; } vulkan::VulkanCommandBuffer* command_buffer = vk_surface->GetCommandBuffer(logical_device_->GetCommandPool()); if (!command_buffer->Begin()) return false; GrBackendRenderTarget backendRT = SkSurfaces::GetBackendRenderTarget( vk_surface->GetSkiaSurface().get(), SkSurfaces::BackendHandleAccess::kFlushRead); if (!backendRT.isValid()) { return false; } GrVkImageInfo imageInfo; if (!GrBackendRenderTargets::GetVkImageInfo(backendRT, &imageInfo)) { return false; } VkImageMemoryBarrier image_barrier = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .pNext = nullptr, .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, .dstAccessMask = 0, .oldLayout = imageInfo.fImageLayout, // Understand why this is causing issues on Intel. TODO(fxb/53449) #if defined(__aarch64__) .newLayout = imageInfo.fImageLayout, #else .newLayout = VK_IMAGE_LAYOUT_GENERAL, #endif .srcQueueFamilyIndex = 0, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_EXTERNAL_KHR, .image = vk_surface->GetVkImage(), .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; if (!command_buffer->InsertPipelineBarrier( VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, // dependencyFlags 0, nullptr, // memory barriers 0, nullptr, // buffer barriers 1, &image_barrier)) return false; GrBackendRenderTargets::SetVkImageLayout(&backendRT, image_barrier.newLayout); if (!command_buffer->End()) return false; if (!logical_device_->QueueSubmit( {}, {}, {vk_surface->GetAcquireVkSemaphore()}, {command_buffer->Handle()}, vk_surface->GetCommandBufferFence())) return false; } return true; } std::unique_ptr<SurfaceProducerSurface> VulkanSurfaceProducer::ProduceSurface( const SkISize& size) { FML_CHECK(valid_); last_produce_time_ = async::Now(async_get_default_dispatcher()); return surface_pool_->AcquireSurface(size); } void VulkanSurfaceProducer::SubmitSurface( std::unique_ptr<SurfaceProducerSurface> surface) { FML_CHECK(valid_); surface_pool_->SubmitSurface(std::move(surface)); } std::unique_ptr<SurfaceProducerSurface> VulkanSurfaceProducer::ProduceOffscreenSurface(const SkISize& size) { return surface_pool_->CreateSurface(size); } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/vulkan_surface_producer.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/vulkan_surface_producer.cc", "repo_id": "engine", "token_count": 3936 }
361
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mapped_resource.h" #include <dlfcn.h> #include <fcntl.h> #include <fuchsia/io/cpp/fidl.h> #include <fuchsia/mem/cpp/fidl.h> #include <lib/fdio/directory.h> #include <lib/fdio/io.h> #include <lib/trace/event.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <zircon/dlfcn.h> #include <zircon/status.h> #include "flutter/fml/logging.h" #include "third_party/dart/runtime/include/dart_api.h" #include "inlines.h" #include "vmo.h" namespace dart_utils { static bool OpenVmo(fuchsia::mem::Buffer* resource_vmo, fdio_ns_t* namespc, const std::string& path, bool executable) { TRACE_DURATION("dart", "LoadFromNamespace", "path", path); if (namespc == nullptr) { // Opening a file in the root namespace expects an absolute path. FML_CHECK(path[0] == '/'); if (!VmoFromFilename(path, executable, resource_vmo)) { return false; } } else { // openat of a path with a leading '/' ignores the namespace fd. // require a relative path. FML_CHECK(path[0] != '/'); auto root_dir = fdio_ns_opendir(namespc); if (root_dir < 0) { FML_LOG(ERROR) << "Failed to open namespace directory"; return false; } bool result = dart_utils::VmoFromFilenameAt(root_dir, path, executable, resource_vmo); close(root_dir); if (!result) { return result; } } return true; } bool MappedResource::LoadFromNamespace(fdio_ns_t* namespc, const std::string& path, MappedResource& resource, bool executable) { fuchsia::mem::Buffer resource_vmo; return OpenVmo(&resource_vmo, namespc, path, executable) && LoadFromVmo(path, std::move(resource_vmo), resource, executable); } bool MappedResource::LoadFromVmo(const std::string& path, fuchsia::mem::Buffer resource_vmo, MappedResource& resource, bool executable) { if (resource_vmo.size == 0) { return true; } uint32_t flags = ZX_VM_PERM_READ; if (executable) { flags |= ZX_VM_PERM_EXECUTE; } uintptr_t addr; zx_status_t status = zx::vmar::root_self()->map(flags, 0, resource_vmo.vmo, 0, resource_vmo.size, &addr); if (status != ZX_OK) { FML_LOG(ERROR) << "Failed to map: " << zx_status_get_string(status); return false; } resource.address_ = reinterpret_cast<void*>(addr); resource.size_ = resource_vmo.size; return true; } MappedResource::~MappedResource() { if (address_ != nullptr) { zx::vmar::root_self()->unmap(reinterpret_cast<uintptr_t>(address_), size_); address_ = nullptr; size_ = 0; } } static int OpenFdExec(const std::string& path, int dirfd) { int fd = -1; zx_status_t result; if (dirfd == AT_FDCWD) { // fdio_open_fd_at does not support AT_FDCWD, by design. Use fdio_open_fd // and expect an absolute path for that usage pattern. FML_CHECK(path[0] == '/'); result = fdio_open_fd( path.c_str(), static_cast<uint32_t>(fuchsia::io::OpenFlags::RIGHT_READABLE | fuchsia::io::OpenFlags::RIGHT_EXECUTABLE), &fd); } else { FML_CHECK(path[0] != '/'); result = fdio_open_fd_at( dirfd, path.c_str(), static_cast<uint32_t>(fuchsia::io::OpenFlags::RIGHT_READABLE | fuchsia::io::OpenFlags::RIGHT_EXECUTABLE), &fd); } if (result != ZX_OK) { FML_LOG(ERROR) << "fdio_open_fd_at(" << path << ") " << "failed: " << zx_status_get_string(result); return -1; } return fd; } bool ElfSnapshot::Load(fdio_ns_t* namespc, const std::string& path) { int root_dir = -1; if (namespc == nullptr) { root_dir = AT_FDCWD; } else { root_dir = fdio_ns_opendir(namespc); if (root_dir < 0) { FML_LOG(ERROR) << "Failed to open namespace directory"; return false; } } return Load(root_dir, path); } bool ElfSnapshot::Load(int dirfd, const std::string& path) { const int fd = OpenFdExec(path, dirfd); if (fd < 0) { FML_LOG(ERROR) << "Failed to open VMO for " << path << " from dir."; return false; } return Load(fd); } bool ElfSnapshot::Load(int fd) { const char* error; handle_ = Dart_LoadELF_Fd(fd, 0, &error, &vm_data_, &vm_instrs_, &isolate_data_, &isolate_instrs_); if (handle_ == nullptr) { FML_LOG(ERROR) << "Failed load ELF: " << error; return false; } return true; } ElfSnapshot::~ElfSnapshot() { Dart_UnloadELF(handle_); } } // namespace dart_utils
engine/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.cc/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.cc", "repo_id": "engine", "token_count": 2290 }
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 "include/flutter/flutter_window_controller.h" #include <algorithm> #include <iostream> namespace flutter { FlutterWindowController::FlutterWindowController( const std::string& icu_data_path) : icu_data_path_(icu_data_path) { init_succeeded_ = FlutterDesktopInit(); } FlutterWindowController::~FlutterWindowController() { if (controller_) { FlutterDesktopDestroyWindow(controller_); } if (init_succeeded_) { FlutterDesktopTerminate(); } } bool FlutterWindowController::CreateWindow( const WindowProperties& window_properties, const std::string& assets_path, const std::vector<std::string>& arguments, const std::string& aot_library_path) { if (!init_succeeded_) { std::cerr << "Could not create window; FlutterDesktopInit failed." << std::endl; return false; } if (controller_) { std::cerr << "Only one Flutter window can exist at a time." << std::endl; return false; } FlutterDesktopWindowProperties c_window_properties = {}; c_window_properties.title = window_properties.title.c_str(); c_window_properties.width = window_properties.width; c_window_properties.height = window_properties.height; c_window_properties.prevent_resize = window_properties.prevent_resize; FlutterDesktopEngineProperties c_engine_properties = {}; c_engine_properties.assets_path = assets_path.c_str(); c_engine_properties.aot_library_path = aot_library_path.c_str(); c_engine_properties.icu_data_path = icu_data_path_.c_str(); std::vector<const char*> engine_switches; std::transform( arguments.begin(), arguments.end(), std::back_inserter(engine_switches), [](const std::string& arg) -> const char* { return arg.c_str(); }); if (!engine_switches.empty()) { c_engine_properties.switches = &engine_switches[0]; c_engine_properties.switches_count = engine_switches.size(); } controller_ = FlutterDesktopCreateWindow(c_window_properties, c_engine_properties); if (!controller_) { std::cerr << "Failed to create window." << std::endl; return false; } window_ = std::make_unique<FlutterWindow>(FlutterDesktopGetWindow(controller_)); return true; } void FlutterWindowController::DestroyWindow() { if (controller_) { FlutterDesktopDestroyWindow(controller_); controller_ = nullptr; window_ = nullptr; } } FlutterDesktopPluginRegistrarRef FlutterWindowController::GetRegistrarForPlugin( const std::string& plugin_name) { if (!controller_) { std::cerr << "Cannot get plugin registrar without a window; call " "CreateWindow first." << std::endl; return nullptr; } return FlutterDesktopGetPluginRegistrar(FlutterDesktopGetEngine(controller_), plugin_name.c_str()); } bool FlutterWindowController::RunEventLoopWithTimeout( std::chrono::milliseconds timeout) { if (!controller_) { std::cerr << "Cannot run event loop without a window window; call " "CreateWindow first." << std::endl; return false; } uint32_t timeout_milliseconds; if (timeout == std::chrono::milliseconds::max()) { // The C API uses 0 to represent no timeout, so convert |max| to 0. timeout_milliseconds = 0; } else if (timeout.count() > UINT32_MAX) { timeout_milliseconds = UINT32_MAX; } else { timeout_milliseconds = static_cast<uint32_t>(timeout.count()); } bool still_running = FlutterDesktopRunWindowEventLoopWithTimeout( controller_, timeout_milliseconds); if (!still_running) { DestroyWindow(); } return still_running; } void FlutterWindowController::RunEventLoop() { while (RunEventLoopWithTimeout()) { } } } // namespace flutter
engine/shell/platform/glfw/client_wrapper/flutter_window_controller.cc/0
{ "file_path": "engine/shell/platform/glfw/client_wrapper/flutter_window_controller.cc", "repo_id": "engine", "token_count": 1401 }
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/glfw/headless_event_loop.h" #include <atomic> #include <utility> namespace flutter { HeadlessEventLoop::HeadlessEventLoop(std::thread::id main_thread_id, const TaskExpiredCallback& on_task_expired) : EventLoop(main_thread_id, on_task_expired) {} HeadlessEventLoop::~HeadlessEventLoop() = default; void HeadlessEventLoop::WaitUntil(const TaskTimePoint& time) { std::mutex& mutex = GetTaskQueueMutex(); std::unique_lock<std::mutex> lock(mutex); task_queue_condition_.wait_until(lock, time); } void HeadlessEventLoop::Wake() { task_queue_condition_.notify_one(); } } // namespace flutter
engine/shell/platform/glfw/headless_event_loop.cc/0
{ "file_path": "engine/shell/platform/glfw/headless_event_loop.cc", "repo_id": "engine", "token_count": 304 }
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_LINUX_FL_ACCESSIBLE_NODE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_ACCESSIBLE_NODE_H_ #include <atk/atk.h> #include <gio/gio.h> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" G_BEGIN_DECLS // ATK g_autoptr macros weren't added until 2.37. Add them manually. // https://gitlab.gnome.org/GNOME/atk/-/issues/10 #if !ATK_CHECK_VERSION(2, 37, 0) G_DEFINE_AUTOPTR_CLEANUP_FUNC(AtkObject, g_object_unref) #endif #define FL_TYPE_ACCESSIBLE_NODE fl_accessible_node_get_type() G_DECLARE_DERIVABLE_TYPE(FlAccessibleNode, fl_accessible_node, FL, ACCESSIBLE_NODE, AtkObject); /** * FlAccessibleNode: * * #FlAccessibleNode is an object that exposes a Flutter accessibility node to * ATK. */ struct _FlAccessibleNodeClass { AtkObjectClass parent_class; void (*set_name)(FlAccessibleNode* node, const gchar* name); void (*set_extents)(FlAccessibleNode* node, gint x, gint y, gint width, gint height); void (*set_flags)(FlAccessibleNode* node, FlutterSemanticsFlag flags); void (*set_actions)(FlAccessibleNode* node, FlutterSemanticsAction actions); void (*set_value)(FlAccessibleNode* node, const gchar* value); void (*set_text_selection)(FlAccessibleNode* node, gint base, gint extent); void (*set_text_direction)(FlAccessibleNode* node, FlutterTextDirection direction); void (*perform_action)(FlAccessibleNode* node, FlutterSemanticsAction action, GBytes* data); }; /** * fl_accessible_node_new: * @engine: the #FlEngine this node came from. * @id: the semantics node ID this object represents. * * Creates a new accessibility object that exposes Flutter accessibility * information to ATK. * * Returns: a new #FlAccessibleNode. */ FlAccessibleNode* fl_accessible_node_new(FlEngine* engine, int32_t id); /** * fl_accessible_node_set_parent: * @node: an #FlAccessibleNode. * @parent: an #AtkObject. * @index: the index of this node in the parent. * * Sets the parent of this node. The parent can be changed at any time. */ void fl_accessible_node_set_parent(FlAccessibleNode* node, AtkObject* parent, gint index); /** * fl_accessible_node_set_children: * @node: an #FlAccessibleNode. * @children: (transfer none) (element-type AtkObject): a list of #AtkObject. * * Sets the children of this node. The children can be changed at any time. */ void fl_accessible_node_set_children(FlAccessibleNode* node, GPtrArray* children); /** * fl_accessible_node_set_name: * @node: an #FlAccessibleNode. * @name: a node name. * * Sets the name of this node as reported to the a11y consumer. */ void fl_accessible_node_set_name(FlAccessibleNode* node, const gchar* name); /** * fl_accessible_node_set_extents: * @node: an #FlAccessibleNode. * @x: x co-ordinate of this node relative to its parent. * @y: y co-ordinate of this node relative to its parent. * @width: width of this node in pixels. * @height: height of this node in pixels. * * Sets the position and size of this node. */ void fl_accessible_node_set_extents(FlAccessibleNode* node, gint x, gint y, gint width, gint height); /** * fl_accessible_node_set_flags: * @node: an #FlAccessibleNode. * @flags: the flags for this node. * * Sets the flags for this node. */ void fl_accessible_node_set_flags(FlAccessibleNode* node, FlutterSemanticsFlag flags); /** * fl_accessible_node_set_actions: * @node: an #FlAccessibleNode. * @actions: the actions this node can perform. * * Sets the actions that this node can perform. */ void fl_accessible_node_set_actions(FlAccessibleNode* node, FlutterSemanticsAction actions); /** * fl_accessible_node_set_value: * @node: an #FlAccessibleNode. * @value: a node value. * * Sets the value of this node. */ void fl_accessible_node_set_value(FlAccessibleNode* node, const gchar* value); /** * fl_accessible_node_set_text_selection: * @node: an #FlAccessibleNode. * @base: the position at which the text selection originates. * @extent: the position at which the text selection terminates. * * Sets the text selection of this node. */ void fl_accessible_node_set_text_selection(FlAccessibleNode* node, gint base, gint extent); /** * fl_accessible_node_set_text_direction: * @node: an #FlAccessibleNode. * @direction: the direction of the text. * * Sets the text direction of this node. */ void fl_accessible_node_set_text_direction(FlAccessibleNode* node, FlutterTextDirection direction); /** * fl_accessible_node_dispatch_action: * @node: an #FlAccessibleNode. * @action: the action being dispatched. * @data: (allow-none): data associated with the action. * * Performs a semantic action for this node. */ void fl_accessible_node_perform_action(FlAccessibleNode* node, FlutterSemanticsAction action, GBytes* data); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_ACCESSIBLE_NODE_H_
engine/shell/platform/linux/fl_accessible_node.h/0
{ "file_path": "engine/shell/platform/linux/fl_accessible_node.h", "repo_id": "engine", "token_count": 2453 }
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/linux/public/flutter_linux/fl_dart_project.h" #include <gmodule.h> #include <cstdlib> #include "gtest/gtest.h" TEST(FlDartProjectTest, GetPaths) { g_autoptr(FlDartProject) project = fl_dart_project_new(); g_autofree gchar* exe_path = g_file_read_link("/proc/self/exe", nullptr); ASSERT_TRUE(exe_path != nullptr); g_autofree gchar* dir = g_path_get_dirname(exe_path); g_autofree gchar* expected_aot_library_path = g_build_filename(dir, "lib", "libapp.so", nullptr); EXPECT_STREQ(fl_dart_project_get_aot_library_path(project), expected_aot_library_path); g_autofree gchar* expected_assets_path = g_build_filename(dir, "data", "flutter_assets", nullptr); EXPECT_STREQ(fl_dart_project_get_assets_path(project), expected_assets_path); g_autofree gchar* expected_icu_data_path = g_build_filename(dir, "data", "icudtl.dat", nullptr); EXPECT_STREQ(fl_dart_project_get_icu_data_path(project), expected_icu_data_path); } TEST(FlDartProjectTest, OverrideAotLibraryPath) { g_autoptr(FlDartProject) project = fl_dart_project_new(); char aot_library_path[] = "/normal/tuesday/night/for/shia/labeouf"; fl_dart_project_set_aot_library_path(project, aot_library_path); EXPECT_STREQ(fl_dart_project_get_aot_library_path(project), aot_library_path); } TEST(FlDartProjectTest, OverrideAssetsPath) { g_autoptr(FlDartProject) project = fl_dart_project_new(); char assets_path[] = "/normal/tuesday/night/for/shia/labeouf"; fl_dart_project_set_assets_path(project, assets_path); EXPECT_STREQ(fl_dart_project_get_assets_path(project), assets_path); } TEST(FlDartProjectTest, OverrideIcuDataPath) { g_autoptr(FlDartProject) project = fl_dart_project_new(); char icu_data_path[] = "/living/in/the/woods/icudtl.dat"; fl_dart_project_set_icu_data_path(project, icu_data_path); EXPECT_STREQ(fl_dart_project_get_icu_data_path(project), icu_data_path); } TEST(FlDartProjectTest, DartEntrypointArgs) { g_autoptr(FlDartProject) project = fl_dart_project_new(); char** retrieved_args = fl_dart_project_get_dart_entrypoint_arguments(project); EXPECT_EQ(retrieved_args, nullptr); GPtrArray* args_array = g_ptr_array_new(); g_ptr_array_add(args_array, const_cast<char*>("arg_one")); g_ptr_array_add(args_array, const_cast<char*>("arg_two")); g_ptr_array_add(args_array, const_cast<char*>("arg_three")); g_ptr_array_add(args_array, nullptr); gchar** args = reinterpret_cast<gchar**>(g_ptr_array_free(args_array, false)); fl_dart_project_set_dart_entrypoint_arguments(project, args); retrieved_args = fl_dart_project_get_dart_entrypoint_arguments(project); // FlDartProject should have done a deep copy of the args EXPECT_NE(retrieved_args, args); EXPECT_EQ(g_strv_length(retrieved_args), 3U); }
engine/shell/platform/linux/fl_dart_project_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_dart_project_test.cc", "repo_id": "engine", "token_count": 1209 }
366
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_key_embedder_responder.h" #include <gtk/gtk.h> #include <cinttypes> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/linux/fl_key_embedder_responder_private.h" #include "flutter/shell/platform/linux/key_mapping.h" constexpr uint64_t kMicrosecondsPerMillisecond = 1000; static const FlutterKeyEvent kEmptyEvent{ .struct_size = sizeof(FlutterKeyEvent), .timestamp = 0, .type = kFlutterKeyEventTypeDown, .physical = 0, .logical = 0, .character = nullptr, .synthesized = false, }; // Look up a hash table that maps a uint64_t to a uint64_t. // // Returns 0 if not found. // // Both key and value should be directly hashed. static uint64_t lookup_hash_table(GHashTable* table, uint64_t key) { return gpointer_to_uint64( g_hash_table_lookup(table, uint64_to_gpointer(key))); } static gboolean hash_table_find_equal_value(gpointer key, gpointer value, gpointer user_data) { return gpointer_to_uint64(value) == gpointer_to_uint64(user_data); } // Look up a hash table that maps a uint64_t to a uint64_t; given its key, // find its value. // // Returns 0 if not found. // // Both key and value should be directly hashed. static uint64_t reverse_lookup_hash_table(GHashTable* table, uint64_t value) { return gpointer_to_uint64(g_hash_table_find( table, hash_table_find_equal_value, uint64_to_gpointer(value))); } static uint64_t to_lower(uint64_t n) { constexpr uint64_t lower_a = 0x61; constexpr uint64_t upper_a = 0x41; constexpr uint64_t upper_z = 0x5a; constexpr uint64_t lower_a_grave = 0xe0; constexpr uint64_t upper_a_grave = 0xc0; constexpr uint64_t upper_thorn = 0xde; constexpr uint64_t division = 0xf7; // ASCII range. if (n >= upper_a && n <= upper_z) { return n - upper_a + lower_a; } // EASCII range. if (n >= upper_a_grave && n <= upper_thorn && n != division) { return n - upper_a_grave + lower_a_grave; } return n; } /* Define FlKeyEmbedderUserData */ /** * FlKeyEmbedderUserData: * The user_data used when #FlKeyEmbedderResponder sends message through the * embedder.SendKeyEvent API. */ #define FL_TYPE_EMBEDDER_USER_DATA fl_key_embedder_user_data_get_type() G_DECLARE_FINAL_TYPE(FlKeyEmbedderUserData, fl_key_embedder_user_data, FL, KEY_EMBEDDER_USER_DATA, GObject); struct _FlKeyEmbedderUserData { GObject parent_instance; FlKeyResponderAsyncCallback callback; gpointer user_data; }; G_DEFINE_TYPE(FlKeyEmbedderUserData, fl_key_embedder_user_data, G_TYPE_OBJECT) static void fl_key_embedder_user_data_dispose(GObject* object); static void fl_key_embedder_user_data_class_init( FlKeyEmbedderUserDataClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_key_embedder_user_data_dispose; } static void fl_key_embedder_user_data_init(FlKeyEmbedderUserData* self) {} static void fl_key_embedder_user_data_dispose(GObject* object) { // The following line suppresses a warning for unused function // FL_IS_KEY_EMBEDDER_USER_DATA. g_return_if_fail(FL_IS_KEY_EMBEDDER_USER_DATA(object)); } // Creates a new FlKeyChannelUserData private class with all information. // // The callback and the user_data might be nullptr. static FlKeyEmbedderUserData* fl_key_embedder_user_data_new( FlKeyResponderAsyncCallback callback, gpointer user_data) { FlKeyEmbedderUserData* self = FL_KEY_EMBEDDER_USER_DATA( g_object_new(FL_TYPE_EMBEDDER_USER_DATA, nullptr)); self->callback = callback; self->user_data = user_data; return self; } /* Define FlKeyEmbedderResponder */ namespace { typedef enum { kStateLogicUndecided, kStateLogicNormal, kStateLogicReversed, } StateLogicInferrence; } struct _FlKeyEmbedderResponder { GObject parent_instance; EmbedderSendKeyEvent send_key_event; void* send_key_event_user_data; // Internal record for states of whether a key is pressed. // // It is a map from Flutter physical key to Flutter logical key. Both keys // and values are directly stored uint64s. This table is freed by the // responder. GHashTable* pressing_records; // Internal record for states of whether a lock mode is enabled. // // It is a bit mask composed of GTK mode bits. guint lock_records; // Internal record for the last observed key mapping. // // It stores the physical key last seen during a key down event for a logical // key. It is used to synthesize modifier keys and lock keys. // // It is a map from Flutter logical key to physical key. Both keys and // values are directly stored uint64s. This table is freed by the responder. GHashTable* mapping_records; // The inferred logic type indicating whether the CapsLock state logic is // reversed on this platform. // // For more information, see #update_caps_lock_state_logic_inferrence. StateLogicInferrence caps_lock_state_logic_inferrence; // Record if any events has been sent during a // |fl_key_embedder_responder_handle_event| call. bool sent_any_events; // A static map from GTK modifier bits to #FlKeyEmbedderCheckedKey to // configure the modifier keys that needs to be tracked and kept synchronous // on. // // The keys are directly stored guints. The values must be freed with g_free. // This table is freed by the responder. GHashTable* modifier_bit_to_checked_keys; // A static map from GTK modifier bits to #FlKeyEmbedderCheckedKey to // configure the lock mode bits that needs to be tracked and kept synchronous // on. // // The keys are directly stored guints. The values must be freed with g_free. // This table is freed by the responder. GHashTable* lock_bit_to_checked_keys; // A static map generated by reverse mapping lock_bit_to_checked_keys. // // It is a map from primary physical keys to lock bits. Both keys and values // are directly stored uint64s. This table is freed by the responder. GHashTable* logical_key_to_lock_bit; }; static void fl_key_embedder_responder_iface_init( FlKeyResponderInterface* iface); static void fl_key_embedder_responder_dispose(GObject* object); #define FL_TYPE_EMBEDDER_RESPONDER_USER_DATA \ fl_key_embedder_responder_get_type() G_DEFINE_TYPE_WITH_CODE( FlKeyEmbedderResponder, fl_key_embedder_responder, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE(FL_TYPE_KEY_RESPONDER, fl_key_embedder_responder_iface_init)) static void fl_key_embedder_responder_handle_event( FlKeyResponder* responder, FlKeyEvent* event, uint64_t specified_logical_key, FlKeyResponderAsyncCallback callback, gpointer user_data); static void fl_key_embedder_responder_iface_init( FlKeyResponderInterface* iface) { iface->handle_event = fl_key_embedder_responder_handle_event; } // Initializes the FlKeyEmbedderResponder class methods. static void fl_key_embedder_responder_class_init( FlKeyEmbedderResponderClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_key_embedder_responder_dispose; } // Initializes an FlKeyEmbedderResponder instance. static void fl_key_embedder_responder_init(FlKeyEmbedderResponder* self) {} // Disposes of an FlKeyEmbedderResponder instance. static void fl_key_embedder_responder_dispose(GObject* object) { FlKeyEmbedderResponder* self = FL_KEY_EMBEDDER_RESPONDER(object); g_clear_pointer(&self->pressing_records, g_hash_table_unref); g_clear_pointer(&self->mapping_records, g_hash_table_unref); g_clear_pointer(&self->modifier_bit_to_checked_keys, g_hash_table_unref); g_clear_pointer(&self->lock_bit_to_checked_keys, g_hash_table_unref); g_clear_pointer(&self->logical_key_to_lock_bit, g_hash_table_unref); G_OBJECT_CLASS(fl_key_embedder_responder_parent_class)->dispose(object); } // Fill in #logical_key_to_lock_bit by associating a logical key with // its corresponding modifier bit. // // This is used as the body of a loop over #lock_bit_to_checked_keys. static void initialize_logical_key_to_lock_bit_loop_body(gpointer lock_bit, gpointer value, gpointer user_data) { FlKeyEmbedderCheckedKey* checked_key = reinterpret_cast<FlKeyEmbedderCheckedKey*>(value); GHashTable* table = reinterpret_cast<GHashTable*>(user_data); g_hash_table_insert(table, uint64_to_gpointer(checked_key->primary_logical_key), GUINT_TO_POINTER(lock_bit)); } // Creates a new FlKeyEmbedderResponder instance. FlKeyEmbedderResponder* fl_key_embedder_responder_new( EmbedderSendKeyEvent send_key_event, void* send_key_event_user_data) { FlKeyEmbedderResponder* self = FL_KEY_EMBEDDER_RESPONDER( g_object_new(FL_TYPE_EMBEDDER_RESPONDER_USER_DATA, nullptr)); self->send_key_event = send_key_event; self->send_key_event_user_data = send_key_event_user_data; self->pressing_records = g_hash_table_new(g_direct_hash, g_direct_equal); self->mapping_records = g_hash_table_new(g_direct_hash, g_direct_equal); self->lock_records = 0; self->caps_lock_state_logic_inferrence = kStateLogicUndecided; self->modifier_bit_to_checked_keys = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, g_free); initialize_modifier_bit_to_checked_keys(self->modifier_bit_to_checked_keys); self->lock_bit_to_checked_keys = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, g_free); initialize_lock_bit_to_checked_keys(self->lock_bit_to_checked_keys); self->logical_key_to_lock_bit = g_hash_table_new(g_direct_hash, g_direct_equal); g_hash_table_foreach(self->lock_bit_to_checked_keys, initialize_logical_key_to_lock_bit_loop_body, self->logical_key_to_lock_bit); return self; } /* Implement FlKeyEmbedderUserData */ static uint64_t apply_id_plane(uint64_t logical_id, uint64_t plane) { return (logical_id & kValueMask) | plane; } static uint64_t event_to_physical_key(const FlKeyEvent* event) { auto found = xkb_to_physical_key_map.find(event->keycode); if (found != xkb_to_physical_key_map.end()) { return found->second; } return apply_id_plane(event->keycode, kGtkPlane); } static uint64_t event_to_logical_key(const FlKeyEvent* event) { guint keyval = event->keyval; auto found = gtk_keyval_to_logical_key_map.find(keyval); if (found != gtk_keyval_to_logical_key_map.end()) { return found->second; } // EASCII range if (keyval < 256) { return apply_id_plane(to_lower(keyval), kUnicodePlane); } // Auto-generate key return apply_id_plane(keyval, kGtkPlane); } static uint64_t event_to_timestamp(const FlKeyEvent* event) { return kMicrosecondsPerMillisecond * static_cast<double>(event->time); } // Returns a newly accocated UTF-8 string from event->keyval that must be // freed later with g_free(). static char* event_to_character(const FlKeyEvent* event) { gunichar unicodeChar = gdk_keyval_to_unicode(event->keyval); glong items_written; gchar* result = g_ucs4_to_utf8(&unicodeChar, 1, NULL, &items_written, NULL); if (items_written == 0) { if (result != NULL) { g_free(result); } return nullptr; } return result; } // Handles a response from the embedder API to a key event sent to the framework // earlier. static void handle_response(bool handled, gpointer user_data) { g_autoptr(FlKeyEmbedderUserData) data = FL_KEY_EMBEDDER_USER_DATA(user_data); g_return_if_fail(data->callback != nullptr); data->callback(handled, data->user_data); } // Sends a synthesized event to the framework with no demand for callback. static void synthesize_simple_event(FlKeyEmbedderResponder* self, FlutterKeyEventType type, uint64_t physical, uint64_t logical, double timestamp) { FlutterKeyEvent out_event; out_event.struct_size = sizeof(out_event); out_event.timestamp = timestamp; out_event.type = type; out_event.physical = physical; out_event.logical = logical; out_event.character = nullptr; out_event.synthesized = true; self->sent_any_events = true; self->send_key_event(&out_event, nullptr, nullptr, self->send_key_event_user_data); } namespace { // Context variables for the foreach call used to synchronize pressing states // and lock states. typedef struct { FlKeyEmbedderResponder* self; guint state; uint64_t event_logical_key; bool is_down; double timestamp; } SyncStateLoopContext; // Context variables for the foreach call used to find the physical key from // a modifier logical key. typedef struct { bool known_modifier_physical_key; uint64_t logical_key; uint64_t physical_key_from_event; uint64_t corrected_physical_key; } ModifierLogicalToPhysicalContext; } // namespace // Update the pressing record. // // If `logical_key` is 0, the record will be set as "released". Otherwise, the // record will be set as "pressed" with this logical key. This function asserts // that the key is pressed if the caller asked to release, and vice versa. static void update_pressing_state(FlKeyEmbedderResponder* self, uint64_t physical_key, uint64_t logical_key) { if (logical_key != 0) { g_return_if_fail(lookup_hash_table(self->pressing_records, physical_key) == 0); g_hash_table_insert(self->pressing_records, uint64_to_gpointer(physical_key), uint64_to_gpointer(logical_key)); } else { g_return_if_fail(lookup_hash_table(self->pressing_records, physical_key) != 0); g_hash_table_remove(self->pressing_records, uint64_to_gpointer(physical_key)); } } // Update the lock record. // // If `is_down` is false, this function is a no-op. Otherwise, this function // finds the lock bit corresponding to `physical_key`, and flips its bit. static void possibly_update_lock_bit(FlKeyEmbedderResponder* self, uint64_t logical_key, bool is_down) { if (!is_down) { return; } const guint mode_bit = GPOINTER_TO_UINT(g_hash_table_lookup( self->logical_key_to_lock_bit, uint64_to_gpointer(logical_key))); if (mode_bit != 0) { self->lock_records ^= mode_bit; } } static void update_mapping_record(FlKeyEmbedderResponder* self, uint64_t physical_key, uint64_t logical_key) { g_hash_table_insert(self->mapping_records, uint64_to_gpointer(logical_key), uint64_to_gpointer(physical_key)); } // Synchronizes the pressing state of a key to its state from the event by // synthesizing events. // // This is used as the body of a loop over #modifier_bit_to_checked_keys. static void synchronize_pressed_states_loop_body(gpointer key, gpointer value, gpointer user_data) { SyncStateLoopContext* context = reinterpret_cast<SyncStateLoopContext*>(user_data); FlKeyEmbedderCheckedKey* checked_key = reinterpret_cast<FlKeyEmbedderCheckedKey*>(value); const guint modifier_bit = GPOINTER_TO_INT(key); FlKeyEmbedderResponder* self = context->self; // Each TestKey contains up to two logical keys, typically the left modifier // and the right modifier, that correspond to the same modifier_bit. We'd // like to infer whether to synthesize a down or up event for each key. // // The hard part is that, if we want to synthesize a down event, we don't know // which physical key to use. Here we assume the keyboard layout do not change // frequently and use the last physical-logical relationship, recorded in // #mapping_records. const uint64_t logical_keys[] = { checked_key->primary_logical_key, checked_key->secondary_logical_key, }; const guint length = checked_key->secondary_logical_key == 0 ? 1 : 2; const bool any_pressed_by_state = (context->state & modifier_bit) != 0; bool any_pressed_by_record = false; // Traverse each logical key of this modifier bit for 2 purposes: // // 1. Perform the synthesization of release events: If the modifier bit is 0 // and the key is pressed, synthesize a release event. // 2. Prepare for the synthesization of press events: If the modifier bit is // 1, and no keys are pressed (discovered here), synthesize a press event // later. for (guint logical_key_idx = 0; logical_key_idx < length; logical_key_idx++) { const uint64_t logical_key = logical_keys[logical_key_idx]; g_return_if_fail(logical_key != 0); const uint64_t pressing_physical_key = reverse_lookup_hash_table(self->pressing_records, logical_key); const bool this_key_pressed_before_event = pressing_physical_key != 0; any_pressed_by_record = any_pressed_by_record || this_key_pressed_before_event; if (this_key_pressed_before_event && !any_pressed_by_state) { const uint64_t recorded_physical_key = lookup_hash_table(self->mapping_records, logical_key); // Since this key has been pressed before, there must have been a recorded // physical key. g_return_if_fail(recorded_physical_key != 0); // In rare cases #recorded_logical_key is different from #logical_key. const uint64_t recorded_logical_key = lookup_hash_table(self->pressing_records, recorded_physical_key); synthesize_simple_event(self, kFlutterKeyEventTypeUp, recorded_physical_key, recorded_logical_key, context->timestamp); update_pressing_state(self, recorded_physical_key, 0); } } // If the modifier should be pressed, synthesize a down event for its primary // key. if (any_pressed_by_state && !any_pressed_by_record) { const uint64_t logical_key = checked_key->primary_logical_key; const uint64_t recorded_physical_key = lookup_hash_table(self->mapping_records, logical_key); // The physical key is derived from past mapping record if possible. // // The event to be synthesized is a key down event. There might not have // been a mapping record, in which case the hard-coded #primary_physical_key // is used. const uint64_t physical_key = recorded_physical_key != 0 ? recorded_physical_key : checked_key->primary_physical_key; if (recorded_physical_key == 0) { update_mapping_record(self, physical_key, logical_key); } synthesize_simple_event(self, kFlutterKeyEventTypeDown, physical_key, logical_key, context->timestamp); update_pressing_state(self, physical_key, logical_key); } } // Find the stage # by the current record, which should be the recorded stage // before the event. static int find_stage_by_record(bool is_down, bool is_enabled) { constexpr int stage_by_record_index[] = { 0, // is_down: 0, is_enabled: 0 2, // 0 1 3, // 1 0 1 // 1 1 }; return stage_by_record_index[(is_down << 1) + is_enabled]; } // Find the stage # by an event for the target key, which should be inferred // stage before the event. static int find_stage_by_self_event(int stage_by_record, bool is_down_event, bool is_state_on, bool reverse_state_logic) { if (!is_state_on) { return reverse_state_logic ? 2 : 0; } if (is_down_event) { return reverse_state_logic ? 0 : 2; } return stage_by_record; } // Find the stage # by an event for a non-target key, which should be inferred // stage during the event. static int find_stage_by_others_event(int stage_by_record, bool is_state_on) { g_return_val_if_fail(stage_by_record >= 0 && stage_by_record < 4, stage_by_record); if (!is_state_on) { return 0; } if (stage_by_record == 0) { return 1; } return stage_by_record; } // Infer the logic type of CapsLock on the current platform if applicable. // // In most cases, when a lock key is pressed or released, its event has the // key's state as 0-1-1-1 for the 4 stages (as documented in // #synchronize_lock_states_loop_body) respectively. But in very rare cases it // produces 1-1-0-1, which we call "reversed state logic". This is observed // when using Chrome Remote Desktop on macOS (likely a bug). // // To detect whether the current platform behaves normally or reversed, this // function is called on the first down event of CapsLock before calculating // stages. This function then store the inferred mode as // self->caps_lock_state_logic_inferrence. // // This does not help if the same app session is used alternatively between a // reversed platform and a normal platform. But this is the best we can do. static void update_caps_lock_state_logic_inferrence( FlKeyEmbedderResponder* self, bool is_down_event, bool enabled_by_state, int stage_by_record) { if (self->caps_lock_state_logic_inferrence != kStateLogicUndecided) { return; } if (!is_down_event) { return; } const int stage_by_event = find_stage_by_self_event( stage_by_record, is_down_event, enabled_by_state, false); if ((stage_by_event == 0 && stage_by_record == 2) || (stage_by_event == 2 && stage_by_record == 0)) { self->caps_lock_state_logic_inferrence = kStateLogicReversed; } else { self->caps_lock_state_logic_inferrence = kStateLogicNormal; } } // Synchronizes the lock state of a key to its state from the event by // synthesizing events. // // This is used as the body of a loop over #lock_bit_to_checked_keys. // // This function might modify #caps_lock_state_logic_inferrence. static void synchronize_lock_states_loop_body(gpointer key, gpointer value, gpointer user_data) { SyncStateLoopContext* context = reinterpret_cast<SyncStateLoopContext*>(user_data); FlKeyEmbedderCheckedKey* checked_key = reinterpret_cast<FlKeyEmbedderCheckedKey*>(value); guint modifier_bit = GPOINTER_TO_INT(key); FlKeyEmbedderResponder* self = context->self; const uint64_t logical_key = checked_key->primary_logical_key; const uint64_t recorded_physical_key = lookup_hash_table(self->mapping_records, logical_key); // The physical key is derived from past mapping record if possible. // // If the event to be synthesized is a key up event, then there must have // been a key down event before, which has updated the mapping record. // If the event to be synthesized is a key down event, then there might // not have been a mapping record, in which case the hard-coded // #primary_physical_key is used. const uint64_t physical_key = recorded_physical_key != 0 ? recorded_physical_key : checked_key->primary_physical_key; // A lock mode key can be at any of a 4-stage cycle, depending on whether it's // pressed and enabled. The following table lists the definition of each // stage (TruePressed and TrueEnabled), the event of the lock key between // every 2 stages (SelfType and SelfState), and the event of other keys at // each stage (OthersState). On certain platforms SelfState uses a reversed // rule for certain keys (SelfState(rvsd), as documented in // #update_caps_lock_state_logic_inferrence). // // # [0] [1] [2] [3] // TruePressed: Released Pressed Released Pressed // TrueEnabled: Disabled Enabled Enabled Disabled // SelfType: Down Up Down Up // SelfState: 0 1 1 1 // SelfState(rvsd): 1 1 0 1 // OthersState: 0 1 1 1 // // When the exact stage can't be derived, choose the stage that requires the // minimal synthesization. const uint64_t pressed_logical_key = recorded_physical_key == 0 ? 0 : lookup_hash_table(self->pressing_records, recorded_physical_key); g_return_if_fail(pressed_logical_key == 0 || pressed_logical_key == logical_key); const int stage_by_record = find_stage_by_record( pressed_logical_key != 0, (self->lock_records & modifier_bit) != 0); const bool enabled_by_state = (context->state & modifier_bit) != 0; const bool this_key_is_event_key = logical_key == context->event_logical_key; if (this_key_is_event_key && checked_key->is_caps_lock) { update_caps_lock_state_logic_inferrence(self, context->is_down, enabled_by_state, stage_by_record); g_return_if_fail(self->caps_lock_state_logic_inferrence != kStateLogicUndecided); } const bool reverse_state_logic = checked_key->is_caps_lock && self->caps_lock_state_logic_inferrence == kStateLogicReversed; const int stage_by_event = this_key_is_event_key ? find_stage_by_self_event(stage_by_record, context->is_down, enabled_by_state, reverse_state_logic) : find_stage_by_others_event(stage_by_record, enabled_by_state); // The destination stage is equal to stage_by_event but shifted cyclically to // be no less than stage_by_record. constexpr int kNumStages = 4; const int destination_stage = stage_by_event >= stage_by_record ? stage_by_event : stage_by_event + kNumStages; g_return_if_fail(stage_by_record <= destination_stage); if (stage_by_record == destination_stage) { return; } for (int current_stage = stage_by_record; current_stage < destination_stage; current_stage += 1) { if (current_stage == 9) { return; } const int standard_current_stage = current_stage % kNumStages; const bool is_down_event = standard_current_stage == 0 || standard_current_stage == 2; if (is_down_event && recorded_physical_key == 0) { update_mapping_record(self, physical_key, logical_key); } FlutterKeyEventType type = is_down_event ? kFlutterKeyEventTypeDown : kFlutterKeyEventTypeUp; update_pressing_state(self, physical_key, is_down_event ? logical_key : 0); possibly_update_lock_bit(self, logical_key, is_down_event); synthesize_simple_event(self, type, physical_key, logical_key, context->timestamp); } } // Find if a given physical key is the primary physical of one of the known // modifier keys. // // This is used as the body of a loop over #modifier_bit_to_checked_keys. static void is_known_modifier_physical_key_loop_body(gpointer key, gpointer value, gpointer user_data) { ModifierLogicalToPhysicalContext* context = reinterpret_cast<ModifierLogicalToPhysicalContext*>(user_data); FlKeyEmbedderCheckedKey* checked_key = reinterpret_cast<FlKeyEmbedderCheckedKey*>(value); if (checked_key->primary_physical_key == context->physical_key_from_event) { context->known_modifier_physical_key = true; } } // Return the primary physical key of a known modifier key which matches the // given logical key. // // This is used as the body of a loop over #modifier_bit_to_checked_keys. static void find_physical_from_logical_loop_body(gpointer key, gpointer value, gpointer user_data) { ModifierLogicalToPhysicalContext* context = reinterpret_cast<ModifierLogicalToPhysicalContext*>(user_data); FlKeyEmbedderCheckedKey* checked_key = reinterpret_cast<FlKeyEmbedderCheckedKey*>(value); if (checked_key->primary_logical_key == context->logical_key || checked_key->secondary_logical_key == context->logical_key) { context->corrected_physical_key = checked_key->primary_physical_key; } } static uint64_t corrected_modifier_physical_key( GHashTable* modifier_bit_to_checked_keys, uint64_t physical_key_from_event, uint64_t logical_key) { ModifierLogicalToPhysicalContext logical_to_physical_context; logical_to_physical_context.known_modifier_physical_key = false; logical_to_physical_context.physical_key_from_event = physical_key_from_event; logical_to_physical_context.logical_key = logical_key; // If no match is found, defaults to the physical key retrieved from the // event. logical_to_physical_context.corrected_physical_key = physical_key_from_event; // Check if the physical key is one of the known modifier physical key. g_hash_table_foreach(modifier_bit_to_checked_keys, is_known_modifier_physical_key_loop_body, &logical_to_physical_context); // If the physical key matches a known modifier key, find the modifier // physical key from the logical key. if (logical_to_physical_context.known_modifier_physical_key) { g_hash_table_foreach(modifier_bit_to_checked_keys, find_physical_from_logical_loop_body, &logical_to_physical_context); } return logical_to_physical_context.corrected_physical_key; } static void fl_key_embedder_responder_handle_event_impl( FlKeyResponder* responder, FlKeyEvent* event, uint64_t specified_logical_key, FlKeyResponderAsyncCallback callback, gpointer user_data) { FlKeyEmbedderResponder* self = FL_KEY_EMBEDDER_RESPONDER(responder); g_return_if_fail(event != nullptr); g_return_if_fail(callback != nullptr); const uint64_t logical_key = specified_logical_key != 0 ? specified_logical_key : event_to_logical_key(event); const uint64_t physical_key_from_event = event_to_physical_key(event); const uint64_t physical_key = corrected_modifier_physical_key( self->modifier_bit_to_checked_keys, physical_key_from_event, logical_key); const double timestamp = event_to_timestamp(event); const bool is_down_event = event->is_press; SyncStateLoopContext sync_state_context; sync_state_context.self = self; sync_state_context.state = event->state; sync_state_context.timestamp = timestamp; sync_state_context.is_down = is_down_event; sync_state_context.event_logical_key = logical_key; // Update lock mode states g_hash_table_foreach(self->lock_bit_to_checked_keys, synchronize_lock_states_loop_body, &sync_state_context); // Update pressing states g_hash_table_foreach(self->modifier_bit_to_checked_keys, synchronize_pressed_states_loop_body, &sync_state_context); // Construct the real event const uint64_t last_logical_record = lookup_hash_table(self->pressing_records, physical_key); FlutterKeyEvent out_event; out_event.struct_size = sizeof(out_event); out_event.timestamp = timestamp; out_event.physical = physical_key; out_event.logical = last_logical_record != 0 ? last_logical_record : logical_key; out_event.character = nullptr; out_event.synthesized = false; g_autofree char* character_to_free = nullptr; if (is_down_event) { if (last_logical_record) { // A key has been pressed that has the exact physical key as a currently // pressed one. This can happen during repeated events. out_event.type = kFlutterKeyEventTypeRepeat; } else { out_event.type = kFlutterKeyEventTypeDown; } character_to_free = event_to_character(event); // Might be null out_event.character = character_to_free; } else { // is_down_event false if (!last_logical_record) { // The physical key has been released before. It might indicate a missed // event due to loss of focus, or multiple keyboards pressed keys with the // same physical key. Ignore the up event. callback(true, user_data); return; } else { out_event.type = kFlutterKeyEventTypeUp; } } if (out_event.type != kFlutterKeyEventTypeRepeat) { update_pressing_state(self, physical_key, is_down_event ? logical_key : 0); } possibly_update_lock_bit(self, logical_key, is_down_event); if (is_down_event) { update_mapping_record(self, physical_key, logical_key); } FlKeyEmbedderUserData* response_data = fl_key_embedder_user_data_new(callback, user_data); self->sent_any_events = true; self->send_key_event(&out_event, handle_response, response_data, self->send_key_event_user_data); } // Sends a key event to the framework. static void fl_key_embedder_responder_handle_event( FlKeyResponder* responder, FlKeyEvent* event, uint64_t specified_logical_key, FlKeyResponderAsyncCallback callback, gpointer user_data) { FlKeyEmbedderResponder* self = FL_KEY_EMBEDDER_RESPONDER(responder); self->sent_any_events = false; fl_key_embedder_responder_handle_event_impl( responder, event, specified_logical_key, callback, user_data); if (!self->sent_any_events) { self->send_key_event(&kEmptyEvent, nullptr, nullptr, self->send_key_event_user_data); } } void fl_key_embedder_responder_sync_modifiers_if_needed( FlKeyEmbedderResponder* responder, guint state, double event_time) { const double timestamp = event_time * kMicrosecondsPerMillisecond; SyncStateLoopContext sync_state_context; sync_state_context.self = responder; sync_state_context.state = state; sync_state_context.timestamp = timestamp; // Update pressing states. g_hash_table_foreach(responder->modifier_bit_to_checked_keys, synchronize_pressed_states_loop_body, &sync_state_context); } GHashTable* fl_key_embedder_responder_get_pressed_state( FlKeyEmbedderResponder* self) { return self->pressing_records; }
engine/shell/platform/linux/fl_key_embedder_responder.cc/0
{ "file_path": "engine/shell/platform/linux/fl_key_embedder_responder.cc", "repo_id": "engine", "token_count": 13771 }
367
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_METHOD_CALL_PRIVATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_METHOD_CALL_PRIVATE_H_ #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_call.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" G_BEGIN_DECLS /** * fl_method_call_new: * @name: a method name. * @args: arguments provided to a method. * @channel: channel call received on. * @response_handle: handle to respond with. * * Creates a method call. * * Returns: a new #FlMethodCall. */ FlMethodCall* fl_method_call_new( const gchar* name, FlValue* args, FlMethodChannel* channel, FlBinaryMessengerResponseHandle* response_handle); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_METHOD_CALL_PRIVATE_H_
engine/shell/platform/linux/fl_method_call_private.h/0
{ "file_path": "engine/shell/platform/linux/fl_method_call_private.h", "repo_id": "engine", "token_count": 405 }
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 <gtk/gtk.h> #include "flutter/shell/platform/linux/fl_binary_messenger_private.h" #include "flutter/shell/platform/linux/fl_method_codec_private.h" #include "flutter/shell/platform/linux/fl_platform_plugin.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "flutter/shell/platform/linux/testing/mock_binary_messenger.h" #include "flutter/testing/testing.h" #include "gmock/gmock.h" #include "gtest/gtest.h" MATCHER_P(SuccessResponse, result, "") { g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response(FL_METHOD_CODEC(codec), arg, nullptr); if (fl_value_equal(fl_method_response_get_result(response, nullptr), result)) { return true; } *result_listener << ::testing::PrintToString(response); return false; } class MethodCallMatcher { public: using is_gtest_matcher = void; explicit MethodCallMatcher(::testing::Matcher<std::string> name, ::testing::Matcher<FlValue*> args) : name_(std::move(name)), args_(std::move(args)) {} bool MatchAndExplain(GBytes* method_call, ::testing::MatchResultListener* result_listener) const { g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GError) error = nullptr; g_autofree gchar* name = nullptr; g_autoptr(FlValue) args = nullptr; gboolean result = fl_method_codec_decode_method_call( FL_METHOD_CODEC(codec), method_call, &name, &args, &error); if (!result) { *result_listener << ::testing::PrintToString(error->message); return false; } if (!name_.MatchAndExplain(name, result_listener)) { *result_listener << " where the name doesn't match: \"" << name << "\""; return false; } if (!args_.MatchAndExplain(args, result_listener)) { *result_listener << " where the args don't match: " << ::testing::PrintToString(args); return false; } return true; } void DescribeTo(std::ostream* os) const { *os << "method name "; name_.DescribeTo(os); *os << " and args "; args_.DescribeTo(os); } void DescribeNegationTo(std::ostream* os) const { *os << "method name "; name_.DescribeNegationTo(os); *os << " or args "; args_.DescribeNegationTo(os); } private: ::testing::Matcher<std::string> name_; ::testing::Matcher<FlValue*> args_; }; static ::testing::Matcher<GBytes*> MethodCall( const std::string& name, ::testing::Matcher<FlValue*> args) { return MethodCallMatcher(::testing::StrEq(name), std::move(args)); } MATCHER_P(FlValueEq, value, "equal to " + ::testing::PrintToString(value)) { return fl_value_equal(arg, value); } G_DECLARE_FINAL_TYPE(FlTestApplication, fl_test_application, FL, TEST_APPLICATION, GtkApplication) struct _FlTestApplication { GtkApplication parent_instance; gboolean* dispose_called; }; G_DEFINE_TYPE(FlTestApplication, fl_test_application, gtk_application_get_type()) static void fl_test_application_startup(GApplication* application) { G_APPLICATION_CLASS(fl_test_application_parent_class)->startup(application); // Add a window to this application, which will hold a reference to the // application and stop it disposing. See // https://gitlab.gnome.org/GNOME/gtk/-/issues/6190 gtk_application_window_new(GTK_APPLICATION(application)); } static void fl_test_application_activate(GApplication* application) { G_APPLICATION_CLASS(fl_test_application_parent_class)->activate(application); ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; g_autoptr(FlPlatformPlugin) plugin = fl_platform_plugin_new(messenger); EXPECT_NE(plugin, nullptr); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(FlValue) exit_result = fl_value_new_map(); fl_value_set_string_take(exit_result, "response", fl_value_new_string("exit")); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(exit_result), ::testing::_)) .WillOnce(::testing::Return(true)); // Request app exit. g_autoptr(FlValue) args = fl_value_new_map(); fl_value_set_string_take(args, "type", fl_value_new_string("required")); g_autoptr(GBytes) message = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "System.exitApplication", args, nullptr); messenger.ReceiveMessage("flutter/platform", message); } static void fl_test_application_dispose(GObject* object) { FlTestApplication* self = FL_TEST_APPLICATION(object); *self->dispose_called = true; G_OBJECT_CLASS(fl_test_application_parent_class)->dispose(object); } static void fl_test_application_class_init(FlTestApplicationClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_test_application_dispose; G_APPLICATION_CLASS(klass)->startup = fl_test_application_startup; G_APPLICATION_CLASS(klass)->activate = fl_test_application_activate; } static void fl_test_application_init(FlTestApplication* self) {} FlTestApplication* fl_test_application_new(gboolean* dispose_called) { FlTestApplication* self = FL_TEST_APPLICATION( g_object_new(fl_test_application_get_type(), nullptr)); // Don't try and register on D-Bus. g_application_set_application_id(G_APPLICATION(self), "dev.flutter.GtkTest"); g_application_set_flags(G_APPLICATION(self), G_APPLICATION_NON_UNIQUE); // Added to stop compiler complaining about an unused function. FL_IS_TEST_APPLICATION(self); self->dispose_called = dispose_called; return self; } TEST(FlPlatformPluginTest, PlaySound) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; g_autoptr(FlPlatformPlugin) plugin = fl_platform_plugin_new(messenger); EXPECT_NE(plugin, nullptr); g_autoptr(FlValue) args = fl_value_new_string("SystemSoundType.alert"); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) message = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "SystemSound.play", args, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/platform", message); } TEST(FlPlatformPluginTest, ExitApplication) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; g_autoptr(FlPlatformPlugin) plugin = fl_platform_plugin_new(messenger); EXPECT_NE(plugin, nullptr); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(FlValue) null = fl_value_new_null(); ON_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillByDefault(testing::Return(TRUE)); // Indicate that the binding is initialized. g_autoptr(GError) error = nullptr; g_autoptr(GBytes) init_message = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "System.initializationComplete", nullptr, &error); messenger.ReceiveMessage("flutter/platform", init_message); g_autoptr(FlValue) request_args = fl_value_new_map(); fl_value_set_string_take(request_args, "type", fl_value_new_string("cancelable")); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/platform"), MethodCall("System.requestAppExit", FlValueEq(request_args)), ::testing::_, ::testing::_, ::testing::_)); g_autoptr(FlValue) args = fl_value_new_map(); fl_value_set_string_take(args, "type", fl_value_new_string("cancelable")); g_autoptr(GBytes) message = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "System.exitApplication", args, nullptr); messenger.ReceiveMessage("flutter/platform", message); } TEST(FlPlatformPluginTest, ExitApplicationDispose) { gtk_init(0, nullptr); gboolean dispose_called = false; FlTestApplication* application = fl_test_application_new(&dispose_called); // Run the application, it will quit after startup. g_application_run(G_APPLICATION(application), 0, nullptr); EXPECT_FALSE(dispose_called); g_object_unref(application); EXPECT_TRUE(dispose_called); }
engine/shell/platform/linux/fl_platform_plugin_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_platform_plugin_test.cc", "repo_id": "engine", "token_count": 3613 }
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. #include "flutter/shell/platform/linux/fl_settings.h" #include "flutter/shell/platform/linux/fl_gnome_settings.h" #include "flutter/shell/platform/linux/fl_settings_portal.h" G_DEFINE_INTERFACE(FlSettings, fl_settings, G_TYPE_OBJECT) enum { kSignalChanged, kSignalLastSignal, }; static guint signals[kSignalLastSignal]; static void fl_settings_default_init(FlSettingsInterface* iface) { /** * FlSettings::changed: * @settings: an #FlSettings * * This signal is emitted after the settings have been changed. */ signals[kSignalChanged] = g_signal_new("changed", G_TYPE_FROM_INTERFACE(iface), G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); } FlClockFormat fl_settings_get_clock_format(FlSettings* self) { return FL_SETTINGS_GET_IFACE(self)->get_clock_format(self); } FlColorScheme fl_settings_get_color_scheme(FlSettings* self) { return FL_SETTINGS_GET_IFACE(self)->get_color_scheme(self); } gboolean fl_settings_get_enable_animations(FlSettings* self) { return FL_SETTINGS_GET_IFACE(self)->get_enable_animations(self); } gboolean fl_settings_get_high_contrast(FlSettings* self) { return FL_SETTINGS_GET_IFACE(self)->get_high_contrast(self); } gdouble fl_settings_get_text_scaling_factor(FlSettings* self) { return FL_SETTINGS_GET_IFACE(self)->get_text_scaling_factor(self); } void fl_settings_emit_changed(FlSettings* self) { g_return_if_fail(FL_IS_SETTINGS(self)); g_signal_emit(self, signals[kSignalChanged], 0); } FlSettings* fl_settings_new() { g_autoptr(FlSettingsPortal) portal = fl_settings_portal_new(); g_autoptr(GError) error = nullptr; if (!fl_settings_portal_start(portal, &error)) { g_debug("XDG desktop portal settings unavailable: %s", error->message); return fl_gnome_settings_new(); } return FL_SETTINGS(g_object_ref(portal)); }
engine/shell/platform/linux/fl_settings.cc/0
{ "file_path": "engine/shell/platform/linux/fl_settings.cc", "repo_id": "engine", "token_count": 764 }
370
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_text_input_plugin.h" #include <gtk/gtk.h> #include "flutter/shell/platform/common/text_editing_delta.h" #include "flutter/shell/platform/common/text_input_model.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h" static constexpr char kChannelName[] = "flutter/textinput"; static constexpr char kBadArgumentsError[] = "Bad Arguments"; static constexpr char kSetClientMethod[] = "TextInput.setClient"; static constexpr char kShowMethod[] = "TextInput.show"; static constexpr char kSetEditingStateMethod[] = "TextInput.setEditingState"; static constexpr char kClearClientMethod[] = "TextInput.clearClient"; static constexpr char kHideMethod[] = "TextInput.hide"; static constexpr char kUpdateEditingStateMethod[] = "TextInputClient.updateEditingState"; static constexpr char kUpdateEditingStateWithDeltasMethod[] = "TextInputClient.updateEditingStateWithDeltas"; static constexpr char kPerformActionMethod[] = "TextInputClient.performAction"; static constexpr char kSetEditableSizeAndTransform[] = "TextInput.setEditableSizeAndTransform"; static constexpr char kSetMarkedTextRect[] = "TextInput.setMarkedTextRect"; static constexpr char kInputActionKey[] = "inputAction"; static constexpr char kTextInputTypeKey[] = "inputType"; static constexpr char kEnableDeltaModel[] = "enableDeltaModel"; static constexpr char kTextInputTypeNameKey[] = "name"; static constexpr char kTextKey[] = "text"; static constexpr char kSelectionBaseKey[] = "selectionBase"; static constexpr char kSelectionExtentKey[] = "selectionExtent"; static constexpr char kSelectionAffinityKey[] = "selectionAffinity"; static constexpr char kSelectionIsDirectionalKey[] = "selectionIsDirectional"; static constexpr char kComposingBaseKey[] = "composingBase"; static constexpr char kComposingExtentKey[] = "composingExtent"; static constexpr char kTransform[] = "transform"; static constexpr char kTextAffinityDownstream[] = "TextAffinity.downstream"; static constexpr char kMultilineInputType[] = "TextInputType.multiline"; static constexpr char kNoneInputType[] = "TextInputType.none"; static constexpr char kNewlineInputAction[] = "TextInputAction.newline"; static constexpr int64_t kClientIdUnset = -1; typedef enum { kFlTextInputTypeText, // Send newline when multi-line and enter is pressed. kFlTextInputTypeMultiline, // The input method is not shown at all. kFlTextInputTypeNone, } FlTextInputType; struct FlTextInputPluginPrivate { GObject parent_instance; FlMethodChannel* channel; // Client ID provided by Flutter to report events with. int64_t client_id; // Input action to perform when enter pressed. gchar* input_action; // The type of the input method. FlTextInputType input_type; // Whether to enable that the engine sends text input updates to the framework // as TextEditingDeltas or as one TextEditingValue. // For more information on the delta model, see: // https://master-api.flutter.dev/flutter/services/TextInputConfiguration/enableDeltaModel.html gboolean enable_delta_model; // Input method. GtkIMContext* im_context; FlTextInputViewDelegate* view_delegate; flutter::TextInputModel* text_model; // A 4x4 matrix that maps from `EditableText` local coordinates to the // coordinate system of `PipelineOwner.rootNode`. double editabletext_transform[4][4]; // The smallest rect, in local coordinates, of the text in the composing // range, or of the caret in the case where there is no current composing // range. This value is updated via `TextInput.setMarkedTextRect` messages // over the text input channel. GdkRectangle composing_rect; }; G_DEFINE_TYPE_WITH_PRIVATE(FlTextInputPlugin, fl_text_input_plugin, G_TYPE_OBJECT) // Completes method call and returns TRUE if the call was successful. static gboolean finish_method(GObject* object, GAsyncResult* result, GError** error) { g_autoptr(FlMethodResponse) response = fl_method_channel_invoke_method_finish( FL_METHOD_CHANNEL(object), result, error); if (response == nullptr) { return FALSE; } return fl_method_response_get_result(response, error) != nullptr; } // Called when a response is received from TextInputClient.updateEditingState() static void update_editing_state_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; if (!finish_method(object, result, &error)) { g_warning("Failed to call %s: %s", kUpdateEditingStateMethod, error->message); } } // Informs Flutter of text input changes. static void update_editing_state(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_int(priv->client_id)); g_autoptr(FlValue) value = fl_value_new_map(); flutter::TextRange selection = priv->text_model->selection(); fl_value_set_string_take( value, kTextKey, fl_value_new_string(priv->text_model->GetText().c_str())); fl_value_set_string_take(value, kSelectionBaseKey, fl_value_new_int(selection.base())); fl_value_set_string_take(value, kSelectionExtentKey, fl_value_new_int(selection.extent())); int composing_base = -1; int composing_extent = -1; if (!priv->text_model->composing_range().collapsed()) { composing_base = priv->text_model->composing_range().base(); composing_extent = priv->text_model->composing_range().extent(); } fl_value_set_string_take(value, kComposingBaseKey, fl_value_new_int(composing_base)); fl_value_set_string_take(value, kComposingExtentKey, fl_value_new_int(composing_extent)); // The following keys are not implemented and set to default values. fl_value_set_string_take(value, kSelectionAffinityKey, fl_value_new_string(kTextAffinityDownstream)); fl_value_set_string_take(value, kSelectionIsDirectionalKey, fl_value_new_bool(FALSE)); fl_value_append(args, value); fl_method_channel_invoke_method(priv->channel, kUpdateEditingStateMethod, args, nullptr, update_editing_state_response_cb, self); } // Informs Flutter of text input changes by passing just the delta. static void update_editing_state_with_delta(FlTextInputPlugin* self, flutter::TextEditingDelta* delta) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_int(priv->client_id)); g_autoptr(FlValue) deltaValue = fl_value_new_map(); fl_value_set_string_take(deltaValue, "oldText", fl_value_new_string(delta->old_text().c_str())); fl_value_set_string_take(deltaValue, "deltaText", fl_value_new_string(delta->delta_text().c_str())); fl_value_set_string_take(deltaValue, "deltaStart", fl_value_new_int(delta->delta_start())); fl_value_set_string_take(deltaValue, "deltaEnd", fl_value_new_int(delta->delta_end())); flutter::TextRange selection = priv->text_model->selection(); fl_value_set_string_take(deltaValue, "selectionBase", fl_value_new_int(selection.base())); fl_value_set_string_take(deltaValue, "selectionExtent", fl_value_new_int(selection.extent())); fl_value_set_string_take(deltaValue, "selectionAffinity", fl_value_new_string(kTextAffinityDownstream)); fl_value_set_string_take(deltaValue, "selectionIsDirectional", fl_value_new_bool(FALSE)); int composing_base = -1; int composing_extent = -1; if (!priv->text_model->composing_range().collapsed()) { composing_base = priv->text_model->composing_range().base(); composing_extent = priv->text_model->composing_range().extent(); } fl_value_set_string_take(deltaValue, "composingBase", fl_value_new_int(composing_base)); fl_value_set_string_take(deltaValue, "composingExtent", fl_value_new_int(composing_extent)); g_autoptr(FlValue) deltas = fl_value_new_list(); fl_value_append(deltas, deltaValue); g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_string(value, "deltas", deltas); fl_value_append(args, value); fl_method_channel_invoke_method( priv->channel, kUpdateEditingStateWithDeltasMethod, args, nullptr, update_editing_state_response_cb, self); } // Called when a response is received from TextInputClient.performAction() static void perform_action_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; if (!finish_method(object, result, &error)) { g_warning("Failed to call %s: %s", kPerformActionMethod, error->message); } } // Inform Flutter that the input has been activated. static void perform_action(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); g_return_if_fail(FL_IS_TEXT_INPUT_PLUGIN(self)); g_return_if_fail(priv->client_id != 0); g_return_if_fail(priv->input_action != nullptr); g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_int(priv->client_id)); fl_value_append_take(args, fl_value_new_string(priv->input_action)); fl_method_channel_invoke_method(priv->channel, kPerformActionMethod, args, nullptr, perform_action_response_cb, self); } // Signal handler for GtkIMContext::preedit-start static void im_preedit_start_cb(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); priv->text_model->BeginComposing(); } // Signal handler for GtkIMContext::preedit-changed static void im_preedit_changed_cb(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); std::string text_before_change = priv->text_model->GetText(); flutter::TextRange composing_before_change = priv->text_model->composing_range(); g_autofree gchar* buf = nullptr; gint cursor_offset = 0; gtk_im_context_get_preedit_string(priv->im_context, &buf, nullptr, &cursor_offset); if (priv->text_model->composing()) { cursor_offset += priv->text_model->composing_range().start(); } else { cursor_offset += priv->text_model->selection().start(); } priv->text_model->UpdateComposingText(buf); priv->text_model->SetSelection(flutter::TextRange(cursor_offset)); if (priv->enable_delta_model) { std::string text(buf); flutter::TextEditingDelta delta = flutter::TextEditingDelta( text_before_change, composing_before_change, text); update_editing_state_with_delta(self, &delta); } else { update_editing_state(self); } } // Signal handler for GtkIMContext::commit static void im_commit_cb(FlTextInputPlugin* self, const gchar* text) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); std::string text_before_change = priv->text_model->GetText(); flutter::TextRange composing_before_change = priv->text_model->composing_range(); flutter::TextRange selection_before_change = priv->text_model->selection(); gboolean was_composing = priv->text_model->composing(); priv->text_model->AddText(text); if (priv->text_model->composing()) { priv->text_model->CommitComposing(); } if (priv->enable_delta_model) { flutter::TextRange replace_range = was_composing ? composing_before_change : selection_before_change; std::unique_ptr<flutter::TextEditingDelta> delta = std::make_unique<flutter::TextEditingDelta>(text_before_change, replace_range, text); update_editing_state_with_delta(self, delta.get()); } else { update_editing_state(self); } } // Signal handler for GtkIMContext::preedit-end static void im_preedit_end_cb(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); priv->text_model->EndComposing(); if (priv->enable_delta_model) { flutter::TextEditingDelta delta = flutter::TextEditingDelta(priv->text_model->GetText()); update_editing_state_with_delta(self, &delta); } else { update_editing_state(self); } } // Signal handler for GtkIMContext::retrieve-surrounding static gboolean im_retrieve_surrounding_cb(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); auto text = priv->text_model->GetText(); size_t cursor_offset = priv->text_model->GetCursorOffset(); gtk_im_context_set_surrounding(priv->im_context, text.c_str(), -1, cursor_offset); return TRUE; } // Signal handler for GtkIMContext::delete-surrounding static gboolean im_delete_surrounding_cb(FlTextInputPlugin* self, gint offset, gint n_chars) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); std::string text_before_change = priv->text_model->GetText(); if (priv->text_model->DeleteSurrounding(offset, n_chars)) { if (priv->enable_delta_model) { flutter::TextEditingDelta delta = flutter::TextEditingDelta( text_before_change, priv->text_model->composing_range(), priv->text_model->GetText()); update_editing_state_with_delta(self, &delta); } else { update_editing_state(self); } } return TRUE; } // Called when the input method client is set up. static FlMethodResponse* set_client(FlTextInputPlugin* self, FlValue* args) { if (fl_value_get_type(args) != FL_VALUE_TYPE_LIST || fl_value_get_length(args) < 2) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Expected 2-element list", nullptr)); } FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); priv->client_id = fl_value_get_int(fl_value_get_list_value(args, 0)); FlValue* config_value = fl_value_get_list_value(args, 1); g_free(priv->input_action); FlValue* input_action_value = fl_value_lookup_string(config_value, kInputActionKey); if (fl_value_get_type(input_action_value) == FL_VALUE_TYPE_STRING) { priv->input_action = g_strdup(fl_value_get_string(input_action_value)); } FlValue* enable_delta_model_value = fl_value_lookup_string(config_value, kEnableDeltaModel); gboolean enable_delta_model = fl_value_get_bool(enable_delta_model_value); priv->enable_delta_model = enable_delta_model; // Reset the input type, then set only if appropriate. priv->input_type = kFlTextInputTypeText; FlValue* input_type_value = fl_value_lookup_string(config_value, kTextInputTypeKey); if (fl_value_get_type(input_type_value) == FL_VALUE_TYPE_MAP) { FlValue* input_type_name = fl_value_lookup_string(input_type_value, kTextInputTypeNameKey); if (fl_value_get_type(input_type_name) == FL_VALUE_TYPE_STRING) { const gchar* input_type = fl_value_get_string(input_type_name); if (g_strcmp0(input_type, kMultilineInputType) == 0) { priv->input_type = kFlTextInputTypeMultiline; } else if (g_strcmp0(input_type, kNoneInputType) == 0) { priv->input_type = kFlTextInputTypeNone; } } } return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Hides the input method. static FlMethodResponse* hide(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); gtk_im_context_focus_out(priv->im_context); return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Shows the input method. static FlMethodResponse* show(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); if (priv->input_type == kFlTextInputTypeNone) { return hide(self); } gtk_im_context_focus_in(priv->im_context); return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Updates the editing state from Flutter. static FlMethodResponse* set_editing_state(FlTextInputPlugin* self, FlValue* args) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); const gchar* text = fl_value_get_string(fl_value_lookup_string(args, kTextKey)); priv->text_model->SetText(text); int64_t selection_base = fl_value_get_int(fl_value_lookup_string(args, kSelectionBaseKey)); int64_t selection_extent = fl_value_get_int(fl_value_lookup_string(args, kSelectionExtentKey)); // Flutter uses -1/-1 for invalid; translate that to 0/0 for the model. if (selection_base == -1 && selection_extent == -1) { selection_base = selection_extent = 0; } priv->text_model->SetText(text); priv->text_model->SetSelection( flutter::TextRange(selection_base, selection_extent)); int64_t composing_base = fl_value_get_int(fl_value_lookup_string(args, kComposingBaseKey)); int64_t composing_extent = fl_value_get_int(fl_value_lookup_string(args, kComposingExtentKey)); if (composing_base == -1 && composing_extent == -1) { priv->text_model->EndComposing(); } else { size_t composing_start = std::min(composing_base, composing_extent); size_t cursor_offset = selection_base - composing_start; priv->text_model->SetComposingRange( flutter::TextRange(composing_base, composing_extent), cursor_offset); } return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Called when the input method client is complete. static FlMethodResponse* clear_client(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); priv->client_id = kClientIdUnset; return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Update the IM cursor position. // // As text is input by the user, the framework sends two streams of updates // over the text input channel: updates to the composing rect (cursor rect when // not in IME composing mode) and updates to the matrix transform from local // coordinates to Flutter root coordinates. This function is called after each // of these updates. It transforms the composing rect to GDK window coordinates // and notifies GTK of the updated cursor position. static void update_im_cursor_position(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); // Skip update if not composing to avoid setting to position 0. if (!priv->text_model->composing()) { return; } // Transform the x, y positions of the cursor from local coordinates to // Flutter view coordinates. gint x = priv->composing_rect.x * priv->editabletext_transform[0][0] + priv->composing_rect.y * priv->editabletext_transform[1][0] + priv->editabletext_transform[3][0] + priv->composing_rect.width; gint y = priv->composing_rect.x * priv->editabletext_transform[0][1] + priv->composing_rect.y * priv->editabletext_transform[1][1] + priv->editabletext_transform[3][1] + priv->composing_rect.height; // Transform from Flutter view coordinates to GTK window coordinates. GdkRectangle preedit_rect = {}; fl_text_input_view_delegate_translate_coordinates( priv->view_delegate, x, y, &preedit_rect.x, &preedit_rect.y); // Set the cursor location in window coordinates so that GTK can position any // system input method windows. gtk_im_context_set_cursor_location(priv->im_context, &preedit_rect); } // Handles updates to the EditableText size and position from the framework. // // On changes to the size or position of the RenderObject underlying the // EditableText, this update may be triggered. It provides an updated size and // transform from the local coordinate system of the EditableText to root // Flutter coordinate system. static FlMethodResponse* set_editable_size_and_transform( FlTextInputPlugin* self, FlValue* args) { FlValue* transform = fl_value_lookup_string(args, kTransform); size_t transform_len = fl_value_get_length(transform); g_warn_if_fail(transform_len == 16); for (size_t i = 0; i < transform_len; ++i) { double val = fl_value_get_float(fl_value_get_list_value(transform, i)); FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); priv->editabletext_transform[i / 4][i % 4] = val; } update_im_cursor_position(self); return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Handles updates to the composing rect from the framework. // // On changes to the state of the EditableText in the framework, this update // may be triggered. It provides an updated rect for the composing region in // local coordinates of the EditableText. In the case where there is no // composing region, the cursor rect is sent. static FlMethodResponse* set_marked_text_rect(FlTextInputPlugin* self, FlValue* args) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); priv->composing_rect.x = fl_value_get_float(fl_value_lookup_string(args, "x")); priv->composing_rect.y = fl_value_get_float(fl_value_lookup_string(args, "y")); priv->composing_rect.width = fl_value_get_float(fl_value_lookup_string(args, "width")); priv->composing_rect.height = fl_value_get_float(fl_value_lookup_string(args, "height")); update_im_cursor_position(self); return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Called when a method call is received from Flutter. static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { FlTextInputPlugin* self = FL_TEXT_INPUT_PLUGIN(user_data); const gchar* method = fl_method_call_get_name(method_call); FlValue* args = fl_method_call_get_args(method_call); g_autoptr(FlMethodResponse) response = nullptr; if (strcmp(method, kSetClientMethod) == 0) { response = set_client(self, args); } else if (strcmp(method, kShowMethod) == 0) { response = show(self); } else if (strcmp(method, kSetEditingStateMethod) == 0) { response = set_editing_state(self, args); } else if (strcmp(method, kClearClientMethod) == 0) { response = clear_client(self); } else if (strcmp(method, kHideMethod) == 0) { response = hide(self); } else if (strcmp(method, kSetEditableSizeAndTransform) == 0) { response = set_editable_size_and_transform(self, args); } else if (strcmp(method, kSetMarkedTextRect) == 0) { response = set_marked_text_rect(self, args); } else { response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); } g_autoptr(GError) error = nullptr; if (!fl_method_call_respond(method_call, response, &error)) { g_warning("Failed to send method call response: %s", error->message); } } // Disposes of an FlTextInputPlugin. static void fl_text_input_plugin_dispose(GObject* object) { FlTextInputPlugin* self = FL_TEXT_INPUT_PLUGIN(object); FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); g_clear_object(&priv->channel); g_clear_pointer(&priv->input_action, g_free); g_clear_object(&priv->im_context); if (priv->text_model != nullptr) { delete priv->text_model; priv->text_model = nullptr; } if (priv->view_delegate != nullptr) { g_object_remove_weak_pointer( G_OBJECT(priv->view_delegate), reinterpret_cast<gpointer*>(&(priv->view_delegate))); priv->view_delegate = nullptr; } G_OBJECT_CLASS(fl_text_input_plugin_parent_class)->dispose(object); } // Implements FlTextInputPlugin::filter_keypress. static gboolean fl_text_input_plugin_filter_keypress_default( FlTextInputPlugin* self, FlKeyEvent* event) { g_return_val_if_fail(FL_IS_TEXT_INPUT_PLUGIN(self), false); FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); if (priv->client_id == kClientIdUnset) { return FALSE; } if (gtk_im_context_filter_keypress( priv->im_context, reinterpret_cast<GdkEventKey*>(event->origin))) { return TRUE; } std::string text_before_change = priv->text_model->GetText(); flutter::TextRange selection_before_change = priv->text_model->selection(); std::string text = priv->text_model->GetText(); // Handle the enter/return key. gboolean do_action = FALSE; // Handle navigation keys. gboolean changed = FALSE; if (event->is_press) { switch (event->keyval) { case GDK_KEY_End: case GDK_KEY_KP_End: if (event->state & GDK_SHIFT_MASK) { changed = priv->text_model->SelectToEnd(); } else { changed = priv->text_model->MoveCursorToEnd(); } break; case GDK_KEY_Return: case GDK_KEY_KP_Enter: case GDK_KEY_ISO_Enter: if (priv->input_type == kFlTextInputTypeMultiline && strcmp(priv->input_action, kNewlineInputAction) == 0) { priv->text_model->AddCodePoint('\n'); text = "\n"; changed = TRUE; } do_action = TRUE; break; case GDK_KEY_Home: case GDK_KEY_KP_Home: if (event->state & GDK_SHIFT_MASK) { changed = priv->text_model->SelectToBeginning(); } else { changed = priv->text_model->MoveCursorToBeginning(); } break; case GDK_KEY_BackSpace: case GDK_KEY_Delete: case GDK_KEY_KP_Delete: case GDK_KEY_Left: case GDK_KEY_KP_Left: case GDK_KEY_Right: case GDK_KEY_KP_Right: // Already handled inside the framework in RenderEditable. break; } } if (changed) { if (priv->enable_delta_model) { flutter::TextEditingDelta delta = flutter::TextEditingDelta( text_before_change, selection_before_change, text); update_editing_state_with_delta(self, &delta); } else { update_editing_state(self); } } if (do_action) { perform_action(self); } return changed; } // Initializes the FlTextInputPlugin class. static void fl_text_input_plugin_class_init(FlTextInputPluginClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_text_input_plugin_dispose; FL_TEXT_INPUT_PLUGIN_CLASS(klass)->filter_keypress = fl_text_input_plugin_filter_keypress_default; } // Initializes an instance of the FlTextInputPlugin class. static void fl_text_input_plugin_init(FlTextInputPlugin* self) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); priv->client_id = kClientIdUnset; priv->input_type = kFlTextInputTypeText; priv->text_model = new flutter::TextInputModel(); } static void init_im_context(FlTextInputPlugin* self, GtkIMContext* im_context) { FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); priv->im_context = GTK_IM_CONTEXT(g_object_ref(im_context)); // On Wayland, this call sets up the input method so it can be enabled // immediately when required. Without it, on-screen keyboard's don't come up // the first time a text field is focused. gtk_im_context_focus_out(priv->im_context); g_signal_connect_object(priv->im_context, "preedit-start", G_CALLBACK(im_preedit_start_cb), self, G_CONNECT_SWAPPED); g_signal_connect_object(priv->im_context, "preedit-end", G_CALLBACK(im_preedit_end_cb), self, G_CONNECT_SWAPPED); g_signal_connect_object(priv->im_context, "preedit-changed", G_CALLBACK(im_preedit_changed_cb), self, G_CONNECT_SWAPPED); g_signal_connect_object(priv->im_context, "commit", G_CALLBACK(im_commit_cb), self, G_CONNECT_SWAPPED); g_signal_connect_object(priv->im_context, "retrieve-surrounding", G_CALLBACK(im_retrieve_surrounding_cb), self, G_CONNECT_SWAPPED); g_signal_connect_object(priv->im_context, "delete-surrounding", G_CALLBACK(im_delete_surrounding_cb), self, G_CONNECT_SWAPPED); } FlTextInputPlugin* fl_text_input_plugin_new( FlBinaryMessenger* messenger, GtkIMContext* im_context, FlTextInputViewDelegate* view_delegate) { g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr); g_return_val_if_fail(GTK_IS_IM_CONTEXT(im_context), nullptr); g_return_val_if_fail(FL_IS_TEXT_INPUT_VIEW_DELEGATE(view_delegate), nullptr); FlTextInputPlugin* self = FL_TEXT_INPUT_PLUGIN( g_object_new(fl_text_input_plugin_get_type(), nullptr)); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); FlTextInputPluginPrivate* priv = static_cast<FlTextInputPluginPrivate*>( fl_text_input_plugin_get_instance_private(self)); priv->channel = fl_method_channel_new(messenger, kChannelName, FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(priv->channel, method_call_cb, self, nullptr); init_im_context(self, im_context); priv->view_delegate = view_delegate; g_object_add_weak_pointer( G_OBJECT(view_delegate), reinterpret_cast<gpointer*>(&(priv->view_delegate))); return self; } // Filters the a keypress given to the plugin through the plugin's // filter_keypress callback. gboolean fl_text_input_plugin_filter_keypress(FlTextInputPlugin* self, FlKeyEvent* event) { g_return_val_if_fail(FL_IS_TEXT_INPUT_PLUGIN(self), FALSE); if (FL_TEXT_INPUT_PLUGIN_GET_CLASS(self)->filter_keypress) { return FL_TEXT_INPUT_PLUGIN_GET_CLASS(self)->filter_keypress(self, event); } return FALSE; }
engine/shell/platform/linux/fl_text_input_plugin.cc/0
{ "file_path": "engine/shell/platform/linux/fl_text_input_plugin.cc", "repo_id": "engine", "token_count": 12315 }
371
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_view_accessible.h" #include "flutter/shell/platform/linux/fl_accessible_node.h" #include "flutter/shell/platform/linux/fl_accessible_text_field.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_view.h" struct _FlViewAccessible { GtkContainerAccessible parent_instance; FlEngine* engine; // Semantics nodes keyed by ID GHashTable* semantics_nodes_by_id; }; enum { kProp0, kPropEngine, kPropLast }; G_DEFINE_TYPE(FlViewAccessible, fl_view_accessible, GTK_TYPE_CONTAINER_ACCESSIBLE) static void init_engine(FlViewAccessible* self, FlEngine* engine) { g_assert(self->engine == nullptr); self->engine = engine; g_object_add_weak_pointer(G_OBJECT(self), reinterpret_cast<gpointer*>(&self->engine)); } static FlEngine* get_engine(FlViewAccessible* self) { if (self->engine == nullptr) { FlView* view = FL_VIEW(gtk_accessible_get_widget(GTK_ACCESSIBLE(self))); init_engine(self, fl_view_get_engine(view)); } return self->engine; } static FlAccessibleNode* create_node(FlViewAccessible* self, FlutterSemanticsNode2* semantics) { FlEngine* engine = get_engine(self); if (semantics->flags & kFlutterSemanticsFlagIsTextField) { return fl_accessible_text_field_new(engine, semantics->id); } return fl_accessible_node_new(engine, semantics->id); } static FlAccessibleNode* lookup_node(FlViewAccessible* self, int32_t id) { return FL_ACCESSIBLE_NODE( g_hash_table_lookup(self->semantics_nodes_by_id, GINT_TO_POINTER(id))); } // Gets the ATK node for the given id. // If the node doesn't exist it will be created. static FlAccessibleNode* get_node(FlViewAccessible* self, FlutterSemanticsNode2* semantics) { FlAccessibleNode* node = lookup_node(self, semantics->id); if (node != nullptr) { return node; } node = create_node(self, semantics); if (semantics->id == 0) { fl_accessible_node_set_parent(node, ATK_OBJECT(self), 0); g_signal_emit_by_name(self, "children-changed::add", 0, node, nullptr); } g_hash_table_insert(self->semantics_nodes_by_id, GINT_TO_POINTER(semantics->id), reinterpret_cast<gpointer>(node)); return node; } // Implements AtkObject::get_n_children static gint fl_view_accessible_get_n_children(AtkObject* accessible) { FlViewAccessible* self = FL_VIEW_ACCESSIBLE(accessible); FlAccessibleNode* node = lookup_node(self, 0); if (node == nullptr) { return 0; } return 1; } // Implements AtkObject::ref_child static AtkObject* fl_view_accessible_ref_child(AtkObject* accessible, gint i) { FlViewAccessible* self = FL_VIEW_ACCESSIBLE(accessible); FlAccessibleNode* node = lookup_node(self, 0); if (i != 0 || node == nullptr) { return nullptr; } return ATK_OBJECT(g_object_ref(node)); } // Implements AtkObject::get_role static AtkRole fl_view_accessible_get_role(AtkObject* accessible) { return ATK_ROLE_PANEL; } // Implements GObject::set_property static void fl_view_accessible_set_property(GObject* object, guint prop_id, const GValue* value, GParamSpec* pspec) { FlViewAccessible* self = FL_VIEW_ACCESSIBLE(object); switch (prop_id) { case kPropEngine: init_engine(self, FL_ENGINE(g_value_get_object(value))); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void fl_view_accessible_dispose(GObject* object) { FlViewAccessible* self = FL_VIEW_ACCESSIBLE(object); g_clear_pointer(&self->semantics_nodes_by_id, g_hash_table_unref); if (self->engine != nullptr) { g_object_remove_weak_pointer(object, reinterpret_cast<gpointer*>(&self->engine)); self->engine = nullptr; } G_OBJECT_CLASS(fl_view_accessible_parent_class)->dispose(object); } static void fl_view_accessible_class_init(FlViewAccessibleClass* klass) { ATK_OBJECT_CLASS(klass)->get_n_children = fl_view_accessible_get_n_children; ATK_OBJECT_CLASS(klass)->ref_child = fl_view_accessible_ref_child; ATK_OBJECT_CLASS(klass)->get_role = fl_view_accessible_get_role; G_OBJECT_CLASS(klass)->dispose = fl_view_accessible_dispose; G_OBJECT_CLASS(klass)->set_property = fl_view_accessible_set_property; 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))); } static void fl_view_accessible_init(FlViewAccessible* self) { self->semantics_nodes_by_id = g_hash_table_new_full( g_direct_hash, g_direct_equal, nullptr, g_object_unref); } void fl_view_accessible_handle_update_semantics( FlViewAccessible* self, const FlutterSemanticsUpdate2* update) { g_autoptr(GHashTable) pending_children = g_hash_table_new_full(g_direct_hash, g_direct_equal, nullptr, reinterpret_cast<GDestroyNotify>(fl_value_unref)); for (size_t i = 0; i < update->node_count; i++) { FlutterSemanticsNode2* node = update->nodes[i]; FlAccessibleNode* atk_node = get_node(self, node); fl_accessible_node_set_flags(atk_node, node->flags); fl_accessible_node_set_actions(atk_node, node->actions); fl_accessible_node_set_name(atk_node, node->label); fl_accessible_node_set_extents( atk_node, node->rect.left + node->transform.transX, node->rect.top + node->transform.transY, node->rect.right - node->rect.left, node->rect.bottom - node->rect.top); fl_accessible_node_set_value(atk_node, node->value); fl_accessible_node_set_text_selection(atk_node, node->text_selection_base, node->text_selection_extent); fl_accessible_node_set_text_direction(atk_node, node->text_direction); FlValue* children = fl_value_new_int32_list( node->children_in_traversal_order, node->child_count); g_hash_table_insert(pending_children, atk_node, children); } g_hash_table_foreach_remove( pending_children, [](gpointer key, gpointer value, gpointer user_data) -> gboolean { FlViewAccessible* self = FL_VIEW_ACCESSIBLE(user_data); FlAccessibleNode* parent = FL_ACCESSIBLE_NODE(key); size_t child_count = fl_value_get_length(static_cast<FlValue*>(value)); const int32_t* children_in_traversal_order = fl_value_get_int32_list(static_cast<FlValue*>(value)); g_autoptr(GPtrArray) children = g_ptr_array_new(); for (size_t i = 0; i < child_count; i++) { FlAccessibleNode* child = lookup_node(self, children_in_traversal_order[i]); g_assert(child != nullptr); fl_accessible_node_set_parent(child, ATK_OBJECT(parent), i); g_ptr_array_add(children, child); } fl_accessible_node_set_children(parent, children); return true; }, self); }
engine/shell/platform/linux/fl_view_accessible.cc/0
{ "file_path": "engine/shell/platform/linux/fl_view_accessible.cc", "repo_id": "engine", "token_count": 3156 }
372
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_MESSAGE_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_MESSAGE_CODEC_H_ #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif #include <glib-object.h> #include <gmodule.h> #include "fl_value.h" G_BEGIN_DECLS /** * FlMessageCodecError: * @FL_MESSAGE_CODEC_ERROR_FAILED: Codec failed due to an unspecified error. * @FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA: Codec ran out of data reading a value. * @FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA: Additional data encountered in * message. * @FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE: Codec encountered an unsupported * #FlValue. * * Errors for #FlMessageCodec objects to set on failures. */ #define FL_MESSAGE_CODEC_ERROR fl_message_codec_error_quark() typedef enum { // NOLINTBEGIN(readability-identifier-naming) FL_MESSAGE_CODEC_ERROR_FAILED, FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA, FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA, FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE, // NOLINTEND(readability-identifier-naming) } FlMessageCodecError; G_MODULE_EXPORT GQuark fl_message_codec_error_quark(void) G_GNUC_CONST; G_MODULE_EXPORT G_DECLARE_DERIVABLE_TYPE(FlMessageCodec, fl_message_codec, FL, MESSAGE_CODEC, GObject) /** * FlMessageCodec: * * #FlMessageCodec is a message encoding/decoding mechanism that operates on * #FlValue objects. Both operations returns errors if the conversion fails. * Such situations should be treated as programming errors. * * #FlMessageCodec matches the MethodCodec class in the Flutter services * library. */ struct _FlMessageCodecClass { GObjectClass parent_class; /** * FlMessageCodec::encode_message: * @codec: an #FlMessageCodec. * @message: message to encode or %NULL to encode the null value. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Virtual method to encode a message. A subclass must implement this method. * If the subclass cannot handle the type of @message then it must generate a * FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE error. * * Returns: a binary message or %NULL on error. */ GBytes* (*encode_message)(FlMessageCodec* codec, FlValue* message, GError** error); /** * FlMessageCodec::decode_message: * @codec: an #FlMessageCodec. * @message: binary message to decode. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Virtual method to decode a message. A subclass must implement this method. * If @message is too small then a #FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA error * must be generated. If @message is too large then a * #FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA error must be generated. * * Returns: an #FlValue or %NULL on error. */ FlValue* (*decode_message)(FlMessageCodec* codec, GBytes* message, GError** error); }; /** * fl_message_codec_encode_message: * @codec: an #FlMessageCodec. * @buffer: buffer to write to. * @message: message to encode or %NULL to encode the null value. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Encodes a message into a binary representation. * * Returns: a binary encoded message or %NULL on error. */ GBytes* fl_message_codec_encode_message(FlMessageCodec* codec, FlValue* message, GError** error); /** * fl_message_codec_decode_message: * @codec: an #FlMessageCodec. * @message: binary message to decode. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Decodes a message from a binary encoding. * * Returns: an #FlValue or %NULL on error. */ FlValue* fl_message_codec_decode_message(FlMessageCodec* codec, GBytes* message, GError** error); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_MESSAGE_CODEC_H_
engine/shell/platform/linux/public/flutter_linux/fl_message_codec.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_message_codec.h", "repo_id": "engine", "token_count": 1855 }
373
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FLUTTER_LINUX_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FLUTTER_LINUX_H_ #define __FLUTTER_LINUX_INSIDE__ #include <flutter_linux/fl_basic_message_channel.h> #include <flutter_linux/fl_binary_codec.h> #include <flutter_linux/fl_binary_messenger.h> #include <flutter_linux/fl_dart_project.h> #include <flutter_linux/fl_engine.h> #include <flutter_linux/fl_event_channel.h> #include <flutter_linux/fl_json_message_codec.h> #include <flutter_linux/fl_json_method_codec.h> #include <flutter_linux/fl_message_codec.h> #include <flutter_linux/fl_method_call.h> #include <flutter_linux/fl_method_channel.h> #include <flutter_linux/fl_method_codec.h> #include <flutter_linux/fl_method_response.h> #include <flutter_linux/fl_pixel_buffer_texture.h> #include <flutter_linux/fl_plugin_registrar.h> #include <flutter_linux/fl_plugin_registry.h> #include <flutter_linux/fl_standard_message_codec.h> #include <flutter_linux/fl_standard_method_codec.h> #include <flutter_linux/fl_string_codec.h> #include <flutter_linux/fl_texture.h> #include <flutter_linux/fl_texture_gl.h> #include <flutter_linux/fl_texture_registrar.h> #include <flutter_linux/fl_value.h> #include <flutter_linux/fl_view.h> #undef __FLUTTER_LINUX_INSIDE__ #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FLUTTER_LINUX_H_
engine/shell/platform/linux/public/flutter_linux/flutter_linux.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/flutter_linux.h", "repo_id": "engine", "token_count": 614 }
374
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_PLUGIN_REGISTRAR_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_PLUGIN_REGISTRAR_H_ #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registrar.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlMockPluginRegistrar, fl_mock_plugin_registrar, FL, MOCK_PLUGIN_REGISTRAR, GObject) FlPluginRegistrar* fl_mock_plugin_registrar_new( FlBinaryMessenger* messenger, FlTextureRegistrar* texture_registrar); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_PLUGIN_REGISTRAR_H_
engine/shell/platform/linux/testing/mock_plugin_registrar.h/0
{ "file_path": "engine/shell/platform/linux/testing/mock_plugin_registrar.h", "repo_id": "engine", "token_count": 441 }
375
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_ACCESSIBILITY_BRIDGE_WINDOWS_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_ACCESSIBILITY_BRIDGE_WINDOWS_H_ #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/accessibility_bridge.h" #include "flutter/third_party/accessibility/ax/platform/ax_fragment_root_delegate_win.h" namespace flutter { class FlutterWindowsEngine; class FlutterWindowsView; class FlutterPlatformNodeDelegateWindows; // The Win32 implementation of AccessibilityBridge. // // This interacts with Windows accessibility APIs, which includes routing // accessibility events fired from the framework to Windows, routing native // Windows accessibility events to the framework, and creating Windows-specific // FlutterPlatformNodeDelegate objects for each node in the semantics tree. /// /// AccessibilityBridgeWindows must be created as a shared_ptr, since some /// methods acquires its weak_ptr. class AccessibilityBridgeWindows : public AccessibilityBridge, public ui::AXFragmentRootDelegateWin { public: AccessibilityBridgeWindows(FlutterWindowsView* view); virtual ~AccessibilityBridgeWindows() = default; // |AccessibilityBridge| void DispatchAccessibilityAction(AccessibilityNodeId target, FlutterSemanticsAction action, fml::MallocMapping data) override; // Dispatches a Windows accessibility event of the specified type, generated // by the accessibility node associated with the specified semantics node. // // This is a virtual method for the convenience of unit tests. virtual void DispatchWinAccessibilityEvent( std::shared_ptr<FlutterPlatformNodeDelegateWindows> node_delegate, ax::mojom::Event event_type); // Sets the accessibility focus to the accessibility node associated with the // specified semantics node. // // This is a virtual method for the convenience of unit tests. virtual void SetFocus( std::shared_ptr<FlutterPlatformNodeDelegateWindows> node_delegate); // |AXFragmentRootDelegateWin| gfx::NativeViewAccessible GetChildOfAXFragmentRoot() override; // |AXFragmentRootDelegateWin| gfx::NativeViewAccessible GetParentOfAXFragmentRoot() override; // |AXFragmentRootDelegateWin| bool IsAXFragmentRootAControlElement() override; protected: // |AccessibilityBridge| void OnAccessibilityEvent( ui::AXEventGenerator::TargetedEvent targeted_event) override; // |AccessibilityBridge| std::shared_ptr<FlutterPlatformNodeDelegate> CreateFlutterPlatformNodeDelegate() override; // Retrieve the focused node for accessibility events. virtual std::weak_ptr<FlutterPlatformNodeDelegate> GetFocusedNode(); private: FlutterWindowsView* view_; FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridgeWindows); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_ACCESSIBILITY_BRIDGE_WINDOWS_H_
engine/shell/platform/windows/accessibility_bridge_windows.h/0
{ "file_path": "engine/shell/platform/windows/accessibility_bridge_windows.h", "repo_id": "engine", "token_count": 946 }
376
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <string> #include "flutter/shell/platform/windows/client_wrapper/include/flutter/plugin_registrar_windows.h" #include "flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace flutter { namespace { using ::testing::Return; // Stub implementation to validate calls to the API. class TestWindowsApi : public testing::StubFlutterWindowsApi { public: void PluginRegistrarRegisterTopLevelWindowProcDelegate( FlutterDesktopWindowProcCallback delegate, void* user_data) override { ++registered_delegate_count_; last_registered_delegate_ = delegate; last_registered_user_data_ = user_data; } MOCK_METHOD(FlutterDesktopViewRef, PluginRegistrarGetView, (), (override)); MOCK_METHOD(FlutterDesktopViewRef, PluginRegistrarGetViewById, (FlutterDesktopViewId), (override)); void PluginRegistrarUnregisterTopLevelWindowProcDelegate( FlutterDesktopWindowProcCallback delegate) override { --registered_delegate_count_; } int registered_delegate_count() { return registered_delegate_count_; } FlutterDesktopWindowProcCallback last_registered_delegate() { return last_registered_delegate_; } void* last_registered_user_data() { return last_registered_user_data_; } private: int registered_delegate_count_ = 0; FlutterDesktopWindowProcCallback last_registered_delegate_ = nullptr; void* last_registered_user_data_ = nullptr; }; // A test plugin that tries to access registrar state during destruction and // reports it out via a flag provided at construction. class TestPlugin : public Plugin { public: // registrar_valid_at_destruction will be set at destruction to indicate // whether or not |registrar->GetView()| was non-null. TestPlugin(PluginRegistrarWindows* registrar, bool* registrar_valid_at_destruction) : registrar_(registrar), registrar_valid_at_destruction_(registrar_valid_at_destruction) {} virtual ~TestPlugin() { *registrar_valid_at_destruction_ = registrar_->GetView() != nullptr; } private: PluginRegistrarWindows* registrar_; bool* registrar_valid_at_destruction_; }; } // namespace TEST(PluginRegistrarWindowsTest, GetView) { auto windows_api = std::make_unique<TestWindowsApi>(); EXPECT_CALL(*windows_api, PluginRegistrarGetView) .WillOnce(Return(reinterpret_cast<FlutterDesktopViewRef>(1))); testing::ScopedStubFlutterWindowsApi scoped_api_stub(std::move(windows_api)); auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub()); PluginRegistrarWindows registrar( reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1)); EXPECT_NE(registrar.GetView(), nullptr); } TEST(PluginRegistrarWindowsTest, GetViewById) { auto windows_api = std::make_unique<TestWindowsApi>(); EXPECT_CALL(*windows_api, PluginRegistrarGetView) .WillRepeatedly(Return(nullptr)); EXPECT_CALL(*windows_api, PluginRegistrarGetViewById(123)) .WillOnce(Return(reinterpret_cast<FlutterDesktopViewRef>(1))); EXPECT_CALL(*windows_api, PluginRegistrarGetViewById(456)) .WillOnce(Return(nullptr)); testing::ScopedStubFlutterWindowsApi scoped_api_stub(std::move(windows_api)); auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub()); PluginRegistrarWindows registrar( reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1)); EXPECT_EQ(registrar.GetView(), nullptr); EXPECT_NE(registrar.GetViewById(123).get(), nullptr); EXPECT_EQ(registrar.GetViewById(456).get(), nullptr); } // Tests that the registrar runs plugin destructors before its own teardown. TEST(PluginRegistrarWindowsTest, PluginDestroyedBeforeRegistrar) { auto windows_api = std::make_unique<TestWindowsApi>(); EXPECT_CALL(*windows_api, PluginRegistrarGetView) .WillRepeatedly(Return(reinterpret_cast<FlutterDesktopViewRef>(1))); testing::ScopedStubFlutterWindowsApi scoped_api_stub(std::move(windows_api)); auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub()); PluginRegistrarWindows registrar( reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1)); auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); bool registrar_valid_at_destruction = false; { PluginRegistrarWindows registrar(dummy_registrar_handle); auto plugin = std::make_unique<TestPlugin>(&registrar, &registrar_valid_at_destruction); registrar.AddPlugin(std::move(plugin)); } EXPECT_TRUE(registrar_valid_at_destruction); } TEST(PluginRegistrarWindowsTest, RegisterUnregister) { auto windows_api = std::make_unique<TestWindowsApi>(); EXPECT_CALL(*windows_api, PluginRegistrarGetView).WillOnce(Return(nullptr)); testing::ScopedStubFlutterWindowsApi scoped_api_stub(std::move(windows_api)); auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub()); PluginRegistrarWindows registrar( reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1)); WindowProcDelegate delegate = [](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { return std::optional<LRESULT>(); }; int id_a = registrar.RegisterTopLevelWindowProcDelegate(delegate); EXPECT_EQ(test_api->registered_delegate_count(), 1); int id_b = registrar.RegisterTopLevelWindowProcDelegate(delegate); // All the C++-level delegates are driven by a since C callback, so the // registration count should stay the same. EXPECT_EQ(test_api->registered_delegate_count(), 1); // Unregistering one of the two delegates shouldn't cause the underlying C // callback to be unregistered. registrar.UnregisterTopLevelWindowProcDelegate(id_a); EXPECT_EQ(test_api->registered_delegate_count(), 1); // Unregistering both should unregister it. registrar.UnregisterTopLevelWindowProcDelegate(id_b); EXPECT_EQ(test_api->registered_delegate_count(), 0); EXPECT_NE(id_a, id_b); } TEST(PluginRegistrarWindowsTest, CallsRegisteredDelegates) { auto windows_api = std::make_unique<TestWindowsApi>(); EXPECT_CALL(*windows_api, PluginRegistrarGetView).WillOnce(Return(nullptr)); testing::ScopedStubFlutterWindowsApi scoped_api_stub(std::move(windows_api)); auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub()); PluginRegistrarWindows registrar( reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1)); HWND dummy_hwnd; bool called_a = false; WindowProcDelegate delegate_a = [&called_a, &dummy_hwnd]( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { called_a = true; EXPECT_EQ(hwnd, dummy_hwnd); EXPECT_EQ(message, 2); EXPECT_EQ(wparam, 3); EXPECT_EQ(lparam, 4); return std::optional<LRESULT>(); }; bool called_b = false; WindowProcDelegate delegate_b = [&called_b](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { called_b = true; return std::optional<LRESULT>(); }; int id_a = registrar.RegisterTopLevelWindowProcDelegate(delegate_a); int id_b = registrar.RegisterTopLevelWindowProcDelegate(delegate_b); LRESULT result = 0; bool handled = test_api->last_registered_delegate()( dummy_hwnd, 2, 3, 4, test_api->last_registered_user_data(), &result); EXPECT_TRUE(called_a); EXPECT_TRUE(called_b); EXPECT_FALSE(handled); } TEST(PluginRegistrarWindowsTest, StopsOnceHandled) { auto windows_api = std::make_unique<TestWindowsApi>(); EXPECT_CALL(*windows_api, PluginRegistrarGetView).WillOnce(Return(nullptr)); testing::ScopedStubFlutterWindowsApi scoped_api_stub(std::move(windows_api)); auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub()); PluginRegistrarWindows registrar( reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1)); bool called_a = false; WindowProcDelegate delegate_a = [&called_a](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { called_a = true; return std::optional<LRESULT>(7); }; bool called_b = false; WindowProcDelegate delegate_b = [&called_b](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { called_b = true; return std::optional<LRESULT>(7); }; int id_a = registrar.RegisterTopLevelWindowProcDelegate(delegate_a); int id_b = registrar.RegisterTopLevelWindowProcDelegate(delegate_b); HWND dummy_hwnd; LRESULT result = 0; bool handled = test_api->last_registered_delegate()( dummy_hwnd, 2, 3, 4, test_api->last_registered_user_data(), &result); // Only one of the delegates should have been called, since each claims to // have fully handled the message. EXPECT_TRUE(called_a || called_b); EXPECT_NE(called_a, called_b); // The return value should propagate through. EXPECT_TRUE(handled); EXPECT_EQ(result, 7); } } // namespace flutter
engine/shell/platform/windows/client_wrapper/plugin_registrar_windows_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/client_wrapper/plugin_registrar_windows_unittests.cc", "repo_id": "engine", "token_count": 3441 }
377
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "dpi_utils.h" #include "flutter/fml/macros.h" namespace flutter { namespace { constexpr UINT kDefaultDpi = 96; // This is the MDT_EFFECTIVE_DPI value from MONITOR_DPI_TYPE, an enum declared // in ShellScalingApi.h. Replicating here to avoid importing the library // directly. constexpr UINT kEffectiveDpiMonitorType = 0; template <typename T> /// Retrieves a function |name| from a given |comBaseModule| into |outProc|. /// Returns a bool indicating whether the function was found. bool AssignProcAddress(HMODULE comBaseModule, const char* name, T*& outProc) { outProc = reinterpret_cast<T*>(GetProcAddress(comBaseModule, name)); return *outProc != nullptr; } /// A helper class for abstracting various Windows DPI related functions across /// Windows OS versions. class DpiHelper { public: DpiHelper(); ~DpiHelper(); /// Returns the DPI for |hwnd|. Supports all DPI awareness modes, and is /// backward compatible down to Windows Vista. If |hwnd| is nullptr, returns /// the DPI for the primary monitor. If Per-Monitor DPI awareness is not /// available, returns the system's DPI. UINT GetDpiForWindow(HWND); /// Returns the DPI of a given monitor. Defaults to 96 if the API is not /// available. UINT GetDpiForMonitor(HMONITOR); private: using GetDpiForWindow_ = UINT __stdcall(HWND); using GetDpiForMonitor_ = HRESULT __stdcall(HMONITOR hmonitor, UINT dpiType, UINT* dpiX, UINT* dpiY); using EnableNonClientDpiScaling_ = BOOL __stdcall(HWND hwnd); GetDpiForWindow_* get_dpi_for_window_ = nullptr; GetDpiForMonitor_* get_dpi_for_monitor_ = nullptr; EnableNonClientDpiScaling_* enable_non_client_dpi_scaling_ = nullptr; HMODULE user32_module_ = nullptr; HMODULE shlib_module_ = nullptr; bool dpi_for_window_supported_ = false; bool dpi_for_monitor_supported_ = false; FML_DISALLOW_COPY_AND_ASSIGN(DpiHelper); }; DpiHelper::DpiHelper() { if ((user32_module_ = LoadLibraryA("User32.dll")) != nullptr) { dpi_for_window_supported_ = (AssignProcAddress( user32_module_, "GetDpiForWindow", get_dpi_for_window_)); } if ((shlib_module_ = LoadLibraryA("Shcore.dll")) != nullptr) { dpi_for_monitor_supported_ = AssignProcAddress( shlib_module_, "GetDpiForMonitor", get_dpi_for_monitor_); } } DpiHelper::~DpiHelper() { if (user32_module_ != nullptr) { FreeLibrary(user32_module_); } if (shlib_module_ != nullptr) { FreeLibrary(shlib_module_); } } UINT DpiHelper::GetDpiForWindow(HWND hwnd) { // GetDpiForWindow returns the DPI for any awareness mode. If not available, // or no |hwnd| is provided, fallback to a per monitor, system, or default // DPI. if (dpi_for_window_supported_ && hwnd != nullptr) { return get_dpi_for_window_(hwnd); } if (dpi_for_monitor_supported_) { HMONITOR monitor = nullptr; if (hwnd != nullptr) { monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTOPRIMARY); } return GetDpiForMonitor(monitor); } HDC hdc = GetDC(hwnd); UINT dpi = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(hwnd, hdc); return dpi; } UINT DpiHelper::GetDpiForMonitor(HMONITOR monitor) { if (dpi_for_monitor_supported_) { if (monitor == nullptr) { const POINT target_point = {0, 0}; monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTOPRIMARY); } UINT dpi_x = 0, dpi_y = 0; HRESULT result = get_dpi_for_monitor_(monitor, kEffectiveDpiMonitorType, &dpi_x, &dpi_y); if (SUCCEEDED(result)) { return dpi_x; } } return kDefaultDpi; } // namespace DpiHelper* GetHelper() { static DpiHelper* dpi_helper = new DpiHelper(); return dpi_helper; } } // namespace UINT GetDpiForHWND(HWND hwnd) { return GetHelper()->GetDpiForWindow(hwnd); } UINT GetDpiForMonitor(HMONITOR monitor) { return GetHelper()->GetDpiForMonitor(monitor); } } // namespace flutter
engine/shell/platform/windows/dpi_utils.cc/0
{ "file_path": "engine/shell/platform/windows/dpi_utils.cc", "repo_id": "engine", "token_count": 1665 }
378